diff options
author | neksard <neksard@yandex-team.ru> | 2022-02-10 16:45:23 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:23 +0300 |
commit | 8f7cf138264e0caa318144bf8a2c950e0b0a8593 (patch) | |
tree | 83bf5c8c8047c42d8475e6095df90ccdc3d1b57f /contrib/libs/grpc | |
parent | d3a398281c6fd1d3672036cb2d63f842d2cb28c5 (diff) | |
download | ydb-8f7cf138264e0caa318144bf8a2c950e0b0a8593.tar.gz |
Restoring authorship annotation for <neksard@yandex-team.ru>. Commit 1 of 2.
Diffstat (limited to 'contrib/libs/grpc')
518 files changed, 29161 insertions, 29161 deletions
diff --git a/contrib/libs/grpc/include/grpc/grpc.h b/contrib/libs/grpc/include/grpc/grpc.h index 6001117521..044c9c53df 100644 --- a/contrib/libs/grpc/include/grpc/grpc.h +++ b/contrib/libs/grpc/include/grpc/grpc.h @@ -63,8 +63,8 @@ GRPCAPI void grpc_dont_init_openssl(void); /** Initialize the grpc library. - After it's called, a matching invocation to grpc_shutdown() is expected. - + After it's called, a matching invocation to grpc_shutdown() is expected. + It is not safe to call any other grpc functions before calling this. (To avoid overhead, little checking is done, and some things may work. We do not warrant that they will continue to do so in future revisions of this @@ -73,9 +73,9 @@ GRPCAPI void grpc_init(void); /** Shut down the grpc library. - Before it's called, there should haven been a matching invocation to - grpc_init(). - + Before it's called, there should haven been a matching invocation to + grpc_init(). + The last call to grpc_shutdown will initiate cleaning up of grpc library internals, which can happen in another thread. Once the clean-up is done, no memory is used by grpc, nor are any instructions executing within the @@ -83,12 +83,12 @@ GRPCAPI void grpc_init(void); have been destroyed. */ GRPCAPI void grpc_shutdown(void); -/** EXPERIMENTAL. Returns 1 if the grpc library has been initialized. - TODO(ericgribkoff) Decide if this should be promoted to non-experimental as - part of stabilizing the fork support API, as tracked in - https://github.com/grpc/grpc/issues/15334 */ -GRPCAPI int grpc_is_initialized(void); - +/** EXPERIMENTAL. Returns 1 if the grpc library has been initialized. + TODO(ericgribkoff) Decide if this should be promoted to non-experimental as + part of stabilizing the fork support API, as tracked in + https://github.com/grpc/grpc/issues/15334 */ +GRPCAPI int grpc_is_initialized(void); + /** EXPERIMENTAL. Blocking shut down grpc library. This is only for wrapped language to use now. */ GRPCAPI void grpc_shutdown_blocking(void); @@ -115,13 +115,13 @@ GRPCAPI grpc_completion_queue* grpc_completion_queue_create_for_next( GRPCAPI grpc_completion_queue* grpc_completion_queue_create_for_pluck( void* reserved); -/** Helper function to create a completion queue with grpc_cq_completion_type - of GRPC_CQ_CALLBACK and grpc_cq_polling_type of GRPC_CQ_DEFAULT_POLLING. - This function is experimental. */ -GRPCAPI grpc_completion_queue* grpc_completion_queue_create_for_callback( - grpc_experimental_completion_queue_functor* shutdown_callback, - void* reserved); - +/** Helper function to create a completion queue with grpc_cq_completion_type + of GRPC_CQ_CALLBACK and grpc_cq_polling_type of GRPC_CQ_DEFAULT_POLLING. + This function is experimental. */ +GRPCAPI grpc_completion_queue* grpc_completion_queue_create_for_callback( + grpc_experimental_completion_queue_functor* shutdown_callback, + void* reserved); + /** Create a completion queue */ GRPCAPI grpc_completion_queue* grpc_completion_queue_create( const grpc_completion_queue_factory* factory, @@ -253,13 +253,13 @@ GRPCAPI void* grpc_call_arena_alloc(grpc_call* call, size_t size); appropriate to call grpc_completion_queue_next or grpc_completion_queue_pluck consequent to the failed grpc_call_start_batch call. - If a call to grpc_call_start_batch with an empty batch returns - GRPC_CALL_OK, the tag is put in the completion queue immediately. + If a call to grpc_call_start_batch with an empty batch returns + GRPC_CALL_OK, the tag is put in the completion queue immediately. THREAD SAFETY: access to grpc_call_start_batch in multi-threaded environment needs to be synchronized. As an optimization, you may synchronize batches containing just send operations independently from batches containing just - receive operations. Access to grpc_call_start_batch with an empty batch is - thread-compatible. */ + receive operations. Access to grpc_call_start_batch with an empty batch is + thread-compatible. */ GRPCAPI grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops, size_t nops, void* tag, void* reserved); @@ -295,11 +295,11 @@ GRPCAPI char* grpc_channel_get_target(grpc_channel* channel); GRPCAPI void grpc_channel_get_info(grpc_channel* channel, const grpc_channel_info* channel_info); -/** EXPERIMENTAL. Resets the channel's connect backoff. - TODO(roth): When we see whether this proves useful, either promote - to non-experimental or remove it. */ -GRPCAPI void grpc_channel_reset_connect_backoff(grpc_channel* channel); - +/** EXPERIMENTAL. Resets the channel's connect backoff. + TODO(roth): When we see whether this proves useful, either promote + to non-experimental or remove it. */ +GRPCAPI void grpc_channel_reset_connect_backoff(grpc_channel* channel); + /** Create a client channel to 'target'. Additional channel level configuration MAY be provided by grpc_channel_args, though the expectation is that most clients will want to simply pass NULL. The user data in 'args' need only @@ -481,56 +481,56 @@ GRPCAPI void grpc_resource_quota_unref(grpc_resource_quota* resource_quota); GRPCAPI void grpc_resource_quota_resize(grpc_resource_quota* resource_quota, size_t new_size); -/** Update the size of the maximum number of threads allowed */ -GRPCAPI void grpc_resource_quota_set_max_threads( - grpc_resource_quota* resource_quota, int new_max_threads); - +/** Update the size of the maximum number of threads allowed */ +GRPCAPI void grpc_resource_quota_set_max_threads( + grpc_resource_quota* resource_quota, int new_max_threads); + /** 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); -/************* CHANNELZ API *************/ -/** Channelz is under active development. The following APIs will see some - churn as the feature is implemented. This comment will be removed once - channelz is officially supported, and these APIs become stable. For now - you may track the progress by following this github issue: - https://github.com/grpc/grpc/issues/15340 - - the following APIs return allocated JSON strings that match the response - objects from the channelz proto, found here: - https://github.com/grpc/grpc/blob/master/src/proto/grpc/channelz/channelz.proto. - - For easy conversion to protobuf, The JSON is formatted according to: - https://developers.google.com/protocol-buffers/docs/proto3#json. */ - -/* Gets all root channels (i.e. channels the application has directly - created). This does not include subchannels nor non-top level channels. - The returned string is allocated and must be freed by the application. */ -GRPCAPI char* grpc_channelz_get_top_channels(intptr_t start_channel_id); - -/* Gets all servers that exist in the process. */ -GRPCAPI char* grpc_channelz_get_servers(intptr_t start_server_id); - -/* Returns a single Server, or else a NOT_FOUND code. */ -GRPCAPI char* grpc_channelz_get_server(intptr_t server_id); - -/* Gets all server sockets that exist in the server. */ -GRPCAPI char* grpc_channelz_get_server_sockets(intptr_t server_id, - intptr_t start_socket_id, - intptr_t max_results); - -/* Returns a single Channel, or else a NOT_FOUND code. The returned string - is allocated and must be freed by the application. */ -GRPCAPI char* grpc_channelz_get_channel(intptr_t channel_id); - -/* Returns a single Subchannel, or else a NOT_FOUND code. The returned string - is allocated and must be freed by the application. */ -GRPCAPI char* grpc_channelz_get_subchannel(intptr_t subchannel_id); - -/* Returns a single Socket, or else a NOT_FOUND code. The returned string - is allocated and must be freed by the application. */ -GRPCAPI char* grpc_channelz_get_socket(intptr_t socket_id); - +/************* CHANNELZ API *************/ +/** Channelz is under active development. The following APIs will see some + churn as the feature is implemented. This comment will be removed once + channelz is officially supported, and these APIs become stable. For now + you may track the progress by following this github issue: + https://github.com/grpc/grpc/issues/15340 + + the following APIs return allocated JSON strings that match the response + objects from the channelz proto, found here: + https://github.com/grpc/grpc/blob/master/src/proto/grpc/channelz/channelz.proto. + + For easy conversion to protobuf, The JSON is formatted according to: + https://developers.google.com/protocol-buffers/docs/proto3#json. */ + +/* Gets all root channels (i.e. channels the application has directly + created). This does not include subchannels nor non-top level channels. + The returned string is allocated and must be freed by the application. */ +GRPCAPI char* grpc_channelz_get_top_channels(intptr_t start_channel_id); + +/* Gets all servers that exist in the process. */ +GRPCAPI char* grpc_channelz_get_servers(intptr_t start_server_id); + +/* Returns a single Server, or else a NOT_FOUND code. */ +GRPCAPI char* grpc_channelz_get_server(intptr_t server_id); + +/* Gets all server sockets that exist in the server. */ +GRPCAPI char* grpc_channelz_get_server_sockets(intptr_t server_id, + intptr_t start_socket_id, + intptr_t max_results); + +/* Returns a single Channel, or else a NOT_FOUND code. The returned string + is allocated and must be freed by the application. */ +GRPCAPI char* grpc_channelz_get_channel(intptr_t channel_id); + +/* Returns a single Subchannel, or else a NOT_FOUND code. The returned string + is allocated and must be freed by the application. */ +GRPCAPI char* grpc_channelz_get_subchannel(intptr_t subchannel_id); + +/* Returns a single Socket, or else a NOT_FOUND code. The returned string + is allocated and must be freed by the application. */ +GRPCAPI char* grpc_channelz_get_socket(intptr_t socket_id); + #ifdef __cplusplus } #endif diff --git a/contrib/libs/grpc/include/grpc/grpc_security.h b/contrib/libs/grpc/include/grpc/grpc_security.h index 1810681b76..9d9ed59b77 100644 --- a/contrib/libs/grpc/include/grpc/grpc_security.h +++ b/contrib/libs/grpc/include/grpc/grpc_security.h @@ -213,26 +213,26 @@ typedef struct { void (*verify_peer_destruct)(void* userdata); } verify_peer_options; -/** Object that holds additional peer-verification options on a secure - channel. */ -typedef struct { - /** If non-NULL this callback will be invoked with the expected - target_name, the peer's certificate (in PEM format), and whatever - userdata pointer is set below. If a non-zero value is returned by this - callback then it is treated as a verification failure. Invocation of - the callback is blocking, so any implementation should be light-weight. - */ - int (*verify_peer_callback)(const char* target_name, const char* peer_pem, - void* userdata); - /** Arbitrary userdata that will be passed as the last argument to - verify_peer_callback. */ - void* verify_peer_callback_userdata; - /** A destruct callback that will be invoked when the channel is being - cleaned up. The userdata argument will be passed to it. The intent is - to perform any cleanup associated with that userdata. */ - void (*verify_peer_destruct)(void* userdata); +/** Object that holds additional peer-verification options on a secure + channel. */ +typedef struct { + /** If non-NULL this callback will be invoked with the expected + target_name, the peer's certificate (in PEM format), and whatever + userdata pointer is set below. If a non-zero value is returned by this + callback then it is treated as a verification failure. Invocation of + the callback is blocking, so any implementation should be light-weight. + */ + int (*verify_peer_callback)(const char* target_name, const char* peer_pem, + void* userdata); + /** Arbitrary userdata that will be passed as the last argument to + verify_peer_callback. */ + void* verify_peer_callback_userdata; + /** A destruct callback that will be invoked when the channel is being + cleaned up. The userdata argument will be passed to it. The intent is + to perform any cleanup associated with that userdata. */ + void (*verify_peer_destruct)(void* userdata); } grpc_ssl_verify_peer_options; - + /** Deprecated in favor of grpc_ssl_server_credentials_create_ex. It will be removed after all of its call sites are migrated to grpc_ssl_server_credentials_create_ex. Creates an SSL credentials object. @@ -255,17 +255,17 @@ typedef struct { particularly on mobile platforms such as iOS. - pem_key_cert_pair is a pointer on the object containing client's private key and certificate chain. This parameter can be NULL if the client does - not have such a key/cert pair. - - verify_options is an optional verify_peer_options object which holds - additional options controlling how peer certificates are verified. For - example, you can supply a callback which receives the peer's certificate - with which you can do additional verification. Can be NULL, in which - case verification will retain default behavior. Any settings in - verify_options are copied during this call, so the verify_options - object can be released afterwards. */ + not have such a key/cert pair. + - verify_options is an optional verify_peer_options object which holds + additional options controlling how peer certificates are verified. For + example, you can supply a callback which receives the peer's certificate + with which you can do additional verification. Can be NULL, in which + case verification will retain default behavior. Any settings in + verify_options are copied during this call, so the verify_options + object can be released afterwards. */ GRPCAPI grpc_channel_credentials* grpc_ssl_credentials_create( const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, - const verify_peer_options* verify_options, void* reserved); + const verify_peer_options* verify_options, void* reserved); /* Creates an SSL credentials object. The security level of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY. @@ -656,14 +656,14 @@ typedef struct grpc_alts_credentials_options grpc_alts_credentials_options; * It is used for experimental purpose for now and subject to change. */ GRPCAPI grpc_alts_credentials_options* -grpc_alts_credentials_client_options_create(void); +grpc_alts_credentials_client_options_create(void); /** * This method creates a grpc ALTS credentials server options instance. * It is used for experimental purpose for now and subject to change. */ GRPCAPI grpc_alts_credentials_options* -grpc_alts_credentials_server_options_create(void); +grpc_alts_credentials_server_options_create(void); /** * This method adds a target service account to grpc client's ALTS credentials @@ -710,69 +710,69 @@ GRPCAPI grpc_channel_credentials* grpc_alts_credentials_create( GRPCAPI grpc_server_credentials* grpc_alts_server_credentials_create( const grpc_alts_credentials_options* options); -/** --- Local channel/server credentials --- **/ - -/** +/** --- Local channel/server credentials --- **/ + +/** * This method creates a local channel credential object. The security level * of the resulting connection is GRPC_PRIVACY_AND_INTEGRITY for UDS and * GRPC_SECURITY_NONE for LOCAL_TCP. It is used for experimental purpose * for now and subject to change. - * - * - type: local connection type - * - * It returns the created local channel credential object. - */ -GRPCAPI grpc_channel_credentials* grpc_local_credentials_create( - grpc_local_connect_type type); - -/** - * This method creates a local server credential object. It is used for - * experimental purpose for now and subject to change. - * - * - type: local connection type - * - * It returns the created local server credential object. - */ -GRPCAPI grpc_server_credentials* grpc_local_server_credentials_create( - grpc_local_connect_type type); - + * + * - type: local connection type + * + * It returns the created local channel credential object. + */ +GRPCAPI grpc_channel_credentials* grpc_local_credentials_create( + grpc_local_connect_type type); + +/** + * This method creates a local server credential object. It is used for + * experimental purpose for now and subject to change. + * + * - type: local connection type + * + * It returns the created local server credential object. + */ +GRPCAPI grpc_server_credentials* grpc_local_server_credentials_create( + grpc_local_connect_type type); + /** --- TLS channel/server credentials --- - * It is used for experimental purpose for now and subject to change. */ - + * It is used for experimental purpose for now and subject to change. */ + /** Struct for indicating errors. It is used for * experimental purpose for now and subject to change. */ typedef struct grpc_tls_error_details grpc_tls_error_details; -/** Config for TLS key materials. It is used for - * experimental purpose for now and subject to change. */ -typedef struct grpc_tls_key_materials_config grpc_tls_key_materials_config; - -/** Config for TLS credential reload. It is used for - * experimental purpose for now and subject to change. */ -typedef struct grpc_tls_credential_reload_config - grpc_tls_credential_reload_config; - -/** Config for TLS server authorization check. It is used for - * experimental purpose for now and subject to change. */ -typedef struct grpc_tls_server_authorization_check_config - grpc_tls_server_authorization_check_config; - -/** TLS credentials options. It is used for - * experimental purpose for now and subject to change. */ -typedef struct grpc_tls_credentials_options grpc_tls_credentials_options; - -/** Create an empty TLS credentials options. It is used for - * experimental purpose for now and subject to change. */ +/** Config for TLS key materials. It is used for + * experimental purpose for now and subject to change. */ +typedef struct grpc_tls_key_materials_config grpc_tls_key_materials_config; + +/** Config for TLS credential reload. It is used for + * experimental purpose for now and subject to change. */ +typedef struct grpc_tls_credential_reload_config + grpc_tls_credential_reload_config; + +/** Config for TLS server authorization check. It is used for + * experimental purpose for now and subject to change. */ +typedef struct grpc_tls_server_authorization_check_config + grpc_tls_server_authorization_check_config; + +/** TLS credentials options. It is used for + * experimental purpose for now and subject to change. */ +typedef struct grpc_tls_credentials_options grpc_tls_credentials_options; + +/** Create an empty TLS credentials options. It is used for + * experimental purpose for now and subject to change. */ GRPCAPI grpc_tls_credentials_options* grpc_tls_credentials_options_create(void); - -/** Set grpc_ssl_client_certificate_request_type field in credentials options - with the provided type. options should not be NULL. - It returns 1 on success and 0 on failure. It is used for - experimental purpose for now and subject to change. */ -GRPCAPI int grpc_tls_credentials_options_set_cert_request_type( - grpc_tls_credentials_options* options, - grpc_ssl_client_certificate_request_type type); - + +/** Set grpc_ssl_client_certificate_request_type field in credentials options + with the provided type. options should not be NULL. + It returns 1 on success and 0 on failure. It is used for + experimental purpose for now and subject to change. */ +GRPCAPI int grpc_tls_credentials_options_set_cert_request_type( + grpc_tls_credentials_options* options, + grpc_ssl_client_certificate_request_type type); + /** Set grpc_tls_server_verification_option field in credentials options with the provided server_verification_option. options should not be NULL. This should be called only on the client side. @@ -786,55 +786,55 @@ GRPCAPI int grpc_tls_credentials_options_set_server_verification_option( grpc_tls_credentials_options* options, grpc_tls_server_verification_option server_verification_option); -/** Set grpc_tls_key_materials_config field in credentials options - with the provided config struct whose ownership is transferred. - Both parameters should not be NULL. - It returns 1 on success and 0 on failure. It is used for - experimental purpose for now and subject to change. */ -GRPCAPI int grpc_tls_credentials_options_set_key_materials_config( - grpc_tls_credentials_options* options, - grpc_tls_key_materials_config* config); - -/** Set grpc_tls_credential_reload_config field in credentials options - with the provided config struct whose ownership is transferred. - Both parameters should not be NULL. - It returns 1 on success and 0 on failure. It is used for - experimental purpose for now and subject to change. */ -GRPCAPI int grpc_tls_credentials_options_set_credential_reload_config( - grpc_tls_credentials_options* options, - grpc_tls_credential_reload_config* config); - -/** Set grpc_tls_server_authorization_check_config field in credentials options - with the provided config struct whose ownership is transferred. - Both parameters should not be NULL. - It returns 1 on success and 0 on failure. It is used for - experimental purpose for now and subject to change. */ -GRPCAPI int grpc_tls_credentials_options_set_server_authorization_check_config( - grpc_tls_credentials_options* options, - grpc_tls_server_authorization_check_config* config); - -/** --- TLS key materials config. --- - It is used for experimental purpose for now and subject to change. */ - -/** Create an empty grpc_tls_key_materials_config instance. - * It is used for experimental purpose for now and subject to change. */ +/** Set grpc_tls_key_materials_config field in credentials options + with the provided config struct whose ownership is transferred. + Both parameters should not be NULL. + It returns 1 on success and 0 on failure. It is used for + experimental purpose for now and subject to change. */ +GRPCAPI int grpc_tls_credentials_options_set_key_materials_config( + grpc_tls_credentials_options* options, + grpc_tls_key_materials_config* config); + +/** Set grpc_tls_credential_reload_config field in credentials options + with the provided config struct whose ownership is transferred. + Both parameters should not be NULL. + It returns 1 on success and 0 on failure. It is used for + experimental purpose for now and subject to change. */ +GRPCAPI int grpc_tls_credentials_options_set_credential_reload_config( + grpc_tls_credentials_options* options, + grpc_tls_credential_reload_config* config); + +/** Set grpc_tls_server_authorization_check_config field in credentials options + with the provided config struct whose ownership is transferred. + Both parameters should not be NULL. + It returns 1 on success and 0 on failure. It is used for + experimental purpose for now and subject to change. */ +GRPCAPI int grpc_tls_credentials_options_set_server_authorization_check_config( + grpc_tls_credentials_options* options, + grpc_tls_server_authorization_check_config* config); + +/** --- TLS key materials config. --- + It is used for experimental purpose for now and subject to change. */ + +/** Create an empty grpc_tls_key_materials_config instance. + * It is used for experimental purpose for now and subject to change. */ GRPCAPI grpc_tls_key_materials_config* grpc_tls_key_materials_config_create( void); - -/** Set grpc_tls_key_materials_config instance with provided a TLS certificate. - It's valid for the caller to provide nullptr pem_root_certs, in which case - the gRPC-provided root cert will be used. pem_key_cert_pairs should not be + +/** Set grpc_tls_key_materials_config instance with provided a TLS certificate. + It's valid for the caller to provide nullptr pem_root_certs, in which case + the gRPC-provided root cert will be used. pem_key_cert_pairs should not be NULL. The ownerships of |pem_root_certs| and |pem_key_cert_pairs| remain with the caller. It returns 1 on success and 0 on failure. It is used for experimental purpose for now and subject to change. - */ -GRPCAPI int grpc_tls_key_materials_config_set_key_materials( - grpc_tls_key_materials_config* config, const char* pem_root_certs, - const grpc_ssl_pem_key_cert_pair** pem_key_cert_pairs, - size_t num_key_cert_pairs); - + */ +GRPCAPI int grpc_tls_key_materials_config_set_key_materials( + grpc_tls_key_materials_config* config, const char* pem_root_certs, + const grpc_ssl_pem_key_cert_pair** pem_key_cert_pairs, + size_t num_key_cert_pairs); + /** Set grpc_tls_key_materials_config instance with a provided version number, which is used to keep track of the version of key materials. It returns 1 on success and 0 on failure. It is used for @@ -850,18 +850,18 @@ GRPCAPI int grpc_tls_key_materials_config_set_version( GRPCAPI int grpc_tls_key_materials_config_get_version( grpc_tls_key_materials_config* config); -/** --- TLS credential reload config. --- - It is used for experimental purpose for now and subject to change.*/ - -typedef struct grpc_tls_credential_reload_arg grpc_tls_credential_reload_arg; - -/** A callback function provided by gRPC to handle the result of credential - reload. It is used when schedule API is implemented asynchronously and - serves to bring the control back to grpc C core. It is used for - experimental purpose for now and subject to change. */ -typedef void (*grpc_tls_on_credential_reload_done_cb)( - grpc_tls_credential_reload_arg* arg); - +/** --- TLS credential reload config. --- + It is used for experimental purpose for now and subject to change.*/ + +typedef struct grpc_tls_credential_reload_arg grpc_tls_credential_reload_arg; + +/** A callback function provided by gRPC to handle the result of credential + reload. It is used when schedule API is implemented asynchronously and + serves to bring the control back to grpc C core. It is used for + experimental purpose for now and subject to change. */ +typedef void (*grpc_tls_on_credential_reload_done_cb)( + grpc_tls_credential_reload_arg* arg); + /** A struct containing all information necessary to schedule/cancel a credential reload request. - cb and cb_user_data represent a gRPC-provided @@ -881,60 +881,60 @@ typedef void (*grpc_tls_on_credential_reload_done_cb)( up any data associated with the context pointer. It is used for experimental purposes for now and subject to change. */ -struct grpc_tls_credential_reload_arg { - grpc_tls_on_credential_reload_done_cb cb; - void* cb_user_data; - grpc_tls_key_materials_config* key_materials_config; +struct grpc_tls_credential_reload_arg { + grpc_tls_on_credential_reload_done_cb cb; + void* cb_user_data; + grpc_tls_key_materials_config* key_materials_config; grpc_ssl_certificate_config_reload_status status; grpc_tls_error_details* error_details; grpc_tls_credential_reload_config* config; void* context; void (*destroy_context)(void* ctx); -}; - -/** Create a grpc_tls_credential_reload_config instance. - - config_user_data is config-specific, read-only user data - that works for all channels created with a credential using the config. - - schedule is a pointer to an application-provided callback used to invoke - credential reload API. The implementation of this method has to be - non-blocking, but can be performed synchronously or asynchronously. +}; + +/** Create a grpc_tls_credential_reload_config instance. + - config_user_data is config-specific, read-only user data + that works for all channels created with a credential using the config. + - schedule is a pointer to an application-provided callback used to invoke + credential reload API. The implementation of this method has to be + non-blocking, but can be performed synchronously or asynchronously. 1) If processing occurs synchronously, it populates arg->key_materials_config, arg->status, and arg->error_details and returns zero. - 2) If processing occurs asynchronously, it returns a non-zero value. - The application then invokes arg->cb when processing is completed. Note - that arg->cb cannot be invoked before schedule API returns. - - cancel is a pointer to an application-provided callback used to cancel - a credential reload request scheduled via an asynchronous schedule API. - arg is used to pinpoint an exact reloading request to be cancelled. - The operation may not have any effect if the request has already been - processed. - - destruct is a pointer to an application-provided callback used to clean up - any data associated with the config. - It is used for experimental purpose for now and subject to change. -*/ -GRPCAPI grpc_tls_credential_reload_config* -grpc_tls_credential_reload_config_create( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_credential_reload_arg* arg), - void (*cancel)(void* config_user_data, grpc_tls_credential_reload_arg* arg), - void (*destruct)(void* config_user_data)); - -/** --- TLS server authorization check config. --- - * It is used for experimental purpose for now and subject to change. */ - -typedef struct grpc_tls_server_authorization_check_arg - grpc_tls_server_authorization_check_arg; - -/** callback function provided by gRPC used to handle the result of server - authorization check. It is used when schedule API is implemented - asynchronously, and serves to bring the control back to gRPC C core. It is - used for experimental purpose for now and subject to change. */ -typedef void (*grpc_tls_on_server_authorization_check_done_cb)( - grpc_tls_server_authorization_check_arg* arg); - -/** A struct containing all information necessary to schedule/cancel a server + 2) If processing occurs asynchronously, it returns a non-zero value. + The application then invokes arg->cb when processing is completed. Note + that arg->cb cannot be invoked before schedule API returns. + - cancel is a pointer to an application-provided callback used to cancel + a credential reload request scheduled via an asynchronous schedule API. + arg is used to pinpoint an exact reloading request to be cancelled. + The operation may not have any effect if the request has already been + processed. + - destruct is a pointer to an application-provided callback used to clean up + any data associated with the config. + It is used for experimental purpose for now and subject to change. +*/ +GRPCAPI grpc_tls_credential_reload_config* +grpc_tls_credential_reload_config_create( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_credential_reload_arg* arg), + void (*cancel)(void* config_user_data, grpc_tls_credential_reload_arg* arg), + void (*destruct)(void* config_user_data)); + +/** --- TLS server authorization check config. --- + * It is used for experimental purpose for now and subject to change. */ + +typedef struct grpc_tls_server_authorization_check_arg + grpc_tls_server_authorization_check_arg; + +/** callback function provided by gRPC used to handle the result of server + authorization check. It is used when schedule API is implemented + asynchronously, and serves to bring the control back to gRPC C core. It is + used for experimental purpose for now and subject to change. */ +typedef void (*grpc_tls_on_server_authorization_check_done_cb)( + grpc_tls_server_authorization_check_arg* arg); + +/** A struct containing all information necessary to schedule/cancel a server authorization check request. - cb and cb_user_data represent a gRPC-provided callback and an argument passed to it. @@ -956,49 +956,49 @@ typedef void (*grpc_tls_on_server_authorization_check_done_cb)( up any data associated with the context pointer. It is used for experimental purpose for now and subject to change. */ -struct grpc_tls_server_authorization_check_arg { - grpc_tls_on_server_authorization_check_done_cb cb; - void* cb_user_data; +struct grpc_tls_server_authorization_check_arg { + grpc_tls_on_server_authorization_check_done_cb cb; + void* cb_user_data; int success; - const char* target_name; - const char* peer_cert; + const char* target_name; + const char* peer_cert; const char* peer_cert_full_chain; - grpc_status_code status; + grpc_status_code status; grpc_tls_error_details* error_details; grpc_tls_server_authorization_check_config* config; void* context; void (*destroy_context)(void* ctx); -}; - -/** Create a grpc_tls_server_authorization_check_config instance. - - config_user_data is config-specific, read-only user data - that works for all channels created with a credential using the config. - - schedule is a pointer to an application-provided callback used to invoke - server authorization check API. The implementation of this method has to - be non-blocking, but can be performed synchronously or asynchronously. - 1)If processing occurs synchronously, it populates arg->result, - arg->status, and arg->error_details and returns zero. - 2) If processing occurs asynchronously, it returns a non-zero value. The - application then invokes arg->cb when processing is completed. Note that - arg->cb cannot be invoked before schedule API returns. - - cancel is a pointer to an application-provided callback used to cancel a - server authorization check request scheduled via an asynchronous schedule - API. arg is used to pinpoint an exact check request to be cancelled. The - operation may not have any effect if the request has already been - processed. - - destruct is a pointer to an application-provided callback used to clean up - any data associated with the config. - It is used for experimental purpose for now and subject to change. -*/ -GRPCAPI grpc_tls_server_authorization_check_config* -grpc_tls_server_authorization_check_config_create( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*cancel)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*destruct)(void* config_user_data)); - +}; + +/** Create a grpc_tls_server_authorization_check_config instance. + - config_user_data is config-specific, read-only user data + that works for all channels created with a credential using the config. + - schedule is a pointer to an application-provided callback used to invoke + server authorization check API. The implementation of this method has to + be non-blocking, but can be performed synchronously or asynchronously. + 1)If processing occurs synchronously, it populates arg->result, + arg->status, and arg->error_details and returns zero. + 2) If processing occurs asynchronously, it returns a non-zero value. The + application then invokes arg->cb when processing is completed. Note that + arg->cb cannot be invoked before schedule API returns. + - cancel is a pointer to an application-provided callback used to cancel a + server authorization check request scheduled via an asynchronous schedule + API. arg is used to pinpoint an exact check request to be cancelled. The + operation may not have any effect if the request has already been + processed. + - destruct is a pointer to an application-provided callback used to clean up + any data associated with the config. + It is used for experimental purpose for now and subject to change. +*/ +GRPCAPI grpc_tls_server_authorization_check_config* +grpc_tls_server_authorization_check_config_create( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*cancel)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*destruct)(void* config_user_data)); + /** * This method creates a TLS channel credential object. * It takes ownership of the options parameter. The security level diff --git a/contrib/libs/grpc/include/grpc/grpc_security_constants.h b/contrib/libs/grpc/include/grpc/grpc_security_constants.h index a62f76753b..6ab519db7e 100644 --- a/contrib/libs/grpc/include/grpc/grpc_security_constants.h +++ b/contrib/libs/grpc/include/grpc/grpc_security_constants.h @@ -60,51 +60,51 @@ typedef enum { } grpc_ssl_certificate_config_reload_status; typedef enum { - /** Server does not request client certificate. - The certificate presented by the client is not checked by the server at - all. (A client may present a self signed or signed certificate or not - present a certificate at all and any of those option would be accepted) */ + /** Server does not request client certificate. + The certificate presented by the client is not checked by the server at + all. (A client may present a self signed or signed certificate or not + present a certificate at all and any of those option would be accepted) */ GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE, /** Server requests client certificate but does not enforce that the client presents a certificate. If the client presents a certificate, the client authentication is left to - the application (the necessary metadata will be available to the - application via authentication context properties, see grpc_auth_context). + the application (the necessary metadata will be available to the + application via authentication context properties, see grpc_auth_context). - The client's key certificate pair must be valid for the SSL connection to - be established. */ + The client's key certificate pair must be valid for the SSL connection to + be established. */ GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY, /** Server requests client certificate but does not enforce that the client presents a certificate. If the client presents a certificate, the client authentication is done by - the gRPC framework. (For a successful connection the client needs to either - present a certificate that can be verified against the root certificate - configured by the server or not present a certificate at all) + the gRPC framework. (For a successful connection the client needs to either + present a certificate that can be verified against the root certificate + configured by the server or not present a certificate at all) - The client's key certificate pair must be valid for the SSL connection to - be established. */ + The client's key certificate pair must be valid for the SSL connection to + be established. */ GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY, - /** Server requests client certificate and enforces that the client presents a + /** Server requests client certificate and enforces that the client presents a certificate. If the client presents a certificate, the client authentication is left to - the application (the necessary metadata will be available to the - application via authentication context properties, see grpc_auth_context). + the application (the necessary metadata will be available to the + application via authentication context properties, see grpc_auth_context). - The client's key certificate pair must be valid for the SSL connection to - be established. */ + The client's key certificate pair must be valid for the SSL connection to + be established. */ GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY, - /** Server requests client certificate and enforces that the client presents a + /** Server requests client certificate and enforces that the client presents a certificate. The certificate presented by the client is verified by the gRPC framework. - (For a successful connection the client needs to present a certificate that - can be verified against the root certificate configured by the server) + (For a successful connection the client needs to present a certificate that + can be verified against the root certificate configured by the server) - The client's key certificate pair must be valid for the SSL connection to - be established. */ + The client's key certificate pair must be valid for the SSL connection to + be established. */ GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY } grpc_ssl_client_certificate_request_type; @@ -133,12 +133,12 @@ typedef enum { GRPC_TLS_SKIP_ALL_SERVER_VERIFICATION } grpc_tls_server_verification_option; -/** - * Type of local connections for which local channel/server credentials will be - * applied. It supports UDS and local TCP connections. - */ -typedef enum { UDS = 0, LOCAL_TCP } grpc_local_connect_type; - +/** + * Type of local connections for which local channel/server credentials will be + * applied. It supports UDS and local TCP connections. + */ +typedef enum { UDS = 0, LOCAL_TCP } grpc_local_connect_type; + /** The TLS versions that are supported by the SSL stack. **/ typedef enum { TLS1_2, TLS1_3 } grpc_tls_version; diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/atm_gcc_sync.h b/contrib/libs/grpc/include/grpc/impl/codegen/atm_gcc_sync.h index 728c3d5412..159d00d49b 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/atm_gcc_sync.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/atm_gcc_sync.h @@ -26,8 +26,8 @@ typedef intptr_t gpr_atm; #define GPR_ATM_MAX INTPTR_MAX #define GPR_ATM_MIN INTPTR_MIN -#define GPR_ATM_INC_CAS_THEN(blah) blah -#define GPR_ATM_INC_ADD_THEN(blah) blah +#define GPR_ATM_INC_CAS_THEN(blah) blah +#define GPR_ATM_INC_ADD_THEN(blah) blah #define GPR_ATM_COMPILE_BARRIER_() __asm__ __volatile__("" : : : "memory") diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/atm_windows.h b/contrib/libs/grpc/include/grpc/impl/codegen/atm_windows.h index c016b90095..046580a03c 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/atm_windows.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/atm_windows.h @@ -25,8 +25,8 @@ typedef intptr_t gpr_atm; #define GPR_ATM_MAX INTPTR_MAX #define GPR_ATM_MIN INTPTR_MIN -#define GPR_ATM_INC_CAS_THEN(blah) blah -#define GPR_ATM_INC_ADD_THEN(blah) blah +#define GPR_ATM_INC_CAS_THEN(blah) blah +#define GPR_ATM_INC_ADD_THEN(blah) blah #define gpr_atm_full_barrier MemoryBarrier diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/compression_types.h b/contrib/libs/grpc/include/grpc/impl/codegen/compression_types.h index f778b005b9..eeb74ed993 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/compression_types.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/compression_types.h @@ -52,8 +52,8 @@ extern "C" { "grpc.compression_enabled_algorithms_bitset" /** \} */ -/** The various compression algorithms supported by gRPC (not sorted by - * compression level) */ +/** The various compression algorithms supported by gRPC (not sorted by + * compression level) */ typedef enum { GRPC_COMPRESS_NONE = 0, GRPC_COMPRESS_DEFLATE, diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/fork.h b/contrib/libs/grpc/include/grpc/impl/codegen/fork.h index 555df3490f..6d653f8c41 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/fork.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/fork.h @@ -37,12 +37,12 @@ * } */ -void grpc_prefork(void); +void grpc_prefork(void); -void grpc_postfork_parent(void); +void grpc_postfork_parent(void); -void grpc_postfork_child(void); +void grpc_postfork_child(void); -void grpc_fork_handlers_auto_register(void); +void grpc_fork_handlers_auto_register(void); #endif /* GRPC_IMPL_CODEGEN_FORK_H */ diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h b/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h index 07066f0e1d..b2a01c7ce5 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/grpc_types.h @@ -164,7 +164,7 @@ typedef struct { /** Maximum time that a channel may exist. Int valued, milliseconds. * INT_MAX means unlimited. */ #define GRPC_ARG_MAX_CONNECTION_AGE_MS "grpc.max_connection_age_ms" -/** Grace period after the channel reaches its max age. Int valued, +/** Grace period after the channel reaches its max age. Int valued, milliseconds. INT_MAX means unlimited. */ #define GRPC_ARG_MAX_CONNECTION_AGE_GRACE_MS "grpc.max_connection_age_grace_ms" /** Timeout after the last RPC finishes on the client channel at which the @@ -206,7 +206,7 @@ typedef struct { data/header frame, Int valued, milliseconds. */ #define GRPC_ARG_HTTP2_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS \ "grpc.http2.min_time_between_pings_ms" -/** Minimum allowed time between a server receiving successive ping frames +/** Minimum allowed time between a server receiving successive ping frames without sending any data/header frame. Int valued, milliseconds */ #define GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS \ @@ -304,16 +304,16 @@ typedef struct { #define GRPC_ARG_SOCKET_MUTATOR "grpc.socket_mutator" /** The grpc_socket_factory instance to create and bind sockets. A pointer. */ #define GRPC_ARG_SOCKET_FACTORY "grpc.socket_factory" -/** The maximum amount of memory used by trace events per channel trace node. - * Once the maximum is reached, subsequent events will evict the oldest events - * from the buffer. The unit for this knob is bytes. Setting it to zero causes - * channel tracing to be disabled. */ -#define GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE \ - "grpc.max_channel_trace_event_memory_per_node" -/** If non-zero, gRPC library will track stats and information at at per channel - * level. Disabling channelz naturally disables channel tracing. The default - * is for channelz to be enabled. */ -#define GRPC_ARG_ENABLE_CHANNELZ "grpc.enable_channelz" +/** The maximum amount of memory used by trace events per channel trace node. + * Once the maximum is reached, subsequent events will evict the oldest events + * from the buffer. The unit for this knob is bytes. Setting it to zero causes + * channel tracing to be disabled. */ +#define GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE \ + "grpc.max_channel_trace_event_memory_per_node" +/** If non-zero, gRPC library will track stats and information at at per channel + * level. Disabling channelz naturally disables channel tracing. The default + * is for channelz to be enabled. */ +#define GRPC_ARG_ENABLE_CHANNELZ "grpc.enable_channelz" /** If non-zero, Cronet transport will coalesce packets to fewer frames * when possible. */ #define GRPC_ARG_USE_CRONET_PACKET_COALESCING \ @@ -376,40 +376,40 @@ typedef struct { #define GRPC_ARG_PER_RPC_RETRY_BUFFER_SIZE "grpc.per_rpc_retry_buffer_size" /** Channel arg that carries the bridged objective c object for custom metrics * logging filter. */ -#define GRPC_ARG_MOBILE_LOG_CONTEXT "grpc.mobile_log_context" +#define GRPC_ARG_MOBILE_LOG_CONTEXT "grpc.mobile_log_context" /** If non-zero, client authority filter is disabled for the channel */ #define GRPC_ARG_DISABLE_CLIENT_AUTHORITY_FILTER \ "grpc.disable_client_authority_filter" -/** If set to zero, disables use of http proxies. Enabled by default. */ -#define GRPC_ARG_ENABLE_HTTP_PROXY "grpc.enable_http_proxy" +/** If set to zero, disables use of http proxies. Enabled by default. */ +#define GRPC_ARG_ENABLE_HTTP_PROXY "grpc.enable_http_proxy" /** Channel arg to set http proxy per channel. If set, the channel arg * value will be prefered over the envrionment variable settings. */ #define GRPC_ARG_HTTP_PROXY "grpc.http_proxy" -/** If set to non zero, surfaces the user agent string to the server. User - agent is surfaced by default. */ -#define GRPC_ARG_SURFACE_USER_AGENT "grpc.surface_user_agent" -/** If set, inhibits health checking (which may be enabled via the - * service config.) */ -#define GRPC_ARG_INHIBIT_HEALTH_CHECKING "grpc.inhibit_health_checking" -/** If set, the channel's resolver is allowed to query for SRV records. - * For example, this is useful as a way to enable the "grpclb" - * load balancing policy. Note that this only works with the "ares" - * DNS resolver, and isn't supported by the "native" DNS resolver. */ -#define GRPC_ARG_DNS_ENABLE_SRV_QUERIES "grpc.dns_enable_srv_queries" +/** If set to non zero, surfaces the user agent string to the server. User + agent is surfaced by default. */ +#define GRPC_ARG_SURFACE_USER_AGENT "grpc.surface_user_agent" +/** If set, inhibits health checking (which may be enabled via the + * service config.) */ +#define GRPC_ARG_INHIBIT_HEALTH_CHECKING "grpc.inhibit_health_checking" +/** If set, the channel's resolver is allowed to query for SRV records. + * For example, this is useful as a way to enable the "grpclb" + * load balancing policy. Note that this only works with the "ares" + * DNS resolver, and isn't supported by the "native" DNS resolver. */ +#define GRPC_ARG_DNS_ENABLE_SRV_QUERIES "grpc.dns_enable_srv_queries" /** If set, determines an upper bound on the number of milliseconds that the * c-ares based DNS resolver will wait on queries before cancelling them. * The default value is 120,000. Setting this to "0" will disable the * overall timeout entirely. Note that this doesn't include internal c-ares * timeouts/backoff/retry logic, and so the actual DNS resolution may time out * sooner than the value specified here. */ -#define GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS "grpc.dns_ares_query_timeout" -/** If set, uses a local subchannel pool within the channel. Otherwise, uses the - * global subchannel pool. */ -#define GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL "grpc.use_local_subchannel_pool" -/** gRPC Objective-C channel pooling domain string. */ -#define GRPC_ARG_CHANNEL_POOL_DOMAIN "grpc.channel_pooling_domain" -/** gRPC Objective-C channel pooling id. */ -#define GRPC_ARG_CHANNEL_ID "grpc.channel_id" +#define GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS "grpc.dns_ares_query_timeout" +/** If set, uses a local subchannel pool within the channel. Otherwise, uses the + * global subchannel pool. */ +#define GRPC_ARG_USE_LOCAL_SUBCHANNEL_POOL "grpc.use_local_subchannel_pool" +/** gRPC Objective-C channel pooling domain string. */ +#define GRPC_ARG_CHANNEL_POOL_DOMAIN "grpc.channel_pooling_domain" +/** gRPC Objective-C channel pooling id. */ +#define GRPC_ARG_CHANNEL_ID "grpc.channel_id" /** \} */ /** Result of a grpc call. If the caller satisfies the prerequisites of a @@ -722,37 +722,37 @@ typedef enum { GRPC_CQ_NEXT, /** Events are popped out by calling grpc_completion_queue_pluck() API ONLY*/ - GRPC_CQ_PLUCK, - - /** EXPERIMENTAL: Events trigger a callback specified as the tag */ - GRPC_CQ_CALLBACK + GRPC_CQ_PLUCK, + + /** EXPERIMENTAL: Events trigger a callback specified as the tag */ + GRPC_CQ_CALLBACK } grpc_cq_completion_type; -/** EXPERIMENTAL: Specifies an interface class to be used as a tag - for callback-based completion queues. This can be used directly, - as the first element of a struct in C, or as a base class in C++. - Its "run" value should be assigned to some non-member function, such as - a static method. */ -typedef struct grpc_experimental_completion_queue_functor { - /** The run member specifies a function that will be called when this - tag is extracted from the completion queue. Its arguments will be a - pointer to this functor and a boolean that indicates whether the - operation succeeded (non-zero) or failed (zero) */ - void (*functor_run)(struct grpc_experimental_completion_queue_functor*, int); - +/** EXPERIMENTAL: Specifies an interface class to be used as a tag + for callback-based completion queues. This can be used directly, + as the first element of a struct in C, or as a base class in C++. + Its "run" value should be assigned to some non-member function, such as + a static method. */ +typedef struct grpc_experimental_completion_queue_functor { + /** The run member specifies a function that will be called when this + tag is extracted from the completion queue. Its arguments will be a + pointer to this functor and a boolean that indicates whether the + operation succeeded (non-zero) or failed (zero) */ + void (*functor_run)(struct grpc_experimental_completion_queue_functor*, int); + /** The inlineable member specifies whether this functor can be run inline. This should only be used for trivial internally-defined functors. */ int inlineable; - /** The following fields are not API. They are meant for internal use. */ - int internal_success; - struct grpc_experimental_completion_queue_functor* internal_next; -} grpc_experimental_completion_queue_functor; - -/* The upgrade to version 2 is currently experimental. */ - -#define GRPC_CQ_CURRENT_VERSION 2 -#define GRPC_CQ_VERSION_MINIMUM_FOR_CALLBACKABLE 2 + /** The following fields are not API. They are meant for internal use. */ + int internal_success; + struct grpc_experimental_completion_queue_functor* internal_next; +} grpc_experimental_completion_queue_functor; + +/* The upgrade to version 2 is currently experimental. */ + +#define GRPC_CQ_CURRENT_VERSION 2 +#define GRPC_CQ_VERSION_MINIMUM_FOR_CALLBACKABLE 2 typedef struct grpc_completion_queue_attributes { /** The version number of this structure. More fields might be added to this structure in future. */ @@ -761,15 +761,15 @@ typedef struct grpc_completion_queue_attributes { grpc_cq_completion_type cq_completion_type; grpc_cq_polling_type cq_polling_type; - - /* END OF VERSION 1 CQ ATTRIBUTES */ - - /* EXPERIMENTAL: START OF VERSION 2 CQ ATTRIBUTES */ - /** When creating a callbackable CQ, pass in a functor to get invoked when - * shutdown is complete */ - grpc_experimental_completion_queue_functor* cq_shutdown_cb; - - /* END OF VERSION 2 CQ ATTRIBUTES */ + + /* END OF VERSION 1 CQ ATTRIBUTES */ + + /* EXPERIMENTAL: START OF VERSION 2 CQ ATTRIBUTES */ + /** When creating a callbackable CQ, pass in a functor to get invoked when + * shutdown is complete */ + grpc_experimental_completion_queue_functor* cq_shutdown_cb; + + /* END OF VERSION 2 CQ ATTRIBUTES */ } grpc_completion_queue_attributes; /** The completion queue factory structure is opaque to the callers of grpc */ diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/log.h b/contrib/libs/grpc/include/grpc/impl/codegen/log.h index ad7f024158..e09ace5f95 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/log.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/log.h @@ -1,112 +1,112 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_IMPL_CODEGEN_LOG_H -#define GRPC_IMPL_CODEGEN_LOG_H - -#include <grpc/impl/codegen/port_platform.h> - -#include <stdarg.h> -#include <stdlib.h> /* for abort() */ - -#ifdef __cplusplus -extern "C" { -#endif - -/** GPR log API. - - Usage (within grpc): - - int argument1 = 3; - char* argument2 = "hello"; - gpr_log(GPR_DEBUG, "format string %d", argument1); - gpr_log(GPR_INFO, "hello world"); - gpr_log(GPR_ERROR, "%d %s!!", argument1, argument2); */ - -/** The severity of a log message - use the #defines below when calling into - gpr_log to additionally supply file and line data */ -typedef enum gpr_log_severity { - GPR_LOG_SEVERITY_DEBUG, - GPR_LOG_SEVERITY_INFO, - GPR_LOG_SEVERITY_ERROR -} gpr_log_severity; - -#define GPR_LOG_VERBOSITY_UNSET -1 - -/** Returns a string representation of the log severity */ -GPRAPI const char* gpr_log_severity_string(gpr_log_severity severity); - -/** Macros to build log contexts at various severity levels */ -#define GPR_DEBUG __FILE__, __LINE__, GPR_LOG_SEVERITY_DEBUG -#define GPR_INFO __FILE__, __LINE__, GPR_LOG_SEVERITY_INFO -#define GPR_ERROR __FILE__, __LINE__, GPR_LOG_SEVERITY_ERROR - -/** Log a message. It's advised to use GPR_xxx above to generate the context - * for each message */ -GPRAPI void gpr_log(const char* file, int line, gpr_log_severity severity, - const char* format, ...) GPR_PRINT_FORMAT_CHECK(4, 5); - -GPRAPI int gpr_should_log(gpr_log_severity severity); - -GPRAPI void gpr_log_message(const char* file, int line, - gpr_log_severity severity, const char* message); - -/** Set global log verbosity */ -GPRAPI void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print); - -GPRAPI void gpr_log_verbosity_init(void); - -/** Log overrides: applications can use this API to intercept logging calls - and use their own implementations */ - -struct gpr_log_func_args { - const char* file; - int line; - gpr_log_severity severity; - const char* message; -}; - -typedef struct gpr_log_func_args gpr_log_func_args; - -typedef void (*gpr_log_func)(gpr_log_func_args* args); -GPRAPI void gpr_set_log_function(gpr_log_func func); - -/** abort() the process if x is zero, having written a line to the log. - - Intended for internal invariants. If the error can be recovered from, - without the possibility of corruption, or might best be reflected via - an exception in a higher-level language, consider returning error code. */ -#define GPR_ASSERT(x) \ - do { \ - if (GPR_UNLIKELY(!(x))) { \ - gpr_log(GPR_ERROR, "assertion failed: %s", #x); \ - abort(); \ - } \ - } while (0) - -#ifndef NDEBUG -#define GPR_DEBUG_ASSERT(x) GPR_ASSERT(x) -#else -#define GPR_DEBUG_ASSERT(x) -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* GRPC_IMPL_CODEGEN_LOG_H */ +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_IMPL_CODEGEN_LOG_H +#define GRPC_IMPL_CODEGEN_LOG_H + +#include <grpc/impl/codegen/port_platform.h> + +#include <stdarg.h> +#include <stdlib.h> /* for abort() */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** GPR log API. + + Usage (within grpc): + + int argument1 = 3; + char* argument2 = "hello"; + gpr_log(GPR_DEBUG, "format string %d", argument1); + gpr_log(GPR_INFO, "hello world"); + gpr_log(GPR_ERROR, "%d %s!!", argument1, argument2); */ + +/** The severity of a log message - use the #defines below when calling into + gpr_log to additionally supply file and line data */ +typedef enum gpr_log_severity { + GPR_LOG_SEVERITY_DEBUG, + GPR_LOG_SEVERITY_INFO, + GPR_LOG_SEVERITY_ERROR +} gpr_log_severity; + +#define GPR_LOG_VERBOSITY_UNSET -1 + +/** Returns a string representation of the log severity */ +GPRAPI const char* gpr_log_severity_string(gpr_log_severity severity); + +/** Macros to build log contexts at various severity levels */ +#define GPR_DEBUG __FILE__, __LINE__, GPR_LOG_SEVERITY_DEBUG +#define GPR_INFO __FILE__, __LINE__, GPR_LOG_SEVERITY_INFO +#define GPR_ERROR __FILE__, __LINE__, GPR_LOG_SEVERITY_ERROR + +/** Log a message. It's advised to use GPR_xxx above to generate the context + * for each message */ +GPRAPI void gpr_log(const char* file, int line, gpr_log_severity severity, + const char* format, ...) GPR_PRINT_FORMAT_CHECK(4, 5); + +GPRAPI int gpr_should_log(gpr_log_severity severity); + +GPRAPI void gpr_log_message(const char* file, int line, + gpr_log_severity severity, const char* message); + +/** Set global log verbosity */ +GPRAPI void gpr_set_log_verbosity(gpr_log_severity min_severity_to_print); + +GPRAPI void gpr_log_verbosity_init(void); + +/** Log overrides: applications can use this API to intercept logging calls + and use their own implementations */ + +struct gpr_log_func_args { + const char* file; + int line; + gpr_log_severity severity; + const char* message; +}; + +typedef struct gpr_log_func_args gpr_log_func_args; + +typedef void (*gpr_log_func)(gpr_log_func_args* args); +GPRAPI void gpr_set_log_function(gpr_log_func func); + +/** abort() the process if x is zero, having written a line to the log. + + Intended for internal invariants. If the error can be recovered from, + without the possibility of corruption, or might best be reflected via + an exception in a higher-level language, consider returning error code. */ +#define GPR_ASSERT(x) \ + do { \ + if (GPR_UNLIKELY(!(x))) { \ + gpr_log(GPR_ERROR, "assertion failed: %s", #x); \ + abort(); \ + } \ + } while (0) + +#ifndef NDEBUG +#define GPR_DEBUG_ASSERT(x) GPR_ASSERT(x) +#else +#define GPR_DEBUG_ASSERT(x) +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* GRPC_IMPL_CODEGEN_LOG_H */ diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h b/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h index 35419f017b..bf508f05fe 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/port_platform.h @@ -113,10 +113,10 @@ #elif defined(ANDROID) || defined(__ANDROID__) #define GPR_PLATFORM_STRING "android" #define GPR_ANDROID 1 -// TODO(apolcyn): re-evaluate support for c-ares -// on android after upgrading our c-ares dependency. -// See https://github.com/grpc/grpc/issues/18038. -#define GRPC_ARES 0 +// TODO(apolcyn): re-evaluate support for c-ares +// on android after upgrading our c-ares dependency. +// See https://github.com/grpc/grpc/issues/18038. +#define GRPC_ARES 0 #ifdef _LP64 #define GPR_ARCH_64 1 #else /* _LP64 */ @@ -169,7 +169,7 @@ #ifdef __GLIBC__ #define GPR_POSIX_CRASH_HANDLER 1 #define GPR_LINUX_PTHREAD_NAME 1 -#include <linux/version.h> +#include <linux/version.h> #else /* musl libc */ #define GPR_MUSL_LIBC_COMPAT 1 #endif @@ -205,7 +205,7 @@ #define GPR_PTHREAD_TLS 1 #define GRPC_CFSTREAM 1 /* the c-ares resolver isn't safe to enable on iOS */ -#define GRPC_ARES 0 +#define GRPC_ARES 0 #else /* TARGET_OS_IPHONE */ #define GPR_PLATFORM_STRING "osx" #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED @@ -247,9 +247,9 @@ #define GPR_POSIX_TIME 1 #define GPR_HAS_PTHREAD_H 1 #define GPR_GETPID_IN_UNISTD_H 1 -#ifndef GRPC_CFSTREAM +#ifndef GRPC_CFSTREAM #define GPR_SUPPORT_CHANNELS_FROM_FD 1 -#endif +#endif #ifdef _LP64 #define GPR_ARCH_64 1 #else /* _LP64 */ @@ -303,49 +303,49 @@ #else /* _LP64 */ #define GPR_ARCH_32 1 #endif /* _LP64 */ -#elif defined(__sun) && defined(__SVR4) -#define GPR_PLATFORM_STRING "solaris" -#define GPR_SOLARIS 1 -#define GPR_CPU_POSIX 1 -#define GPR_GCC_ATOMIC 1 -#define GPR_GCC_TLS 1 -#define GPR_POSIX_LOG 1 -#define GPR_POSIX_ENV 1 -#define GPR_POSIX_TMPFILE 1 -#define GPR_POSIX_STRING 1 -#define GPR_POSIX_SUBPROCESS 1 -#define GPR_POSIX_SYNC 1 -#define GPR_POSIX_TIME 1 +#elif defined(__sun) && defined(__SVR4) +#define GPR_PLATFORM_STRING "solaris" +#define GPR_SOLARIS 1 +#define GPR_CPU_POSIX 1 +#define GPR_GCC_ATOMIC 1 +#define GPR_GCC_TLS 1 +#define GPR_POSIX_LOG 1 +#define GPR_POSIX_ENV 1 +#define GPR_POSIX_TMPFILE 1 +#define GPR_POSIX_STRING 1 +#define GPR_POSIX_SUBPROCESS 1 +#define GPR_POSIX_SYNC 1 +#define GPR_POSIX_TIME 1 #define GPR_HAS_PTHREAD_H 1 -#define GPR_GETPID_IN_UNISTD_H 1 -#ifdef _LP64 -#define GPR_ARCH_64 1 -#else /* _LP64 */ -#define GPR_ARCH_32 1 -#endif /* _LP64 */ -#elif defined(_AIX) -#define GPR_PLATFORM_STRING "aix" -#ifndef _ALL_SOURCE -#define _ALL_SOURCE -#endif -#define GPR_AIX 1 -#define GPR_CPU_POSIX 1 -#define GPR_GCC_ATOMIC 1 -#define GPR_GCC_TLS 1 -#define GPR_POSIX_LOG 1 -#define GPR_POSIX_ENV 1 -#define GPR_POSIX_TMPFILE 1 -#define GPR_POSIX_STRING 1 -#define GPR_POSIX_SUBPROCESS 1 -#define GPR_POSIX_SYNC 1 -#define GPR_POSIX_TIME 1 +#define GPR_GETPID_IN_UNISTD_H 1 +#ifdef _LP64 +#define GPR_ARCH_64 1 +#else /* _LP64 */ +#define GPR_ARCH_32 1 +#endif /* _LP64 */ +#elif defined(_AIX) +#define GPR_PLATFORM_STRING "aix" +#ifndef _ALL_SOURCE +#define _ALL_SOURCE +#endif +#define GPR_AIX 1 +#define GPR_CPU_POSIX 1 +#define GPR_GCC_ATOMIC 1 +#define GPR_GCC_TLS 1 +#define GPR_POSIX_LOG 1 +#define GPR_POSIX_ENV 1 +#define GPR_POSIX_TMPFILE 1 +#define GPR_POSIX_STRING 1 +#define GPR_POSIX_SUBPROCESS 1 +#define GPR_POSIX_SYNC 1 +#define GPR_POSIX_TIME 1 #define GPR_HAS_PTHREAD_H 1 -#define GPR_GETPID_IN_UNISTD_H 1 -#ifdef _LP64 -#define GPR_ARCH_64 1 -#else /* _LP64 */ -#define GPR_ARCH_32 1 -#endif /* _LP64 */ +#define GPR_GETPID_IN_UNISTD_H 1 +#ifdef _LP64 +#define GPR_ARCH_64 1 +#else /* _LP64 */ +#define GPR_ARCH_32 1 +#endif /* _LP64 */ #elif defined(__native_client__) #define GPR_PLATFORM_STRING "nacl" #ifndef _BSD_SOURCE @@ -537,9 +537,9 @@ typedef unsigned __int64 uint64_t; #ifndef GRPC_ARES #define GRPC_ARES 1 #endif - -#ifndef GRPC_IF_NAMETOINDEX -#define GRPC_IF_NAMETOINDEX 1 + +#ifndef GRPC_IF_NAMETOINDEX +#define GRPC_IF_NAMETOINDEX 1 #endif #ifndef GRPC_MUST_USE_RESULT @@ -592,14 +592,14 @@ typedef unsigned __int64 uint64_t; #define CENSUSAPI GRPCAPI #endif -#ifndef GPR_HAS_ATTRIBUTE -#ifdef __has_attribute -#define GPR_HAS_ATTRIBUTE(a) __has_attribute(a) -#else -#define GPR_HAS_ATTRIBUTE(a) 0 -#endif -#endif /* GPR_HAS_ATTRIBUTE */ - +#ifndef GPR_HAS_ATTRIBUTE +#ifdef __has_attribute +#define GPR_HAS_ATTRIBUTE(a) __has_attribute(a) +#else +#define GPR_HAS_ATTRIBUTE(a) 0 +#endif +#endif /* GPR_HAS_ATTRIBUTE */ + #ifndef GPR_HAS_FEATURE #ifdef __has_feature #define GPR_HAS_FEATURE(a) __has_feature(a) @@ -608,27 +608,27 @@ typedef unsigned __int64 uint64_t; #endif #endif /* GPR_HAS_FEATURE */ -#ifndef GPR_ATTRIBUTE_NOINLINE -#if GPR_HAS_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__)) -#define GPR_ATTRIBUTE_NOINLINE __attribute__((noinline)) -#define GPR_HAS_ATTRIBUTE_NOINLINE 1 -#else -#define GPR_ATTRIBUTE_NOINLINE -#endif -#endif /* GPR_ATTRIBUTE_NOINLINE */ - -#ifndef GPR_ATTRIBUTE_WEAK -/* Attribute weak is broken on LLVM/windows: - * https://bugs.llvm.org/show_bug.cgi?id=37598 */ -#if (GPR_HAS_ATTRIBUTE(weak) || (defined(__GNUC__) && !defined(__clang__))) && \ - !(defined(__llvm__) && defined(_WIN32)) -#define GPR_ATTRIBUTE_WEAK __attribute__((weak)) -#define GPR_HAS_ATTRIBUTE_WEAK 1 -#else -#define GPR_ATTRIBUTE_WEAK -#endif -#endif /* GPR_ATTRIBUTE_WEAK */ - +#ifndef GPR_ATTRIBUTE_NOINLINE +#if GPR_HAS_ATTRIBUTE(noinline) || (defined(__GNUC__) && !defined(__clang__)) +#define GPR_ATTRIBUTE_NOINLINE __attribute__((noinline)) +#define GPR_HAS_ATTRIBUTE_NOINLINE 1 +#else +#define GPR_ATTRIBUTE_NOINLINE +#endif +#endif /* GPR_ATTRIBUTE_NOINLINE */ + +#ifndef GPR_ATTRIBUTE_WEAK +/* Attribute weak is broken on LLVM/windows: + * https://bugs.llvm.org/show_bug.cgi?id=37598 */ +#if (GPR_HAS_ATTRIBUTE(weak) || (defined(__GNUC__) && !defined(__clang__))) && \ + !(defined(__llvm__) && defined(_WIN32)) +#define GPR_ATTRIBUTE_WEAK __attribute__((weak)) +#define GPR_HAS_ATTRIBUTE_WEAK 1 +#else +#define GPR_ATTRIBUTE_WEAK +#endif +#endif /* GPR_ATTRIBUTE_WEAK */ + #ifndef GPR_ATTRIBUTE_NO_TSAN /* (1) */ #if GPR_HAS_FEATURE(thread_sanitizer) #define GPR_ATTRIBUTE_NO_TSAN __attribute__((no_sanitize("thread"))) @@ -638,13 +638,13 @@ typedef unsigned __int64 uint64_t; #endif /* GPR_ATTRIBUTE_NO_TSAN (2) */ #endif /* GPR_ATTRIBUTE_NO_TSAN (1) */ -/* GRPC_TSAN_ENABLED will be defined, when compiled with thread sanitizer. */ +/* GRPC_TSAN_ENABLED will be defined, when compiled with thread sanitizer. */ #ifndef GRPC_TSAN_SUPPRESSED -#if defined(__SANITIZE_THREAD__) -#define GRPC_TSAN_ENABLED +#if defined(__SANITIZE_THREAD__) +#define GRPC_TSAN_ENABLED #elif GPR_HAS_FEATURE(thread_sanitizer) -#define GRPC_TSAN_ENABLED -#endif +#define GRPC_TSAN_ENABLED +#endif #endif /* GRPC_ASAN_ENABLED will be defined, when compiled with address sanitizer. */ @@ -653,9 +653,9 @@ typedef unsigned __int64 uint64_t; #define GRPC_ASAN_ENABLED #elif GPR_HAS_FEATURE(address_sanitizer) #define GRPC_ASAN_ENABLED +#endif #endif -#endif - + /* GRPC_ALLOW_EXCEPTIONS should be 0 or 1 if exceptions are allowed or not */ #ifndef GRPC_ALLOW_EXCEPTIONS #ifdef GPR_WINDOWS diff --git a/contrib/libs/grpc/include/grpc/impl/codegen/slice.h b/contrib/libs/grpc/include/grpc/impl/codegen/slice.h index 3567b1e88b..1318fe2812 100644 --- a/contrib/libs/grpc/include/grpc/impl/codegen/slice.h +++ b/contrib/libs/grpc/include/grpc/impl/codegen/slice.h @@ -61,7 +61,7 @@ struct grpc_slice { struct grpc_slice_refcount* refcount; union grpc_slice_data { struct grpc_slice_refcounted { - size_t length; + size_t length; uint8_t* bytes; } refcounted; struct grpc_slice_inlined { diff --git a/contrib/libs/grpc/include/grpc/module.modulemap b/contrib/libs/grpc/include/grpc/module.modulemap index 06c1e97736..922e29a188 100644 --- a/contrib/libs/grpc/include/grpc/module.modulemap +++ b/contrib/libs/grpc/include/grpc/module.modulemap @@ -11,7 +11,7 @@ framework module grpc { header "impl/codegen/gpr_slice.h" header "impl/codegen/gpr_types.h" header "impl/codegen/grpc_types.h" - header "impl/codegen/log.h" + header "impl/codegen/log.h" header "impl/codegen/port_platform.h" header "impl/codegen/propagation_bits.h" header "impl/codegen/slice.h" diff --git a/contrib/libs/grpc/include/grpc/support/log.h b/contrib/libs/grpc/include/grpc/support/log.h index 8d8742b95d..6970c6ddef 100644 --- a/contrib/libs/grpc/include/grpc/support/log.h +++ b/contrib/libs/grpc/include/grpc/support/log.h @@ -19,8 +19,8 @@ #ifndef GRPC_SUPPORT_LOG_H #define GRPC_SUPPORT_LOG_H -#include <grpc/support/port_platform.h> +#include <grpc/support/port_platform.h> -#include <grpc/impl/codegen/log.h> +#include <grpc/impl/codegen/log.h> #endif /* GRPC_SUPPORT_LOG_H */ diff --git a/contrib/libs/grpc/include/grpc/support/string_util.h b/contrib/libs/grpc/include/grpc/support/string_util.h index 2679160c1b..59c60fc041 100644 --- a/contrib/libs/grpc/include/grpc/support/string_util.h +++ b/contrib/libs/grpc/include/grpc/support/string_util.h @@ -21,8 +21,8 @@ #include <grpc/support/port_platform.h> -#include <grpc/impl/codegen/gpr_types.h> - +#include <grpc/impl/codegen/gpr_types.h> + #ifdef __cplusplus extern "C" { #endif diff --git a/contrib/libs/grpc/include/grpcpp/channel.h b/contrib/libs/grpc/include/grpcpp/channel.h index 6a31ff7aa9..f569b4c419 100644 --- a/contrib/libs/grpc/include/grpcpp/channel.h +++ b/contrib/libs/grpc/include/grpcpp/channel.h @@ -43,13 +43,13 @@ std::shared_ptr<Channel> CreateChannelInternal( std::unique_ptr<experimental::ClientInterceptorFactoryInterface>> interceptor_creators); -namespace experimental { -/// Resets the channel's connection backoff. -/// TODO(roth): Once we see whether this proves useful, either create a gRFC -/// and change this to be a method of the Channel class, or remove it. -void ChannelResetConnectionBackoff(Channel* channel); -} // namespace experimental - +namespace experimental { +/// Resets the channel's connection backoff. +/// TODO(roth): Once we see whether this proves useful, either create a gRFC +/// and change this to be a method of the Channel class, or remove it. +void ChannelResetConnectionBackoff(Channel* channel); +} // namespace experimental + /// Channels represent a connection to an endpoint. Created by \a CreateChannel. class Channel final : public ::grpc::ChannelInterface, public ::grpc::internal::CallHook, diff --git a/contrib/libs/grpc/include/grpcpp/create_channel.h b/contrib/libs/grpc/include/grpcpp/create_channel.h index 4b94a08e45..0c2cca87a0 100644 --- a/contrib/libs/grpc/include/grpcpp/create_channel.h +++ b/contrib/libs/grpc/include/grpcpp/create_channel.h @@ -53,7 +53,7 @@ std::shared_ptr<Channel> CreateCustomChannel( const std::shared_ptr<ChannelCredentials>& creds, const ChannelArguments& args); -namespace experimental { +namespace experimental { /// Create a new \em custom \a Channel pointing to \a target with \a /// interceptors being invoked per call. /// @@ -66,13 +66,13 @@ namespace experimental { /// fail) is returned. /// \param args Options for channel creation. std::shared_ptr<Channel> CreateCustomChannelWithInterceptors( - const grpc::string& target, - const std::shared_ptr<ChannelCredentials>& creds, - const ChannelArguments& args, - std::vector< - std::unique_ptr<experimental::ClientInterceptorFactoryInterface>> + const grpc::string& target, + const std::shared_ptr<ChannelCredentials>& creds, + const ChannelArguments& args, + std::vector< + std::unique_ptr<experimental::ClientInterceptorFactoryInterface>> interceptor_creators); -} // namespace experimental +} // namespace experimental } // namespace grpc #endif // GRPCPP_CREATE_CHANNEL_H diff --git a/contrib/libs/grpc/include/grpcpp/create_channel_posix.h b/contrib/libs/grpc/include/grpcpp/create_channel_posix.h index c6755b0aa6..c5840f1511 100644 --- a/contrib/libs/grpc/include/grpcpp/create_channel_posix.h +++ b/contrib/libs/grpc/include/grpcpp/create_channel_posix.h @@ -45,8 +45,8 @@ std::shared_ptr<grpc::Channel> CreateInsecureChannelFromFd( std::shared_ptr<grpc::Channel> CreateCustomInsecureChannelFromFd( const TString& target, int fd, const grpc::ChannelArguments& args); -namespace experimental { - +namespace experimental { + /// Create a new \a Channel communicating over given file descriptor with custom /// channel arguments. /// @@ -57,12 +57,12 @@ namespace experimental { std::shared_ptr<grpc::Channel> CreateCustomInsecureChannelWithInterceptorsFromFd( const TString& target, int fd, const grpc::ChannelArguments& args, - std::unique_ptr<std::vector< + std::unique_ptr<std::vector< std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>>> interceptor_creators); - -} // namespace experimental - + +} // namespace experimental + #endif // GPR_SUPPORT_CHANNELS_FROM_FD } // namespace grpc diff --git a/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h b/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h index 95cb93e321..2485e13f35 100644 --- a/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h +++ b/contrib/libs/grpc/include/grpcpp/ext/channelz_service_plugin.h @@ -1,36 +1,36 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H -#define GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H +#define GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H + #include <grpcpp/ext/channelz_service_plugin_impl.h> - -namespace grpc { -namespace channelz { -namespace experimental { - + +namespace grpc { +namespace channelz { +namespace experimental { + static inline void InitChannelzService() { ::grpc_impl::channelz::experimental::InitChannelzService(); } - -} // namespace experimental -} // namespace channelz -} // namespace grpc - -#endif // GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H + +} // namespace experimental +} // namespace channelz +} // namespace grpc + +#endif // GRPCPP_EXT_CHANNELZ_SERVICE_PLUGIN_H diff --git a/contrib/libs/grpc/include/grpcpp/ext/server_load_reporting.h b/contrib/libs/grpc/include/grpcpp/ext/server_load_reporting.h index 987a48ee79..90f0a68d69 100644 --- a/contrib/libs/grpc/include/grpcpp/ext/server_load_reporting.h +++ b/contrib/libs/grpc/include/grpcpp/ext/server_load_reporting.h @@ -1,35 +1,35 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_EXT_SERVER_LOAD_REPORTING_H -#define GRPCPP_EXT_SERVER_LOAD_REPORTING_H - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_EXT_SERVER_LOAD_REPORTING_H +#define GRPCPP_EXT_SERVER_LOAD_REPORTING_H + #include <grpc/support/port_platform.h> - + #include <grpc/load_reporting.h> #include <grpcpp/impl/codegen/config.h> #include <grpcpp/impl/codegen/server_context.h> #include <grpcpp/impl/server_builder_option.h> -namespace grpc { -namespace load_reporter { -namespace experimental { - +namespace grpc { +namespace load_reporter { +namespace experimental { + // The ServerBuilderOption to enable server-side load reporting feature. To // enable the feature, please make sure the binary builds with the // grpcpp_server_load_reporting library and set this option in the @@ -41,14 +41,14 @@ class LoadReportingServiceServerBuilderOption void UpdatePlugins(std::vector<std::unique_ptr<::grpc::ServerBuilderPlugin>>* plugins) override; }; - + // Adds the load reporting cost with \a cost_name and \a cost_value in the // trailing metadata of the server context. void AddLoadReportingCost(grpc::ServerContext* ctx, const TString& cost_name, double cost_value); - -} // namespace experimental -} // namespace load_reporter -} // namespace grpc - -#endif // GRPCPP_EXT_SERVER_LOAD_REPORTING_H + +} // namespace experimental +} // namespace load_reporter +} // namespace grpc + +#endif // GRPCPP_EXT_SERVER_LOAD_REPORTING_H diff --git a/contrib/libs/grpc/include/grpcpp/generic/async_generic_service.h b/contrib/libs/grpc/include/grpcpp/generic/async_generic_service.h index 2c67edc517..8607c0f5c9 100644 --- a/contrib/libs/grpc/include/grpcpp/generic/async_generic_service.h +++ b/contrib/libs/grpc/include/grpcpp/generic/async_generic_service.h @@ -1,6 +1,6 @@ /* * - * Copyright 2018 gRPC authors. + * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,6 @@ #ifndef GRPCPP_GENERIC_ASYNC_GENERIC_SERVICE_H #define GRPCPP_GENERIC_ASYNC_GENERIC_SERVICE_H -#include <grpcpp/impl/codegen/async_generic_service.h> +#include <grpcpp/impl/codegen/async_generic_service.h> #endif // GRPCPP_GENERIC_ASYNC_GENERIC_SERVICE_H diff --git a/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h b/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h index 102d2591c9..0412867636 100644 --- a/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h +++ b/contrib/libs/grpc/include/grpcpp/generic/generic_stub.h @@ -20,7 +20,7 @@ #define GRPCPP_GENERIC_GENERIC_STUB_H #include <functional> - + #include <grpcpp/client_context.h> #include <grpcpp/impl/rpc_method.h> #include <grpcpp/support/async_stream.h> diff --git a/contrib/libs/grpc/include/grpcpp/health_check_service_interface.h b/contrib/libs/grpc/include/grpcpp/health_check_service_interface.h index de055a82ea..925cce16df 100644 --- a/contrib/libs/grpc/include/grpcpp/health_check_service_interface.h +++ b/contrib/libs/grpc/include/grpcpp/health_check_service_interface.h @@ -37,7 +37,7 @@ class HealthCheckServiceInterface { bool serving) = 0; /// Apply to all registered service names. virtual void SetServingStatus(bool serving) = 0; - + /// Set all registered service names to not serving and prevent future /// state changes. virtual void Shutdown() {} diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h index a812b086a2..cb82f446da 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/async_generic_service.h @@ -1,84 +1,84 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H -#define GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H - +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H +#define GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H + #include <grpc/impl/codegen/port_platform.h> #include <grpcpp/impl/codegen/async_stream.h> -#include <grpcpp/impl/codegen/byte_buffer.h> +#include <grpcpp/impl/codegen/byte_buffer.h> #include <grpcpp/impl/codegen/server_callback.h> #include <grpcpp/impl/codegen/server_callback_handlers.h> - -struct grpc_server; - -namespace grpc { - + +struct grpc_server; + +namespace grpc { + typedef ServerAsyncReaderWriter<ByteBuffer, ByteBuffer> - GenericServerAsyncReaderWriter; + GenericServerAsyncReaderWriter; typedef ServerAsyncResponseWriter<ByteBuffer> GenericServerAsyncResponseWriter; typedef ServerAsyncReader<ByteBuffer, ByteBuffer> GenericServerAsyncReader; typedef ServerAsyncWriter<ByteBuffer> GenericServerAsyncWriter; - + class GenericServerContext final : public ServerContext { - public: + public: const TString& method() const { return method_; } const TString& host() const { return host_; } - - private: + + private: friend class ServerInterface; - + TString method_; TString host_; -}; - -// A generic service at the server side accepts all RPC methods and hosts. It is -// typically used in proxies. The generic service can be registered to a server -// which also has other services. -// Sample usage: -// ServerBuilder builder; -// auto cq = builder.AddCompletionQueue(); -// AsyncGenericService generic_service; -// builder.RegisterAsyncGenericService(&generic_service); -// auto server = builder.BuildAndStart(); -// -// // request a new call -// GenericServerContext context; -// GenericServerAsyncReaderWriter stream; -// generic_service.RequestCall(&context, &stream, cq.get(), cq.get(), tag); -// -// When tag is retrieved from cq->Next(), context.method() can be used to look -// at the method and the RPC can be handled accordingly. -class AsyncGenericService final { - public: - AsyncGenericService() : server_(nullptr) {} - - void RequestCall(GenericServerContext* ctx, - GenericServerAsyncReaderWriter* reader_writer, +}; + +// A generic service at the server side accepts all RPC methods and hosts. It is +// typically used in proxies. The generic service can be registered to a server +// which also has other services. +// Sample usage: +// ServerBuilder builder; +// auto cq = builder.AddCompletionQueue(); +// AsyncGenericService generic_service; +// builder.RegisterAsyncGenericService(&generic_service); +// auto server = builder.BuildAndStart(); +// +// // request a new call +// GenericServerContext context; +// GenericServerAsyncReaderWriter stream; +// generic_service.RequestCall(&context, &stream, cq.get(), cq.get(), tag); +// +// When tag is retrieved from cq->Next(), context.method() can be used to look +// at the method and the RPC can be handled accordingly. +class AsyncGenericService final { + public: + AsyncGenericService() : server_(nullptr) {} + + void RequestCall(GenericServerContext* ctx, + GenericServerAsyncReaderWriter* reader_writer, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag); - - private: + + private: friend class grpc::Server; grpc::Server* server_; -}; - +}; + #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL namespace experimental { #endif @@ -137,6 +137,6 @@ class CallbackGenericService { #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL } // namespace experimental #endif -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_ASYNC_GENERIC_SERVICE_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h index 6e64ec9981..5b157cb43e 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/byte_buffer.h @@ -54,7 +54,7 @@ class ExternalConnectionAcceptorImpl; template <class R> class DeserializeFuncType; class GrpcByteBufferPeer; - + } // namespace internal /// A sequence of bytes. class ByteBuffer final { @@ -89,9 +89,9 @@ class ByteBuffer final { } /// Constuct a byte buffer by referencing elements of existing buffer - /// \a buf. Wrapper of core function grpc_byte_buffer_copy . This is not - /// a deep copy; it is just a referencing. As a result, its performance is - /// size-independent. + /// \a buf. Wrapper of core function grpc_byte_buffer_copy . This is not + /// a deep copy; it is just a referencing. As a result, its performance is + /// size-independent. ByteBuffer(const ByteBuffer& buf) : buffer_(nullptr) { operator=(buf); } ~ByteBuffer() { @@ -100,9 +100,9 @@ class ByteBuffer final { } } - /// Wrapper of core function grpc_byte_buffer_copy . This is not - /// a deep copy; it is just a referencing. As a result, its performance is - /// size-independent. + /// Wrapper of core function grpc_byte_buffer_copy . This is not + /// a deep copy; it is just a referencing. As a result, its performance is + /// size-independent. ByteBuffer& operator=(const ByteBuffer& buf) { if (this != &buf) { Clear(); // first remove existing data @@ -127,9 +127,9 @@ class ByteBuffer final { /// Make a duplicate copy of the internals of this byte /// buffer so that we have our own owned version of it. - /// bbuf.Duplicate(); is equivalent to bbuf=bbuf; but is actually readable. - /// This is not a deep copy; it is a referencing and its performance - /// is size-independent. + /// bbuf.Duplicate(); is equivalent to bbuf=bbuf; but is actually readable. + /// This is not a deep copy; it is a referencing and its performance + /// is size-independent. void Duplicate() { buffer_ = g_core_codegen_interface->grpc_byte_buffer_copy(buffer_); } @@ -164,13 +164,13 @@ class ByteBuffer final { friend class internal::CallOpGenericRecvMessage; template <class ServiceType, class RequestType, class ResponseType> friend class internal::RpcMethodHandler; - template <class ServiceType, class RequestType, class ResponseType> + template <class ServiceType, class RequestType, class ResponseType> friend class internal::ServerStreamingHandler; - template <class RequestType, class ResponseType> + template <class RequestType, class ResponseType> friend class internal::CallbackUnaryHandler; - template <class RequestType, class ResponseType> + template <class RequestType, class ResponseType> friend class internal::CallbackServerStreamingHandler; - template <StatusCode code> + template <StatusCode code> friend class internal::ErrorMethodHandler; template <class R> friend class internal::DeserializeFuncType; diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/call.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/call.h index b229286215..eda6697777 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/call.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/call.h @@ -1,6 +1,6 @@ /* * - * Copyright 2018 gRPC authors. + * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,27 +18,27 @@ #ifndef GRPCPP_IMPL_CODEGEN_CALL_H #define GRPCPP_IMPL_CODEGEN_CALL_H -#include <grpc/impl/codegen/grpc_types.h> +#include <grpc/impl/codegen/grpc_types.h> #include <grpcpp/impl/codegen/call_hook.h> namespace grpc { class CompletionQueue; -namespace experimental { -class ClientRpcInfo; -class ServerRpcInfo; -} // namespace experimental +namespace experimental { +class ClientRpcInfo; +class ServerRpcInfo; +} // namespace experimental namespace internal { class CallHook; -class CallOpSetInterface; +class CallOpSetInterface; /// Straightforward wrapping of the C call object class Call final { public: - Call() - : call_hook_(nullptr), - cq_(nullptr), - call_(nullptr), - max_receive_message_size_(-1) {} + Call() + : call_hook_(nullptr), + cq_(nullptr), + call_(nullptr), + max_receive_message_size_(-1) {} /** call is owned by the caller */ Call(grpc_call* call, CallHook* call_hook, ::grpc::CompletionQueue* cq) : call_hook_(call_hook), @@ -47,21 +47,21 @@ class Call final { max_receive_message_size_(-1) {} Call(grpc_call* call, CallHook* call_hook, ::grpc::CompletionQueue* cq, - experimental::ClientRpcInfo* rpc_info) + experimental::ClientRpcInfo* rpc_info) : call_hook_(call_hook), cq_(cq), call_(call), - max_receive_message_size_(-1), - client_rpc_info_(rpc_info) {} + max_receive_message_size_(-1), + client_rpc_info_(rpc_info) {} Call(grpc_call* call, CallHook* call_hook, ::grpc::CompletionQueue* cq, - int max_receive_message_size, experimental::ServerRpcInfo* rpc_info) - : call_hook_(call_hook), - cq_(cq), - call_(call), - max_receive_message_size_(max_receive_message_size), - server_rpc_info_(rpc_info) {} - + int max_receive_message_size, experimental::ServerRpcInfo* rpc_info) + : call_hook_(call_hook), + cq_(cq), + call_(call), + max_receive_message_size_(max_receive_message_size), + server_rpc_info_(rpc_info) {} + void PerformOps(CallOpSetInterface* ops) { call_hook_->PerformOpsOnCall(ops, this); } @@ -71,21 +71,21 @@ class Call final { int max_receive_message_size() const { return max_receive_message_size_; } - experimental::ClientRpcInfo* client_rpc_info() const { - return client_rpc_info_; - } - - experimental::ServerRpcInfo* server_rpc_info() const { - return server_rpc_info_; - } - + experimental::ClientRpcInfo* client_rpc_info() const { + return client_rpc_info_; + } + + experimental::ServerRpcInfo* server_rpc_info() const { + return server_rpc_info_; + } + private: CallHook* call_hook_; ::grpc::CompletionQueue* cq_; grpc_call* call_; int max_receive_message_size_; - experimental::ClientRpcInfo* client_rpc_info_ = nullptr; - experimental::ServerRpcInfo* server_rpc_info_ = nullptr; + experimental::ClientRpcInfo* client_rpc_info_ = nullptr; + experimental::ServerRpcInfo* server_rpc_info_ = nullptr; }; } // namespace internal } // namespace grpc diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h index 379333164a..21baa3ad19 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set.h @@ -1,460 +1,460 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#if defined(__GNUC__) -#pragma GCC system_header -#endif - -#ifndef GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H -#define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H - -#include <cstring> -#include <map> -#include <memory> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#if defined(__GNUC__) +#pragma GCC system_header +#endif + +#ifndef GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H +#define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H + +#include <cstring> +#include <map> +#include <memory> + #include <grpc/impl/codegen/compression_types.h> #include <grpc/impl/codegen/grpc_types.h> -#include <grpcpp/impl/codegen/byte_buffer.h> -#include <grpcpp/impl/codegen/call.h> -#include <grpcpp/impl/codegen/call_hook.h> -#include <grpcpp/impl/codegen/call_op_set_interface.h> +#include <grpcpp/impl/codegen/byte_buffer.h> +#include <grpcpp/impl/codegen/call.h> +#include <grpcpp/impl/codegen/call_hook.h> +#include <grpcpp/impl/codegen/call_op_set_interface.h> #include <grpcpp/impl/codegen/client_context.h> #include <grpcpp/impl/codegen/completion_queue.h> -#include <grpcpp/impl/codegen/completion_queue_tag.h> -#include <grpcpp/impl/codegen/config.h> -#include <grpcpp/impl/codegen/core_codegen_interface.h> -#include <grpcpp/impl/codegen/intercepted_channel.h> -#include <grpcpp/impl/codegen/interceptor_common.h> -#include <grpcpp/impl/codegen/serialization_traits.h> -#include <grpcpp/impl/codegen/slice.h> -#include <grpcpp/impl/codegen/string_ref.h> - -namespace grpc { - -extern CoreCodegenInterface* g_core_codegen_interface; - -namespace internal { -class Call; -class CallHook; - -// TODO(yangg) if the map is changed before we send, the pointers will be a -// mess. Make sure it does not happen. -inline grpc_metadata* FillMetadataArray( +#include <grpcpp/impl/codegen/completion_queue_tag.h> +#include <grpcpp/impl/codegen/config.h> +#include <grpcpp/impl/codegen/core_codegen_interface.h> +#include <grpcpp/impl/codegen/intercepted_channel.h> +#include <grpcpp/impl/codegen/interceptor_common.h> +#include <grpcpp/impl/codegen/serialization_traits.h> +#include <grpcpp/impl/codegen/slice.h> +#include <grpcpp/impl/codegen/string_ref.h> + +namespace grpc { + +extern CoreCodegenInterface* g_core_codegen_interface; + +namespace internal { +class Call; +class CallHook; + +// TODO(yangg) if the map is changed before we send, the pointers will be a +// mess. Make sure it does not happen. +inline grpc_metadata* FillMetadataArray( const std::multimap<TString, TString>& metadata, size_t* metadata_count, const TString& optional_error_details) { - *metadata_count = metadata.size() + (optional_error_details.empty() ? 0 : 1); - if (*metadata_count == 0) { - return nullptr; - } - grpc_metadata* metadata_array = - (grpc_metadata*)(g_core_codegen_interface->gpr_malloc( - (*metadata_count) * sizeof(grpc_metadata))); - size_t i = 0; - for (auto iter = metadata.cbegin(); iter != metadata.cend(); ++iter, ++i) { - metadata_array[i].key = SliceReferencingString(iter->first); - metadata_array[i].value = SliceReferencingString(iter->second); - } - if (!optional_error_details.empty()) { - metadata_array[i].key = - g_core_codegen_interface->grpc_slice_from_static_buffer( - kBinaryErrorDetailsKey, sizeof(kBinaryErrorDetailsKey) - 1); - metadata_array[i].value = SliceReferencingString(optional_error_details); - } - return metadata_array; -} -} // namespace internal - -/// Per-message write options. -class WriteOptions { - public: - WriteOptions() : flags_(0), last_message_(false) {} - WriteOptions(const WriteOptions& other) - : flags_(other.flags_), last_message_(other.last_message_) {} - + *metadata_count = metadata.size() + (optional_error_details.empty() ? 0 : 1); + if (*metadata_count == 0) { + return nullptr; + } + grpc_metadata* metadata_array = + (grpc_metadata*)(g_core_codegen_interface->gpr_malloc( + (*metadata_count) * sizeof(grpc_metadata))); + size_t i = 0; + for (auto iter = metadata.cbegin(); iter != metadata.cend(); ++iter, ++i) { + metadata_array[i].key = SliceReferencingString(iter->first); + metadata_array[i].value = SliceReferencingString(iter->second); + } + if (!optional_error_details.empty()) { + metadata_array[i].key = + g_core_codegen_interface->grpc_slice_from_static_buffer( + kBinaryErrorDetailsKey, sizeof(kBinaryErrorDetailsKey) - 1); + metadata_array[i].value = SliceReferencingString(optional_error_details); + } + return metadata_array; +} +} // namespace internal + +/// Per-message write options. +class WriteOptions { + public: + WriteOptions() : flags_(0), last_message_(false) {} + WriteOptions(const WriteOptions& other) + : flags_(other.flags_), last_message_(other.last_message_) {} + /// Default assignment operator WriteOptions& operator=(const WriteOptions& other) = default; - /// Clear all flags. - inline void Clear() { flags_ = 0; } - - /// Returns raw flags bitset. - inline uint32_t flags() const { return flags_; } - - /// Sets flag for the disabling of compression for the next message write. - /// - /// \sa GRPC_WRITE_NO_COMPRESS - inline WriteOptions& set_no_compression() { - SetBit(GRPC_WRITE_NO_COMPRESS); - return *this; - } - - /// Clears flag for the disabling of compression for the next message write. - /// - /// \sa GRPC_WRITE_NO_COMPRESS - inline WriteOptions& clear_no_compression() { - ClearBit(GRPC_WRITE_NO_COMPRESS); - return *this; - } - - /// Get value for the flag indicating whether compression for the next - /// message write is forcefully disabled. - /// - /// \sa GRPC_WRITE_NO_COMPRESS - inline bool get_no_compression() const { - return GetBit(GRPC_WRITE_NO_COMPRESS); - } - - /// Sets flag indicating that the write may be buffered and need not go out on - /// the wire immediately. - /// - /// \sa GRPC_WRITE_BUFFER_HINT - inline WriteOptions& set_buffer_hint() { - SetBit(GRPC_WRITE_BUFFER_HINT); - return *this; - } - - /// Clears flag indicating that the write may be buffered and need not go out - /// on the wire immediately. - /// - /// \sa GRPC_WRITE_BUFFER_HINT - inline WriteOptions& clear_buffer_hint() { - ClearBit(GRPC_WRITE_BUFFER_HINT); - return *this; - } - - /// Get value for the flag indicating that the write may be buffered and need - /// not go out on the wire immediately. - /// - /// \sa GRPC_WRITE_BUFFER_HINT - inline bool get_buffer_hint() const { return GetBit(GRPC_WRITE_BUFFER_HINT); } - - /// corked bit: aliases set_buffer_hint currently, with the intent that - /// set_buffer_hint will be removed in the future - inline WriteOptions& set_corked() { - SetBit(GRPC_WRITE_BUFFER_HINT); - return *this; - } - - inline WriteOptions& clear_corked() { - ClearBit(GRPC_WRITE_BUFFER_HINT); - return *this; - } - - inline bool is_corked() const { return GetBit(GRPC_WRITE_BUFFER_HINT); } - - /// last-message bit: indicates this is the last message in a stream - /// client-side: makes Write the equivalent of performing Write, WritesDone - /// in a single step - /// server-side: hold the Write until the service handler returns (sync api) - /// or until Finish is called (async api) - inline WriteOptions& set_last_message() { - last_message_ = true; - return *this; - } - - /// Clears flag indicating that this is the last message in a stream, - /// disabling coalescing. - inline WriteOptions& clear_last_message() { - last_message_ = false; - return *this; - } - - /// Guarantee that all bytes have been written to the socket before completing - /// this write (usually writes are completed when they pass flow control). - inline WriteOptions& set_write_through() { - SetBit(GRPC_WRITE_THROUGH); - return *this; - } - - inline bool is_write_through() const { return GetBit(GRPC_WRITE_THROUGH); } - - /// Get value for the flag indicating that this is the last message, and - /// should be coalesced with trailing metadata. - /// - /// \sa GRPC_WRITE_LAST_MESSAGE - bool is_last_message() const { return last_message_; } - - private: - void SetBit(const uint32_t mask) { flags_ |= mask; } - - void ClearBit(const uint32_t mask) { flags_ &= ~mask; } - - bool GetBit(const uint32_t mask) const { return (flags_ & mask) != 0; } - - uint32_t flags_; - bool last_message_; -}; - -namespace internal { - + /// Clear all flags. + inline void Clear() { flags_ = 0; } + + /// Returns raw flags bitset. + inline uint32_t flags() const { return flags_; } + + /// Sets flag for the disabling of compression for the next message write. + /// + /// \sa GRPC_WRITE_NO_COMPRESS + inline WriteOptions& set_no_compression() { + SetBit(GRPC_WRITE_NO_COMPRESS); + return *this; + } + + /// Clears flag for the disabling of compression for the next message write. + /// + /// \sa GRPC_WRITE_NO_COMPRESS + inline WriteOptions& clear_no_compression() { + ClearBit(GRPC_WRITE_NO_COMPRESS); + return *this; + } + + /// Get value for the flag indicating whether compression for the next + /// message write is forcefully disabled. + /// + /// \sa GRPC_WRITE_NO_COMPRESS + inline bool get_no_compression() const { + return GetBit(GRPC_WRITE_NO_COMPRESS); + } + + /// Sets flag indicating that the write may be buffered and need not go out on + /// the wire immediately. + /// + /// \sa GRPC_WRITE_BUFFER_HINT + inline WriteOptions& set_buffer_hint() { + SetBit(GRPC_WRITE_BUFFER_HINT); + return *this; + } + + /// Clears flag indicating that the write may be buffered and need not go out + /// on the wire immediately. + /// + /// \sa GRPC_WRITE_BUFFER_HINT + inline WriteOptions& clear_buffer_hint() { + ClearBit(GRPC_WRITE_BUFFER_HINT); + return *this; + } + + /// Get value for the flag indicating that the write may be buffered and need + /// not go out on the wire immediately. + /// + /// \sa GRPC_WRITE_BUFFER_HINT + inline bool get_buffer_hint() const { return GetBit(GRPC_WRITE_BUFFER_HINT); } + + /// corked bit: aliases set_buffer_hint currently, with the intent that + /// set_buffer_hint will be removed in the future + inline WriteOptions& set_corked() { + SetBit(GRPC_WRITE_BUFFER_HINT); + return *this; + } + + inline WriteOptions& clear_corked() { + ClearBit(GRPC_WRITE_BUFFER_HINT); + return *this; + } + + inline bool is_corked() const { return GetBit(GRPC_WRITE_BUFFER_HINT); } + + /// last-message bit: indicates this is the last message in a stream + /// client-side: makes Write the equivalent of performing Write, WritesDone + /// in a single step + /// server-side: hold the Write until the service handler returns (sync api) + /// or until Finish is called (async api) + inline WriteOptions& set_last_message() { + last_message_ = true; + return *this; + } + + /// Clears flag indicating that this is the last message in a stream, + /// disabling coalescing. + inline WriteOptions& clear_last_message() { + last_message_ = false; + return *this; + } + + /// Guarantee that all bytes have been written to the socket before completing + /// this write (usually writes are completed when they pass flow control). + inline WriteOptions& set_write_through() { + SetBit(GRPC_WRITE_THROUGH); + return *this; + } + + inline bool is_write_through() const { return GetBit(GRPC_WRITE_THROUGH); } + + /// Get value for the flag indicating that this is the last message, and + /// should be coalesced with trailing metadata. + /// + /// \sa GRPC_WRITE_LAST_MESSAGE + bool is_last_message() const { return last_message_; } + + private: + void SetBit(const uint32_t mask) { flags_ |= mask; } + + void ClearBit(const uint32_t mask) { flags_ &= ~mask; } + + bool GetBit(const uint32_t mask) const { return (flags_ & mask) != 0; } + + uint32_t flags_; + bool last_message_; +}; + +namespace internal { + /// Default argument for CallOpSet. The Unused parameter is unused by /// the class, but can be used for generating multiple names for the /// same thing. template <int Unused> -class CallNoOp { - protected: +class CallNoOp { + protected: void AddOp(grpc_op* /*ops*/, size_t* /*nops*/) {} void FinishOp(bool* /*status*/) {} - void SetInterceptionHookPoint( + void SetInterceptionHookPoint( InterceptorBatchMethodsImpl* /*interceptor_methods*/) {} - void SetFinishInterceptionHookPoint( + void SetFinishInterceptionHookPoint( InterceptorBatchMethodsImpl* /*interceptor_methods*/) {} void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) { } -}; - -class CallOpSendInitialMetadata { - public: - CallOpSendInitialMetadata() : send_(false) { - maybe_compression_level_.is_set = false; - } - +}; + +class CallOpSendInitialMetadata { + public: + CallOpSendInitialMetadata() : send_(false) { + maybe_compression_level_.is_set = false; + } + void SendInitialMetadata(std::multimap<TString, TString>* metadata, - uint32_t flags) { - maybe_compression_level_.is_set = false; - send_ = true; - flags_ = flags; - metadata_map_ = metadata; - } - - void set_compression_level(grpc_compression_level level) { - maybe_compression_level_.is_set = true; - maybe_compression_level_.level = level; - } - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (!send_ || hijacked_) return; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_SEND_INITIAL_METADATA; - op->flags = flags_; - op->reserved = NULL; - initial_metadata_ = - FillMetadataArray(*metadata_map_, &initial_metadata_count_, ""); - op->data.send_initial_metadata.count = initial_metadata_count_; - op->data.send_initial_metadata.metadata = initial_metadata_; - op->data.send_initial_metadata.maybe_compression_level.is_set = - maybe_compression_level_.is_set; - if (maybe_compression_level_.is_set) { - op->data.send_initial_metadata.maybe_compression_level.level = - maybe_compression_level_.level; - } - } + uint32_t flags) { + maybe_compression_level_.is_set = false; + send_ = true; + flags_ = flags; + metadata_map_ = metadata; + } + + void set_compression_level(grpc_compression_level level) { + maybe_compression_level_.is_set = true; + maybe_compression_level_.level = level; + } + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (!send_ || hijacked_) return; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->flags = flags_; + op->reserved = NULL; + initial_metadata_ = + FillMetadataArray(*metadata_map_, &initial_metadata_count_, ""); + op->data.send_initial_metadata.count = initial_metadata_count_; + op->data.send_initial_metadata.metadata = initial_metadata_; + op->data.send_initial_metadata.maybe_compression_level.is_set = + maybe_compression_level_.is_set; + if (maybe_compression_level_.is_set) { + op->data.send_initial_metadata.maybe_compression_level.level = + maybe_compression_level_.level; + } + } void FinishOp(bool* /*status*/) { - if (!send_ || hijacked_) return; - g_core_codegen_interface->gpr_free(initial_metadata_); - send_ = false; - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (!send_) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA); - interceptor_methods->SetSendInitialMetadata(metadata_map_); - } - - void SetFinishInterceptionHookPoint( + if (!send_ || hijacked_) return; + g_core_codegen_interface->gpr_free(initial_metadata_); + send_ = false; + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (!send_) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA); + interceptor_methods->SetSendInitialMetadata(metadata_map_); + } + + void SetFinishInterceptionHookPoint( InterceptorBatchMethodsImpl* /*interceptor_methods*/) {} - + void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) { - hijacked_ = true; - } - - bool hijacked_ = false; - bool send_; - uint32_t flags_; - size_t initial_metadata_count_; + hijacked_ = true; + } + + bool hijacked_ = false; + bool send_; + uint32_t flags_; + size_t initial_metadata_count_; std::multimap<TString, TString>* metadata_map_; - grpc_metadata* initial_metadata_; - struct { - bool is_set; - grpc_compression_level level; - } maybe_compression_level_; -}; - -class CallOpSendMessage { - public: - CallOpSendMessage() : send_buf_() {} - - /// Send \a message using \a options for the write. The \a options are cleared - /// after use. - template <class M> - Status SendMessage(const M& message, - WriteOptions options) GRPC_MUST_USE_RESULT; - - template <class M> - Status SendMessage(const M& message) GRPC_MUST_USE_RESULT; - - /// Send \a message using \a options for the write. The \a options are cleared - /// after use. This form of SendMessage allows gRPC to reference \a message - /// beyond the lifetime of SendMessage. - template <class M> - Status SendMessagePtr(const M* message, - WriteOptions options) GRPC_MUST_USE_RESULT; - - /// This form of SendMessage allows gRPC to reference \a message beyond the - /// lifetime of SendMessage. - template <class M> - Status SendMessagePtr(const M* message) GRPC_MUST_USE_RESULT; - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (msg_ == nullptr && !send_buf_.Valid()) return; - if (hijacked_) { - serializer_ = nullptr; - return; - } - if (msg_ != nullptr) { - GPR_CODEGEN_ASSERT(serializer_(msg_).ok()); - } - serializer_ = nullptr; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_SEND_MESSAGE; - op->flags = write_options_.flags(); - op->reserved = NULL; - op->data.send_message.send_message = send_buf_.c_buffer(); - // Flags are per-message: clear them after use. - write_options_.Clear(); - } - void FinishOp(bool* status) { - if (msg_ == nullptr && !send_buf_.Valid()) return; - if (hijacked_ && failed_send_) { - // Hijacking interceptor failed this Op - *status = false; - } else if (!*status) { - // This Op was passed down to core and the Op failed - failed_send_ = true; - } - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (msg_ == nullptr && !send_buf_.Valid()) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_SEND_MESSAGE); - interceptor_methods->SetSendMessage(&send_buf_, &msg_, &failed_send_, - serializer_); - } - - void SetFinishInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (msg_ != nullptr || send_buf_.Valid()) { - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::POST_SEND_MESSAGE); - } - send_buf_.Clear(); - msg_ = nullptr; - // The contents of the SendMessage value that was previously set - // has had its references stolen by core's operations - interceptor_methods->SetSendMessage(nullptr, nullptr, &failed_send_, - nullptr); - } - + grpc_metadata* initial_metadata_; + struct { + bool is_set; + grpc_compression_level level; + } maybe_compression_level_; +}; + +class CallOpSendMessage { + public: + CallOpSendMessage() : send_buf_() {} + + /// Send \a message using \a options for the write. The \a options are cleared + /// after use. + template <class M> + Status SendMessage(const M& message, + WriteOptions options) GRPC_MUST_USE_RESULT; + + template <class M> + Status SendMessage(const M& message) GRPC_MUST_USE_RESULT; + + /// Send \a message using \a options for the write. The \a options are cleared + /// after use. This form of SendMessage allows gRPC to reference \a message + /// beyond the lifetime of SendMessage. + template <class M> + Status SendMessagePtr(const M* message, + WriteOptions options) GRPC_MUST_USE_RESULT; + + /// This form of SendMessage allows gRPC to reference \a message beyond the + /// lifetime of SendMessage. + template <class M> + Status SendMessagePtr(const M* message) GRPC_MUST_USE_RESULT; + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (msg_ == nullptr && !send_buf_.Valid()) return; + if (hijacked_) { + serializer_ = nullptr; + return; + } + if (msg_ != nullptr) { + GPR_CODEGEN_ASSERT(serializer_(msg_).ok()); + } + serializer_ = nullptr; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_SEND_MESSAGE; + op->flags = write_options_.flags(); + op->reserved = NULL; + op->data.send_message.send_message = send_buf_.c_buffer(); + // Flags are per-message: clear them after use. + write_options_.Clear(); + } + void FinishOp(bool* status) { + if (msg_ == nullptr && !send_buf_.Valid()) return; + if (hijacked_ && failed_send_) { + // Hijacking interceptor failed this Op + *status = false; + } else if (!*status) { + // This Op was passed down to core and the Op failed + failed_send_ = true; + } + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (msg_ == nullptr && !send_buf_.Valid()) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_SEND_MESSAGE); + interceptor_methods->SetSendMessage(&send_buf_, &msg_, &failed_send_, + serializer_); + } + + void SetFinishInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (msg_ != nullptr || send_buf_.Valid()) { + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::POST_SEND_MESSAGE); + } + send_buf_.Clear(); + msg_ = nullptr; + // The contents of the SendMessage value that was previously set + // has had its references stolen by core's operations + interceptor_methods->SetSendMessage(nullptr, nullptr, &failed_send_, + nullptr); + } + void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) { - hijacked_ = true; - } - - private: - const void* msg_ = nullptr; // The original non-serialized message - bool hijacked_ = false; - bool failed_send_ = false; - ByteBuffer send_buf_; - WriteOptions write_options_; - std::function<Status(const void*)> serializer_; -}; - -template <class M> -Status CallOpSendMessage::SendMessage(const M& message, WriteOptions options) { - write_options_ = options; - serializer_ = [this](const void* message) { - bool own_buf; - send_buf_.Clear(); - // TODO(vjpai): Remove the void below when possible - // The void in the template parameter below should not be needed - // (since it should be implicit) but is needed due to an observed - // difference in behavior between clang and gcc for certain internal users - Status result = SerializationTraits<M, void>::Serialize( - *static_cast<const M*>(message), send_buf_.bbuf_ptr(), &own_buf); - if (!own_buf) { - send_buf_.Duplicate(); - } - return result; - }; - // Serialize immediately only if we do not have access to the message pointer - if (msg_ == nullptr) { - Status result = serializer_(&message); - serializer_ = nullptr; - return result; - } - return Status(); -} - -template <class M> -Status CallOpSendMessage::SendMessage(const M& message) { - return SendMessage(message, WriteOptions()); -} - -template <class M> -Status CallOpSendMessage::SendMessagePtr(const M* message, - WriteOptions options) { - msg_ = message; - return SendMessage(*message, options); -} - -template <class M> -Status CallOpSendMessage::SendMessagePtr(const M* message) { - msg_ = message; - return SendMessage(*message, WriteOptions()); -} - -template <class R> -class CallOpRecvMessage { - public: - void RecvMessage(R* message) { message_ = message; } - - // Do not change status if no message is received. - void AllowNoMessage() { allow_not_getting_message_ = true; } - + hijacked_ = true; + } + + private: + const void* msg_ = nullptr; // The original non-serialized message + bool hijacked_ = false; + bool failed_send_ = false; + ByteBuffer send_buf_; + WriteOptions write_options_; + std::function<Status(const void*)> serializer_; +}; + +template <class M> +Status CallOpSendMessage::SendMessage(const M& message, WriteOptions options) { + write_options_ = options; + serializer_ = [this](const void* message) { + bool own_buf; + send_buf_.Clear(); + // TODO(vjpai): Remove the void below when possible + // The void in the template parameter below should not be needed + // (since it should be implicit) but is needed due to an observed + // difference in behavior between clang and gcc for certain internal users + Status result = SerializationTraits<M, void>::Serialize( + *static_cast<const M*>(message), send_buf_.bbuf_ptr(), &own_buf); + if (!own_buf) { + send_buf_.Duplicate(); + } + return result; + }; + // Serialize immediately only if we do not have access to the message pointer + if (msg_ == nullptr) { + Status result = serializer_(&message); + serializer_ = nullptr; + return result; + } + return Status(); +} + +template <class M> +Status CallOpSendMessage::SendMessage(const M& message) { + return SendMessage(message, WriteOptions()); +} + +template <class M> +Status CallOpSendMessage::SendMessagePtr(const M* message, + WriteOptions options) { + msg_ = message; + return SendMessage(*message, options); +} + +template <class M> +Status CallOpSendMessage::SendMessagePtr(const M* message) { + msg_ = message; + return SendMessage(*message, WriteOptions()); +} + +template <class R> +class CallOpRecvMessage { + public: + void RecvMessage(R* message) { message_ = message; } + + // Do not change status if no message is received. + void AllowNoMessage() { allow_not_getting_message_ = true; } + bool got_message = false; - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (message_ == nullptr || hijacked_) return; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_RECV_MESSAGE; - op->flags = 0; - op->reserved = NULL; - op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr(); - } - - void FinishOp(bool* status) { + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (message_ == nullptr || hijacked_) return; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_RECV_MESSAGE; + op->flags = 0; + op->reserved = NULL; + op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr(); + } + + void FinishOp(bool* status) { if (message_ == nullptr) return; - if (recv_buf_.Valid()) { - if (*status) { - got_message = *status = - SerializationTraits<R>::Deserialize(recv_buf_.bbuf_ptr(), message_) - .ok(); - recv_buf_.Release(); - } else { - got_message = false; - recv_buf_.Clear(); - } + if (recv_buf_.Valid()) { + if (*status) { + got_message = *status = + SerializationTraits<R>::Deserialize(recv_buf_.bbuf_ptr(), message_) + .ok(); + recv_buf_.Release(); + } else { + got_message = false; + recv_buf_.Clear(); + } } else if (hijacked_) { if (hijacked_recv_message_failed_) { FinishOpRecvMessageFailureHandler(status); @@ -463,34 +463,34 @@ class CallOpRecvMessage { // to be performed since the message is already in its non-serialized // form. } - } else { + } else { FinishOpRecvMessageFailureHandler(status); - } - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (message_ == nullptr) return; + } + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (message_ == nullptr) return; interceptor_methods->SetRecvMessage(message_, &hijacked_recv_message_failed_); - } - - void SetFinishInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (message_ == nullptr) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::POST_RECV_MESSAGE); - if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr); - } - void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { - hijacked_ = true; - if (message_ == nullptr) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_RECV_MESSAGE); - got_message = true; - } - - private: + } + + void SetFinishInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (message_ == nullptr) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::POST_RECV_MESSAGE); + if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr); + } + void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { + hijacked_ = true; + if (message_ == nullptr) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_RECV_MESSAGE); + got_message = true; + } + + private: // Sets got_message and \a status for a failed recv message op void FinishOpRecvMessageFailureHandler(bool* status) { got_message = false; @@ -500,69 +500,69 @@ class CallOpRecvMessage { } R* message_ = nullptr; - ByteBuffer recv_buf_; + ByteBuffer recv_buf_; bool allow_not_getting_message_ = false; - bool hijacked_ = false; + bool hijacked_ = false; bool hijacked_recv_message_failed_ = false; -}; - -class DeserializeFunc { - public: - virtual Status Deserialize(ByteBuffer* buf) = 0; - virtual ~DeserializeFunc() {} -}; - -template <class R> -class DeserializeFuncType final : public DeserializeFunc { - public: - DeserializeFuncType(R* message) : message_(message) {} - Status Deserialize(ByteBuffer* buf) override { - return SerializationTraits<R>::Deserialize(buf->bbuf_ptr(), message_); - } - - ~DeserializeFuncType() override {} - - private: - R* message_; // Not a managed pointer because management is external to this -}; - -class CallOpGenericRecvMessage { - public: - template <class R> - void RecvMessage(R* message) { - // Use an explicit base class pointer to avoid resolution error in the - // following unique_ptr::reset for some old implementations. - DeserializeFunc* func = new DeserializeFuncType<R>(message); - deserialize_.reset(func); - message_ = message; - } - - // Do not change status if no message is received. - void AllowNoMessage() { allow_not_getting_message_ = true; } - +}; + +class DeserializeFunc { + public: + virtual Status Deserialize(ByteBuffer* buf) = 0; + virtual ~DeserializeFunc() {} +}; + +template <class R> +class DeserializeFuncType final : public DeserializeFunc { + public: + DeserializeFuncType(R* message) : message_(message) {} + Status Deserialize(ByteBuffer* buf) override { + return SerializationTraits<R>::Deserialize(buf->bbuf_ptr(), message_); + } + + ~DeserializeFuncType() override {} + + private: + R* message_; // Not a managed pointer because management is external to this +}; + +class CallOpGenericRecvMessage { + public: + template <class R> + void RecvMessage(R* message) { + // Use an explicit base class pointer to avoid resolution error in the + // following unique_ptr::reset for some old implementations. + DeserializeFunc* func = new DeserializeFuncType<R>(message); + deserialize_.reset(func); + message_ = message; + } + + // Do not change status if no message is received. + void AllowNoMessage() { allow_not_getting_message_ = true; } + bool got_message = false; - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (!deserialize_ || hijacked_) return; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_RECV_MESSAGE; - op->flags = 0; - op->reserved = NULL; - op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr(); - } - - void FinishOp(bool* status) { + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (!deserialize_ || hijacked_) return; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_RECV_MESSAGE; + op->flags = 0; + op->reserved = NULL; + op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr(); + } + + void FinishOp(bool* status) { if (!deserialize_) return; - if (recv_buf_.Valid()) { - if (*status) { - got_message = true; - *status = deserialize_->Deserialize(&recv_buf_).ok(); - recv_buf_.Release(); - } else { - got_message = false; - recv_buf_.Clear(); - } + if (recv_buf_.Valid()) { + if (*status) { + got_message = true; + *status = deserialize_->Deserialize(&recv_buf_).ok(); + recv_buf_.Release(); + } else { + got_message = false; + recv_buf_.Clear(); + } } else if (hijacked_) { if (hijacked_recv_message_failed_) { FinishOpRecvMessageFailureHandler(status); @@ -571,38 +571,38 @@ class CallOpGenericRecvMessage { // to be performed since the message is already in its non-serialized // form. } - } else { - got_message = false; - if (!allow_not_getting_message_) { - *status = false; - } - } - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (!deserialize_) return; + } else { + got_message = false; + if (!allow_not_getting_message_) { + *status = false; + } + } + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (!deserialize_) return; interceptor_methods->SetRecvMessage(message_, &hijacked_recv_message_failed_); - } - - void SetFinishInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (!deserialize_) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::POST_RECV_MESSAGE); - if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr); + } + + void SetFinishInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (!deserialize_) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::POST_RECV_MESSAGE); + if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr); deserialize_.reset(); - } - void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { - hijacked_ = true; - if (!deserialize_) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_RECV_MESSAGE); - got_message = true; - } - - private: + } + void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { + hijacked_ = true; + if (!deserialize_) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_RECV_MESSAGE); + got_message = true; + } + + private: // Sets got_message and \a status for a failed recv message op void FinishOpRecvMessageFailureHandler(bool* status) { got_message = false; @@ -612,190 +612,190 @@ class CallOpGenericRecvMessage { } void* message_ = nullptr; - std::unique_ptr<DeserializeFunc> deserialize_; - ByteBuffer recv_buf_; + std::unique_ptr<DeserializeFunc> deserialize_; + ByteBuffer recv_buf_; bool allow_not_getting_message_ = false; bool hijacked_ = false; bool hijacked_recv_message_failed_ = false; -}; - -class CallOpClientSendClose { - public: - CallOpClientSendClose() : send_(false) {} - - void ClientSendClose() { send_ = true; } - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (!send_ || hijacked_) return; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; - op->flags = 0; - op->reserved = NULL; - } +}; + +class CallOpClientSendClose { + public: + CallOpClientSendClose() : send_(false) {} + + void ClientSendClose() { send_ = true; } + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (!send_ || hijacked_) return; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; + op->flags = 0; + op->reserved = NULL; + } void FinishOp(bool* /*status*/) { send_ = false; } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (!send_) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_SEND_CLOSE); - } - - void SetFinishInterceptionHookPoint( + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (!send_) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_SEND_CLOSE); + } + + void SetFinishInterceptionHookPoint( InterceptorBatchMethodsImpl* /*interceptor_methods*/) {} - + void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) { - hijacked_ = true; - } - - private: - bool hijacked_ = false; - bool send_; -}; - -class CallOpServerSendStatus { - public: - CallOpServerSendStatus() : send_status_available_(false) {} - - void ServerSendStatus( + hijacked_ = true; + } + + private: + bool hijacked_ = false; + bool send_; +}; + +class CallOpServerSendStatus { + public: + CallOpServerSendStatus() : send_status_available_(false) {} + + void ServerSendStatus( std::multimap<TString, TString>* trailing_metadata, - const Status& status) { - send_error_details_ = status.error_details(); - metadata_map_ = trailing_metadata; - send_status_available_ = true; - send_status_code_ = static_cast<grpc_status_code>(status.error_code()); - send_error_message_ = status.error_message(); - } - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (!send_status_available_ || hijacked_) return; - trailing_metadata_ = FillMetadataArray( - *metadata_map_, &trailing_metadata_count_, send_error_details_); - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_SEND_STATUS_FROM_SERVER; - op->data.send_status_from_server.trailing_metadata_count = - trailing_metadata_count_; - op->data.send_status_from_server.trailing_metadata = trailing_metadata_; - op->data.send_status_from_server.status = send_status_code_; - error_message_slice_ = SliceReferencingString(send_error_message_); - op->data.send_status_from_server.status_details = - send_error_message_.empty() ? nullptr : &error_message_slice_; - op->flags = 0; - op->reserved = NULL; - } - + const Status& status) { + send_error_details_ = status.error_details(); + metadata_map_ = trailing_metadata; + send_status_available_ = true; + send_status_code_ = static_cast<grpc_status_code>(status.error_code()); + send_error_message_ = status.error_message(); + } + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (!send_status_available_ || hijacked_) return; + trailing_metadata_ = FillMetadataArray( + *metadata_map_, &trailing_metadata_count_, send_error_details_); + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_SEND_STATUS_FROM_SERVER; + op->data.send_status_from_server.trailing_metadata_count = + trailing_metadata_count_; + op->data.send_status_from_server.trailing_metadata = trailing_metadata_; + op->data.send_status_from_server.status = send_status_code_; + error_message_slice_ = SliceReferencingString(send_error_message_); + op->data.send_status_from_server.status_details = + send_error_message_.empty() ? nullptr : &error_message_slice_; + op->flags = 0; + op->reserved = NULL; + } + void FinishOp(bool* /*status*/) { - if (!send_status_available_ || hijacked_) return; - g_core_codegen_interface->gpr_free(trailing_metadata_); - send_status_available_ = false; - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (!send_status_available_) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_SEND_STATUS); - interceptor_methods->SetSendTrailingMetadata(metadata_map_); - interceptor_methods->SetSendStatus(&send_status_code_, &send_error_details_, - &send_error_message_); - } - - void SetFinishInterceptionHookPoint( + if (!send_status_available_ || hijacked_) return; + g_core_codegen_interface->gpr_free(trailing_metadata_); + send_status_available_ = false; + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (!send_status_available_) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_SEND_STATUS); + interceptor_methods->SetSendTrailingMetadata(metadata_map_); + interceptor_methods->SetSendStatus(&send_status_code_, &send_error_details_, + &send_error_message_); + } + + void SetFinishInterceptionHookPoint( InterceptorBatchMethodsImpl* /*interceptor_methods*/) {} - + void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) { - hijacked_ = true; - } - - private: - bool hijacked_ = false; - bool send_status_available_; - grpc_status_code send_status_code_; + hijacked_ = true; + } + + private: + bool hijacked_ = false; + bool send_status_available_; + grpc_status_code send_status_code_; TString send_error_details_; TString send_error_message_; - size_t trailing_metadata_count_; + size_t trailing_metadata_count_; std::multimap<TString, TString>* metadata_map_; - grpc_metadata* trailing_metadata_; - grpc_slice error_message_slice_; -}; - -class CallOpRecvInitialMetadata { - public: - CallOpRecvInitialMetadata() : metadata_map_(nullptr) {} - + grpc_metadata* trailing_metadata_; + grpc_slice error_message_slice_; +}; + +class CallOpRecvInitialMetadata { + public: + CallOpRecvInitialMetadata() : metadata_map_(nullptr) {} + void RecvInitialMetadata(::grpc::ClientContext* context) { - context->initial_metadata_received_ = true; - metadata_map_ = &context->recv_initial_metadata_; - } - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (metadata_map_ == nullptr || hijacked_) return; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_RECV_INITIAL_METADATA; - op->data.recv_initial_metadata.recv_initial_metadata = metadata_map_->arr(); - op->flags = 0; - op->reserved = NULL; - } - + context->initial_metadata_received_ = true; + metadata_map_ = &context->recv_initial_metadata_; + } + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (metadata_map_ == nullptr || hijacked_) return; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_RECV_INITIAL_METADATA; + op->data.recv_initial_metadata.recv_initial_metadata = metadata_map_->arr(); + op->flags = 0; + op->reserved = NULL; + } + void FinishOp(bool* /*status*/) { - if (metadata_map_ == nullptr || hijacked_) return; - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - interceptor_methods->SetRecvInitialMetadata(metadata_map_); - } - - void SetFinishInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (metadata_map_ == nullptr) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA); - metadata_map_ = nullptr; - } - - void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { - hijacked_ = true; - if (metadata_map_ == nullptr) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA); - } - - private: - bool hijacked_ = false; - MetadataMap* metadata_map_; -}; - -class CallOpClientRecvStatus { - public: - CallOpClientRecvStatus() - : recv_status_(nullptr), debug_error_string_(nullptr) {} - + if (metadata_map_ == nullptr || hijacked_) return; + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + interceptor_methods->SetRecvInitialMetadata(metadata_map_); + } + + void SetFinishInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (metadata_map_ == nullptr) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA); + metadata_map_ = nullptr; + } + + void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { + hijacked_ = true; + if (metadata_map_ == nullptr) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA); + } + + private: + bool hijacked_ = false; + MetadataMap* metadata_map_; +}; + +class CallOpClientRecvStatus { + public: + CallOpClientRecvStatus() + : recv_status_(nullptr), debug_error_string_(nullptr) {} + void ClientRecvStatus(::grpc::ClientContext* context, Status* status) { - client_context_ = context; - metadata_map_ = &client_context_->trailing_metadata_; - recv_status_ = status; - error_message_ = g_core_codegen_interface->grpc_empty_slice(); - } - - protected: - void AddOp(grpc_op* ops, size_t* nops) { - if (recv_status_ == nullptr || hijacked_) return; - grpc_op* op = &ops[(*nops)++]; - op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; - op->data.recv_status_on_client.trailing_metadata = metadata_map_->arr(); - op->data.recv_status_on_client.status = &status_code_; - op->data.recv_status_on_client.status_details = &error_message_; - op->data.recv_status_on_client.error_string = &debug_error_string_; - op->flags = 0; - op->reserved = NULL; - } - + client_context_ = context; + metadata_map_ = &client_context_->trailing_metadata_; + recv_status_ = status; + error_message_ = g_core_codegen_interface->grpc_empty_slice(); + } + + protected: + void AddOp(grpc_op* ops, size_t* nops) { + if (recv_status_ == nullptr || hijacked_) return; + grpc_op* op = &ops[(*nops)++]; + op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; + op->data.recv_status_on_client.trailing_metadata = metadata_map_->arr(); + op->data.recv_status_on_client.status = &status_code_; + op->data.recv_status_on_client.status_details = &error_message_; + op->data.recv_status_on_client.error_string = &debug_error_string_; + op->flags = 0; + op->reserved = NULL; + } + void FinishOp(bool* /*status*/) { - if (recv_status_ == nullptr || hijacked_) return; + if (recv_status_ == nullptr || hijacked_) return; if (static_cast<StatusCode>(status_code_) == StatusCode::OK) { *recv_status_ = Status(); GPR_CODEGEN_DEBUG_ASSERT(debug_error_string_ == nullptr); @@ -814,156 +814,156 @@ class CallOpClientRecvStatus { } // TODO(soheil): Find callers that set debug string even for status OK, // and fix them. - g_core_codegen_interface->grpc_slice_unref(error_message_); - } - - void SetInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - interceptor_methods->SetRecvStatus(recv_status_); - interceptor_methods->SetRecvTrailingMetadata(metadata_map_); - } - - void SetFinishInterceptionHookPoint( - InterceptorBatchMethodsImpl* interceptor_methods) { - if (recv_status_ == nullptr) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::POST_RECV_STATUS); - recv_status_ = nullptr; - } - - void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { - hijacked_ = true; - if (recv_status_ == nullptr) return; - interceptor_methods->AddInterceptionHookPoint( - experimental::InterceptionHookPoints::PRE_RECV_STATUS); - } - - private: - bool hijacked_ = false; + g_core_codegen_interface->grpc_slice_unref(error_message_); + } + + void SetInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + interceptor_methods->SetRecvStatus(recv_status_); + interceptor_methods->SetRecvTrailingMetadata(metadata_map_); + } + + void SetFinishInterceptionHookPoint( + InterceptorBatchMethodsImpl* interceptor_methods) { + if (recv_status_ == nullptr) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::POST_RECV_STATUS); + recv_status_ = nullptr; + } + + void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) { + hijacked_ = true; + if (recv_status_ == nullptr) return; + interceptor_methods->AddInterceptionHookPoint( + experimental::InterceptionHookPoints::PRE_RECV_STATUS); + } + + private: + bool hijacked_ = false; ::grpc::ClientContext* client_context_; - MetadataMap* metadata_map_; - Status* recv_status_; - const char* debug_error_string_; - grpc_status_code status_code_; - grpc_slice error_message_; -}; - -template <class Op1 = CallNoOp<1>, class Op2 = CallNoOp<2>, - class Op3 = CallNoOp<3>, class Op4 = CallNoOp<4>, - class Op5 = CallNoOp<5>, class Op6 = CallNoOp<6>> -class CallOpSet; - -/// Primary implementation of CallOpSetInterface. -/// Since we cannot use variadic templates, we declare slots up to -/// the maximum count of ops we'll need in a set. We leverage the -/// empty base class optimization to slim this class (especially -/// when there are many unused slots used). To avoid duplicate base classes, + MetadataMap* metadata_map_; + Status* recv_status_; + const char* debug_error_string_; + grpc_status_code status_code_; + grpc_slice error_message_; +}; + +template <class Op1 = CallNoOp<1>, class Op2 = CallNoOp<2>, + class Op3 = CallNoOp<3>, class Op4 = CallNoOp<4>, + class Op5 = CallNoOp<5>, class Op6 = CallNoOp<6>> +class CallOpSet; + +/// Primary implementation of CallOpSetInterface. +/// Since we cannot use variadic templates, we declare slots up to +/// the maximum count of ops we'll need in a set. We leverage the +/// empty base class optimization to slim this class (especially +/// when there are many unused slots used). To avoid duplicate base classes, /// the template parameter for CallNoOp is varied by argument position. -template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6> -class CallOpSet : public CallOpSetInterface, - public Op1, - public Op2, - public Op3, - public Op4, - public Op5, - public Op6 { - public: - CallOpSet() : core_cq_tag_(this), return_tag_(this) {} - // The copy constructor and assignment operator reset the value of - // core_cq_tag_, return_tag_, done_intercepting_ and interceptor_methods_ - // since those are only meaningful on a specific object, not across objects. - CallOpSet(const CallOpSet& other) - : core_cq_tag_(this), - return_tag_(this), - call_(other.call_), - done_intercepting_(false), - interceptor_methods_(InterceptorBatchMethodsImpl()) {} - - CallOpSet& operator=(const CallOpSet& other) { - core_cq_tag_ = this; - return_tag_ = this; - call_ = other.call_; - done_intercepting_ = false; - interceptor_methods_ = InterceptorBatchMethodsImpl(); - return *this; - } - - void FillOps(Call* call) override { - done_intercepting_ = false; - g_core_codegen_interface->grpc_call_ref(call->call()); - call_ = - *call; // It's fine to create a copy of call since it's just pointers - - if (RunInterceptors()) { - ContinueFillOpsAfterInterception(); - } else { - // After the interceptors are run, ContinueFillOpsAfterInterception will - // be run - } - } - - bool FinalizeResult(void** tag, bool* status) override { - if (done_intercepting_) { - // Complete the avalanching since we are done with this batch of ops - call_.cq()->CompleteAvalanching(); - // We have already finished intercepting and filling in the results. This - // round trip from the core needed to be made because interceptors were - // run - *tag = return_tag_; - *status = saved_status_; - g_core_codegen_interface->grpc_call_unref(call_.call()); - return true; - } - - this->Op1::FinishOp(status); - this->Op2::FinishOp(status); - this->Op3::FinishOp(status); - this->Op4::FinishOp(status); - this->Op5::FinishOp(status); - this->Op6::FinishOp(status); - saved_status_ = *status; - if (RunInterceptorsPostRecv()) { - *tag = return_tag_; - g_core_codegen_interface->grpc_call_unref(call_.call()); - return true; - } - // Interceptors are going to be run, so we can't return the tag just yet. - // After the interceptors are run, ContinueFinalizeResultAfterInterception - return false; - } - - void set_output_tag(void* return_tag) { return_tag_ = return_tag; } - - void* core_cq_tag() override { return core_cq_tag_; } - - /// set_core_cq_tag is used to provide a different core CQ tag than "this". - /// This is used for callback-based tags, where the core tag is the core - /// callback function. It does not change the use or behavior of any other - /// function (such as FinalizeResult) - void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } - - // This will be called while interceptors are run if the RPC is a hijacked - // RPC. This should set hijacking state for each of the ops. - void SetHijackingState() override { - this->Op1::SetHijackingState(&interceptor_methods_); - this->Op2::SetHijackingState(&interceptor_methods_); - this->Op3::SetHijackingState(&interceptor_methods_); - this->Op4::SetHijackingState(&interceptor_methods_); - this->Op5::SetHijackingState(&interceptor_methods_); - this->Op6::SetHijackingState(&interceptor_methods_); - } - - // Should be called after interceptors are done running - void ContinueFillOpsAfterInterception() override { - static const size_t MAX_OPS = 6; - grpc_op ops[MAX_OPS]; - size_t nops = 0; - this->Op1::AddOp(ops, &nops); - this->Op2::AddOp(ops, &nops); - this->Op3::AddOp(ops, &nops); - this->Op4::AddOp(ops, &nops); - this->Op5::AddOp(ops, &nops); - this->Op6::AddOp(ops, &nops); +template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6> +class CallOpSet : public CallOpSetInterface, + public Op1, + public Op2, + public Op3, + public Op4, + public Op5, + public Op6 { + public: + CallOpSet() : core_cq_tag_(this), return_tag_(this) {} + // The copy constructor and assignment operator reset the value of + // core_cq_tag_, return_tag_, done_intercepting_ and interceptor_methods_ + // since those are only meaningful on a specific object, not across objects. + CallOpSet(const CallOpSet& other) + : core_cq_tag_(this), + return_tag_(this), + call_(other.call_), + done_intercepting_(false), + interceptor_methods_(InterceptorBatchMethodsImpl()) {} + + CallOpSet& operator=(const CallOpSet& other) { + core_cq_tag_ = this; + return_tag_ = this; + call_ = other.call_; + done_intercepting_ = false; + interceptor_methods_ = InterceptorBatchMethodsImpl(); + return *this; + } + + void FillOps(Call* call) override { + done_intercepting_ = false; + g_core_codegen_interface->grpc_call_ref(call->call()); + call_ = + *call; // It's fine to create a copy of call since it's just pointers + + if (RunInterceptors()) { + ContinueFillOpsAfterInterception(); + } else { + // After the interceptors are run, ContinueFillOpsAfterInterception will + // be run + } + } + + bool FinalizeResult(void** tag, bool* status) override { + if (done_intercepting_) { + // Complete the avalanching since we are done with this batch of ops + call_.cq()->CompleteAvalanching(); + // We have already finished intercepting and filling in the results. This + // round trip from the core needed to be made because interceptors were + // run + *tag = return_tag_; + *status = saved_status_; + g_core_codegen_interface->grpc_call_unref(call_.call()); + return true; + } + + this->Op1::FinishOp(status); + this->Op2::FinishOp(status); + this->Op3::FinishOp(status); + this->Op4::FinishOp(status); + this->Op5::FinishOp(status); + this->Op6::FinishOp(status); + saved_status_ = *status; + if (RunInterceptorsPostRecv()) { + *tag = return_tag_; + g_core_codegen_interface->grpc_call_unref(call_.call()); + return true; + } + // Interceptors are going to be run, so we can't return the tag just yet. + // After the interceptors are run, ContinueFinalizeResultAfterInterception + return false; + } + + void set_output_tag(void* return_tag) { return_tag_ = return_tag; } + + void* core_cq_tag() override { return core_cq_tag_; } + + /// set_core_cq_tag is used to provide a different core CQ tag than "this". + /// This is used for callback-based tags, where the core tag is the core + /// callback function. It does not change the use or behavior of any other + /// function (such as FinalizeResult) + void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } + + // This will be called while interceptors are run if the RPC is a hijacked + // RPC. This should set hijacking state for each of the ops. + void SetHijackingState() override { + this->Op1::SetHijackingState(&interceptor_methods_); + this->Op2::SetHijackingState(&interceptor_methods_); + this->Op3::SetHijackingState(&interceptor_methods_); + this->Op4::SetHijackingState(&interceptor_methods_); + this->Op5::SetHijackingState(&interceptor_methods_); + this->Op6::SetHijackingState(&interceptor_methods_); + } + + // Should be called after interceptors are done running + void ContinueFillOpsAfterInterception() override { + static const size_t MAX_OPS = 6; + grpc_op ops[MAX_OPS]; + size_t nops = 0; + this->Op1::AddOp(ops, &nops); + this->Op2::AddOp(ops, &nops); + this->Op3::AddOp(ops, &nops); + this->Op4::AddOp(ops, &nops); + this->Op5::AddOp(ops, &nops); + this->Op6::AddOp(ops, &nops); grpc_call_error err = g_core_codegen_interface->grpc_call_start_batch( call_.call(), ops, nops, core_cq_tag(), nullptr); @@ -976,62 +976,62 @@ class CallOpSet : public CallOpSetInterface, // g_core_codegen_interface->grpc_call_error_to_string(err)); GPR_CODEGEN_ASSERT(false); } - } - - // Should be called after interceptors are done running on the finalize result - // path - void ContinueFinalizeResultAfterInterception() override { - done_intercepting_ = true; + } + + // Should be called after interceptors are done running on the finalize result + // path + void ContinueFinalizeResultAfterInterception() override { + done_intercepting_ = true; // The following call_start_batch is internally-generated so no need for an // explanatory log on failure. GPR_CODEGEN_ASSERT(g_core_codegen_interface->grpc_call_start_batch( call_.call(), nullptr, 0, core_cq_tag(), nullptr) == GRPC_CALL_OK); - } - - private: - // Returns true if no interceptors need to be run - bool RunInterceptors() { - interceptor_methods_.ClearState(); - interceptor_methods_.SetCallOpSetInterface(this); - interceptor_methods_.SetCall(&call_); - this->Op1::SetInterceptionHookPoint(&interceptor_methods_); - this->Op2::SetInterceptionHookPoint(&interceptor_methods_); - this->Op3::SetInterceptionHookPoint(&interceptor_methods_); - this->Op4::SetInterceptionHookPoint(&interceptor_methods_); - this->Op5::SetInterceptionHookPoint(&interceptor_methods_); - this->Op6::SetInterceptionHookPoint(&interceptor_methods_); - if (interceptor_methods_.InterceptorsListEmpty()) { - return true; - } - // This call will go through interceptors and would need to - // schedule new batches, so delay completion queue shutdown - call_.cq()->RegisterAvalanching(); - return interceptor_methods_.RunInterceptors(); - } - // Returns true if no interceptors need to be run - bool RunInterceptorsPostRecv() { - // Call and OpSet had already been set on the set state. - // SetReverse also clears previously set hook points - interceptor_methods_.SetReverse(); - this->Op1::SetFinishInterceptionHookPoint(&interceptor_methods_); - this->Op2::SetFinishInterceptionHookPoint(&interceptor_methods_); - this->Op3::SetFinishInterceptionHookPoint(&interceptor_methods_); - this->Op4::SetFinishInterceptionHookPoint(&interceptor_methods_); - this->Op5::SetFinishInterceptionHookPoint(&interceptor_methods_); - this->Op6::SetFinishInterceptionHookPoint(&interceptor_methods_); - return interceptor_methods_.RunInterceptors(); - } - - void* core_cq_tag_; - void* return_tag_; - Call call_; - bool done_intercepting_ = false; - InterceptorBatchMethodsImpl interceptor_methods_; - bool saved_status_; -}; - -} // namespace internal -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H + } + + private: + // Returns true if no interceptors need to be run + bool RunInterceptors() { + interceptor_methods_.ClearState(); + interceptor_methods_.SetCallOpSetInterface(this); + interceptor_methods_.SetCall(&call_); + this->Op1::SetInterceptionHookPoint(&interceptor_methods_); + this->Op2::SetInterceptionHookPoint(&interceptor_methods_); + this->Op3::SetInterceptionHookPoint(&interceptor_methods_); + this->Op4::SetInterceptionHookPoint(&interceptor_methods_); + this->Op5::SetInterceptionHookPoint(&interceptor_methods_); + this->Op6::SetInterceptionHookPoint(&interceptor_methods_); + if (interceptor_methods_.InterceptorsListEmpty()) { + return true; + } + // This call will go through interceptors and would need to + // schedule new batches, so delay completion queue shutdown + call_.cq()->RegisterAvalanching(); + return interceptor_methods_.RunInterceptors(); + } + // Returns true if no interceptors need to be run + bool RunInterceptorsPostRecv() { + // Call and OpSet had already been set on the set state. + // SetReverse also clears previously set hook points + interceptor_methods_.SetReverse(); + this->Op1::SetFinishInterceptionHookPoint(&interceptor_methods_); + this->Op2::SetFinishInterceptionHookPoint(&interceptor_methods_); + this->Op3::SetFinishInterceptionHookPoint(&interceptor_methods_); + this->Op4::SetFinishInterceptionHookPoint(&interceptor_methods_); + this->Op5::SetFinishInterceptionHookPoint(&interceptor_methods_); + this->Op6::SetFinishInterceptionHookPoint(&interceptor_methods_); + return interceptor_methods_.RunInterceptors(); + } + + void* core_cq_tag_; + void* return_tag_; + Call call_; + bool done_intercepting_ = false; + InterceptorBatchMethodsImpl interceptor_methods_; + bool saved_status_; +}; + +} // namespace internal +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set_interface.h index 3b74566a6d..664dae0e6a 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set_interface.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/call_op_set_interface.h @@ -1,59 +1,59 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H -#define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H - -#include <grpcpp/impl/codegen/completion_queue_tag.h> - -namespace grpc { -namespace internal { - -class Call; - -/// An abstract collection of call ops, used to generate the -/// grpc_call_op structure to pass down to the lower layers, -/// and as it is-a CompletionQueueTag, also massages the final -/// completion into the correct form for consumption in the C++ -/// API. -class CallOpSetInterface : public CompletionQueueTag { - public: - /// Fills in grpc_op, starting from ops[*nops] and moving - /// upwards. - virtual void FillOps(internal::Call* call) = 0; - - /// Get the tag to be used at the core completion queue. Generally, the - /// value of core_cq_tag will be "this". However, it can be overridden if we - /// want core to process the tag differently (e.g., as a core callback) - virtual void* core_cq_tag() = 0; - - // This will be called while interceptors are run if the RPC is a hijacked - // RPC. This should set hijacking state for each of the ops. - virtual void SetHijackingState() = 0; - - // Should be called after interceptors are done running - virtual void ContinueFillOpsAfterInterception() = 0; - - // Should be called after interceptors are done running on the finalize result - // path - virtual void ContinueFinalizeResultAfterInterception() = 0; -}; -} // namespace internal -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H +#define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H + +#include <grpcpp/impl/codegen/completion_queue_tag.h> + +namespace grpc { +namespace internal { + +class Call; + +/// An abstract collection of call ops, used to generate the +/// grpc_call_op structure to pass down to the lower layers, +/// and as it is-a CompletionQueueTag, also massages the final +/// completion into the correct form for consumption in the C++ +/// API. +class CallOpSetInterface : public CompletionQueueTag { + public: + /// Fills in grpc_op, starting from ops[*nops] and moving + /// upwards. + virtual void FillOps(internal::Call* call) = 0; + + /// Get the tag to be used at the core completion queue. Generally, the + /// value of core_cq_tag will be "this". However, it can be overridden if we + /// want core to process the tag differently (e.g., as a core callback) + virtual void* core_cq_tag() = 0; + + // This will be called while interceptors are run if the RPC is a hijacked + // RPC. This should set hijacking state for each of the ops. + virtual void SetHijackingState() = 0; + + // Should be called after interceptors are done running + virtual void ContinueFillOpsAfterInterception() = 0; + + // Should be called after interceptors are done running on the finalize result + // path + virtual void ContinueFinalizeResultAfterInterception() = 0; +}; +} // namespace internal +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_INTERFACE_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h index 3c3bfd7e76..784ac3f835 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/callback_common.h @@ -1,226 +1,226 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#if defined(__GNUC__) -#pragma GCC system_header -#endif - -#ifndef GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H -#define GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H - -#include <functional> - -#include <grpc/impl/codegen/grpc_types.h> -#include <grpcpp/impl/codegen/call.h> -#include <grpcpp/impl/codegen/channel_interface.h> -#include <grpcpp/impl/codegen/config.h> -#include <grpcpp/impl/codegen/core_codegen_interface.h> -#include <grpcpp/impl/codegen/status.h> - -namespace grpc { -namespace internal { - -/// An exception-safe way of invoking a user-specified callback function -// TODO(vjpai): decide whether it is better for this to take a const lvalue -// parameter or an rvalue parameter, or if it even matters -template <class Func, class... Args> -void CatchingCallback(Func&& func, Args&&... args) { -#if GRPC_ALLOW_EXCEPTIONS - try { - func(std::forward<Args>(args)...); - } catch (...) { - // nothing to return or change here, just don't crash the library - } -#else // GRPC_ALLOW_EXCEPTIONS - func(std::forward<Args>(args)...); -#endif // GRPC_ALLOW_EXCEPTIONS -} - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#if defined(__GNUC__) +#pragma GCC system_header +#endif + +#ifndef GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H +#define GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H + +#include <functional> + +#include <grpc/impl/codegen/grpc_types.h> +#include <grpcpp/impl/codegen/call.h> +#include <grpcpp/impl/codegen/channel_interface.h> +#include <grpcpp/impl/codegen/config.h> +#include <grpcpp/impl/codegen/core_codegen_interface.h> +#include <grpcpp/impl/codegen/status.h> + +namespace grpc { +namespace internal { + +/// An exception-safe way of invoking a user-specified callback function +// TODO(vjpai): decide whether it is better for this to take a const lvalue +// parameter or an rvalue parameter, or if it even matters +template <class Func, class... Args> +void CatchingCallback(Func&& func, Args&&... args) { +#if GRPC_ALLOW_EXCEPTIONS + try { + func(std::forward<Args>(args)...); + } catch (...) { + // nothing to return or change here, just don't crash the library + } +#else // GRPC_ALLOW_EXCEPTIONS + func(std::forward<Args>(args)...); +#endif // GRPC_ALLOW_EXCEPTIONS +} + template <class Reactor, class Func, class... Args> Reactor* CatchingReactorGetter(Func&& func, Args&&... args) { -#if GRPC_ALLOW_EXCEPTIONS - try { - return func(std::forward<Args>(args)...); - } catch (...) { - // fail the RPC, don't crash the library - return nullptr; - } -#else // GRPC_ALLOW_EXCEPTIONS - return func(std::forward<Args>(args)...); -#endif // GRPC_ALLOW_EXCEPTIONS -} - -// The contract on these tags is that they are single-shot. They must be -// constructed and then fired at exactly one point. There is no expectation -// that they can be reused without reconstruction. - -class CallbackWithStatusTag - : public grpc_experimental_completion_queue_functor { - public: - // always allocated against a call arena, no memory free required +#if GRPC_ALLOW_EXCEPTIONS + try { + return func(std::forward<Args>(args)...); + } catch (...) { + // fail the RPC, don't crash the library + return nullptr; + } +#else // GRPC_ALLOW_EXCEPTIONS + return func(std::forward<Args>(args)...); +#endif // GRPC_ALLOW_EXCEPTIONS +} + +// The contract on these tags is that they are single-shot. They must be +// constructed and then fired at exactly one point. There is no expectation +// that they can be reused without reconstruction. + +class CallbackWithStatusTag + : public grpc_experimental_completion_queue_functor { + public: + // always allocated against a call arena, no memory free required static void operator delete(void* /*ptr*/, std::size_t size) { GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithStatusTag)); - } - - // This operator should never be called as the memory should be freed as part - // of the arena destruction. It only exists to provide a matching operator - // delete to the operator new so that some compilers will not complain (see - // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this - // there are no tests catching the compiler warning. + } + + // This operator should never be called as the memory should be freed as part + // of the arena destruction. It only exists to provide a matching operator + // delete to the operator new so that some compilers will not complain (see + // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this + // there are no tests catching the compiler warning. static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); } - - CallbackWithStatusTag(grpc_call* call, std::function<void(Status)> f, - CompletionQueueTag* ops) - : call_(call), func_(std::move(f)), ops_(ops) { - g_core_codegen_interface->grpc_call_ref(call); - functor_run = &CallbackWithStatusTag::StaticRun; + + CallbackWithStatusTag(grpc_call* call, std::function<void(Status)> f, + CompletionQueueTag* ops) + : call_(call), func_(std::move(f)), ops_(ops) { + g_core_codegen_interface->grpc_call_ref(call); + functor_run = &CallbackWithStatusTag::StaticRun; // A client-side callback should never be run inline since they will always // have work to do from the user application. So, set the parent's // inlineable field to false inlineable = false; - } - ~CallbackWithStatusTag() {} - Status* status_ptr() { return &status_; } - - // force_run can not be performed on a tag if operations using this tag - // have been sent to PerformOpsOnCall. It is intended for error conditions - // that are detected before the operations are internally processed. - void force_run(Status s) { - status_ = std::move(s); - Run(true); - } - - private: - grpc_call* call_; - std::function<void(Status)> func_; - CompletionQueueTag* ops_; - Status status_; - - static void StaticRun(grpc_experimental_completion_queue_functor* cb, - int ok) { - static_cast<CallbackWithStatusTag*>(cb)->Run(static_cast<bool>(ok)); - } - void Run(bool ok) { - void* ignored = ops_; - - if (!ops_->FinalizeResult(&ignored, &ok)) { - // The tag was swallowed - return; - } - GPR_CODEGEN_ASSERT(ignored == ops_); - - // Last use of func_ or status_, so ok to move them out - auto func = std::move(func_); - auto status = std::move(status_); - func_ = nullptr; // reset to clear this out for sure - status_ = Status(); // reset to clear this out for sure - CatchingCallback(std::move(func), std::move(status)); - g_core_codegen_interface->grpc_call_unref(call_); - } -}; - -/// CallbackWithSuccessTag can be reused multiple times, and will be used in -/// this fashion for streaming operations. As a result, it shouldn't clear -/// anything up until its destructor -class CallbackWithSuccessTag - : public grpc_experimental_completion_queue_functor { - public: - // always allocated against a call arena, no memory free required + } + ~CallbackWithStatusTag() {} + Status* status_ptr() { return &status_; } + + // force_run can not be performed on a tag if operations using this tag + // have been sent to PerformOpsOnCall. It is intended for error conditions + // that are detected before the operations are internally processed. + void force_run(Status s) { + status_ = std::move(s); + Run(true); + } + + private: + grpc_call* call_; + std::function<void(Status)> func_; + CompletionQueueTag* ops_; + Status status_; + + static void StaticRun(grpc_experimental_completion_queue_functor* cb, + int ok) { + static_cast<CallbackWithStatusTag*>(cb)->Run(static_cast<bool>(ok)); + } + void Run(bool ok) { + void* ignored = ops_; + + if (!ops_->FinalizeResult(&ignored, &ok)) { + // The tag was swallowed + return; + } + GPR_CODEGEN_ASSERT(ignored == ops_); + + // Last use of func_ or status_, so ok to move them out + auto func = std::move(func_); + auto status = std::move(status_); + func_ = nullptr; // reset to clear this out for sure + status_ = Status(); // reset to clear this out for sure + CatchingCallback(std::move(func), std::move(status)); + g_core_codegen_interface->grpc_call_unref(call_); + } +}; + +/// CallbackWithSuccessTag can be reused multiple times, and will be used in +/// this fashion for streaming operations. As a result, it shouldn't clear +/// anything up until its destructor +class CallbackWithSuccessTag + : public grpc_experimental_completion_queue_functor { + public: + // always allocated against a call arena, no memory free required static void operator delete(void* /*ptr*/, std::size_t size) { GPR_CODEGEN_ASSERT(size == sizeof(CallbackWithSuccessTag)); - } - - // This operator should never be called as the memory should be freed as part - // of the arena destruction. It only exists to provide a matching operator - // delete to the operator new so that some compilers will not complain (see - // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this - // there are no tests catching the compiler warning. + } + + // This operator should never be called as the memory should be freed as part + // of the arena destruction. It only exists to provide a matching operator + // delete to the operator new so that some compilers will not complain (see + // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this + // there are no tests catching the compiler warning. static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); } - - CallbackWithSuccessTag() : call_(nullptr) {} - - CallbackWithSuccessTag(const CallbackWithSuccessTag&) = delete; - CallbackWithSuccessTag& operator=(const CallbackWithSuccessTag&) = delete; - - ~CallbackWithSuccessTag() { Clear(); } - - // Set can only be called on a default-constructed or Clear'ed tag. - // It should never be called on a tag that was constructed with arguments - // or on a tag that has been Set before unless the tag has been cleared. + + CallbackWithSuccessTag() : call_(nullptr) {} + + CallbackWithSuccessTag(const CallbackWithSuccessTag&) = delete; + CallbackWithSuccessTag& operator=(const CallbackWithSuccessTag&) = delete; + + ~CallbackWithSuccessTag() { Clear(); } + + // Set can only be called on a default-constructed or Clear'ed tag. + // It should never be called on a tag that was constructed with arguments + // or on a tag that has been Set before unless the tag has been cleared. // can_inline indicates that this particular callback can be executed inline // (without needing a thread hop) and is only used for library-provided server // callbacks. - void Set(grpc_call* call, std::function<void(bool)> f, + void Set(grpc_call* call, std::function<void(bool)> f, CompletionQueueTag* ops, bool can_inline) { - GPR_CODEGEN_ASSERT(call_ == nullptr); - g_core_codegen_interface->grpc_call_ref(call); - call_ = call; - func_ = std::move(f); - ops_ = ops; - functor_run = &CallbackWithSuccessTag::StaticRun; + GPR_CODEGEN_ASSERT(call_ == nullptr); + g_core_codegen_interface->grpc_call_ref(call); + call_ = call; + func_ = std::move(f); + ops_ = ops; + functor_run = &CallbackWithSuccessTag::StaticRun; inlineable = can_inline; - } - - void Clear() { - if (call_ != nullptr) { - grpc_call* call = call_; - call_ = nullptr; - func_ = nullptr; - g_core_codegen_interface->grpc_call_unref(call); - } - } - - CompletionQueueTag* ops() { return ops_; } - - // force_run can not be performed on a tag if operations using this tag - // have been sent to PerformOpsOnCall. It is intended for error conditions - // that are detected before the operations are internally processed. - void force_run(bool ok) { Run(ok); } - - /// check if this tag is currently set - operator bool() const { return call_ != nullptr; } - - private: - grpc_call* call_; - std::function<void(bool)> func_; - CompletionQueueTag* ops_; - - static void StaticRun(grpc_experimental_completion_queue_functor* cb, - int ok) { - static_cast<CallbackWithSuccessTag*>(cb)->Run(static_cast<bool>(ok)); - } - void Run(bool ok) { - void* ignored = ops_; - // Allow a "false" return value from FinalizeResult to silence the - // callback, just as it silences a CQ tag in the async cases + } + + void Clear() { + if (call_ != nullptr) { + grpc_call* call = call_; + call_ = nullptr; + func_ = nullptr; + g_core_codegen_interface->grpc_call_unref(call); + } + } + + CompletionQueueTag* ops() { return ops_; } + + // force_run can not be performed on a tag if operations using this tag + // have been sent to PerformOpsOnCall. It is intended for error conditions + // that are detected before the operations are internally processed. + void force_run(bool ok) { Run(ok); } + + /// check if this tag is currently set + operator bool() const { return call_ != nullptr; } + + private: + grpc_call* call_; + std::function<void(bool)> func_; + CompletionQueueTag* ops_; + + static void StaticRun(grpc_experimental_completion_queue_functor* cb, + int ok) { + static_cast<CallbackWithSuccessTag*>(cb)->Run(static_cast<bool>(ok)); + } + void Run(bool ok) { + void* ignored = ops_; + // Allow a "false" return value from FinalizeResult to silence the + // callback, just as it silences a CQ tag in the async cases #ifndef NDEBUG - auto* ops = ops_; + auto* ops = ops_; #endif - bool do_callback = ops_->FinalizeResult(&ignored, &ok); + bool do_callback = ops_->FinalizeResult(&ignored, &ok); GPR_CODEGEN_DEBUG_ASSERT(ignored == ops); - - if (do_callback) { - CatchingCallback(func_, ok); - } - } -}; - -} // namespace internal -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H + + if (do_callback) { + CatchingCallback(func_, ok); + } + } +}; + +} // namespace internal +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_CALLBACK_COMMON_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h index ea0752d90e..da3b6726d3 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/channel_interface.h @@ -16,15 +16,15 @@ * */ -#if defined(__GNUC__) -#pragma GCC system_header -#endif - +#if defined(__GNUC__) +#pragma GCC system_header +#endif + #ifndef GRPCPP_IMPL_CODEGEN_CHANNEL_INTERFACE_H #define GRPCPP_IMPL_CODEGEN_CHANNEL_INTERFACE_H #include <grpc/impl/codegen/connectivity_state.h> -#include <grpcpp/impl/codegen/call.h> +#include <grpcpp/impl/codegen/call.h> #include <grpcpp/impl/codegen/status.h> #include <grpcpp/impl/codegen/time.h> @@ -37,7 +37,7 @@ template <class W, class R> class ClientReaderWriter; namespace internal { template <class InputMessage, class OutputMessage> -class CallbackUnaryCallImpl; +class CallbackUnaryCallImpl; template <class R> class ClientAsyncReaderFactory; template <class W> @@ -46,12 +46,12 @@ template <class W, class R> class ClientAsyncReaderWriterFactory; template <class R> class ClientAsyncResponseReaderFactory; -template <class W, class R> -class ClientCallbackReaderWriterFactory; -template <class R> -class ClientCallbackReaderFactory; -template <class W> -class ClientCallbackWriterFactory; +template <class W, class R> +class ClientCallbackReaderWriterFactory; +template <class R> +class ClientCallbackReaderFactory; +template <class W> +class ClientCallbackWriterFactory; class ClientCallbackUnaryFactory; } // namespace internal @@ -67,7 +67,7 @@ namespace internal { class Call; class CallOpSetInterface; class RpcMethod; -class InterceptedChannel; +class InterceptedChannel; template <class InputMessage, class OutputMessage> class BlockingUnaryCallImpl; } // namespace internal @@ -122,20 +122,20 @@ class ChannelInterface { friend class ::grpc::internal::ClientAsyncReaderWriterFactory; template <class R> friend class ::grpc::internal::ClientAsyncResponseReaderFactory; - template <class W, class R> + template <class W, class R> friend class ::grpc::internal::ClientCallbackReaderWriterFactory; - template <class R> + template <class R> friend class ::grpc::internal::ClientCallbackReaderFactory; - template <class W> + template <class W> friend class ::grpc::internal::ClientCallbackWriterFactory; friend class ::grpc::internal::ClientCallbackUnaryFactory; template <class InputMessage, class OutputMessage> friend class ::grpc::internal::BlockingUnaryCallImpl; - template <class InputMessage, class OutputMessage> + template <class InputMessage, class OutputMessage> friend class ::grpc::internal::CallbackUnaryCallImpl; friend class ::grpc::internal::RpcMethod; friend class ::grpc::experimental::DelegatingChannel; - friend class ::grpc::internal::InterceptedChannel; + friend class ::grpc::internal::InterceptedChannel; virtual internal::Call CreateCall(const internal::RpcMethod& method, ::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; @@ -148,28 +148,28 @@ class ChannelInterface { void* tag) = 0; virtual bool WaitForStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline) = 0; - - // EXPERIMENTAL - // This is needed to keep codegen_test_minimal happy. InterceptedChannel needs - // to make use of this but can't directly call Channel's implementation - // because of the test. - // Returns an empty Call object (rather than being pure) since this is a new - // method and adding a new pure method to an interface would be a breaking - // change (even though this is private and non-API) + + // EXPERIMENTAL + // This is needed to keep codegen_test_minimal happy. InterceptedChannel needs + // to make use of this but can't directly call Channel's implementation + // because of the test. + // Returns an empty Call object (rather than being pure) since this is a new + // method and adding a new pure method to an interface would be a breaking + // change (even though this is private and non-API) virtual internal::Call CreateCallInternal( const internal::RpcMethod& /*method*/, ::grpc::ClientContext* /*context*/, ::grpc::CompletionQueue* /*cq*/, size_t /*interceptor_pos*/) { - return internal::Call(); - } - - // EXPERIMENTAL - // A method to get the callbackable completion queue associated with this - // channel. If the return value is nullptr, this channel doesn't support - // callback operations. - // TODO(vjpai): Consider a better default like using a global CQ - // Returns nullptr (rather than being pure) since this is a post-1.0 method - // and adding a new pure method to an interface would be a breaking change - // (even though this is private and non-API) + return internal::Call(); + } + + // EXPERIMENTAL + // A method to get the callbackable completion queue associated with this + // channel. If the return value is nullptr, this channel doesn't support + // callback operations. + // TODO(vjpai): Consider a better default like using a global CQ + // Returns nullptr (rather than being pure) since this is a post-1.0 method + // and adding a new pure method to an interface would be a breaking change + // (even though this is private and non-API) virtual ::grpc::CompletionQueue* CallbackCQ() { return nullptr; } }; } // namespace grpc diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h index 90c817ceaa..560edf491d 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_callback.h @@ -1,25 +1,25 @@ -/* - * +/* + * * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H -#define GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H +#define GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H #include <atomic> #include <functional> - + #include <grpcpp/impl/codegen/call.h> #include <grpcpp/impl/codegen/call_op_set.h> #include <grpcpp/impl/codegen/callback_common.h> @@ -27,8 +27,8 @@ #include <grpcpp/impl/codegen/config.h> #include <grpcpp/impl/codegen/core_codegen_interface.h> #include <grpcpp/impl/codegen/status.h> - -namespace grpc { + +namespace grpc { class Channel; class ClientContext; @@ -1190,30 +1190,30 @@ class ClientCallbackUnaryFactory { } // namespace internal // TODO(vjpai): Remove namespace experimental when de-experimentalized fully. -namespace experimental { - -template <class Response> +namespace experimental { + +template <class Response> using ClientCallbackReader = ::grpc::ClientCallbackReader<Response>; -template <class Request> +template <class Request> using ClientCallbackWriter = ::grpc::ClientCallbackWriter<Request>; - -template <class Request, class Response> + +template <class Request, class Response> using ClientCallbackReaderWriter = ::grpc::ClientCallbackReaderWriter<Request, Response>; - -template <class Response> + +template <class Response> using ClientReadReactor = ::grpc::ClientReadReactor<Response>; - -template <class Request> + +template <class Request> using ClientWriteReactor = ::grpc::ClientWriteReactor<Request>; - -template <class Request, class Response> + +template <class Request, class Response> using ClientBidiReactor = ::grpc::ClientBidiReactor<Request, Response>; - + typedef ::grpc::ClientUnaryReactor ClientUnaryReactor; -} // namespace experimental +} // namespace experimental -} // namespace grpc -#endif // GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H +} // namespace grpc +#endif // GRPCPP_IMPL_CODEGEN_CLIENT_CALLBACK_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h index 78be1f7597..3d59da196b 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_interceptor.h @@ -1,190 +1,190 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H -#define GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H - -#include <memory> -#include <vector> - -#include <grpcpp/impl/codegen/interceptor.h> -#include <grpcpp/impl/codegen/rpc_method.h> -#include <grpcpp/impl/codegen/string_ref.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H +#define GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H + +#include <memory> +#include <vector> + +#include <grpcpp/impl/codegen/interceptor.h> +#include <grpcpp/impl/codegen/rpc_method.h> +#include <grpcpp/impl/codegen/string_ref.h> + namespace grpc { - + class Channel; -class ClientContext; - -namespace internal { -class InterceptorBatchMethodsImpl; -} - -namespace experimental { -class ClientRpcInfo; - -// A factory interface for creation of client interceptors. A vector of -// factories can be provided at channel creation which will be used to create a -// new vector of client interceptors per RPC. Client interceptor authors should -// create a subclass of ClientInterceptorFactorInterface which creates objects -// of their interceptors. -class ClientInterceptorFactoryInterface { - public: - virtual ~ClientInterceptorFactoryInterface() {} - // Returns a pointer to an Interceptor object on successful creation, nullptr - // otherwise. If nullptr is returned, this server interceptor factory is - // ignored for the purposes of that RPC. - virtual Interceptor* CreateClientInterceptor(ClientRpcInfo* info) = 0; -}; -} // namespace experimental - -namespace internal { -extern experimental::ClientInterceptorFactoryInterface* - g_global_client_interceptor_factory; -} - -/// ClientRpcInfo represents the state of a particular RPC as it -/// appears to an interceptor. It is created and owned by the library and -/// passed to the CreateClientInterceptor method of the application's -/// ClientInterceptorFactoryInterface implementation -namespace experimental { -class ClientRpcInfo { - public: - // TODO(yashykt): Stop default-constructing ClientRpcInfo and remove UNKNOWN - // from the list of possible Types. - /// Type categorizes RPCs by unary or streaming type - enum class Type { - UNARY, - CLIENT_STREAMING, - SERVER_STREAMING, - BIDI_STREAMING, - UNKNOWN // UNKNOWN is not API and will be removed later - }; - +class ClientContext; + +namespace internal { +class InterceptorBatchMethodsImpl; +} + +namespace experimental { +class ClientRpcInfo; + +// A factory interface for creation of client interceptors. A vector of +// factories can be provided at channel creation which will be used to create a +// new vector of client interceptors per RPC. Client interceptor authors should +// create a subclass of ClientInterceptorFactorInterface which creates objects +// of their interceptors. +class ClientInterceptorFactoryInterface { + public: + virtual ~ClientInterceptorFactoryInterface() {} + // Returns a pointer to an Interceptor object on successful creation, nullptr + // otherwise. If nullptr is returned, this server interceptor factory is + // ignored for the purposes of that RPC. + virtual Interceptor* CreateClientInterceptor(ClientRpcInfo* info) = 0; +}; +} // namespace experimental + +namespace internal { +extern experimental::ClientInterceptorFactoryInterface* + g_global_client_interceptor_factory; +} + +/// ClientRpcInfo represents the state of a particular RPC as it +/// appears to an interceptor. It is created and owned by the library and +/// passed to the CreateClientInterceptor method of the application's +/// ClientInterceptorFactoryInterface implementation +namespace experimental { +class ClientRpcInfo { + public: + // TODO(yashykt): Stop default-constructing ClientRpcInfo and remove UNKNOWN + // from the list of possible Types. + /// Type categorizes RPCs by unary or streaming type + enum class Type { + UNARY, + CLIENT_STREAMING, + SERVER_STREAMING, + BIDI_STREAMING, + UNKNOWN // UNKNOWN is not API and will be removed later + }; + ~ClientRpcInfo() {} - - // Delete copy constructor but allow default move constructor - ClientRpcInfo(const ClientRpcInfo&) = delete; - ClientRpcInfo(ClientRpcInfo&&) = default; - - // Getter methods - - /// Return the fully-specified method name - const char* method() const { return method_; } - - /// Return a pointer to the channel on which the RPC is being sent - ChannelInterface* channel() { return channel_; } - - /// Return a pointer to the underlying ClientContext structure associated - /// with the RPC to support features that apply to it + + // Delete copy constructor but allow default move constructor + ClientRpcInfo(const ClientRpcInfo&) = delete; + ClientRpcInfo(ClientRpcInfo&&) = default; + + // Getter methods + + /// Return the fully-specified method name + const char* method() const { return method_; } + + /// Return a pointer to the channel on which the RPC is being sent + ChannelInterface* channel() { return channel_; } + + /// Return a pointer to the underlying ClientContext structure associated + /// with the RPC to support features that apply to it grpc::ClientContext* client_context() { return ctx_; } - - /// Return the type of the RPC (unary or a streaming flavor) - Type type() const { return type_; } - - private: - static_assert(Type::UNARY == - static_cast<Type>(internal::RpcMethod::NORMAL_RPC), - "violated expectation about Type enum"); - static_assert(Type::CLIENT_STREAMING == - static_cast<Type>(internal::RpcMethod::CLIENT_STREAMING), - "violated expectation about Type enum"); - static_assert(Type::SERVER_STREAMING == - static_cast<Type>(internal::RpcMethod::SERVER_STREAMING), - "violated expectation about Type enum"); - static_assert(Type::BIDI_STREAMING == - static_cast<Type>(internal::RpcMethod::BIDI_STREAMING), - "violated expectation about Type enum"); - - // Default constructor should only be used by ClientContext - ClientRpcInfo() = default; - - // Constructor will only be called from ClientContext + + /// Return the type of the RPC (unary or a streaming flavor) + Type type() const { return type_; } + + private: + static_assert(Type::UNARY == + static_cast<Type>(internal::RpcMethod::NORMAL_RPC), + "violated expectation about Type enum"); + static_assert(Type::CLIENT_STREAMING == + static_cast<Type>(internal::RpcMethod::CLIENT_STREAMING), + "violated expectation about Type enum"); + static_assert(Type::SERVER_STREAMING == + static_cast<Type>(internal::RpcMethod::SERVER_STREAMING), + "violated expectation about Type enum"); + static_assert(Type::BIDI_STREAMING == + static_cast<Type>(internal::RpcMethod::BIDI_STREAMING), + "violated expectation about Type enum"); + + // Default constructor should only be used by ClientContext + ClientRpcInfo() = default; + + // Constructor will only be called from ClientContext ClientRpcInfo(grpc::ClientContext* ctx, internal::RpcMethod::RpcType type, const char* method, grpc::ChannelInterface* channel) - : ctx_(ctx), - type_(static_cast<Type>(type)), - method_(method), - channel_(channel) {} - - // Move assignment should only be used by ClientContext - // TODO(yashykt): Delete move assignment - ClientRpcInfo& operator=(ClientRpcInfo&&) = default; - - // Runs interceptor at pos \a pos. - void RunInterceptor( - experimental::InterceptorBatchMethods* interceptor_methods, size_t pos) { - GPR_CODEGEN_ASSERT(pos < interceptors_.size()); - interceptors_[pos]->Intercept(interceptor_methods); - } - - void RegisterInterceptors( - const std::vector<std::unique_ptr< - experimental::ClientInterceptorFactoryInterface>>& creators, - size_t interceptor_pos) { - if (interceptor_pos > creators.size()) { - // No interceptors to register - return; - } + : ctx_(ctx), + type_(static_cast<Type>(type)), + method_(method), + channel_(channel) {} + + // Move assignment should only be used by ClientContext + // TODO(yashykt): Delete move assignment + ClientRpcInfo& operator=(ClientRpcInfo&&) = default; + + // Runs interceptor at pos \a pos. + void RunInterceptor( + experimental::InterceptorBatchMethods* interceptor_methods, size_t pos) { + GPR_CODEGEN_ASSERT(pos < interceptors_.size()); + interceptors_[pos]->Intercept(interceptor_methods); + } + + void RegisterInterceptors( + const std::vector<std::unique_ptr< + experimental::ClientInterceptorFactoryInterface>>& creators, + size_t interceptor_pos) { + if (interceptor_pos > creators.size()) { + // No interceptors to register + return; + } // NOTE: The following is not a range-based for loop because it will only // iterate over a portion of the creators vector. - for (auto it = creators.begin() + interceptor_pos; it != creators.end(); - ++it) { - auto* interceptor = (*it)->CreateClientInterceptor(this); - if (interceptor != nullptr) { - interceptors_.push_back( - std::unique_ptr<experimental::Interceptor>(interceptor)); - } - } - if (internal::g_global_client_interceptor_factory != nullptr) { - interceptors_.push_back(std::unique_ptr<experimental::Interceptor>( - internal::g_global_client_interceptor_factory - ->CreateClientInterceptor(this))); - } - } - + for (auto it = creators.begin() + interceptor_pos; it != creators.end(); + ++it) { + auto* interceptor = (*it)->CreateClientInterceptor(this); + if (interceptor != nullptr) { + interceptors_.push_back( + std::unique_ptr<experimental::Interceptor>(interceptor)); + } + } + if (internal::g_global_client_interceptor_factory != nullptr) { + interceptors_.push_back(std::unique_ptr<experimental::Interceptor>( + internal::g_global_client_interceptor_factory + ->CreateClientInterceptor(this))); + } + } + grpc::ClientContext* ctx_ = nullptr; - // TODO(yashykt): make type_ const once move-assignment is deleted - Type type_{Type::UNKNOWN}; - const char* method_ = nullptr; - grpc::ChannelInterface* channel_ = nullptr; - std::vector<std::unique_ptr<experimental::Interceptor>> interceptors_; - bool hijacked_ = false; - size_t hijacked_interceptor_ = 0; - - friend class internal::InterceptorBatchMethodsImpl; + // TODO(yashykt): make type_ const once move-assignment is deleted + Type type_{Type::UNKNOWN}; + const char* method_ = nullptr; + grpc::ChannelInterface* channel_ = nullptr; + std::vector<std::unique_ptr<experimental::Interceptor>> interceptors_; + bool hijacked_ = false; + size_t hijacked_interceptor_ = 0; + + friend class internal::InterceptorBatchMethodsImpl; friend class grpc::ClientContext; -}; - -// PLEASE DO NOT USE THIS. ALWAYS PREFER PER CHANNEL INTERCEPTORS OVER A GLOBAL -// INTERCEPTOR. IF USAGE IS ABSOLUTELY NECESSARY, PLEASE READ THE SAFETY NOTES. -// Registers a global client interceptor factory object, which is used for all +}; + +// PLEASE DO NOT USE THIS. ALWAYS PREFER PER CHANNEL INTERCEPTORS OVER A GLOBAL +// INTERCEPTOR. IF USAGE IS ABSOLUTELY NECESSARY, PLEASE READ THE SAFETY NOTES. +// Registers a global client interceptor factory object, which is used for all // RPCs made in this process. The application is responsible for maintaining the // life of the object while gRPC operations are in progress. The global // interceptor factory should only be registered once at the start of the // process before any gRPC operations have begun. -void RegisterGlobalClientInterceptorFactory( - ClientInterceptorFactoryInterface* factory); - +void RegisterGlobalClientInterceptorFactory( + ClientInterceptorFactoryInterface* factory); + // For testing purposes only void TestOnlyResetGlobalClientInterceptorFactory(); -} // namespace experimental -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H +} // namespace experimental +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_CLIENT_INTERCEPTOR_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h index 098bb50ee2..2c13cedf64 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/client_unary_call.h @@ -47,18 +47,18 @@ class BlockingUnaryCallImpl { grpc::ClientContext* context, const InputMessage& request, OutputMessage* result) { ::grpc::CompletionQueue cq(grpc_completion_queue_attributes{ - GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING, - nullptr}); // Pluckable completion queue + GRPC_CQ_CURRENT_VERSION, GRPC_CQ_PLUCK, GRPC_CQ_DEFAULT_POLLING, + nullptr}); // Pluckable completion queue ::grpc::internal::Call call(channel->CreateCall(method, context, &cq)); CallOpSet<CallOpSendInitialMetadata, CallOpSendMessage, CallOpRecvInitialMetadata, CallOpRecvMessage<OutputMessage>, CallOpClientSendClose, CallOpClientRecvStatus> ops; - status_ = ops.SendMessagePtr(&request); + status_ = ops.SendMessagePtr(&request); if (!status_.ok()) { return; } - ops.SendInitialMetadata(&context->send_initial_metadata_, + ops.SendInitialMetadata(&context->send_initial_metadata_, context->initial_metadata_flags()); ops.RecvInitialMetadata(context); ops.RecvMessage(result); @@ -66,17 +66,17 @@ class BlockingUnaryCallImpl { ops.ClientSendClose(); ops.ClientRecvStatus(context, &status_); call.PerformOps(&ops); - cq.Pluck(&ops); - // Some of the ops might fail. If the ops fail in the core layer, status - // would reflect the error. But, if the ops fail in the C++ layer, the - // status would still be the same as the one returned by gRPC Core. This can - // happen if deserialization of the message fails. - // TODO(yashykt): If deserialization fails, but the status received is OK, - // then it might be a good idea to change the status to something better - // than StatusCode::UNIMPLEMENTED to reflect this. - if (!ops.got_message && status_.ok()) { - status_ = Status(StatusCode::UNIMPLEMENTED, - "No message returned for unary request"); + cq.Pluck(&ops); + // Some of the ops might fail. If the ops fail in the core layer, status + // would reflect the error. But, if the ops fail in the C++ layer, the + // status would still be the same as the one returned by gRPC Core. This can + // happen if deserialization of the message fails. + // TODO(yashykt): If deserialization fails, but the status received is OK, + // then it might be a good idea to change the status to something better + // than StatusCode::UNIMPLEMENTED to reflect this. + if (!ops.got_message && status_.ok()) { + status_ = Status(StatusCode::UNIMPLEMENTED, + "No message returned for unary request"); } } Status status() { return status_; } diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/completion_queue_tag.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/completion_queue_tag.h index 304386a9ec..b97dde069c 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/completion_queue_tag.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/completion_queue_tag.h @@ -26,25 +26,25 @@ namespace internal { class CompletionQueueTag { public: virtual ~CompletionQueueTag() {} - - /// FinalizeResult must be called before informing user code that the - /// operation bound to the underlying core completion queue tag has - /// completed. In practice, this means: - /// - /// 1. For the sync API - before returning from Pluck - /// 2. For the CQ-based async API - before returning from Next - /// 3. For the callback-based API - before invoking the user callback - /// - /// This is the method that translates from core-side tag/status to - /// C++ API-observable tag/status. - /// - /// The return value is the status of the operation (returning status is the - /// general behavior of this function). If this function returns false, the - /// tag is dropped and not returned from the completion queue: this concept is - /// for events that are observed at core but not requested by the user - /// application (e.g., server shutdown, for server unimplemented method - /// responses, or for cases where a server-side RPC doesn't have a completion - /// notification registered using AsyncNotifyWhenDone) + + /// FinalizeResult must be called before informing user code that the + /// operation bound to the underlying core completion queue tag has + /// completed. In practice, this means: + /// + /// 1. For the sync API - before returning from Pluck + /// 2. For the CQ-based async API - before returning from Next + /// 3. For the callback-based API - before invoking the user callback + /// + /// This is the method that translates from core-side tag/status to + /// C++ API-observable tag/status. + /// + /// The return value is the status of the operation (returning status is the + /// general behavior of this function). If this function returns false, the + /// tag is dropped and not returned from the completion queue: this concept is + /// for events that are observed at core but not requested by the user + /// application (e.g., server shutdown, for server unimplemented method + /// responses, or for cases where a server-side RPC doesn't have a completion + /// notification registered using AsyncNotifyWhenDone) virtual bool FinalizeResult(void** tag, bool* status) = 0; }; } // namespace internal diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h index c4012fb00c..cb3088f985 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/config_protobuf.h @@ -63,12 +63,12 @@ #define GRPC_CUSTOM_CODEDINPUTSTREAM ::google::protobuf::io::CodedInputStream #endif -#ifndef GRPC_CUSTOM_JSONUTIL +#ifndef GRPC_CUSTOM_JSONUTIL #include <google/protobuf/util/json_util.h> -#define GRPC_CUSTOM_JSONUTIL ::google::protobuf::util -#define GRPC_CUSTOM_UTIL_STATUS ::google::protobuf::util::Status -#endif - +#define GRPC_CUSTOM_JSONUTIL ::google::protobuf::util +#define GRPC_CUSTOM_UTIL_STATUS ::google::protobuf::util::Status +#endif + namespace grpc { namespace protobuf { @@ -86,12 +86,12 @@ typedef GRPC_CUSTOM_SERVICEDESCRIPTOR ServiceDescriptor; typedef GRPC_CUSTOM_SIMPLEDESCRIPTORDATABASE SimpleDescriptorDatabase; typedef GRPC_CUSTOM_SOURCELOCATION SourceLocation; -namespace util { -typedef GRPC_CUSTOM_UTIL_STATUS Status; -} // namespace util - -namespace json = GRPC_CUSTOM_JSONUTIL; - +namespace util { +typedef GRPC_CUSTOM_UTIL_STATUS Status; +} // namespace util + +namespace json = GRPC_CUSTOM_JSONUTIL; + namespace io { typedef GRPC_CUSTOM_ZEROCOPYOUTPUTSTREAM ZeroCopyOutputStream; typedef GRPC_CUSTOM_ZEROCOPYINPUTSTREAM ZeroCopyInputStream; diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h index 50c8da4ffe..f050930be7 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen.h @@ -42,7 +42,7 @@ class CoreCodegen final : public CoreCodegenInterface { void* reserved) override; grpc_completion_queue* grpc_completion_queue_create_for_pluck( void* reserved) override; - void grpc_completion_queue_shutdown(grpc_completion_queue* cq) override; + void grpc_completion_queue_shutdown(grpc_completion_queue* cq) 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, @@ -64,9 +64,9 @@ class CoreCodegen final : public CoreCodegenInterface { void gpr_cv_signal(gpr_cv* cv) override; void gpr_cv_broadcast(gpr_cv* cv) override; - grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops, - size_t nops, void* tag, - void* reserved) override; + grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops, + size_t nops, void* tag, + void* reserved) override; grpc_call_error grpc_call_cancel_with_status(grpc_call* call, grpc_status_code status, const char* description, diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h index c08cf6c683..837948a583 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/core_codegen_interface.h @@ -53,7 +53,7 @@ class CoreCodegenInterface { void* reserved) = 0; virtual grpc_completion_queue* grpc_completion_queue_create_for_pluck( void* reserved) = 0; - virtual void grpc_completion_queue_shutdown(grpc_completion_queue* cq) = 0; + virtual void grpc_completion_queue_shutdown(grpc_completion_queue* cq) = 0; virtual void grpc_completion_queue_destroy(grpc_completion_queue* cq) = 0; virtual grpc_event grpc_completion_queue_pluck(grpc_completion_queue* cq, void* tag, @@ -104,9 +104,9 @@ class CoreCodegenInterface { virtual grpc_slice grpc_slice_new_with_len(void* p, size_t len, void (*destroy)(void*, size_t)) = 0; - virtual grpc_call_error grpc_call_start_batch(grpc_call* call, - const grpc_op* ops, size_t nops, - void* tag, void* reserved) = 0; + virtual grpc_call_error grpc_call_start_batch(grpc_call* call, + const grpc_op* ops, size_t nops, + void* tag, void* reserved) = 0; virtual grpc_call_error grpc_call_cancel_with_status(grpc_call* call, grpc_status_code status, const char* description, @@ -150,15 +150,15 @@ extern CoreCodegenInterface* g_core_codegen_interface; } \ } while (0) -/// Codegen specific version of \a GPR_DEBUG_ASSERT. -#ifndef NDEBUG -#define GPR_CODEGEN_DEBUG_ASSERT(x) GPR_CODEGEN_ASSERT(x) -#else -#define GPR_CODEGEN_DEBUG_ASSERT(x) \ - do { \ - } while (0) -#endif - +/// Codegen specific version of \a GPR_DEBUG_ASSERT. +#ifndef NDEBUG +#define GPR_CODEGEN_DEBUG_ASSERT(x) GPR_CODEGEN_ASSERT(x) +#else +#define GPR_CODEGEN_DEBUG_ASSERT(x) \ + do { \ + } while (0) +#endif + } // namespace grpc #endif // GRPCPP_IMPL_CODEGEN_CORE_CODEGEN_INTERFACE_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h index c729970ca8..d3472737ba 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/intercepted_channel.h @@ -1,84 +1,84 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H -#define GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H - -#include <grpcpp/impl/codegen/channel_interface.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H +#define GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H + +#include <grpcpp/impl/codegen/channel_interface.h> + namespace grpc { class CompletionQueue; -namespace internal { - -class InterceptorBatchMethodsImpl; - -/// An InterceptedChannel is available to client Interceptors. An -/// InterceptedChannel is unique to an interceptor, and when an RPC is started -/// on this channel, only those interceptors that come after this interceptor -/// see the RPC. -class InterceptedChannel : public ChannelInterface { - public: - virtual ~InterceptedChannel() { channel_ = nullptr; } - - /// 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) override { - return channel_->GetState(try_to_connect); - } - - private: - InterceptedChannel(ChannelInterface* channel, size_t pos) - : channel_(channel), interceptor_pos_(pos) {} - +namespace internal { + +class InterceptorBatchMethodsImpl; + +/// An InterceptedChannel is available to client Interceptors. An +/// InterceptedChannel is unique to an interceptor, and when an RPC is started +/// on this channel, only those interceptors that come after this interceptor +/// see the RPC. +class InterceptedChannel : public ChannelInterface { + public: + virtual ~InterceptedChannel() { channel_ = nullptr; } + + /// 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) override { + return channel_->GetState(try_to_connect); + } + + private: + InterceptedChannel(ChannelInterface* channel, size_t pos) + : channel_(channel), interceptor_pos_(pos) {} + Call CreateCall(const RpcMethod& method, ::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override { - return channel_->CreateCallInternal(method, context, cq, interceptor_pos_); - } - - void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) override { - return channel_->PerformOpsOnCall(ops, call); - } - void* RegisterMethod(const char* method) override { - return channel_->RegisterMethod(method); - } - - void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, + return channel_->CreateCallInternal(method, context, cq, interceptor_pos_); + } + + void PerformOpsOnCall(CallOpSetInterface* ops, Call* call) override { + return channel_->PerformOpsOnCall(ops, call); + } + void* RegisterMethod(const char* method) override { + return channel_->RegisterMethod(method); + } + + void NotifyOnStateChangeImpl(grpc_connectivity_state last_observed, gpr_timespec deadline, ::grpc::CompletionQueue* cq, - void* tag) override { - return channel_->NotifyOnStateChangeImpl(last_observed, deadline, cq, tag); - } - bool WaitForStateChangeImpl(grpc_connectivity_state last_observed, - gpr_timespec deadline) override { - return channel_->WaitForStateChangeImpl(last_observed, deadline); - } - + void* tag) override { + return channel_->NotifyOnStateChangeImpl(last_observed, deadline, cq, tag); + } + bool WaitForStateChangeImpl(grpc_connectivity_state last_observed, + gpr_timespec deadline) override { + return channel_->WaitForStateChangeImpl(last_observed, deadline); + } + ::grpc::CompletionQueue* CallbackCQ() override { return channel_->CallbackCQ(); } - - ChannelInterface* channel_; - size_t interceptor_pos_; - - friend class InterceptorBatchMethodsImpl; -}; -} // namespace internal -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H + + ChannelInterface* channel_; + size_t interceptor_pos_; + + friend class InterceptorBatchMethodsImpl; +}; +} // namespace internal +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTED_CHANNEL_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h index d0afa03a17..5c9cb78db5 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor.h @@ -1,228 +1,228 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H -#define GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H +#define GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H + #include <memory> -#include <grpc/impl/codegen/grpc_types.h> -#include <grpcpp/impl/codegen/byte_buffer.h> -#include <grpcpp/impl/codegen/config.h> -#include <grpcpp/impl/codegen/core_codegen_interface.h> -#include <grpcpp/impl/codegen/metadata_map.h> - -namespace grpc { - -class ChannelInterface; -class Status; - -namespace experimental { - -/// An enumeration of different possible points at which the \a Intercept -/// method of the \a Interceptor interface may be called. Any given call -/// to \a Intercept will include one or more of these hook points, and -/// each hook point makes certain types of information available to the -/// interceptor. -/// In these enumeration names, PRE_SEND means that an interception has taken -/// place between the time the application provided a certain type of data -/// (e.g., initial metadata, status) and the time that that data goes to the -/// other side. POST_SEND means that the data has been committed for going to -/// the other side (even if it has not yet been received at the other side). -/// PRE_RECV means an interception between the time that a certain -/// operation has been requested and it is available. POST_RECV means that a -/// result is available but has not yet been passed back to the application. -/// A batch of interception points will only contain either PRE or POST hooks -/// but not both types. For example, a batch with PRE_SEND hook points will not -/// contain POST_RECV or POST_SEND ops. Likewise, a batch with POST_* ops can -/// not contain PRE_* ops. -enum class InterceptionHookPoints { - /// The first three in this list are for clients and servers - PRE_SEND_INITIAL_METADATA, - PRE_SEND_MESSAGE, - POST_SEND_MESSAGE, - PRE_SEND_STATUS, // server only - PRE_SEND_CLOSE, // client only: WritesDone for stream; after write in unary - /// The following three are for hijacked clients only. A batch with PRE_RECV_* - /// hook points will never contain hook points of other types. - PRE_RECV_INITIAL_METADATA, - PRE_RECV_MESSAGE, - PRE_RECV_STATUS, - /// The following two are for all clients and servers - POST_RECV_INITIAL_METADATA, - POST_RECV_MESSAGE, - POST_RECV_STATUS, // client only - POST_RECV_CLOSE, // server only - /// This is a special hook point available to both clients and servers when - /// TryCancel() is performed. - /// - No other hook points will be present along with this. - /// - It is illegal for an interceptor to block/delay this operation. - /// - ALL interceptors see this hook point irrespective of whether the - /// RPC was hijacked or not. - PRE_SEND_CANCEL, - NUM_INTERCEPTION_HOOKS -}; - -/// Class that is passed as an argument to the \a Intercept method -/// of the application's \a Interceptor interface implementation. It has five -/// purposes: -/// 1. Indicate which hook points are present at a specific interception -/// 2. Allow an interceptor to inform the library that an RPC should -/// continue to the next stage of its processing (which may be another -/// interceptor or the main path of the library) -/// 3. Allow an interceptor to hijack the processing of the RPC (only for -/// client-side RPCs with PRE_SEND_INITIAL_METADATA) so that it does not -/// proceed with normal processing beyond that stage -/// 4. Access the relevant fields of an RPC at each interception point -/// 5. Set some fields of an RPC at each interception point, when possible -class InterceptorBatchMethods { - public: +#include <grpc/impl/codegen/grpc_types.h> +#include <grpcpp/impl/codegen/byte_buffer.h> +#include <grpcpp/impl/codegen/config.h> +#include <grpcpp/impl/codegen/core_codegen_interface.h> +#include <grpcpp/impl/codegen/metadata_map.h> + +namespace grpc { + +class ChannelInterface; +class Status; + +namespace experimental { + +/// An enumeration of different possible points at which the \a Intercept +/// method of the \a Interceptor interface may be called. Any given call +/// to \a Intercept will include one or more of these hook points, and +/// each hook point makes certain types of information available to the +/// interceptor. +/// In these enumeration names, PRE_SEND means that an interception has taken +/// place between the time the application provided a certain type of data +/// (e.g., initial metadata, status) and the time that that data goes to the +/// other side. POST_SEND means that the data has been committed for going to +/// the other side (even if it has not yet been received at the other side). +/// PRE_RECV means an interception between the time that a certain +/// operation has been requested and it is available. POST_RECV means that a +/// result is available but has not yet been passed back to the application. +/// A batch of interception points will only contain either PRE or POST hooks +/// but not both types. For example, a batch with PRE_SEND hook points will not +/// contain POST_RECV or POST_SEND ops. Likewise, a batch with POST_* ops can +/// not contain PRE_* ops. +enum class InterceptionHookPoints { + /// The first three in this list are for clients and servers + PRE_SEND_INITIAL_METADATA, + PRE_SEND_MESSAGE, + POST_SEND_MESSAGE, + PRE_SEND_STATUS, // server only + PRE_SEND_CLOSE, // client only: WritesDone for stream; after write in unary + /// The following three are for hijacked clients only. A batch with PRE_RECV_* + /// hook points will never contain hook points of other types. + PRE_RECV_INITIAL_METADATA, + PRE_RECV_MESSAGE, + PRE_RECV_STATUS, + /// The following two are for all clients and servers + POST_RECV_INITIAL_METADATA, + POST_RECV_MESSAGE, + POST_RECV_STATUS, // client only + POST_RECV_CLOSE, // server only + /// This is a special hook point available to both clients and servers when + /// TryCancel() is performed. + /// - No other hook points will be present along with this. + /// - It is illegal for an interceptor to block/delay this operation. + /// - ALL interceptors see this hook point irrespective of whether the + /// RPC was hijacked or not. + PRE_SEND_CANCEL, + NUM_INTERCEPTION_HOOKS +}; + +/// Class that is passed as an argument to the \a Intercept method +/// of the application's \a Interceptor interface implementation. It has five +/// purposes: +/// 1. Indicate which hook points are present at a specific interception +/// 2. Allow an interceptor to inform the library that an RPC should +/// continue to the next stage of its processing (which may be another +/// interceptor or the main path of the library) +/// 3. Allow an interceptor to hijack the processing of the RPC (only for +/// client-side RPCs with PRE_SEND_INITIAL_METADATA) so that it does not +/// proceed with normal processing beyond that stage +/// 4. Access the relevant fields of an RPC at each interception point +/// 5. Set some fields of an RPC at each interception point, when possible +class InterceptorBatchMethods { + public: virtual ~InterceptorBatchMethods() {} - /// Determine whether the current batch has an interception hook point - /// of type \a type - virtual bool QueryInterceptionHookPoint(InterceptionHookPoints type) = 0; - /// Signal that the interceptor is done intercepting the current batch of the - /// RPC. Every interceptor must either call Proceed or Hijack on each - /// interception. In most cases, only Proceed will be used. Explicit use of - /// Proceed is what enables interceptors to delay the processing of RPCs - /// while they perform other work. - /// Proceed is a no-op if the batch contains PRE_SEND_CANCEL. Simply returning - /// from the Intercept method does the job of continuing the RPC in this case. - /// This is because PRE_SEND_CANCEL is always in a separate batch and is not - /// allowed to be delayed. - virtual void Proceed() = 0; - /// Indicate that the interceptor has hijacked the RPC (only valid if the - /// batch contains send_initial_metadata on the client side). Later - /// interceptors in the interceptor list will not be called. Later batches - /// on the same RPC will go through interception, but only up to the point - /// of the hijacking interceptor. - virtual void Hijack() = 0; - - /// Send Message Methods - /// GetSerializedSendMessage and GetSendMessage/ModifySendMessage are the - /// available methods to view and modify the request payload. An interceptor - /// can access the payload in either serialized form or non-serialized form - /// but not both at the same time. - /// gRPC performs serialization in a lazy manner, which means - /// that a call to GetSerializedSendMessage will result in a serialization - /// operation if the payload stored is not in the serialized form already; the - /// non-serialized form will be lost and GetSendMessage will no longer return - /// a valid pointer, and this will remain true for later interceptors too. - /// This can change however if ModifySendMessage is used to replace the - /// current payload. Note that ModifySendMessage requires a new payload - /// message in the non-serialized form. This will overwrite the existing - /// payload irrespective of whether it had been serialized earlier. Also note - /// that gRPC Async API requires early serialization of the payload which - /// means that the payload would be available in the serialized form only - /// unless an interceptor replaces the payload with ModifySendMessage. - - /// Returns a modifable ByteBuffer holding the serialized form of the message - /// that is going to be sent. Valid for PRE_SEND_MESSAGE interceptions. - /// A return value of nullptr indicates that this ByteBuffer is not valid. - virtual ByteBuffer* GetSerializedSendMessage() = 0; - - /// Returns a non-modifiable pointer to the non-serialized form of the message - /// to be sent. Valid for PRE_SEND_MESSAGE interceptions. A return value of - /// nullptr indicates that this field is not valid. - virtual const void* GetSendMessage() = 0; - - /// Overwrites the message to be sent with \a message. \a message should be in - /// the non-serialized form expected by the method. Valid for PRE_SEND_MESSAGE - /// interceptions. Note that the interceptor is responsible for maintaining - /// the life of the message till it is serialized or it receives the - /// POST_SEND_MESSAGE interception point, whichever happens earlier. The - /// modifying interceptor may itself force early serialization by calling - /// GetSerializedSendMessage. - virtual void ModifySendMessage(const void* message) = 0; - - /// Checks whether the SEND MESSAGE op succeeded. Valid for POST_SEND_MESSAGE - /// interceptions. - virtual bool GetSendMessageStatus() = 0; - - /// Returns a modifiable multimap of the initial metadata to be sent. Valid - /// for PRE_SEND_INITIAL_METADATA interceptions. A value of nullptr indicates - /// that this field is not valid. + /// Determine whether the current batch has an interception hook point + /// of type \a type + virtual bool QueryInterceptionHookPoint(InterceptionHookPoints type) = 0; + /// Signal that the interceptor is done intercepting the current batch of the + /// RPC. Every interceptor must either call Proceed or Hijack on each + /// interception. In most cases, only Proceed will be used. Explicit use of + /// Proceed is what enables interceptors to delay the processing of RPCs + /// while they perform other work. + /// Proceed is a no-op if the batch contains PRE_SEND_CANCEL. Simply returning + /// from the Intercept method does the job of continuing the RPC in this case. + /// This is because PRE_SEND_CANCEL is always in a separate batch and is not + /// allowed to be delayed. + virtual void Proceed() = 0; + /// Indicate that the interceptor has hijacked the RPC (only valid if the + /// batch contains send_initial_metadata on the client side). Later + /// interceptors in the interceptor list will not be called. Later batches + /// on the same RPC will go through interception, but only up to the point + /// of the hijacking interceptor. + virtual void Hijack() = 0; + + /// Send Message Methods + /// GetSerializedSendMessage and GetSendMessage/ModifySendMessage are the + /// available methods to view and modify the request payload. An interceptor + /// can access the payload in either serialized form or non-serialized form + /// but not both at the same time. + /// gRPC performs serialization in a lazy manner, which means + /// that a call to GetSerializedSendMessage will result in a serialization + /// operation if the payload stored is not in the serialized form already; the + /// non-serialized form will be lost and GetSendMessage will no longer return + /// a valid pointer, and this will remain true for later interceptors too. + /// This can change however if ModifySendMessage is used to replace the + /// current payload. Note that ModifySendMessage requires a new payload + /// message in the non-serialized form. This will overwrite the existing + /// payload irrespective of whether it had been serialized earlier. Also note + /// that gRPC Async API requires early serialization of the payload which + /// means that the payload would be available in the serialized form only + /// unless an interceptor replaces the payload with ModifySendMessage. + + /// Returns a modifable ByteBuffer holding the serialized form of the message + /// that is going to be sent. Valid for PRE_SEND_MESSAGE interceptions. + /// A return value of nullptr indicates that this ByteBuffer is not valid. + virtual ByteBuffer* GetSerializedSendMessage() = 0; + + /// Returns a non-modifiable pointer to the non-serialized form of the message + /// to be sent. Valid for PRE_SEND_MESSAGE interceptions. A return value of + /// nullptr indicates that this field is not valid. + virtual const void* GetSendMessage() = 0; + + /// Overwrites the message to be sent with \a message. \a message should be in + /// the non-serialized form expected by the method. Valid for PRE_SEND_MESSAGE + /// interceptions. Note that the interceptor is responsible for maintaining + /// the life of the message till it is serialized or it receives the + /// POST_SEND_MESSAGE interception point, whichever happens earlier. The + /// modifying interceptor may itself force early serialization by calling + /// GetSerializedSendMessage. + virtual void ModifySendMessage(const void* message) = 0; + + /// Checks whether the SEND MESSAGE op succeeded. Valid for POST_SEND_MESSAGE + /// interceptions. + virtual bool GetSendMessageStatus() = 0; + + /// Returns a modifiable multimap of the initial metadata to be sent. Valid + /// for PRE_SEND_INITIAL_METADATA interceptions. A value of nullptr indicates + /// that this field is not valid. virtual std::multimap<TString, TString>* GetSendInitialMetadata() = 0; - - /// Returns the status to be sent. Valid for PRE_SEND_STATUS interceptions. - virtual Status GetSendStatus() = 0; - - /// Overwrites the status with \a status. Valid for PRE_SEND_STATUS - /// interceptions. - virtual void ModifySendStatus(const Status& status) = 0; - - /// Returns a modifiable multimap of the trailing metadata to be sent. Valid - /// for PRE_SEND_STATUS interceptions. A value of nullptr indicates - /// that this field is not valid. + + /// Returns the status to be sent. Valid for PRE_SEND_STATUS interceptions. + virtual Status GetSendStatus() = 0; + + /// Overwrites the status with \a status. Valid for PRE_SEND_STATUS + /// interceptions. + virtual void ModifySendStatus(const Status& status) = 0; + + /// Returns a modifiable multimap of the trailing metadata to be sent. Valid + /// for PRE_SEND_STATUS interceptions. A value of nullptr indicates + /// that this field is not valid. virtual std::multimap<TString, TString>* - GetSendTrailingMetadata() = 0; - - /// Returns a pointer to the modifiable received message. Note that the - /// message is already deserialized but the type is not set; the interceptor - /// should static_cast to the appropriate type before using it. This is valid + GetSendTrailingMetadata() = 0; + + /// Returns a pointer to the modifiable received message. Note that the + /// message is already deserialized but the type is not set; the interceptor + /// should static_cast to the appropriate type before using it. This is valid /// for PRE_RECV_MESSAGE and POST_RECV_MESSAGE interceptions; nullptr for not /// valid - virtual void* GetRecvMessage() = 0; - - /// Returns a modifiable multimap of the received initial metadata. + virtual void* GetRecvMessage() = 0; + + /// Returns a modifiable multimap of the received initial metadata. /// Valid for PRE_RECV_INITIAL_METADATA and POST_RECV_INITIAL_METADATA /// interceptions; nullptr if not valid - virtual std::multimap<grpc::string_ref, grpc::string_ref>* - GetRecvInitialMetadata() = 0; - + virtual std::multimap<grpc::string_ref, grpc::string_ref>* + GetRecvInitialMetadata() = 0; + /// Returns a modifiable view of the received status on PRE_RECV_STATUS and /// POST_RECV_STATUS interceptions; nullptr if not valid. - virtual Status* GetRecvStatus() = 0; - - /// Returns a modifiable multimap of the received trailing metadata on + virtual Status* GetRecvStatus() = 0; + + /// Returns a modifiable multimap of the received trailing metadata on /// PRE_RECV_STATUS and POST_RECV_STATUS interceptions; nullptr if not valid - virtual std::multimap<grpc::string_ref, grpc::string_ref>* - GetRecvTrailingMetadata() = 0; - - /// Gets an intercepted channel. When a call is started on this interceptor, - /// only interceptors after the current interceptor are created from the - /// factory objects registered with the channel. This allows calls to be - /// started from interceptors without infinite regress through the interceptor - /// list. - virtual std::unique_ptr<ChannelInterface> GetInterceptedChannel() = 0; - - /// On a hijacked RPC, an interceptor can decide to fail a PRE_RECV_MESSAGE - /// op. This would be a signal to the reader that there will be no more - /// messages, or the stream has failed or been cancelled. - virtual void FailHijackedRecvMessage() = 0; - - /// On a hijacked RPC/ to-be hijacked RPC, this can be called to fail a SEND - /// MESSAGE op - virtual void FailHijackedSendMessage() = 0; -}; - -/// Interface for an interceptor. Interceptor authors must create a class -/// that derives from this parent class. -class Interceptor { - public: - virtual ~Interceptor() {} - - /// The one public method of an Interceptor interface. Override this to - /// trigger the desired actions at the hook points described above. - virtual void Intercept(InterceptorBatchMethods* methods) = 0; -}; - -} // namespace experimental -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H + virtual std::multimap<grpc::string_ref, grpc::string_ref>* + GetRecvTrailingMetadata() = 0; + + /// Gets an intercepted channel. When a call is started on this interceptor, + /// only interceptors after the current interceptor are created from the + /// factory objects registered with the channel. This allows calls to be + /// started from interceptors without infinite regress through the interceptor + /// list. + virtual std::unique_ptr<ChannelInterface> GetInterceptedChannel() = 0; + + /// On a hijacked RPC, an interceptor can decide to fail a PRE_RECV_MESSAGE + /// op. This would be a signal to the reader that there will be no more + /// messages, or the stream has failed or been cancelled. + virtual void FailHijackedRecvMessage() = 0; + + /// On a hijacked RPC/ to-be hijacked RPC, this can be called to fail a SEND + /// MESSAGE op + virtual void FailHijackedSendMessage() = 0; +}; + +/// Interface for an interceptor. Interceptor authors must create a class +/// that derives from this parent class. +class Interceptor { + public: + virtual ~Interceptor() {} + + /// The one public method of an Interceptor interface. Override this to + /// trigger the desired actions at the hook points described above. + virtual void Intercept(InterceptorBatchMethods* methods) = 0; +}; + +} // namespace experimental +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTOR_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h index 714351f543..62c879fdec 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/interceptor_common.h @@ -1,558 +1,558 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#if defined(__GNUC__) -#pragma GCC system_header -#endif - -#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H -#define GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H - -#include <array> -#include <functional> - -#include <grpcpp/impl/codegen/call.h> -#include <grpcpp/impl/codegen/call_op_set_interface.h> -#include <grpcpp/impl/codegen/client_interceptor.h> -#include <grpcpp/impl/codegen/intercepted_channel.h> -#include <grpcpp/impl/codegen/server_interceptor.h> - -#include <grpc/impl/codegen/grpc_types.h> - -namespace grpc { -namespace internal { - -class InterceptorBatchMethodsImpl - : public experimental::InterceptorBatchMethods { - public: - InterceptorBatchMethodsImpl() { - for (auto i = static_cast<experimental::InterceptionHookPoints>(0); - i < experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS; - i = static_cast<experimental::InterceptionHookPoints>( - static_cast<size_t>(i) + 1)) { - hooks_[static_cast<size_t>(i)] = false; - } - } - - ~InterceptorBatchMethodsImpl() {} - - bool QueryInterceptionHookPoint( - experimental::InterceptionHookPoints type) override { - return hooks_[static_cast<size_t>(type)]; - } - - void Proceed() override { - if (call_->client_rpc_info() != nullptr) { - return ProceedClient(); - } - GPR_CODEGEN_ASSERT(call_->server_rpc_info() != nullptr); - ProceedServer(); - } - - void Hijack() override { - // Only the client can hijack when sending down initial metadata - GPR_CODEGEN_ASSERT(!reverse_ && ops_ != nullptr && - call_->client_rpc_info() != nullptr); - // It is illegal to call Hijack twice - GPR_CODEGEN_ASSERT(!ran_hijacking_interceptor_); - auto* rpc_info = call_->client_rpc_info(); - rpc_info->hijacked_ = true; - rpc_info->hijacked_interceptor_ = current_interceptor_index_; - ClearHookPoints(); - ops_->SetHijackingState(); - ran_hijacking_interceptor_ = true; - rpc_info->RunInterceptor(this, current_interceptor_index_); - } - - void AddInterceptionHookPoint(experimental::InterceptionHookPoints type) { - hooks_[static_cast<size_t>(type)] = true; - } - - ByteBuffer* GetSerializedSendMessage() override { - GPR_CODEGEN_ASSERT(orig_send_message_ != nullptr); - if (*orig_send_message_ != nullptr) { - GPR_CODEGEN_ASSERT(serializer_(*orig_send_message_).ok()); - *orig_send_message_ = nullptr; - } - return send_message_; - } - - const void* GetSendMessage() override { - GPR_CODEGEN_ASSERT(orig_send_message_ != nullptr); - return *orig_send_message_; - } - - void ModifySendMessage(const void* message) override { - GPR_CODEGEN_ASSERT(orig_send_message_ != nullptr); - *orig_send_message_ = message; - } - - bool GetSendMessageStatus() override { return !*fail_send_message_; } - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#if defined(__GNUC__) +#pragma GCC system_header +#endif + +#ifndef GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H +#define GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H + +#include <array> +#include <functional> + +#include <grpcpp/impl/codegen/call.h> +#include <grpcpp/impl/codegen/call_op_set_interface.h> +#include <grpcpp/impl/codegen/client_interceptor.h> +#include <grpcpp/impl/codegen/intercepted_channel.h> +#include <grpcpp/impl/codegen/server_interceptor.h> + +#include <grpc/impl/codegen/grpc_types.h> + +namespace grpc { +namespace internal { + +class InterceptorBatchMethodsImpl + : public experimental::InterceptorBatchMethods { + public: + InterceptorBatchMethodsImpl() { + for (auto i = static_cast<experimental::InterceptionHookPoints>(0); + i < experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS; + i = static_cast<experimental::InterceptionHookPoints>( + static_cast<size_t>(i) + 1)) { + hooks_[static_cast<size_t>(i)] = false; + } + } + + ~InterceptorBatchMethodsImpl() {} + + bool QueryInterceptionHookPoint( + experimental::InterceptionHookPoints type) override { + return hooks_[static_cast<size_t>(type)]; + } + + void Proceed() override { + if (call_->client_rpc_info() != nullptr) { + return ProceedClient(); + } + GPR_CODEGEN_ASSERT(call_->server_rpc_info() != nullptr); + ProceedServer(); + } + + void Hijack() override { + // Only the client can hijack when sending down initial metadata + GPR_CODEGEN_ASSERT(!reverse_ && ops_ != nullptr && + call_->client_rpc_info() != nullptr); + // It is illegal to call Hijack twice + GPR_CODEGEN_ASSERT(!ran_hijacking_interceptor_); + auto* rpc_info = call_->client_rpc_info(); + rpc_info->hijacked_ = true; + rpc_info->hijacked_interceptor_ = current_interceptor_index_; + ClearHookPoints(); + ops_->SetHijackingState(); + ran_hijacking_interceptor_ = true; + rpc_info->RunInterceptor(this, current_interceptor_index_); + } + + void AddInterceptionHookPoint(experimental::InterceptionHookPoints type) { + hooks_[static_cast<size_t>(type)] = true; + } + + ByteBuffer* GetSerializedSendMessage() override { + GPR_CODEGEN_ASSERT(orig_send_message_ != nullptr); + if (*orig_send_message_ != nullptr) { + GPR_CODEGEN_ASSERT(serializer_(*orig_send_message_).ok()); + *orig_send_message_ = nullptr; + } + return send_message_; + } + + const void* GetSendMessage() override { + GPR_CODEGEN_ASSERT(orig_send_message_ != nullptr); + return *orig_send_message_; + } + + void ModifySendMessage(const void* message) override { + GPR_CODEGEN_ASSERT(orig_send_message_ != nullptr); + *orig_send_message_ = message; + } + + bool GetSendMessageStatus() override { return !*fail_send_message_; } + std::multimap<TString, TString>* GetSendInitialMetadata() override { - return send_initial_metadata_; - } - - Status GetSendStatus() override { - return Status(static_cast<StatusCode>(*code_), *error_message_, - *error_details_); - } - - void ModifySendStatus(const Status& status) override { - *code_ = static_cast<grpc_status_code>(status.error_code()); - *error_details_ = status.error_details(); - *error_message_ = status.error_message(); - } - + return send_initial_metadata_; + } + + Status GetSendStatus() override { + return Status(static_cast<StatusCode>(*code_), *error_message_, + *error_details_); + } + + void ModifySendStatus(const Status& status) override { + *code_ = static_cast<grpc_status_code>(status.error_code()); + *error_details_ = status.error_details(); + *error_message_ = status.error_message(); + } + std::multimap<TString, TString>* GetSendTrailingMetadata() override { - return send_trailing_metadata_; - } - - void* GetRecvMessage() override { return recv_message_; } - - std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvInitialMetadata() - override { - return recv_initial_metadata_->map(); - } - - Status* GetRecvStatus() override { return recv_status_; } - - void FailHijackedSendMessage() override { - GPR_CODEGEN_ASSERT(hooks_[static_cast<size_t>( - experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)]); - *fail_send_message_ = true; - } - - std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvTrailingMetadata() - override { - return recv_trailing_metadata_->map(); - } - - void SetSendMessage(ByteBuffer* buf, const void** msg, - bool* fail_send_message, - std::function<Status(const void*)> serializer) { - send_message_ = buf; - orig_send_message_ = msg; - fail_send_message_ = fail_send_message; - serializer_ = serializer; - } - - void SetSendInitialMetadata( + return send_trailing_metadata_; + } + + void* GetRecvMessage() override { return recv_message_; } + + std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvInitialMetadata() + override { + return recv_initial_metadata_->map(); + } + + Status* GetRecvStatus() override { return recv_status_; } + + void FailHijackedSendMessage() override { + GPR_CODEGEN_ASSERT(hooks_[static_cast<size_t>( + experimental::InterceptionHookPoints::PRE_SEND_MESSAGE)]); + *fail_send_message_ = true; + } + + std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvTrailingMetadata() + override { + return recv_trailing_metadata_->map(); + } + + void SetSendMessage(ByteBuffer* buf, const void** msg, + bool* fail_send_message, + std::function<Status(const void*)> serializer) { + send_message_ = buf; + orig_send_message_ = msg; + fail_send_message_ = fail_send_message; + serializer_ = serializer; + } + + void SetSendInitialMetadata( std::multimap<TString, TString>* metadata) { - send_initial_metadata_ = metadata; - } - + send_initial_metadata_ = metadata; + } + void SetSendStatus(grpc_status_code* code, TString* error_details, TString* error_message) { - code_ = code; - error_details_ = error_details; - error_message_ = error_message; - } - - void SetSendTrailingMetadata( + code_ = code; + error_details_ = error_details; + error_message_ = error_message; + } + + void SetSendTrailingMetadata( std::multimap<TString, TString>* metadata) { - send_trailing_metadata_ = metadata; - } - + send_trailing_metadata_ = metadata; + } + void SetRecvMessage(void* message, bool* hijacked_recv_message_failed) { - recv_message_ = message; + recv_message_ = message; hijacked_recv_message_failed_ = hijacked_recv_message_failed; - } - - void SetRecvInitialMetadata(MetadataMap* map) { - recv_initial_metadata_ = map; - } - - void SetRecvStatus(Status* status) { recv_status_ = status; } - - void SetRecvTrailingMetadata(MetadataMap* map) { - recv_trailing_metadata_ = map; - } - - std::unique_ptr<ChannelInterface> GetInterceptedChannel() override { - auto* info = call_->client_rpc_info(); - if (info == nullptr) { - return std::unique_ptr<ChannelInterface>(nullptr); - } - // The intercepted channel starts from the interceptor just after the - // current interceptor - return std::unique_ptr<ChannelInterface>(new InterceptedChannel( - info->channel(), current_interceptor_index_ + 1)); - } - - void FailHijackedRecvMessage() override { - GPR_CODEGEN_ASSERT(hooks_[static_cast<size_t>( - experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)]); + } + + void SetRecvInitialMetadata(MetadataMap* map) { + recv_initial_metadata_ = map; + } + + void SetRecvStatus(Status* status) { recv_status_ = status; } + + void SetRecvTrailingMetadata(MetadataMap* map) { + recv_trailing_metadata_ = map; + } + + std::unique_ptr<ChannelInterface> GetInterceptedChannel() override { + auto* info = call_->client_rpc_info(); + if (info == nullptr) { + return std::unique_ptr<ChannelInterface>(nullptr); + } + // The intercepted channel starts from the interceptor just after the + // current interceptor + return std::unique_ptr<ChannelInterface>(new InterceptedChannel( + info->channel(), current_interceptor_index_ + 1)); + } + + void FailHijackedRecvMessage() override { + GPR_CODEGEN_ASSERT(hooks_[static_cast<size_t>( + experimental::InterceptionHookPoints::PRE_RECV_MESSAGE)]); *hijacked_recv_message_failed_ = true; - } - - // Clears all state - void ClearState() { - reverse_ = false; - ran_hijacking_interceptor_ = false; - ClearHookPoints(); - } - - // Prepares for Post_recv operations - void SetReverse() { - reverse_ = true; - ran_hijacking_interceptor_ = false; - ClearHookPoints(); - } - - // This needs to be set before interceptors are run - void SetCall(Call* call) { call_ = call; } - - // This needs to be set before interceptors are run using RunInterceptors(). - // Alternatively, RunInterceptors(std::function<void(void)> f) can be used. - void SetCallOpSetInterface(CallOpSetInterface* ops) { ops_ = ops; } - - // SetCall should have been called before this. - // Returns true if the interceptors list is empty - bool InterceptorsListEmpty() { - auto* client_rpc_info = call_->client_rpc_info(); - if (client_rpc_info != nullptr) { - if (client_rpc_info->interceptors_.size() == 0) { - return true; - } else { - return false; - } - } - - auto* server_rpc_info = call_->server_rpc_info(); - if (server_rpc_info == nullptr || - server_rpc_info->interceptors_.size() == 0) { - return true; - } - return false; - } - - // This should be used only by subclasses of CallOpSetInterface. SetCall and - // SetCallOpSetInterface should have been called before this. After all the - // interceptors are done running, either ContinueFillOpsAfterInterception or - // ContinueFinalizeOpsAfterInterception will be called. Note that neither of - // them is invoked if there were no interceptors registered. - bool RunInterceptors() { - GPR_CODEGEN_ASSERT(ops_); - auto* client_rpc_info = call_->client_rpc_info(); - if (client_rpc_info != nullptr) { - if (client_rpc_info->interceptors_.size() == 0) { - return true; - } else { - RunClientInterceptors(); - return false; - } - } - - auto* server_rpc_info = call_->server_rpc_info(); - if (server_rpc_info == nullptr || - server_rpc_info->interceptors_.size() == 0) { - return true; - } - RunServerInterceptors(); - return false; - } - - // Returns true if no interceptors are run. Returns false otherwise if there - // are interceptors registered. After the interceptors are done running \a f - // will be invoked. This is to be used only by BaseAsyncRequest and - // SyncRequest. - bool RunInterceptors(std::function<void(void)> f) { - // This is used only by the server for initial call request - GPR_CODEGEN_ASSERT(reverse_ == true); - GPR_CODEGEN_ASSERT(call_->client_rpc_info() == nullptr); - auto* server_rpc_info = call_->server_rpc_info(); - if (server_rpc_info == nullptr || - server_rpc_info->interceptors_.size() == 0) { - return true; - } - callback_ = std::move(f); - RunServerInterceptors(); - return false; - } - - private: - void RunClientInterceptors() { - auto* rpc_info = call_->client_rpc_info(); - if (!reverse_) { - current_interceptor_index_ = 0; - } else { - if (rpc_info->hijacked_) { - current_interceptor_index_ = rpc_info->hijacked_interceptor_; - } else { - current_interceptor_index_ = rpc_info->interceptors_.size() - 1; - } - } - rpc_info->RunInterceptor(this, current_interceptor_index_); - } - - void RunServerInterceptors() { - auto* rpc_info = call_->server_rpc_info(); - if (!reverse_) { - current_interceptor_index_ = 0; - } else { - current_interceptor_index_ = rpc_info->interceptors_.size() - 1; - } - rpc_info->RunInterceptor(this, current_interceptor_index_); - } - - void ProceedClient() { - auto* rpc_info = call_->client_rpc_info(); - if (rpc_info->hijacked_ && !reverse_ && - current_interceptor_index_ == rpc_info->hijacked_interceptor_ && - !ran_hijacking_interceptor_) { - // We now need to provide hijacked recv ops to this interceptor - ClearHookPoints(); - ops_->SetHijackingState(); - ran_hijacking_interceptor_ = true; - rpc_info->RunInterceptor(this, current_interceptor_index_); - return; - } - if (!reverse_) { - current_interceptor_index_++; - // We are going down the stack of interceptors - if (current_interceptor_index_ < rpc_info->interceptors_.size()) { - if (rpc_info->hijacked_ && - current_interceptor_index_ > rpc_info->hijacked_interceptor_) { - // This is a hijacked RPC and we are done with hijacking - ops_->ContinueFillOpsAfterInterception(); - } else { - rpc_info->RunInterceptor(this, current_interceptor_index_); - } - } else { - // we are done running all the interceptors without any hijacking - ops_->ContinueFillOpsAfterInterception(); - } - } else { - // We are going up the stack of interceptors - if (current_interceptor_index_ > 0) { - // Continue running interceptors - current_interceptor_index_--; - rpc_info->RunInterceptor(this, current_interceptor_index_); - } else { - // we are done running all the interceptors without any hijacking - ops_->ContinueFinalizeResultAfterInterception(); - } - } - } - - void ProceedServer() { - auto* rpc_info = call_->server_rpc_info(); - if (!reverse_) { - current_interceptor_index_++; - if (current_interceptor_index_ < rpc_info->interceptors_.size()) { - return rpc_info->RunInterceptor(this, current_interceptor_index_); - } else if (ops_) { - return ops_->ContinueFillOpsAfterInterception(); - } - } else { - // We are going up the stack of interceptors - if (current_interceptor_index_ > 0) { - // Continue running interceptors - current_interceptor_index_--; - return rpc_info->RunInterceptor(this, current_interceptor_index_); - } else if (ops_) { - return ops_->ContinueFinalizeResultAfterInterception(); - } - } - GPR_CODEGEN_ASSERT(callback_); - callback_(); - } - - void ClearHookPoints() { - for (auto i = static_cast<experimental::InterceptionHookPoints>(0); - i < experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS; - i = static_cast<experimental::InterceptionHookPoints>( - static_cast<size_t>(i) + 1)) { - hooks_[static_cast<size_t>(i)] = false; - } - } - - std::array<bool, - static_cast<size_t>( - experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS)> - hooks_; - - size_t current_interceptor_index_ = 0; // Current iterator - bool reverse_ = false; - bool ran_hijacking_interceptor_ = false; - Call* call_ = nullptr; // The Call object is present along with CallOpSet - // object/callback - CallOpSetInterface* ops_ = nullptr; - std::function<void(void)> callback_; - - ByteBuffer* send_message_ = nullptr; - bool* fail_send_message_ = nullptr; - const void** orig_send_message_ = nullptr; - std::function<Status(const void*)> serializer_; - + } + + // Clears all state + void ClearState() { + reverse_ = false; + ran_hijacking_interceptor_ = false; + ClearHookPoints(); + } + + // Prepares for Post_recv operations + void SetReverse() { + reverse_ = true; + ran_hijacking_interceptor_ = false; + ClearHookPoints(); + } + + // This needs to be set before interceptors are run + void SetCall(Call* call) { call_ = call; } + + // This needs to be set before interceptors are run using RunInterceptors(). + // Alternatively, RunInterceptors(std::function<void(void)> f) can be used. + void SetCallOpSetInterface(CallOpSetInterface* ops) { ops_ = ops; } + + // SetCall should have been called before this. + // Returns true if the interceptors list is empty + bool InterceptorsListEmpty() { + auto* client_rpc_info = call_->client_rpc_info(); + if (client_rpc_info != nullptr) { + if (client_rpc_info->interceptors_.size() == 0) { + return true; + } else { + return false; + } + } + + auto* server_rpc_info = call_->server_rpc_info(); + if (server_rpc_info == nullptr || + server_rpc_info->interceptors_.size() == 0) { + return true; + } + return false; + } + + // This should be used only by subclasses of CallOpSetInterface. SetCall and + // SetCallOpSetInterface should have been called before this. After all the + // interceptors are done running, either ContinueFillOpsAfterInterception or + // ContinueFinalizeOpsAfterInterception will be called. Note that neither of + // them is invoked if there were no interceptors registered. + bool RunInterceptors() { + GPR_CODEGEN_ASSERT(ops_); + auto* client_rpc_info = call_->client_rpc_info(); + if (client_rpc_info != nullptr) { + if (client_rpc_info->interceptors_.size() == 0) { + return true; + } else { + RunClientInterceptors(); + return false; + } + } + + auto* server_rpc_info = call_->server_rpc_info(); + if (server_rpc_info == nullptr || + server_rpc_info->interceptors_.size() == 0) { + return true; + } + RunServerInterceptors(); + return false; + } + + // Returns true if no interceptors are run. Returns false otherwise if there + // are interceptors registered. After the interceptors are done running \a f + // will be invoked. This is to be used only by BaseAsyncRequest and + // SyncRequest. + bool RunInterceptors(std::function<void(void)> f) { + // This is used only by the server for initial call request + GPR_CODEGEN_ASSERT(reverse_ == true); + GPR_CODEGEN_ASSERT(call_->client_rpc_info() == nullptr); + auto* server_rpc_info = call_->server_rpc_info(); + if (server_rpc_info == nullptr || + server_rpc_info->interceptors_.size() == 0) { + return true; + } + callback_ = std::move(f); + RunServerInterceptors(); + return false; + } + + private: + void RunClientInterceptors() { + auto* rpc_info = call_->client_rpc_info(); + if (!reverse_) { + current_interceptor_index_ = 0; + } else { + if (rpc_info->hijacked_) { + current_interceptor_index_ = rpc_info->hijacked_interceptor_; + } else { + current_interceptor_index_ = rpc_info->interceptors_.size() - 1; + } + } + rpc_info->RunInterceptor(this, current_interceptor_index_); + } + + void RunServerInterceptors() { + auto* rpc_info = call_->server_rpc_info(); + if (!reverse_) { + current_interceptor_index_ = 0; + } else { + current_interceptor_index_ = rpc_info->interceptors_.size() - 1; + } + rpc_info->RunInterceptor(this, current_interceptor_index_); + } + + void ProceedClient() { + auto* rpc_info = call_->client_rpc_info(); + if (rpc_info->hijacked_ && !reverse_ && + current_interceptor_index_ == rpc_info->hijacked_interceptor_ && + !ran_hijacking_interceptor_) { + // We now need to provide hijacked recv ops to this interceptor + ClearHookPoints(); + ops_->SetHijackingState(); + ran_hijacking_interceptor_ = true; + rpc_info->RunInterceptor(this, current_interceptor_index_); + return; + } + if (!reverse_) { + current_interceptor_index_++; + // We are going down the stack of interceptors + if (current_interceptor_index_ < rpc_info->interceptors_.size()) { + if (rpc_info->hijacked_ && + current_interceptor_index_ > rpc_info->hijacked_interceptor_) { + // This is a hijacked RPC and we are done with hijacking + ops_->ContinueFillOpsAfterInterception(); + } else { + rpc_info->RunInterceptor(this, current_interceptor_index_); + } + } else { + // we are done running all the interceptors without any hijacking + ops_->ContinueFillOpsAfterInterception(); + } + } else { + // We are going up the stack of interceptors + if (current_interceptor_index_ > 0) { + // Continue running interceptors + current_interceptor_index_--; + rpc_info->RunInterceptor(this, current_interceptor_index_); + } else { + // we are done running all the interceptors without any hijacking + ops_->ContinueFinalizeResultAfterInterception(); + } + } + } + + void ProceedServer() { + auto* rpc_info = call_->server_rpc_info(); + if (!reverse_) { + current_interceptor_index_++; + if (current_interceptor_index_ < rpc_info->interceptors_.size()) { + return rpc_info->RunInterceptor(this, current_interceptor_index_); + } else if (ops_) { + return ops_->ContinueFillOpsAfterInterception(); + } + } else { + // We are going up the stack of interceptors + if (current_interceptor_index_ > 0) { + // Continue running interceptors + current_interceptor_index_--; + return rpc_info->RunInterceptor(this, current_interceptor_index_); + } else if (ops_) { + return ops_->ContinueFinalizeResultAfterInterception(); + } + } + GPR_CODEGEN_ASSERT(callback_); + callback_(); + } + + void ClearHookPoints() { + for (auto i = static_cast<experimental::InterceptionHookPoints>(0); + i < experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS; + i = static_cast<experimental::InterceptionHookPoints>( + static_cast<size_t>(i) + 1)) { + hooks_[static_cast<size_t>(i)] = false; + } + } + + std::array<bool, + static_cast<size_t>( + experimental::InterceptionHookPoints::NUM_INTERCEPTION_HOOKS)> + hooks_; + + size_t current_interceptor_index_ = 0; // Current iterator + bool reverse_ = false; + bool ran_hijacking_interceptor_ = false; + Call* call_ = nullptr; // The Call object is present along with CallOpSet + // object/callback + CallOpSetInterface* ops_ = nullptr; + std::function<void(void)> callback_; + + ByteBuffer* send_message_ = nullptr; + bool* fail_send_message_ = nullptr; + const void** orig_send_message_ = nullptr; + std::function<Status(const void*)> serializer_; + std::multimap<TString, TString>* send_initial_metadata_; - - grpc_status_code* code_ = nullptr; + + grpc_status_code* code_ = nullptr; TString* error_details_ = nullptr; TString* error_message_ = nullptr; - + std::multimap<TString, TString>* send_trailing_metadata_ = nullptr; - - void* recv_message_ = nullptr; + + void* recv_message_ = nullptr; bool* hijacked_recv_message_failed_ = nullptr; - - MetadataMap* recv_initial_metadata_ = nullptr; - - Status* recv_status_ = nullptr; - - MetadataMap* recv_trailing_metadata_ = nullptr; -}; - -// A special implementation of InterceptorBatchMethods to send a Cancel -// notification down the interceptor stack -class CancelInterceptorBatchMethods - : public experimental::InterceptorBatchMethods { - public: - bool QueryInterceptionHookPoint( - experimental::InterceptionHookPoints type) override { - if (type == experimental::InterceptionHookPoints::PRE_SEND_CANCEL) { - return true; - } else { - return false; - } - } - - void Proceed() override { - // This is a no-op. For actual continuation of the RPC simply needs to - // return from the Intercept method - } - - void Hijack() override { - // Only the client can hijack when sending down initial metadata - GPR_CODEGEN_ASSERT(false && - "It is illegal to call Hijack on a method which has a " - "Cancel notification"); - } - - ByteBuffer* GetSerializedSendMessage() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetSendMessage on a method which " - "has a Cancel notification"); - return nullptr; - } - - bool GetSendMessageStatus() override { - GPR_CODEGEN_ASSERT( - false && - "It is illegal to call GetSendMessageStatus on a method which " - "has a Cancel notification"); - return false; - } - - const void* GetSendMessage() override { - GPR_CODEGEN_ASSERT( - false && - "It is illegal to call GetOriginalSendMessage on a method which " - "has a Cancel notification"); - return nullptr; - } - + + MetadataMap* recv_initial_metadata_ = nullptr; + + Status* recv_status_ = nullptr; + + MetadataMap* recv_trailing_metadata_ = nullptr; +}; + +// A special implementation of InterceptorBatchMethods to send a Cancel +// notification down the interceptor stack +class CancelInterceptorBatchMethods + : public experimental::InterceptorBatchMethods { + public: + bool QueryInterceptionHookPoint( + experimental::InterceptionHookPoints type) override { + if (type == experimental::InterceptionHookPoints::PRE_SEND_CANCEL) { + return true; + } else { + return false; + } + } + + void Proceed() override { + // This is a no-op. For actual continuation of the RPC simply needs to + // return from the Intercept method + } + + void Hijack() override { + // Only the client can hijack when sending down initial metadata + GPR_CODEGEN_ASSERT(false && + "It is illegal to call Hijack on a method which has a " + "Cancel notification"); + } + + ByteBuffer* GetSerializedSendMessage() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetSendMessage on a method which " + "has a Cancel notification"); + return nullptr; + } + + bool GetSendMessageStatus() override { + GPR_CODEGEN_ASSERT( + false && + "It is illegal to call GetSendMessageStatus on a method which " + "has a Cancel notification"); + return false; + } + + const void* GetSendMessage() override { + GPR_CODEGEN_ASSERT( + false && + "It is illegal to call GetOriginalSendMessage on a method which " + "has a Cancel notification"); + return nullptr; + } + void ModifySendMessage(const void* /*message*/) override { - GPR_CODEGEN_ASSERT( - false && - "It is illegal to call ModifySendMessage on a method which " - "has a Cancel notification"); - } - + GPR_CODEGEN_ASSERT( + false && + "It is illegal to call ModifySendMessage on a method which " + "has a Cancel notification"); + } + std::multimap<TString, TString>* GetSendInitialMetadata() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetSendInitialMetadata on a " - "method which has a Cancel notification"); - return nullptr; - } - - Status GetSendStatus() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetSendStatus on a method which " - "has a Cancel notification"); - return Status(); - } - + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetSendInitialMetadata on a " + "method which has a Cancel notification"); + return nullptr; + } + + Status GetSendStatus() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetSendStatus on a method which " + "has a Cancel notification"); + return Status(); + } + void ModifySendStatus(const Status& /*status*/) override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call ModifySendStatus on a method " - "which has a Cancel notification"); - return; - } - + GPR_CODEGEN_ASSERT(false && + "It is illegal to call ModifySendStatus on a method " + "which has a Cancel notification"); + return; + } + std::multimap<TString, TString>* GetSendTrailingMetadata() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetSendTrailingMetadata on a " - "method which has a Cancel notification"); - return nullptr; - } - - void* GetRecvMessage() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetRecvMessage on a method which " - "has a Cancel notification"); - return nullptr; - } - - std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvInitialMetadata() - override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetRecvInitialMetadata on a " - "method which has a Cancel notification"); - return nullptr; - } - - Status* GetRecvStatus() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetRecvStatus on a method which " - "has a Cancel notification"); - return nullptr; - } - - std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvTrailingMetadata() - override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetRecvTrailingMetadata on a " - "method which has a Cancel notification"); - return nullptr; - } - - std::unique_ptr<ChannelInterface> GetInterceptedChannel() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call GetInterceptedChannel on a " - "method which has a Cancel notification"); - return std::unique_ptr<ChannelInterface>(nullptr); - } - - void FailHijackedRecvMessage() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call FailHijackedRecvMessage on a " - "method which has a Cancel notification"); - } - - void FailHijackedSendMessage() override { - GPR_CODEGEN_ASSERT(false && - "It is illegal to call FailHijackedSendMessage on a " - "method which has a Cancel notification"); - } -}; -} // namespace internal -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetSendTrailingMetadata on a " + "method which has a Cancel notification"); + return nullptr; + } + + void* GetRecvMessage() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetRecvMessage on a method which " + "has a Cancel notification"); + return nullptr; + } + + std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvInitialMetadata() + override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetRecvInitialMetadata on a " + "method which has a Cancel notification"); + return nullptr; + } + + Status* GetRecvStatus() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetRecvStatus on a method which " + "has a Cancel notification"); + return nullptr; + } + + std::multimap<grpc::string_ref, grpc::string_ref>* GetRecvTrailingMetadata() + override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetRecvTrailingMetadata on a " + "method which has a Cancel notification"); + return nullptr; + } + + std::unique_ptr<ChannelInterface> GetInterceptedChannel() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call GetInterceptedChannel on a " + "method which has a Cancel notification"); + return std::unique_ptr<ChannelInterface>(nullptr); + } + + void FailHijackedRecvMessage() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call FailHijackedRecvMessage on a " + "method which has a Cancel notification"); + } + + void FailHijackedSendMessage() override { + GPR_CODEGEN_ASSERT(false && + "It is illegal to call FailHijackedSendMessage on a " + "method which has a Cancel notification"); + } +}; +} // namespace internal +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_INTERCEPTOR_COMMON_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/metadata_map.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/metadata_map.h index 03afc0781a..4ad0727ef8 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/metadata_map.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/metadata_map.h @@ -19,77 +19,77 @@ #ifndef GRPCPP_IMPL_CODEGEN_METADATA_MAP_H #define GRPCPP_IMPL_CODEGEN_METADATA_MAP_H -#include <map> - -#include <grpc/impl/codegen/log.h> +#include <map> + +#include <grpc/impl/codegen/log.h> #include <grpcpp/impl/codegen/slice.h> namespace grpc { namespace internal { - -const char kBinaryErrorDetailsKey[] = "grpc-status-details-bin"; - + +const char kBinaryErrorDetailsKey[] = "grpc-status-details-bin"; + class MetadataMap { public: - MetadataMap() { Setup(); } - - ~MetadataMap() { Destroy(); } + MetadataMap() { Setup(); } + ~MetadataMap() { Destroy(); } + TString GetBinaryErrorDetails() { - // if filled_, extract from the multimap for O(log(n)) - if (filled_) { - auto iter = map_.find(kBinaryErrorDetailsKey); - if (iter != map_.end()) { + // if filled_, extract from the multimap for O(log(n)) + if (filled_) { + auto iter = map_.find(kBinaryErrorDetailsKey); + if (iter != map_.end()) { return TString(iter->second.begin(), iter->second.length()); - } - } - // if not yet filled, take the O(n) lookup to avoid allocating the - // multimap until it is requested. - // TODO(ncteisen): plumb this through core as a first class object, just - // like code and message. - else { - for (size_t i = 0; i < arr_.count; i++) { - if (strncmp(reinterpret_cast<const char*>( - GRPC_SLICE_START_PTR(arr_.metadata[i].key)), - kBinaryErrorDetailsKey, - GRPC_SLICE_LENGTH(arr_.metadata[i].key)) == 0) { + } + } + // if not yet filled, take the O(n) lookup to avoid allocating the + // multimap until it is requested. + // TODO(ncteisen): plumb this through core as a first class object, just + // like code and message. + else { + for (size_t i = 0; i < arr_.count; i++) { + if (strncmp(reinterpret_cast<const char*>( + GRPC_SLICE_START_PTR(arr_.metadata[i].key)), + kBinaryErrorDetailsKey, + GRPC_SLICE_LENGTH(arr_.metadata[i].key)) == 0) { return TString(reinterpret_cast<const char*>( GRPC_SLICE_START_PTR(arr_.metadata[i].value)), GRPC_SLICE_LENGTH(arr_.metadata[i].value)); - } - } - } + } + } + } return TString(); - } - - std::multimap<grpc::string_ref, grpc::string_ref>* map() { - FillMap(); - return &map_; - } - grpc_metadata_array* arr() { return &arr_; } - - void Reset() { - filled_ = false; - map_.clear(); - Destroy(); - Setup(); - } - - private: - bool filled_ = false; - grpc_metadata_array arr_; - std::multimap<grpc::string_ref, grpc::string_ref> map_; - - void Destroy() { + } + + std::multimap<grpc::string_ref, grpc::string_ref>* map() { + FillMap(); + return &map_; + } + grpc_metadata_array* arr() { return &arr_; } + + void Reset() { + filled_ = false; + map_.clear(); + Destroy(); + Setup(); + } + + private: + bool filled_ = false; + grpc_metadata_array arr_; + std::multimap<grpc::string_ref, grpc::string_ref> map_; + + void Destroy() { g_core_codegen_interface->grpc_metadata_array_destroy(&arr_); } - void Setup() { memset(&arr_, 0, sizeof(arr_)); } - + void Setup() { memset(&arr_, 0, sizeof(arr_)); } + void FillMap() { - if (filled_) return; - filled_ = true; + if (filled_) return; + filled_ = true; for (size_t i = 0; i < arr_.count; i++) { // TODO(yangg) handle duplicates? map_.insert(std::pair<grpc::string_ref, grpc::string_ref>( diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h index 4fcc211243..e0f65fccf1 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/rpc_service_method.h @@ -25,7 +25,7 @@ #include <memory> #include <vector> -#include <grpc/impl/codegen/log.h> +#include <grpc/impl/codegen/log.h> #include <grpcpp/impl/codegen/byte_buffer.h> #include <grpcpp/impl/codegen/config.h> #include <grpcpp/impl/codegen/rpc_method.h> @@ -39,26 +39,26 @@ class MethodHandler { public: virtual ~MethodHandler() {} struct HandlerParameter { - /// Constructor for HandlerParameter - /// - /// \param c : the gRPC Call structure for this server call - /// \param context : the ServerContext structure for this server call - /// \param req : the request payload, if appropriate for this RPC - /// \param req_status : the request status after any interceptors have run + /// Constructor for HandlerParameter + /// + /// \param c : the gRPC Call structure for this server call + /// \param context : the ServerContext structure for this server call + /// \param req : the request payload, if appropriate for this RPC + /// \param req_status : the request status after any interceptors have run /// \param handler_data: internal data for the handler. /// \param requester : used only by the callback API. It is a function - /// called by the RPC Controller to request another RPC (and also - /// to set up the state required to make that request possible) + /// called by the RPC Controller to request another RPC (and also + /// to set up the state required to make that request possible) HandlerParameter(Call* c, ::grpc::ServerContextBase* context, void* req, Status req_status, void* handler_data, std::function<void()> requester) - : call(c), - server_context(context), - request(req), - status(req_status), + : call(c), + server_context(context), + request(req), + status(req_status), internal_data(handler_data), - call_requester(std::move(requester)) {} - ~HandlerParameter() {} + call_requester(std::move(requester)) {} + ~HandlerParameter() {} Call* const call; ::grpc::ServerContextBase* const server_context; void* const request; @@ -67,17 +67,17 @@ class MethodHandler { const std::function<void()> call_requester; }; virtual void RunHandler(const HandlerParameter& param) = 0; - - /* Returns a pointer to the deserialized request. \a status reflects the - result of deserialization. This pointer and the status should be filled in - a HandlerParameter and passed to RunHandler. It is illegal to access the - pointer after calling RunHandler. Ownership of the deserialized request is - retained by the handler. Returns nullptr if deserialization failed. */ + + /* Returns a pointer to the deserialized request. \a status reflects the + result of deserialization. This pointer and the status should be filled in + a HandlerParameter and passed to RunHandler. It is illegal to access the + pointer after calling RunHandler. Ownership of the deserialized request is + retained by the handler. Returns nullptr if deserialization failed. */ virtual void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req, Status* /*status*/, void** /*handler_data*/) { - GPR_CODEGEN_ASSERT(req == nullptr); - return nullptr; - } + GPR_CODEGEN_ASSERT(req == nullptr); + return nullptr; + } }; /// Server side rpc method class @@ -86,65 +86,65 @@ class RpcServiceMethod : public RpcMethod { /// Takes ownership of the handler RpcServiceMethod(const char* name, RpcMethod::RpcType type, MethodHandler* handler) - : RpcMethod(name, type), - server_tag_(nullptr), - api_type_(ApiType::SYNC), - handler_(handler) {} - - enum class ApiType { - SYNC, - ASYNC, - RAW, - CALL_BACK, // not CALLBACK because that is reserved in Windows - RAW_CALL_BACK, - }; + : RpcMethod(name, type), + server_tag_(nullptr), + api_type_(ApiType::SYNC), + handler_(handler) {} + enum class ApiType { + SYNC, + ASYNC, + RAW, + CALL_BACK, // not CALLBACK because that is reserved in Windows + RAW_CALL_BACK, + }; + void set_server_tag(void* tag) { server_tag_ = tag; } void* server_tag() const { return server_tag_; } /// if MethodHandler is nullptr, then this is an async method MethodHandler* handler() const { return handler_.get(); } - ApiType api_type() const { return api_type_; } + ApiType api_type() const { return api_type_; } void SetHandler(MethodHandler* handler) { handler_.reset(handler); } - void SetServerApiType(RpcServiceMethod::ApiType type) { - if ((api_type_ == ApiType::SYNC) && - (type == ApiType::ASYNC || type == ApiType::RAW)) { - // this marks this method as async - handler_.reset(); - } else if (api_type_ != ApiType::SYNC) { - // this is not an error condition, as it allows users to declare a server - // like WithRawMethod_foo<AsyncService>. However since it - // overwrites behavior, it should be logged. - gpr_log( - GPR_INFO, - "You are marking method %s as '%s', even though it was " - "previously marked '%s'. This behavior will overwrite the original " - "behavior. If you expected this then ignore this message.", - name(), TypeToString(api_type_), TypeToString(type)); - } - api_type_ = type; - } + void SetServerApiType(RpcServiceMethod::ApiType type) { + if ((api_type_ == ApiType::SYNC) && + (type == ApiType::ASYNC || type == ApiType::RAW)) { + // this marks this method as async + handler_.reset(); + } else if (api_type_ != ApiType::SYNC) { + // this is not an error condition, as it allows users to declare a server + // like WithRawMethod_foo<AsyncService>. However since it + // overwrites behavior, it should be logged. + gpr_log( + GPR_INFO, + "You are marking method %s as '%s', even though it was " + "previously marked '%s'. This behavior will overwrite the original " + "behavior. If you expected this then ignore this message.", + name(), TypeToString(api_type_), TypeToString(type)); + } + api_type_ = type; + } private: void* server_tag_; - ApiType api_type_; + ApiType api_type_; std::unique_ptr<MethodHandler> handler_; - - const char* TypeToString(RpcServiceMethod::ApiType type) { - switch (type) { - case ApiType::SYNC: - return "sync"; - case ApiType::ASYNC: - return "async"; - case ApiType::RAW: - return "raw"; - case ApiType::CALL_BACK: - return "callback"; - case ApiType::RAW_CALL_BACK: - return "raw_callback"; - default: - GPR_UNREACHABLE_CODE(return "unknown"); - } - } + + const char* TypeToString(RpcServiceMethod::ApiType type) { + switch (type) { + case ApiType::SYNC: + return "sync"; + case ApiType::ASYNC: + return "async"; + case ApiType::RAW: + return "raw"; + case ApiType::CALL_BACK: + return "callback"; + case ApiType::RAW_CALL_BACK: + return "raw_callback"; + default: + GPR_UNREACHABLE_CODE(return "unknown"); + } + } }; } // namespace internal diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback.h index 3794a9ffa7..cb46e4dec7 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_callback.h @@ -1,27 +1,27 @@ -/* - * +/* + * * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H -#define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H - + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H +#define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H + #include <atomic> #include <functional> #include <type_traits> - + #include <grpcpp/impl/codegen/call.h> #include <grpcpp/impl/codegen/call_op_set.h> #include <grpcpp/impl/codegen/callback_common.h> @@ -30,7 +30,7 @@ #include <grpcpp/impl/codegen/message_allocator.h> #include <grpcpp/impl/codegen/status.h> -namespace grpc { +namespace grpc { // Declare base class of all reactors as internal namespace internal { @@ -774,21 +774,21 @@ using UnimplementedBidiReactor = } // namespace internal // TODO(vjpai): Remove namespace experimental when de-experimentalized fully. -namespace experimental { +namespace experimental { -template <class Request> +template <class Request> using ServerReadReactor = ::grpc::ServerReadReactor<Request>; - -template <class Response> + +template <class Response> using ServerWriteReactor = ::grpc::ServerWriteReactor<Response>; - -template <class Request, class Response> + +template <class Request, class Response> using ServerBidiReactor = ::grpc::ServerBidiReactor<Request, Response>; - + using ServerUnaryReactor = ::grpc::ServerUnaryReactor; + +} // namespace experimental -} // namespace experimental - -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h index 7598e72a40..0f176f8132 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interceptor.h @@ -1,139 +1,139 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H -#define GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H - -#include <atomic> -#include <vector> - -#include <grpcpp/impl/codegen/interceptor.h> -#include <grpcpp/impl/codegen/rpc_method.h> -#include <grpcpp/impl/codegen/string_ref.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H +#define GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H + +#include <atomic> +#include <vector> + +#include <grpcpp/impl/codegen/interceptor.h> +#include <grpcpp/impl/codegen/rpc_method.h> +#include <grpcpp/impl/codegen/string_ref.h> + namespace grpc { class ServerContextBase; -namespace internal { -class InterceptorBatchMethodsImpl; -} - -namespace experimental { -class ServerRpcInfo; - -// A factory interface for creation of server interceptors. A vector of -// factories can be provided to ServerBuilder which will be used to create a new -// vector of server interceptors per RPC. Server interceptor authors should -// create a subclass of ServerInterceptorFactorInterface which creates objects -// of their interceptors. -class ServerInterceptorFactoryInterface { - public: - virtual ~ServerInterceptorFactoryInterface() {} - // Returns a pointer to an Interceptor object on successful creation, nullptr - // otherwise. If nullptr is returned, this server interceptor factory is - // ignored for the purposes of that RPC. - virtual Interceptor* CreateServerInterceptor(ServerRpcInfo* info) = 0; -}; - -/// ServerRpcInfo represents the state of a particular RPC as it -/// appears to an interceptor. It is created and owned by the library and -/// passed to the CreateServerInterceptor method of the application's -/// ServerInterceptorFactoryInterface implementation -class ServerRpcInfo { - public: - /// Type categorizes RPCs by unary or streaming type - enum class Type { UNARY, CLIENT_STREAMING, SERVER_STREAMING, BIDI_STREAMING }; - +namespace internal { +class InterceptorBatchMethodsImpl; +} + +namespace experimental { +class ServerRpcInfo; + +// A factory interface for creation of server interceptors. A vector of +// factories can be provided to ServerBuilder which will be used to create a new +// vector of server interceptors per RPC. Server interceptor authors should +// create a subclass of ServerInterceptorFactorInterface which creates objects +// of their interceptors. +class ServerInterceptorFactoryInterface { + public: + virtual ~ServerInterceptorFactoryInterface() {} + // Returns a pointer to an Interceptor object on successful creation, nullptr + // otherwise. If nullptr is returned, this server interceptor factory is + // ignored for the purposes of that RPC. + virtual Interceptor* CreateServerInterceptor(ServerRpcInfo* info) = 0; +}; + +/// ServerRpcInfo represents the state of a particular RPC as it +/// appears to an interceptor. It is created and owned by the library and +/// passed to the CreateServerInterceptor method of the application's +/// ServerInterceptorFactoryInterface implementation +class ServerRpcInfo { + public: + /// Type categorizes RPCs by unary or streaming type + enum class Type { UNARY, CLIENT_STREAMING, SERVER_STREAMING, BIDI_STREAMING }; + ~ServerRpcInfo() {} - - // Delete all copy and move constructors and assignments - ServerRpcInfo(const ServerRpcInfo&) = delete; - ServerRpcInfo& operator=(const ServerRpcInfo&) = delete; - ServerRpcInfo(ServerRpcInfo&&) = delete; - ServerRpcInfo& operator=(ServerRpcInfo&&) = delete; - - // Getter methods - - /// Return the fully-specified method name - const char* method() const { return method_; } - - /// Return the type of the RPC (unary or a streaming flavor) - Type type() const { return type_; } - - /// Return a pointer to the underlying ServerContext structure associated - /// with the RPC to support features that apply to it + + // Delete all copy and move constructors and assignments + ServerRpcInfo(const ServerRpcInfo&) = delete; + ServerRpcInfo& operator=(const ServerRpcInfo&) = delete; + ServerRpcInfo(ServerRpcInfo&&) = delete; + ServerRpcInfo& operator=(ServerRpcInfo&&) = delete; + + // Getter methods + + /// Return the fully-specified method name + const char* method() const { return method_; } + + /// Return the type of the RPC (unary or a streaming flavor) + Type type() const { return type_; } + + /// Return a pointer to the underlying ServerContext structure associated + /// with the RPC to support features that apply to it ServerContextBase* server_context() { return ctx_; } - - private: - static_assert(Type::UNARY == - static_cast<Type>(internal::RpcMethod::NORMAL_RPC), - "violated expectation about Type enum"); - static_assert(Type::CLIENT_STREAMING == - static_cast<Type>(internal::RpcMethod::CLIENT_STREAMING), - "violated expectation about Type enum"); - static_assert(Type::SERVER_STREAMING == - static_cast<Type>(internal::RpcMethod::SERVER_STREAMING), - "violated expectation about Type enum"); - static_assert(Type::BIDI_STREAMING == - static_cast<Type>(internal::RpcMethod::BIDI_STREAMING), - "violated expectation about Type enum"); - + + private: + static_assert(Type::UNARY == + static_cast<Type>(internal::RpcMethod::NORMAL_RPC), + "violated expectation about Type enum"); + static_assert(Type::CLIENT_STREAMING == + static_cast<Type>(internal::RpcMethod::CLIENT_STREAMING), + "violated expectation about Type enum"); + static_assert(Type::SERVER_STREAMING == + static_cast<Type>(internal::RpcMethod::SERVER_STREAMING), + "violated expectation about Type enum"); + static_assert(Type::BIDI_STREAMING == + static_cast<Type>(internal::RpcMethod::BIDI_STREAMING), + "violated expectation about Type enum"); + ServerRpcInfo(ServerContextBase* ctx, const char* method, - internal::RpcMethod::RpcType type) + internal::RpcMethod::RpcType type) : ctx_(ctx), method_(method), type_(static_cast<Type>(type)) {} - - // Runs interceptor at pos \a pos. - void RunInterceptor( - experimental::InterceptorBatchMethods* interceptor_methods, size_t pos) { - GPR_CODEGEN_ASSERT(pos < interceptors_.size()); - interceptors_[pos]->Intercept(interceptor_methods); - } - - void RegisterInterceptors( - const std::vector< - std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>& - creators) { - for (const auto& creator : creators) { - auto* interceptor = creator->CreateServerInterceptor(this); - if (interceptor != nullptr) { - interceptors_.push_back( - std::unique_ptr<experimental::Interceptor>(interceptor)); - } - } - } - + + // Runs interceptor at pos \a pos. + void RunInterceptor( + experimental::InterceptorBatchMethods* interceptor_methods, size_t pos) { + GPR_CODEGEN_ASSERT(pos < interceptors_.size()); + interceptors_[pos]->Intercept(interceptor_methods); + } + + void RegisterInterceptors( + const std::vector< + std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>& + creators) { + for (const auto& creator : creators) { + auto* interceptor = creator->CreateServerInterceptor(this); + if (interceptor != nullptr) { + interceptors_.push_back( + std::unique_ptr<experimental::Interceptor>(interceptor)); + } + } + } + void Ref() { ref_.fetch_add(1, std::memory_order_relaxed); } - void Unref() { + void Unref() { if (GPR_UNLIKELY(ref_.fetch_sub(1, std::memory_order_acq_rel) == 1)) { - delete this; - } - } - + delete this; + } + } + ServerContextBase* ctx_ = nullptr; - const char* method_ = nullptr; - const Type type_; + const char* method_ = nullptr; + const Type type_; std::atomic<intptr_t> ref_{1}; - std::vector<std::unique_ptr<experimental::Interceptor>> interceptors_; - - friend class internal::InterceptorBatchMethodsImpl; + std::vector<std::unique_ptr<experimental::Interceptor>> interceptors_; + + friend class internal::InterceptorBatchMethodsImpl; friend class grpc::ServerContextBase; -}; - -} // namespace experimental -} // namespace grpc - -#endif // GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H +}; + +} // namespace experimental +} // namespace grpc + +#endif // GRPCPP_IMPL_CODEGEN_SERVER_INTERCEPTOR_H diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h index d97b725025..6b538812ed 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/server_interface.h @@ -23,7 +23,7 @@ #include <grpc/impl/codegen/grpc_types.h> #include <grpcpp/impl/codegen/byte_buffer.h> -#include <grpcpp/impl/codegen/call.h> +#include <grpcpp/impl/codegen/call.h> #include <grpcpp/impl/codegen/call_hook.h> #include <grpcpp/impl/codegen/completion_queue_tag.h> #include <grpcpp/impl/codegen/core_codegen_interface.h> @@ -66,35 +66,35 @@ class ServerInterface : public internal::CallHook { public: virtual ~ServerInterface() {} - /// \a Shutdown does the following things: - /// - /// 1. Shutdown the server: deactivate all listening ports, mark it in - /// "shutdown mode" so that further call Request's or incoming RPC matches - /// are no longer allowed. Also return all Request'ed-but-not-yet-active - /// calls as failed (!ok). This refers to calls that have been requested - /// at the server by the server-side library or application code but that - /// have not yet been matched to incoming RPCs from the client. Note that - /// this would even include default calls added automatically by the gRPC - /// C++ API without the user's input (e.g., "Unimplemented RPC method") - /// - /// 2. Block until all rpc method handlers invoked automatically by the sync - /// API finish. - /// - /// 3. If all pending calls complete (and all their operations are - /// retrieved by Next) before \a deadline expires, this finishes - /// gracefully. Otherwise, forcefully cancel all pending calls associated - /// with the server after \a deadline expires. In the case of the sync API, - /// if the RPC function for a streaming call has already been started and - /// takes a week to complete, the RPC function won't be forcefully - /// terminated (since that would leave state corrupt and incomplete) and - /// the method handler will just keep running (which will prevent the - /// server from completing the "join" operation that it needs to do at - /// shutdown time). + /// \a Shutdown does the following things: /// + /// 1. Shutdown the server: deactivate all listening ports, mark it in + /// "shutdown mode" so that further call Request's or incoming RPC matches + /// are no longer allowed. Also return all Request'ed-but-not-yet-active + /// calls as failed (!ok). This refers to calls that have been requested + /// at the server by the server-side library or application code but that + /// have not yet been matched to incoming RPCs from the client. Note that + /// this would even include default calls added automatically by the gRPC + /// C++ API without the user's input (e.g., "Unimplemented RPC method") + /// + /// 2. Block until all rpc method handlers invoked automatically by the sync + /// API finish. + /// + /// 3. If all pending calls complete (and all their operations are + /// retrieved by Next) before \a deadline expires, this finishes + /// gracefully. Otherwise, forcefully cancel all pending calls associated + /// with the server after \a deadline expires. In the case of the sync API, + /// if the RPC function for a streaming call has already been started and + /// takes a week to complete, the RPC function won't be forcefully + /// terminated (since that would leave state corrupt and incomplete) and + /// the method handler will just keep running (which will prevent the + /// server from completing the "join" operation that it needs to do at + /// shutdown time). + /// /// All completion queue associated with the server (for example, for async /// serving) must be shutdown *after* this method has returned: /// See \a ServerBuilder::AddCompletionQueue for details. - /// They must also be drained (by repeated Next) after being shutdown. + /// They must also be drained (by repeated Next) after being shutdown. /// /// \param deadline How long to wait until pending rpcs are forcefully /// terminated. @@ -103,7 +103,7 @@ class ServerInterface : public internal::CallHook { ShutdownInternal(TimePoint<T>(deadline).raw_time()); } - /// Shutdown the server without a deadline and forced cancellation. + /// Shutdown the server without a deadline and forced cancellation. /// /// All completion queue associated with the server (for example, for async /// serving) must be shutdown *after* this method has returned: @@ -200,9 +200,9 @@ class ServerInterface : public internal::CallHook { bool FinalizeResult(void** tag, bool* status) override; - private: - void ContinueFinalizeResultAfterInterception(); - + private: + void ContinueFinalizeResultAfterInterception(); + protected: ServerInterface* const server_; ::grpc::ServerContext* const context_; @@ -212,12 +212,12 @@ class ServerInterface : public internal::CallHook { void* const tag_; const bool delete_on_finalize_; grpc_call* call_; - internal::Call call_wrapper_; - internal::InterceptorBatchMethodsImpl interceptor_methods_; - bool done_intercepting_; + internal::Call call_wrapper_; + internal::InterceptorBatchMethodsImpl interceptor_methods_; + bool done_intercepting_; }; - /// RegisteredAsyncRequest is not part of the C++ API + /// RegisteredAsyncRequest is not part of the C++ API class RegisteredAsyncRequest : public BaseAsyncRequest { public: RegisteredAsyncRequest(ServerInterface* server, @@ -228,38 +228,38 @@ class ServerInterface : public internal::CallHook { void* tag, const char* name, internal::RpcMethod::RpcType type); - virtual bool FinalizeResult(void** tag, bool* status) override { - /* If we are done intercepting, then there is nothing more for us to do */ - if (done_intercepting_) { - return BaseAsyncRequest::FinalizeResult(tag, status); - } + virtual bool FinalizeResult(void** tag, bool* status) override { + /* If we are done intercepting, then there is nothing more for us to do */ + if (done_intercepting_) { + return BaseAsyncRequest::FinalizeResult(tag, status); + } call_wrapper_ = ::grpc::internal::Call( - call_, server_, call_cq_, server_->max_receive_message_size(), - context_->set_server_rpc_info(name_, type_, - *server_->interceptor_creators())); - return BaseAsyncRequest::FinalizeResult(tag, status); - } + call_, server_, call_cq_, server_->max_receive_message_size(), + context_->set_server_rpc_info(name_, type_, + *server_->interceptor_creators())); + return BaseAsyncRequest::FinalizeResult(tag, status); + } protected: void IssueRequest(void* registered_method, grpc_byte_buffer** payload, ::grpc::ServerCompletionQueue* notification_cq); - const char* name_; - const internal::RpcMethod::RpcType type_; + const char* name_; + const internal::RpcMethod::RpcType type_; }; class NoPayloadAsyncRequest final : public RegisteredAsyncRequest { public: - NoPayloadAsyncRequest(internal::RpcServiceMethod* registered_method, + NoPayloadAsyncRequest(internal::RpcServiceMethod* registered_method, ServerInterface* server, ::grpc::ServerContext* context, internal::ServerAsyncStreamingInterface* stream, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag) - : RegisteredAsyncRequest( - server, context, stream, call_cq, notification_cq, tag, - registered_method->name(), registered_method->method_type()) { - IssueRequest(registered_method->server_tag(), nullptr, notification_cq); + : RegisteredAsyncRequest( + server, context, stream, call_cq, notification_cq, tag, + registered_method->name(), registered_method->method_type()) { + IssueRequest(registered_method->server_tag(), nullptr, notification_cq); } // uses RegisteredAsyncRequest::FinalizeResult @@ -268,19 +268,19 @@ class ServerInterface : public internal::CallHook { template <class Message> class PayloadAsyncRequest final : public RegisteredAsyncRequest { public: - PayloadAsyncRequest(internal::RpcServiceMethod* registered_method, + PayloadAsyncRequest(internal::RpcServiceMethod* registered_method, ServerInterface* server, ::grpc::ServerContext* context, internal::ServerAsyncStreamingInterface* stream, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag, Message* request) - : RegisteredAsyncRequest( - server, context, stream, call_cq, notification_cq, tag, - registered_method->name(), registered_method->method_type()), + : RegisteredAsyncRequest( + server, context, stream, call_cq, notification_cq, tag, + registered_method->name(), registered_method->method_type()), registered_method_(registered_method), request_(request) { - IssueRequest(registered_method->server_tag(), payload_.bbuf_ptr(), - notification_cq); + IssueRequest(registered_method->server_tag(), payload_.bbuf_ptr(), + notification_cq); } ~PayloadAsyncRequest() { @@ -288,10 +288,10 @@ class ServerInterface : public internal::CallHook { } bool FinalizeResult(void** tag, bool* status) override { - /* If we are done intercepting, then there is nothing more for us to do */ - if (done_intercepting_) { - return RegisteredAsyncRequest::FinalizeResult(tag, status); - } + /* If we are done intercepting, then there is nothing more for us to do */ + if (done_intercepting_) { + return RegisteredAsyncRequest::FinalizeResult(tag, status); + } if (*status) { if (!payload_.Valid() || !SerializationTraits<Message>::Deserialize( payload_.bbuf_ptr(), request_) @@ -310,15 +310,15 @@ class ServerInterface : public internal::CallHook { return false; } } - /* Set interception point for recv message */ - interceptor_methods_.AddInterceptionHookPoint( - experimental::InterceptionHookPoints::POST_RECV_MESSAGE); - interceptor_methods_.SetRecvMessage(request_, nullptr); + /* Set interception point for recv message */ + interceptor_methods_.AddInterceptionHookPoint( + experimental::InterceptionHookPoints::POST_RECV_MESSAGE); + interceptor_methods_.SetRecvMessage(request_, nullptr); return RegisteredAsyncRequest::FinalizeResult(tag, status); } private: - internal::RpcServiceMethod* const registered_method_; + internal::RpcServiceMethod* const registered_method_; Message* const request_; ByteBuffer payload_; }; @@ -345,8 +345,8 @@ class ServerInterface : public internal::CallHook { ::grpc::ServerCompletionQueue* notification_cq, void* tag, Message* message) { GPR_CODEGEN_ASSERT(method); - new PayloadAsyncRequest<Message>(method, this, context, stream, call_cq, - notification_cq, tag, message); + new PayloadAsyncRequest<Message>(method, this, context, stream, call_cq, + notification_cq, tag, message); } void RequestAsyncCall(internal::RpcServiceMethod* method, @@ -356,8 +356,8 @@ class ServerInterface : public internal::CallHook { ::grpc::ServerCompletionQueue* notification_cq, void* tag) { GPR_CODEGEN_ASSERT(method); - new NoPayloadAsyncRequest(method, this, context, stream, call_cq, - notification_cq, tag); + new NoPayloadAsyncRequest(method, this, context, stream, call_cq, + notification_cq, tag); } void RequestAsyncGenericCall(GenericServerContext* context, @@ -368,27 +368,27 @@ class ServerInterface : public internal::CallHook { new GenericAsyncRequest(this, context, stream, call_cq, notification_cq, tag, true); } - - private: - // EXPERIMENTAL - // Getter method for the vector of interceptor factory objects. - // Returns a nullptr (rather than being pure) since this is a post-1.0 method - // and adding a new pure method to an interface would be a breaking change - // (even though this is private and non-API) - virtual std::vector< - std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>* - interceptor_creators() { - return nullptr; - } - - // EXPERIMENTAL - // A method to get the callbackable completion queue associated with this - // server. If the return value is nullptr, this server doesn't support - // callback operations. - // TODO(vjpai): Consider a better default like using a global CQ - // Returns nullptr (rather than being pure) since this is a post-1.0 method - // and adding a new pure method to an interface would be a breaking change - // (even though this is private and non-API) + + private: + // EXPERIMENTAL + // Getter method for the vector of interceptor factory objects. + // Returns a nullptr (rather than being pure) since this is a post-1.0 method + // and adding a new pure method to an interface would be a breaking change + // (even though this is private and non-API) + virtual std::vector< + std::unique_ptr<experimental::ServerInterceptorFactoryInterface>>* + interceptor_creators() { + return nullptr; + } + + // EXPERIMENTAL + // A method to get the callbackable completion queue associated with this + // server. If the return value is nullptr, this server doesn't support + // callback operations. + // TODO(vjpai): Consider a better default like using a global CQ + // Returns nullptr (rather than being pure) since this is a post-1.0 method + // and adding a new pure method to an interface would be a breaking change + // (even though this is private and non-API) virtual ::grpc::CompletionQueue* CallbackCQ() { return nullptr; } }; diff --git a/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h b/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h index 30be904a3c..5875fa5294 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h +++ b/contrib/libs/grpc/include/grpcpp/impl/codegen/service_type.h @@ -77,18 +77,18 @@ class Service { return false; } - bool has_callback_methods() const { + bool has_callback_methods() const { for (const auto& method : methods_) { if (method && (method->api_type() == internal::RpcServiceMethod::ApiType::CALL_BACK || method->api_type() == internal::RpcServiceMethod::ApiType::RAW_CALL_BACK)) { - return true; - } - } - return false; - } - + return true; + } + } + return false; + } + bool has_generic_methods() const { for (const auto& method : methods_) { if (method.get() == nullptr) { @@ -99,29 +99,29 @@ class Service { } protected: - // TODO(vjpai): Promote experimental contents once callback API is accepted - class experimental_type { - public: - explicit experimental_type(Service* service) : service_(service) {} - - void MarkMethodCallback(int index, internal::MethodHandler* handler) { + // TODO(vjpai): Promote experimental contents once callback API is accepted + class experimental_type { + public: + explicit experimental_type(Service* service) : service_(service) {} + + void MarkMethodCallback(int index, internal::MethodHandler* handler) { service_->MarkMethodCallbackInternal(index, handler); - } - - void MarkMethodRawCallback(int index, internal::MethodHandler* handler) { + } + + void MarkMethodRawCallback(int index, internal::MethodHandler* handler) { service_->MarkMethodRawCallbackInternal(index, handler); - } - + } + internal::MethodHandler* GetHandler(int index) { return service_->GetHandlerInternal(index); } - private: - Service* service_; - }; - - experimental_type experimental() { return experimental_type(this); } - + private: + Service* service_; + }; + + experimental_type experimental() { return experimental_type(this); } + template <class Message> void RequestAsyncUnary(int index, ::grpc::ServerContext* context, Message* request, @@ -129,11 +129,11 @@ class Service { ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag) { - // Typecast the index to size_t for indexing into a vector - // while preserving the API that existed before a compiler - // warning was first seen (grpc/grpc#11664) - size_t idx = static_cast<size_t>(index); - server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, + // Typecast the index to size_t for indexing into a vector + // while preserving the API that existed before a compiler + // warning was first seen (grpc/grpc#11664) + size_t idx = static_cast<size_t>(index); + server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, notification_cq, tag, request); } void RequestAsyncClientStreaming( @@ -141,8 +141,8 @@ class Service { internal::ServerAsyncStreamingInterface* stream, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag) { - size_t idx = static_cast<size_t>(index); - server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, + size_t idx = static_cast<size_t>(index); + server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, notification_cq, tag); } template <class Message> @@ -151,8 +151,8 @@ class Service { internal::ServerAsyncStreamingInterface* stream, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag) { - size_t idx = static_cast<size_t>(index); - server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, + size_t idx = static_cast<size_t>(index); + server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, notification_cq, tag, request); } void RequestAsyncBidiStreaming( @@ -160,8 +160,8 @@ class Service { internal::ServerAsyncStreamingInterface* stream, ::grpc::CompletionQueue* call_cq, ::grpc::ServerCompletionQueue* notification_cq, void* tag) { - size_t idx = static_cast<size_t>(index); - server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, + size_t idx = static_cast<size_t>(index); + server_->RequestAsyncCall(methods_[idx].get(), context, stream, call_cq, notification_cq, tag); } @@ -170,50 +170,50 @@ class Service { } void MarkMethodAsync(int index) { - // This does not have to be a hard error, however no one has approached us - // with a use case yet. Please file an issue if you believe you have one. - size_t idx = static_cast<size_t>(index); + // This does not have to be a hard error, however no one has approached us + // with a use case yet. Please file an issue if you believe you have one. + size_t idx = static_cast<size_t>(index); GPR_CODEGEN_ASSERT( - methods_[idx].get() != nullptr && + methods_[idx].get() != nullptr && "Cannot mark the method as 'async' because it has already been " "marked as 'generic'."); - methods_[idx]->SetServerApiType(internal::RpcServiceMethod::ApiType::ASYNC); - } - - void MarkMethodRaw(int index) { - // This does not have to be a hard error, however no one has approached us - // with a use case yet. Please file an issue if you believe you have one. - size_t idx = static_cast<size_t>(index); - GPR_CODEGEN_ASSERT(methods_[idx].get() != nullptr && - "Cannot mark the method as 'raw' because it has already " - "been marked as 'generic'."); - methods_[idx]->SetServerApiType(internal::RpcServiceMethod::ApiType::RAW); + methods_[idx]->SetServerApiType(internal::RpcServiceMethod::ApiType::ASYNC); } + void MarkMethodRaw(int index) { + // This does not have to be a hard error, however no one has approached us + // with a use case yet. Please file an issue if you believe you have one. + size_t idx = static_cast<size_t>(index); + GPR_CODEGEN_ASSERT(methods_[idx].get() != nullptr && + "Cannot mark the method as 'raw' because it has already " + "been marked as 'generic'."); + methods_[idx]->SetServerApiType(internal::RpcServiceMethod::ApiType::RAW); + } + void MarkMethodGeneric(int index) { - // This does not have to be a hard error, however no one has approached us - // with a use case yet. Please file an issue if you believe you have one. - size_t idx = static_cast<size_t>(index); + // This does not have to be a hard error, however no one has approached us + // with a use case yet. Please file an issue if you believe you have one. + size_t idx = static_cast<size_t>(index); GPR_CODEGEN_ASSERT( - methods_[idx]->handler() != nullptr && + methods_[idx]->handler() != nullptr && "Cannot mark the method as 'generic' because it has already been " - "marked as 'async' or 'raw'."); - methods_[idx].reset(); + "marked as 'async' or 'raw'."); + methods_[idx].reset(); } void MarkMethodStreamed(int index, internal::MethodHandler* streamed_method) { - // This does not have to be a hard error, however no one has approached us - // with a use case yet. Please file an issue if you believe you have one. - size_t idx = static_cast<size_t>(index); - GPR_CODEGEN_ASSERT(methods_[idx] && methods_[idx]->handler() && + // This does not have to be a hard error, however no one has approached us + // with a use case yet. Please file an issue if you believe you have one. + size_t idx = static_cast<size_t>(index); + GPR_CODEGEN_ASSERT(methods_[idx] && methods_[idx]->handler() && "Cannot mark an async or generic method Streamed"); - methods_[idx]->SetHandler(streamed_method); + methods_[idx]->SetHandler(streamed_method); // From the server's point of view, streamed unary is a special // case of BIDI_STREAMING that has 1 read and 1 write, in that order, // and split server-side streaming is BIDI_STREAMING with 1 read and // any number of writes, in that order. - methods_[idx]->SetMethodType(internal::RpcMethod::BIDI_STREAMING); + methods_[idx]->SetMethodType(internal::RpcMethod::BIDI_STREAMING); } #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL diff --git a/contrib/libs/grpc/include/grpcpp/impl/grpc_library.h b/contrib/libs/grpc/include/grpcpp/impl/grpc_library.h index 3711c09879..eb6fc56c44 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/grpc_library.h +++ b/contrib/libs/grpc/include/grpcpp/impl/grpc_library.h @@ -40,12 +40,12 @@ class GrpcLibraryInitializer final { public: GrpcLibraryInitializer() { if (grpc::g_glip == nullptr) { - static auto* const g_gli = new GrpcLibrary(); - grpc::g_glip = g_gli; + static auto* const g_gli = new GrpcLibrary(); + grpc::g_glip = g_gli; } if (grpc::g_core_codegen_interface == nullptr) { - static auto* const g_core_codegen = new CoreCodegen(); - grpc::g_core_codegen_interface = g_core_codegen; + static auto* const g_core_codegen = new CoreCodegen(); + grpc::g_core_codegen_interface = g_core_codegen; } } diff --git a/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h b/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h index 8fedca2b14..8703e9d75b 100644 --- a/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h +++ b/contrib/libs/grpc/include/grpcpp/impl/server_builder_plugin.h @@ -41,9 +41,9 @@ class ServerBuilderPlugin { virtual ~ServerBuilderPlugin() {} virtual TString name() = 0; - /// UpdateServerBuilder will be called at an early stage in - /// ServerBuilder::BuildAndStart(), right after the ServerBuilderOptions have - /// done their updates. + /// UpdateServerBuilder will be called at an early stage in + /// ServerBuilder::BuildAndStart(), right after the ServerBuilderOptions have + /// done their updates. virtual void UpdateServerBuilder(ServerBuilder* /*builder*/) {} /// InitServer will be called in ServerBuilder::BuildAndStart(), after the diff --git a/contrib/libs/grpc/include/grpcpp/opencensus.h b/contrib/libs/grpc/include/grpcpp/opencensus.h index 0da949ab73..262b82de26 100644 --- a/contrib/libs/grpc/include/grpcpp/opencensus.h +++ b/contrib/libs/grpc/include/grpcpp/opencensus.h @@ -1,36 +1,36 @@ -/* - * +/* + * * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_OPENCENSUS_H -#define GRPCPP_OPENCENSUS_H - + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_OPENCENSUS_H +#define GRPCPP_OPENCENSUS_H + #include "opencensus/trace/span.h" - + namespace grpc { class ServerContext; // These symbols in this file will not be included in the binary unless // grpc_opencensus_plugin build target was added as a dependency. At the moment // it is only setup to be built with Bazel. - + // Registers the OpenCensus plugin with gRPC, so that it will be used for future // RPCs. This must be called before any views are created. void RegisterOpenCensusPlugin(); - + // RPC stats definitions, defined by // https://github.com/census-instrumentation/opencensus-specs/blob/master/stats/gRPC.md @@ -42,6 +42,6 @@ void RegisterOpenCensusViewsForExport(); // Returns the tracing Span for the current RPC. ::opencensus::trace::Span GetSpanFromServerContext(ServerContext* context); -} // namespace grpc - -#endif // GRPCPP_OPENCENSUS_H +} // namespace grpc + +#endif // GRPCPP_OPENCENSUS_H diff --git a/contrib/libs/grpc/include/grpcpp/security/credentials.h b/contrib/libs/grpc/include/grpcpp/security/credentials.h index 339e9d4c27..ebaafc6b32 100644 --- a/contrib/libs/grpc/include/grpcpp/security/credentials.h +++ b/contrib/libs/grpc/include/grpcpp/security/credentials.h @@ -19,10 +19,10 @@ #ifndef GRPCPP_SECURITY_CREDENTIALS_H #define GRPCPP_SECURITY_CREDENTIALS_H -#if defined(__GNUC__) -#pragma GCC system_header -#endif - +#if defined(__GNUC__) +#pragma GCC system_header +#endif + #include <map> #include <memory> #include <vector> @@ -49,7 +49,7 @@ std::shared_ptr<Channel> CreateCustomChannel( const grpc::string& target, const std::shared_ptr<grpc::ChannelCredentials>& creds, const grpc::ChannelArguments& args); - + namespace experimental { std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors( const grpc::string& target, @@ -59,7 +59,7 @@ std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors( std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators); } - + /// A channel credentials object encapsulates all the state needed by a client /// to authenticate with a server for a given channel. /// It can make various assertions, e.g., about the client’s identity, role @@ -310,7 +310,7 @@ struct AltsCredentialsOptions { /// Builds ALTS Credentials given ALTS specific options std::shared_ptr<ChannelCredentials> AltsCredentials( const AltsCredentialsOptions& options); - + /// Builds Local Credentials. std::shared_ptr<ChannelCredentials> LocalCredentials( grpc_local_connect_type type); diff --git a/contrib/libs/grpc/include/grpcpp/security/server_credentials.h b/contrib/libs/grpc/include/grpcpp/security/server_credentials.h index d0a532360a..5199bb5bff 100644 --- a/contrib/libs/grpc/include/grpcpp/security/server_credentials.h +++ b/contrib/libs/grpc/include/grpcpp/security/server_credentials.h @@ -99,7 +99,7 @@ std::shared_ptr<ServerCredentials> AltsServerCredentials( /// Builds Local ServerCredentials. std::shared_ptr<ServerCredentials> AltsServerCredentials( const AltsServerCredentialsOptions& options); - + std::shared_ptr<ServerCredentials> LocalServerCredentials( grpc_local_connect_type type); diff --git a/contrib/libs/grpc/include/grpcpp/support/client_callback.h b/contrib/libs/grpc/include/grpcpp/support/client_callback.h index 063fdc4f85..1c22caca7f 100644 --- a/contrib/libs/grpc/include/grpcpp/support/client_callback.h +++ b/contrib/libs/grpc/include/grpcpp/support/client_callback.h @@ -1,24 +1,24 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_SUPPORT_CLIENT_CALLBACK_H -#define GRPCPP_SUPPORT_CLIENT_CALLBACK_H - -#include <grpcpp/impl/codegen/client_callback.h> - -#endif // GRPCPP_SUPPORT_CLIENT_CALLBACK_H +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_SUPPORT_CLIENT_CALLBACK_H +#define GRPCPP_SUPPORT_CLIENT_CALLBACK_H + +#include <grpcpp/impl/codegen/client_callback.h> + +#endif // GRPCPP_SUPPORT_CLIENT_CALLBACK_H diff --git a/contrib/libs/grpc/include/grpcpp/support/client_interceptor.h b/contrib/libs/grpc/include/grpcpp/support/client_interceptor.h index 50810e3fe3..063c663219 100644 --- a/contrib/libs/grpc/include/grpcpp/support/client_interceptor.h +++ b/contrib/libs/grpc/include/grpcpp/support/client_interceptor.h @@ -1,24 +1,24 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_SUPPORT_CLIENT_INTERCEPTOR_H -#define GRPCPP_SUPPORT_CLIENT_INTERCEPTOR_H - -#include <grpcpp/impl/codegen/client_interceptor.h> - -#endif // GRPCPP_SUPPORT_CLIENT_INTERCEPTOR_H +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_SUPPORT_CLIENT_INTERCEPTOR_H +#define GRPCPP_SUPPORT_CLIENT_INTERCEPTOR_H + +#include <grpcpp/impl/codegen/client_interceptor.h> + +#endif // GRPCPP_SUPPORT_CLIENT_INTERCEPTOR_H diff --git a/contrib/libs/grpc/include/grpcpp/support/interceptor.h b/contrib/libs/grpc/include/grpcpp/support/interceptor.h index 7ff79516ba..0f51a84521 100644 --- a/contrib/libs/grpc/include/grpcpp/support/interceptor.h +++ b/contrib/libs/grpc/include/grpcpp/support/interceptor.h @@ -1,24 +1,24 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_SUPPORT_INTERCEPTOR_H -#define GRPCPP_SUPPORT_INTERCEPTOR_H - -#include <grpcpp/impl/codegen/interceptor.h> - -#endif // GRPCPP_SUPPORT_INTERCEPTOR_H +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_SUPPORT_INTERCEPTOR_H +#define GRPCPP_SUPPORT_INTERCEPTOR_H + +#include <grpcpp/impl/codegen/interceptor.h> + +#endif // GRPCPP_SUPPORT_INTERCEPTOR_H diff --git a/contrib/libs/grpc/include/grpcpp/support/server_callback.h b/contrib/libs/grpc/include/grpcpp/support/server_callback.h index b0aeeb53c5..d91dc9be3d 100644 --- a/contrib/libs/grpc/include/grpcpp/support/server_callback.h +++ b/contrib/libs/grpc/include/grpcpp/support/server_callback.h @@ -1,24 +1,24 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_SUPPORT_SERVER_CALLBACK_H -#define GRPCPP_SUPPORT_SERVER_CALLBACK_H - -#include <grpcpp/impl/codegen/server_callback.h> - -#endif // GRPCPP_SUPPORT_SERVER_CALLBACK_H +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_SUPPORT_SERVER_CALLBACK_H +#define GRPCPP_SUPPORT_SERVER_CALLBACK_H + +#include <grpcpp/impl/codegen/server_callback.h> + +#endif // GRPCPP_SUPPORT_SERVER_CALLBACK_H diff --git a/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h b/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h index b0a6229b66..180b41b376 100644 --- a/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h +++ b/contrib/libs/grpc/include/grpcpp/support/server_interceptor.h @@ -1,24 +1,24 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H -#define GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H - -#include <grpcpp/impl/codegen/server_interceptor.h> - -#endif // GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H +#define GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H + +#include <grpcpp/impl/codegen/server_interceptor.h> + +#endif // GRPCPP_SUPPORT_SERVER_INTERCEPTOR_H diff --git a/contrib/libs/grpc/src/compiler/cpp_generator.cc b/contrib/libs/grpc/src/compiler/cpp_generator.cc index 5759177474..446d8858ae 100644 --- a/contrib/libs/grpc/src/compiler/cpp_generator.cc +++ b/contrib/libs/grpc/src/compiler/cpp_generator.cc @@ -146,19 +146,19 @@ TString GetHeaderIncludes(grpc_generator::File* file, // fully de-experimentalized since we will no longer be using // macros from it. static const char* headers_strs[] = { - "functional", + "functional", "grpc/impl/codegen/port_platform.h", - "grpcpp/impl/codegen/async_generic_service.h", + "grpcpp/impl/codegen/async_generic_service.h", "grpcpp/impl/codegen/async_stream.h", "grpcpp/impl/codegen/async_unary_call.h", - "grpcpp/impl/codegen/client_callback.h", + "grpcpp/impl/codegen/client_callback.h", "grpcpp/impl/codegen/client_context.h", "grpcpp/impl/codegen/completion_queue.h", "grpcpp/impl/codegen/message_allocator.h", "grpcpp/impl/codegen/method_handler.h", "grpcpp/impl/codegen/proto_utils.h", "grpcpp/impl/codegen/rpc_method.h", - "grpcpp/impl/codegen/server_callback.h", + "grpcpp/impl/codegen/server_callback.h", "grpcpp/impl/codegen/server_callback_handlers.h", "grpcpp/impl/codegen/server_context.h", "grpcpp/impl/codegen/service_type.h", @@ -583,33 +583,33 @@ void PrintHeaderClientMethod(grpc_generator::Printer* printer, } } -void PrintHeaderClientMethodCallbackInterfacesStart( - grpc_generator::Printer* printer, +void PrintHeaderClientMethodCallbackInterfacesStart( + grpc_generator::Printer* printer, std::map<TString, TString>* /*vars*/) { - // This declares the interface for the callback-based API. The components - // are pure; even though this is new (post-1.0) API, it can be pure because - // it is an entirely new interface that happens to be scoped within - // StubInterface, not new additions to StubInterface itself - printer->Print("class experimental_async_interface {\n"); - // All methods in this new interface are public. There is no need for private - // "Raw" methods since the callback-based API returns unowned raw pointers - printer->Print(" public:\n"); - printer->Indent(); - printer->Print("virtual ~experimental_async_interface() {}\n"); -} - -void PrintHeaderClientMethodCallbackInterfaces( - grpc_generator::Printer* printer, const grpc_generator::Method* method, + // This declares the interface for the callback-based API. The components + // are pure; even though this is new (post-1.0) API, it can be pure because + // it is an entirely new interface that happens to be scoped within + // StubInterface, not new additions to StubInterface itself + printer->Print("class experimental_async_interface {\n"); + // All methods in this new interface are public. There is no need for private + // "Raw" methods since the callback-based API returns unowned raw pointers + printer->Print(" public:\n"); + printer->Indent(); + printer->Print("virtual ~experimental_async_interface() {}\n"); +} + +void PrintHeaderClientMethodCallbackInterfaces( + grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - - if (method->NoStreaming()) { - printer->Print(*vars, - "virtual void $Method$(::grpc::ClientContext* context, " - "const $Request$* request, $Response$* response, " - "std::function<void(::grpc::Status)>) = 0;\n"); + (*vars)["Method"] = method->name(); + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + + if (method->NoStreaming()) { + printer->Print(*vars, + "virtual void $Method$(::grpc::ClientContext* context, " + "const $Request$* request, $Response$* response, " + "std::function<void(::grpc::Status)>) = 0;\n"); // TODO(vjpai): Remove experimental versions and macros when callback API is // fully de-experimentalized. printer->Print(*vars, @@ -622,92 +622,92 @@ void PrintHeaderClientMethodCallbackInterfaces( "const $Request$* request, $Response$* response, " "::grpc::experimental::ClientUnaryReactor* reactor) = 0;\n" "#endif\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print(*vars, + } else if (ClientOnlyStreaming(method)) { + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" - "virtual void $Method$(::grpc::ClientContext* context, " - "$Response$* response, " + "virtual void $Method$(::grpc::ClientContext* context, " + "$Response$* response, " "::grpc::ClientWriteReactor< $Request$>* " "reactor) = 0;\n" "#else\n" "virtual void $Method$(::grpc::ClientContext* context, " "$Response$* response, " - "::grpc::experimental::ClientWriteReactor< $Request$>* " + "::grpc::experimental::ClientWriteReactor< $Request$>* " "reactor) = 0;\n" "#endif\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print(*vars, + } else if (ServerOnlyStreaming(method)) { + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" - "virtual void $Method$(::grpc::ClientContext* context, " - "$Request$* request, " + "virtual void $Method$(::grpc::ClientContext* context, " + "$Request$* request, " "::grpc::ClientReadReactor< $Response$>* " "reactor) = 0;\n" "#else\n" "virtual void $Method$(::grpc::ClientContext* context, " "$Request$* request, " - "::grpc::experimental::ClientReadReactor< $Response$>* " + "::grpc::experimental::ClientReadReactor< $Response$>* " "reactor) = 0;\n" "#endif\n"); - } else if (method->BidiStreaming()) { - printer->Print(*vars, + } else if (method->BidiStreaming()) { + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" - "virtual void $Method$(::grpc::ClientContext* context, " + "virtual void $Method$(::grpc::ClientContext* context, " "::grpc::ClientBidiReactor< " "$Request$,$Response$>* reactor) = 0;\n" "#else\n" "virtual void $Method$(::grpc::ClientContext* context, " - "::grpc::experimental::ClientBidiReactor< " + "::grpc::experimental::ClientBidiReactor< " "$Request$,$Response$>* reactor) = 0;\n" "#endif\n"); - } -} - -void PrintHeaderClientMethodCallbackInterfacesEnd( - grpc_generator::Printer* printer, + } +} + +void PrintHeaderClientMethodCallbackInterfacesEnd( + grpc_generator::Printer* printer, std::map<TString, TString>* /*vars*/) { - printer->Outdent(); - printer->Print("};\n"); + printer->Outdent(); + printer->Print("};\n"); printer->Print( "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" "typedef class experimental_async_interface async_interface;\n" "#endif\n"); - - // Declare a function to give the async stub contents. It can't be pure - // since this is a new API in StubInterface, but it is meaningless by default - // (since any stub that wants to use it must have its own implementation of - // the callback functions therein), so make the default return value nullptr. - // Intentionally include the word "class" to avoid possible shadowing. - printer->Print( + + // Declare a function to give the async stub contents. It can't be pure + // since this is a new API in StubInterface, but it is meaningless by default + // (since any stub that wants to use it must have its own implementation of + // the callback functions therein), so make the default return value nullptr. + // Intentionally include the word "class" to avoid possible shadowing. + printer->Print( "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" "async_interface* async() { return experimental_async(); }\n" "#endif\n"); printer->Print( - "virtual class experimental_async_interface* experimental_async() { " - "return nullptr; }\n"); -} - -void PrintHeaderClientMethodCallbackStart( - grpc_generator::Printer* printer, + "virtual class experimental_async_interface* experimental_async() { " + "return nullptr; }\n"); +} + +void PrintHeaderClientMethodCallbackStart( + grpc_generator::Printer* printer, std::map<TString, TString>* /*vars*/) { - // This declares the stub entry for the callback-based API. - printer->Print("class experimental_async final :\n"); - printer->Print(" public StubInterface::experimental_async_interface {\n"); - printer->Print(" public:\n"); - printer->Indent(); -} - + // This declares the stub entry for the callback-based API. + printer->Print("class experimental_async final :\n"); + printer->Print(" public StubInterface::experimental_async_interface {\n"); + printer->Print(" public:\n"); + printer->Indent(); +} + void PrintHeaderClientMethodCallback(grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { - (*vars)["Method"] = method->name(); - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - - if (method->NoStreaming()) { - printer->Print(*vars, - "void $Method$(::grpc::ClientContext* context, " - "const $Request$* request, $Response$* response, " - "std::function<void(::grpc::Status)>) override;\n"); + (*vars)["Method"] = method->name(); + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + + if (method->NoStreaming()) { + printer->Print(*vars, + "void $Method$(::grpc::ClientContext* context, " + "const $Request$* request, $Response$* response, " + "std::function<void(::grpc::Status)>) override;\n"); printer->Print( *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" @@ -719,67 +719,67 @@ void PrintHeaderClientMethodCallback(grpc_generator::Printer* printer, "const $Request$* request, $Response$* response, " "::grpc::experimental::ClientUnaryReactor* reactor) override;\n" "#endif\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print(*vars, + } else if (ClientOnlyStreaming(method)) { + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" - "void $Method$(::grpc::ClientContext* context, " - "$Response$* response, " + "void $Method$(::grpc::ClientContext* context, " + "$Response$* response, " "::grpc::ClientWriteReactor< $Request$>* " "reactor) override;\n" "#else\n" "void $Method$(::grpc::ClientContext* context, " "$Response$* response, " - "::grpc::experimental::ClientWriteReactor< $Request$>* " + "::grpc::experimental::ClientWriteReactor< $Request$>* " "reactor) override;\n" "#endif\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print(*vars, + } else if (ServerOnlyStreaming(method)) { + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" - "void $Method$(::grpc::ClientContext* context, " - "$Request$* request, " + "void $Method$(::grpc::ClientContext* context, " + "$Request$* request, " "::grpc::ClientReadReactor< $Response$>* " "reactor) override;\n" "#else\n" "void $Method$(::grpc::ClientContext* context, " "$Request$* request, " - "::grpc::experimental::ClientReadReactor< $Response$>* " + "::grpc::experimental::ClientReadReactor< $Response$>* " "reactor) override;\n" "#endif\n"); - - } else if (method->BidiStreaming()) { - printer->Print(*vars, + + } else if (method->BidiStreaming()) { + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" - "void $Method$(::grpc::ClientContext* context, " + "void $Method$(::grpc::ClientContext* context, " "::grpc::ClientBidiReactor< " "$Request$,$Response$>* reactor) override;\n" "#else\n" "void $Method$(::grpc::ClientContext* context, " - "::grpc::experimental::ClientBidiReactor< " + "::grpc::experimental::ClientBidiReactor< " "$Request$,$Response$>* reactor) override;\n" "#endif\n"); - } -} - -void PrintHeaderClientMethodCallbackEnd( - grpc_generator::Printer* printer, + } +} + +void PrintHeaderClientMethodCallbackEnd( + grpc_generator::Printer* printer, std::map<TString, TString>* /*vars*/) { - printer->Outdent(); - printer->Print(" private:\n"); - printer->Indent(); - printer->Print("friend class Stub;\n"); - printer->Print("explicit experimental_async(Stub* stub): stub_(stub) { }\n"); - // include a function with a dummy use of stub_ to avoid an unused - // private member warning for service with no methods - printer->Print("Stub* stub() { return stub_; }\n"); - printer->Print("Stub* stub_;\n"); - printer->Outdent(); - printer->Print("};\n"); - - printer->Print( - "class experimental_async_interface* experimental_async() override { " - "return &async_stub_; }\n"); -} - + printer->Outdent(); + printer->Print(" private:\n"); + printer->Indent(); + printer->Print("friend class Stub;\n"); + printer->Print("explicit experimental_async(Stub* stub): stub_(stub) { }\n"); + // include a function with a dummy use of stub_ to avoid an unused + // private member warning for service with no methods + printer->Print("Stub* stub() { return stub_; }\n"); + printer->Print("Stub* stub_;\n"); + printer->Outdent(); + printer->Print("};\n"); + + printer->Print( + "class experimental_async_interface* experimental_async() override { " + "return &async_stub_; }\n"); +} + void PrintHeaderClientMethodData(grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { @@ -822,11 +822,11 @@ void PrintHeaderServerMethodSync(grpc_generator::Printer* printer, printer->Print(method->GetTrailingComments("//").c_str()); } -// Helper generator. Disables the sync API for Request and Response, then adds -// in an async API for RealRequest and RealResponse types. This is to be used -// to generate async and raw async APIs. -void PrintHeaderServerAsyncMethodsHelper( - grpc_generator::Printer* printer, const grpc_generator::Method* method, +// Helper generator. Disables the sync API for Request and Response, then adds +// in an async API for RealRequest and RealResponse types. This is to be used +// to generate async and raw async APIs. +void PrintHeaderServerAsyncMethodsHelper( + grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { if (method->NoStreaming()) { printer->Print( @@ -841,8 +841,8 @@ void PrintHeaderServerAsyncMethodsHelper( printer->Print( *vars, "void Request$Method$(" - "::grpc::ServerContext* context, $RealRequest$* request, " - "::grpc::ServerAsyncResponseWriter< $RealResponse$>* response, " + "::grpc::ServerContext* context, $RealRequest$* request, " + "::grpc::ServerAsyncResponseWriter< $RealResponse$>* response, " "::grpc::CompletionQueue* new_call_cq, " "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); printer->Print(*vars, @@ -864,7 +864,7 @@ void PrintHeaderServerAsyncMethodsHelper( *vars, "void Request$Method$(" "::grpc::ServerContext* context, " - "::grpc::ServerAsyncReader< $RealResponse$, $RealRequest$>* reader, " + "::grpc::ServerAsyncReader< $RealResponse$, $RealRequest$>* reader, " "::grpc::CompletionQueue* new_call_cq, " "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); printer->Print(*vars, @@ -885,8 +885,8 @@ void PrintHeaderServerAsyncMethodsHelper( printer->Print( *vars, "void Request$Method$(" - "::grpc::ServerContext* context, $RealRequest$* request, " - "::grpc::ServerAsyncWriter< $RealResponse$>* writer, " + "::grpc::ServerContext* context, $RealRequest$* request, " + "::grpc::ServerAsyncWriter< $RealResponse$>* writer, " "::grpc::CompletionQueue* new_call_cq, " "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); printer->Print( @@ -901,7 +901,7 @@ void PrintHeaderServerAsyncMethodsHelper( "::grpc::Status $Method$(" "::grpc::ServerContext* /*context*/, " "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - " override {\n" + " override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -909,8 +909,8 @@ void PrintHeaderServerAsyncMethodsHelper( *vars, "void Request$Method$(" "::grpc::ServerContext* context, " - "::grpc::ServerAsyncReaderWriter< $RealResponse$, $RealRequest$>* " - "stream, " + "::grpc::ServerAsyncReaderWriter< $RealResponse$, $RealRequest$>* " + "stream, " "::grpc::CompletionQueue* new_call_cq, " "::grpc::ServerCompletionQueue* notification_cq, void *tag) {\n"); printer->Print(*vars, @@ -918,56 +918,56 @@ void PrintHeaderServerAsyncMethodsHelper( "context, stream, new_call_cq, notification_cq, tag);\n"); printer->Print("}\n"); } -} - -void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer, - const grpc_generator::Method* method, +} + +void PrintHeaderServerMethodAsync(grpc_generator::Printer* printer, + const grpc_generator::Method* method, std::map<TString, TString>* vars) { - (*vars)["Method"] = method->name(); - // These will be disabled - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - // These will be used for the async API - (*vars)["RealRequest"] = method->input_type_name(); - (*vars)["RealResponse"] = method->output_type_name(); - printer->Print(*vars, "template <class BaseClass>\n"); - printer->Print(*vars, - "class WithAsyncMethod_$Method$ : public BaseClass {\n"); - printer->Print( - " private:\n" + (*vars)["Method"] = method->name(); + // These will be disabled + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + // These will be used for the async API + (*vars)["RealRequest"] = method->input_type_name(); + (*vars)["RealResponse"] = method->output_type_name(); + printer->Print(*vars, "template <class BaseClass>\n"); + printer->Print(*vars, + "class WithAsyncMethod_$Method$ : public BaseClass {\n"); + printer->Print( + " private:\n" " void BaseClassMustBeDerivedFromService(const Service* /*service*/) " "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, - "WithAsyncMethod_$Method$() {\n" - " ::grpc::Service::MarkMethodAsync($Idx$);\n" - "}\n"); - printer->Print(*vars, - "~WithAsyncMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - PrintHeaderServerAsyncMethodsHelper(printer, method, vars); + printer->Print(" public:\n"); + printer->Indent(); + printer->Print(*vars, + "WithAsyncMethod_$Method$() {\n" + " ::grpc::Service::MarkMethodAsync($Idx$);\n" + "}\n"); + printer->Print(*vars, + "~WithAsyncMethod_$Method$() override {\n" + " BaseClassMustBeDerivedFromService(this);\n" + "}\n"); + PrintHeaderServerAsyncMethodsHelper(printer, method, vars); printer->Outdent(); printer->Print(*vars, "};\n"); } -// Helper generator. Disables the sync API for Request and Response, then adds -// in a callback API for RealRequest and RealResponse types. This is to be used -// to generate callback and raw callback APIs. -void PrintHeaderServerCallbackMethodsHelper( - grpc_generator::Printer* printer, const grpc_generator::Method* method, +// Helper generator. Disables the sync API for Request and Response, then adds +// in a callback API for RealRequest and RealResponse types. This is to be used +// to generate callback and raw callback APIs. +void PrintHeaderServerCallbackMethodsHelper( + grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { - if (method->NoStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" + if (method->NoStreaming()) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" "virtual ::grpc::ServerUnaryReactor* $Method$(\n" @@ -982,41 +982,41 @@ void PrintHeaderServerCallbackMethodsHelper( "$RealResponse$* /*response*/)\n" "#endif\n" " { return nullptr; }\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" + } else if (ClientOnlyStreaming(method)) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" "::grpc::ServerContext* /*context*/, " "::grpc::ServerReader< $Request$>* /*reader*/, " "$Response$* /*response*/) override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); - printer->Print(*vars, + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); + printer->Print(*vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" "virtual ::grpc::ServerReadReactor< " "$RealRequest$>* $Method$(\n" " ::grpc::CallbackServerContext* " "/*context*/, $RealResponse$* /*response*/)\n" "#else\n" - "virtual ::grpc::experimental::ServerReadReactor< " + "virtual ::grpc::experimental::ServerReadReactor< " "$RealRequest$>* $Method$(\n" " ::grpc::experimental::CallbackServerContext* " "/*context*/, $RealResponse$* /*response*/)\n" "#endif\n" " { return nullptr; }\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" + } else if (ServerOnlyStreaming(method)) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" "::grpc::ServerContext* /*context*/, const $Request$* /*request*/, " "::grpc::ServerWriter< $Response$>* /*writer*/) override " - "{\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + "{\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); printer->Print( *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" @@ -1030,17 +1030,17 @@ void PrintHeaderServerCallbackMethodsHelper( "/*context*/, const $RealRequest$* /*request*/)\n" "#endif\n" " { return nullptr; }\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, - "// disable synchronous version of this method\n" - "::grpc::Status $Method$(" + } else if (method->BidiStreaming()) { + printer->Print( + *vars, + "// disable synchronous version of this method\n" + "::grpc::Status $Method$(" "::grpc::ServerContext* /*context*/, " "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - " override {\n" - " abort();\n" - " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" - "}\n"); + " override {\n" + " abort();\n" + " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" + "}\n"); printer->Print( *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" @@ -1054,33 +1054,33 @@ void PrintHeaderServerCallbackMethodsHelper( " ::grpc::experimental::CallbackServerContext* /*context*/)\n" "#endif\n" " { return nullptr; }\n"); - } -} - + } +} + void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { - (*vars)["Method"] = method->name(); - // These will be disabled - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - // These will be used for the callback API - (*vars)["RealRequest"] = method->input_type_name(); - (*vars)["RealResponse"] = method->output_type_name(); - printer->Print(*vars, "template <class BaseClass>\n"); - printer->Print( - *vars, - "class ExperimentalWithCallbackMethod_$Method$ : public BaseClass {\n"); - printer->Print( - " private:\n" + (*vars)["Method"] = method->name(); + // These will be disabled + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + // These will be used for the callback API + (*vars)["RealRequest"] = method->input_type_name(); + (*vars)["RealResponse"] = method->output_type_name(); + printer->Print(*vars, "template <class BaseClass>\n"); + printer->Print( + *vars, + "class ExperimentalWithCallbackMethod_$Method$ : public BaseClass {\n"); + printer->Print( + " private:\n" " void BaseClassMustBeDerivedFromService(const Service* /*service*/) " "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, "ExperimentalWithCallbackMethod_$Method$() {\n"); - if (method->NoStreaming()) { - printer->Print( - *vars, + printer->Print(" public:\n"); + printer->Indent(); + printer->Print(*vars, "ExperimentalWithCallbackMethod_$Method$() {\n"); + if (method->NoStreaming()) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1088,7 +1088,7 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "#endif\n" " MarkMethodCallback($Idx$,\n" " new ::grpc::internal::CallbackUnaryHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1114,9 +1114,9 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, " static_cast<::grpc::internal::CallbackUnaryHandler< " "$RealRequest$, $RealResponse$>*>(handler)\n" " ->SetMessageAllocator(allocator);\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, + } else if (ClientOnlyStreaming(method)) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1124,7 +1124,7 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "#endif\n" " MarkMethodCallback($Idx$,\n" " new ::grpc::internal::CallbackClientStreamingHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1135,9 +1135,9 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "$RealResponse$* " "response) { " "return this->$Method$(context, response); }));\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, + } else if (ServerOnlyStreaming(method)) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1145,7 +1145,7 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "#endif\n" " MarkMethodCallback($Idx$,\n" " new ::grpc::internal::CallbackServerStreamingHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1156,9 +1156,9 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "const $RealRequest$* " "request) { " "return this->$Method$(context, request); }));\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, + } else if (method->BidiStreaming()) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1166,7 +1166,7 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "#endif\n" " MarkMethodCallback($Idx$,\n" " new ::grpc::internal::CallbackBidiHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1175,41 +1175,41 @@ void PrintHeaderServerMethodCallback(grpc_generator::Printer* printer, "#endif\n" " context) " "{ return this->$Method$(context); }));\n"); - } - printer->Print(*vars, "}\n"); - printer->Print(*vars, - "~ExperimentalWithCallbackMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - PrintHeaderServerCallbackMethodsHelper(printer, method, vars); - printer->Outdent(); - printer->Print(*vars, "};\n"); -} - -void PrintHeaderServerMethodRawCallback( - grpc_generator::Printer* printer, const grpc_generator::Method* method, + } + printer->Print(*vars, "}\n"); + printer->Print(*vars, + "~ExperimentalWithCallbackMethod_$Method$() override {\n" + " BaseClassMustBeDerivedFromService(this);\n" + "}\n"); + PrintHeaderServerCallbackMethodsHelper(printer, method, vars); + printer->Outdent(); + printer->Print(*vars, "};\n"); +} + +void PrintHeaderServerMethodRawCallback( + grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { - (*vars)["Method"] = method->name(); - // These will be disabled - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - // These will be used for raw API - (*vars)["RealRequest"] = "::grpc::ByteBuffer"; - (*vars)["RealResponse"] = "::grpc::ByteBuffer"; - printer->Print(*vars, "template <class BaseClass>\n"); - printer->Print(*vars, - "class ExperimentalWithRawCallbackMethod_$Method$ : public " - "BaseClass {\n"); - printer->Print( - " private:\n" + (*vars)["Method"] = method->name(); + // These will be disabled + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + // These will be used for raw API + (*vars)["RealRequest"] = "::grpc::ByteBuffer"; + (*vars)["RealResponse"] = "::grpc::ByteBuffer"; + printer->Print(*vars, "template <class BaseClass>\n"); + printer->Print(*vars, + "class ExperimentalWithRawCallbackMethod_$Method$ : public " + "BaseClass {\n"); + printer->Print( + " private:\n" " void BaseClassMustBeDerivedFromService(const Service* /*service*/) " "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, "ExperimentalWithRawCallbackMethod_$Method$() {\n"); - if (method->NoStreaming()) { - printer->Print( - *vars, + printer->Print(" public:\n"); + printer->Indent(); + printer->Print(*vars, "ExperimentalWithRawCallbackMethod_$Method$() {\n"); + if (method->NoStreaming()) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1217,7 +1217,7 @@ void PrintHeaderServerMethodRawCallback( "#endif\n" " MarkMethodRawCallback($Idx$,\n" " new ::grpc::internal::CallbackUnaryHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1229,9 +1229,9 @@ void PrintHeaderServerMethodRawCallback( "request, " "$RealResponse$* response) { return " "this->$Method$(context, request, response); }));\n"); - } else if (ClientOnlyStreaming(method)) { - printer->Print( - *vars, + } else if (ClientOnlyStreaming(method)) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1239,7 +1239,7 @@ void PrintHeaderServerMethodRawCallback( "#endif\n" " MarkMethodRawCallback($Idx$,\n" " new ::grpc::internal::CallbackClientStreamingHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1249,9 +1249,9 @@ void PrintHeaderServerMethodRawCallback( " context, " "$RealResponse$* response) " "{ return this->$Method$(context, response); }));\n"); - } else if (ServerOnlyStreaming(method)) { - printer->Print( - *vars, + } else if (ServerOnlyStreaming(method)) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1259,7 +1259,7 @@ void PrintHeaderServerMethodRawCallback( "#endif\n" " MarkMethodRawCallback($Idx$,\n" " new ::grpc::internal::CallbackServerStreamingHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1270,9 +1270,9 @@ void PrintHeaderServerMethodRawCallback( "const" "$RealRequest$* request) { return " "this->$Method$(context, request); }));\n"); - } else if (method->BidiStreaming()) { - printer->Print( - *vars, + } else if (method->BidiStreaming()) { + printer->Print( + *vars, "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::Service::\n" "#else\n" @@ -1280,7 +1280,7 @@ void PrintHeaderServerMethodRawCallback( "#endif\n" " MarkMethodRawCallback($Idx$,\n" " new ::grpc::internal::CallbackBidiHandler< " - "$RealRequest$, $RealResponse$>(\n" + "$RealRequest$, $RealResponse$>(\n" " [this](\n" "#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n" " ::grpc::CallbackServerContext*\n" @@ -1289,17 +1289,17 @@ void PrintHeaderServerMethodRawCallback( "#endif\n" " context) " "{ return this->$Method$(context); }));\n"); - } - printer->Print(*vars, "}\n"); - printer->Print(*vars, - "~ExperimentalWithRawCallbackMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - PrintHeaderServerCallbackMethodsHelper(printer, method, vars); - printer->Outdent(); - printer->Print(*vars, "};\n"); -} - + } + printer->Print(*vars, "}\n"); + printer->Print(*vars, + "~ExperimentalWithRawCallbackMethod_$Method$() override {\n" + " BaseClassMustBeDerivedFromService(this);\n" + "}\n"); + PrintHeaderServerCallbackMethodsHelper(printer, method, vars); + printer->Outdent(); + printer->Print(*vars, "};\n"); +} + void PrintHeaderServerMethodStreamedUnary( grpc_generator::Printer* printer, const grpc_generator::Method* method, std::map<TString, TString>* vars) { @@ -1471,7 +1471,7 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer, "::grpc::Status $Method$(" "::grpc::ServerContext* /*context*/, " "::grpc::ServerReaderWriter< $Response$, $Request$>* /*stream*/) " - " override {\n" + " override {\n" " abort();\n" " return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, \"\");\n" "}\n"); @@ -1480,37 +1480,37 @@ void PrintHeaderServerMethodGeneric(grpc_generator::Printer* printer, printer->Print(*vars, "};\n"); } -void PrintHeaderServerMethodRaw(grpc_generator::Printer* printer, - const grpc_generator::Method* method, +void PrintHeaderServerMethodRaw(grpc_generator::Printer* printer, + const grpc_generator::Method* method, std::map<TString, TString>* vars) { - (*vars)["Method"] = method->name(); - // These will be disabled - (*vars)["Request"] = method->input_type_name(); - (*vars)["Response"] = method->output_type_name(); - // These will be used for raw API - (*vars)["RealRequest"] = "::grpc::ByteBuffer"; - (*vars)["RealResponse"] = "::grpc::ByteBuffer"; - printer->Print(*vars, "template <class BaseClass>\n"); - printer->Print(*vars, "class WithRawMethod_$Method$ : public BaseClass {\n"); - printer->Print( - " private:\n" + (*vars)["Method"] = method->name(); + // These will be disabled + (*vars)["Request"] = method->input_type_name(); + (*vars)["Response"] = method->output_type_name(); + // These will be used for raw API + (*vars)["RealRequest"] = "::grpc::ByteBuffer"; + (*vars)["RealResponse"] = "::grpc::ByteBuffer"; + printer->Print(*vars, "template <class BaseClass>\n"); + printer->Print(*vars, "class WithRawMethod_$Method$ : public BaseClass {\n"); + printer->Print( + " private:\n" " void BaseClassMustBeDerivedFromService(const Service* /*service*/) " "{}\n"); - printer->Print(" public:\n"); - printer->Indent(); - printer->Print(*vars, - "WithRawMethod_$Method$() {\n" - " ::grpc::Service::MarkMethodRaw($Idx$);\n" - "}\n"); - printer->Print(*vars, - "~WithRawMethod_$Method$() override {\n" - " BaseClassMustBeDerivedFromService(this);\n" - "}\n"); - PrintHeaderServerAsyncMethodsHelper(printer, method, vars); - printer->Outdent(); - printer->Print(*vars, "};\n"); -} - + printer->Print(" public:\n"); + printer->Indent(); + printer->Print(*vars, + "WithRawMethod_$Method$() {\n" + " ::grpc::Service::MarkMethodRaw($Idx$);\n" + "}\n"); + printer->Print(*vars, + "~WithRawMethod_$Method$() override {\n" + " BaseClassMustBeDerivedFromService(this);\n" + "}\n"); + PrintHeaderServerAsyncMethodsHelper(printer, method, vars); + printer->Outdent(); + printer->Print(*vars, "};\n"); +} + void PrintHeaderService(grpc_generator::Printer* printer, const grpc_generator::Service* service, std::map<TString, TString>* vars) { @@ -1540,14 +1540,14 @@ void PrintHeaderService(grpc_generator::Printer* printer, true); printer->Print(service->method(i)->GetTrailingComments("//").c_str()); } - PrintHeaderClientMethodCallbackInterfacesStart(printer, vars); - for (int i = 0; i < service->method_count(); ++i) { - printer->Print(service->method(i)->GetLeadingComments("//").c_str()); - PrintHeaderClientMethodCallbackInterfaces(printer, service->method(i).get(), + PrintHeaderClientMethodCallbackInterfacesStart(printer, vars); + for (int i = 0; i < service->method_count(); ++i) { + printer->Print(service->method(i)->GetLeadingComments("//").c_str()); + PrintHeaderClientMethodCallbackInterfaces(printer, service->method(i).get(), vars); - printer->Print(service->method(i)->GetTrailingComments("//").c_str()); - } - PrintHeaderClientMethodCallbackInterfacesEnd(printer, vars); + printer->Print(service->method(i)->GetTrailingComments("//").c_str()); + } + PrintHeaderClientMethodCallbackInterfacesEnd(printer, vars); printer->Outdent(); printer->Print("private:\n"); printer->Indent(); @@ -1567,16 +1567,16 @@ void PrintHeaderService(grpc_generator::Printer* printer, for (int i = 0; i < service->method_count(); ++i) { PrintHeaderClientMethod(printer, service->method(i).get(), vars, true); } - PrintHeaderClientMethodCallbackStart(printer, vars); - for (int i = 0; i < service->method_count(); ++i) { + PrintHeaderClientMethodCallbackStart(printer, vars); + for (int i = 0; i < service->method_count(); ++i) { PrintHeaderClientMethodCallback(printer, service->method(i).get(), vars); - } - PrintHeaderClientMethodCallbackEnd(printer, vars); + } + PrintHeaderClientMethodCallbackEnd(printer, vars); printer->Outdent(); printer->Print("\n private:\n"); printer->Indent(); printer->Print("std::shared_ptr< ::grpc::ChannelInterface> channel_;\n"); - printer->Print("class experimental_async async_stub_{this};\n"); + printer->Print("class experimental_async async_stub_{this};\n"); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderClientMethod(printer, service->method(i).get(), vars, false); } @@ -1614,7 +1614,7 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print("typedef "); for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); + (*vars)["method_name"] = service->method(i)->name(); printer->Print(*vars, "WithAsyncMethod_$method_name$<"); } printer->Print("Service"); @@ -1623,23 +1623,23 @@ void PrintHeaderService(grpc_generator::Printer* printer, } printer->Print(" AsyncService;\n"); - // Server side - Callback - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodCallback(printer, service->method(i).get(), vars); - } - + // Server side - Callback + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodCallback(printer, service->method(i).get(), vars); + } + printer->Print("#ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL\n"); - printer->Print("typedef "); - - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); - printer->Print(*vars, "ExperimentalWithCallbackMethod_$method_name$<"); - } - printer->Print("Service"); - for (int i = 0; i < service->method_count(); ++i) { - printer->Print(" >"); - } + printer->Print("typedef "); + + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["method_name"] = service->method(i)->name(); + printer->Print(*vars, "ExperimentalWithCallbackMethod_$method_name$<"); + } + printer->Print("Service"); + for (int i = 0; i < service->method_count(); ++i) { + printer->Print(" >"); + } printer->Print(" CallbackService;\n"); printer->Print("#endif\n\n"); @@ -1653,26 +1653,26 @@ void PrintHeaderService(grpc_generator::Printer* printer, for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); } - printer->Print(" ExperimentalCallbackService;\n"); - + printer->Print(" ExperimentalCallbackService;\n"); + // Server side - Generic for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); PrintHeaderServerMethodGeneric(printer, service->method(i).get(), vars); } - // Server side - Raw - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodRaw(printer, service->method(i).get(), vars); - } - - // Server side - Raw Callback - for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Idx"] = as_string(i); - PrintHeaderServerMethodRawCallback(printer, service->method(i).get(), vars); - } - + // Server side - Raw + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodRaw(printer, service->method(i).get(), vars); + } + + // Server side - Raw Callback + for (int i = 0; i < service->method_count(); ++i) { + (*vars)["Idx"] = as_string(i); + PrintHeaderServerMethodRawCallback(printer, service->method(i).get(), vars); + } + // Server side - Streamed Unary for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); @@ -1682,7 +1682,7 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print("typedef "); for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); + (*vars)["method_name"] = service->method(i)->name(); if (service->method(i)->NoStreaming()) { printer->Print(*vars, "WithStreamedUnaryMethod_$method_name$<"); } @@ -1704,7 +1704,7 @@ void PrintHeaderService(grpc_generator::Printer* printer, printer->Print("typedef "); for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); + (*vars)["method_name"] = service->method(i)->name(); auto method = service->method(i); if (ServerOnlyStreaming(method.get())) { printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); @@ -1722,7 +1722,7 @@ void PrintHeaderService(grpc_generator::Printer* printer, // Server side - typedef for controlled both unary and server-side streaming printer->Print("typedef "); for (int i = 0; i < service->method_count(); ++i) { - (*vars)["method_name"] = service->method(i)->name(); + (*vars)["method_name"] = service->method(i)->name(); auto method = service->method(i); if (ServerOnlyStreaming(method.get())) { printer->Print(*vars, "WithSplitStreamingMethod_$method_name$<"); @@ -1841,16 +1841,16 @@ TString GetSourceIncludes(grpc_generator::File* file, auto printer = file->CreatePrinter(&output); std::map<TString, TString> vars; static const char* headers_strs[] = { - "functional", + "functional", "grpcpp/impl/codegen/async_stream.h", "grpcpp/impl/codegen/async_unary_call.h", "grpcpp/impl/codegen/channel_interface.h", "grpcpp/impl/codegen/client_unary_call.h", - "grpcpp/impl/codegen/client_callback.h", + "grpcpp/impl/codegen/client_callback.h", "grpcpp/impl/codegen/message_allocator.h", "grpcpp/impl/codegen/method_handler.h", "grpcpp/impl/codegen/rpc_service_method.h", - "grpcpp/impl/codegen/server_callback.h", + "grpcpp/impl/codegen/server_callback.h", "grpcpp/impl/codegen/server_callback_handlers.h", "grpcpp/impl/codegen/server_context.h", "grpcpp/impl/codegen/service_type.h", @@ -1895,17 +1895,17 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, " return ::grpc::internal::BlockingUnaryCall" "(channel_.get(), rpcmethod_$Method$_, " "context, request, response);\n}\n\n"); - - printer->Print(*vars, - "void $ns$$Service$::Stub::experimental_async::$Method$(" - "::grpc::ClientContext* context, " - "const $Request$* request, $Response$* response, " - "std::function<void(::grpc::Status)> f) {\n"); - printer->Print(*vars, + + printer->Print(*vars, + "void $ns$$Service$::Stub::experimental_async::$Method$(" + "::grpc::ClientContext* context, " + "const $Request$* request, $Response$* response, " + "std::function<void(::grpc::Status)> f) {\n"); + printer->Print(*vars, " ::grpc::internal::CallbackUnaryCall" - "(stub_->channel_.get(), stub_->rpcmethod_$Method$_, " - "context, request, response, std::move(f));\n}\n\n"); - + "(stub_->channel_.get(), stub_->rpcmethod_$Method$_, " + "context, request, response, std::move(f));\n}\n\n"); + printer->Print(*vars, "void $ns$$Service$::Stub::experimental_async::$Method$(" "::grpc::ClientContext* context, " @@ -1953,21 +1953,21 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "rpcmethod_$Method$_, " "context, response);\n" "}\n\n"); - - printer->Print( - *vars, - "void $ns$$Service$::" - "Stub::experimental_async::$Method$(::grpc::ClientContext* context, " - "$Response$* response, " - "::grpc::experimental::ClientWriteReactor< $Request$>* reactor) {\n"); - printer->Print(*vars, + + printer->Print( + *vars, + "void $ns$$Service$::" + "Stub::experimental_async::$Method$(::grpc::ClientContext* context, " + "$Response$* response, " + "::grpc::experimental::ClientWriteReactor< $Request$>* reactor) {\n"); + printer->Print(*vars, " ::grpc::internal::ClientCallbackWriterFactory< " - "$Request$>::Create(" - "stub_->channel_.get(), " - "stub_->rpcmethod_$Method$_, " - "context, response, reactor);\n" - "}\n\n"); - + "$Request$>::Create(" + "stub_->channel_.get(), " + "stub_->rpcmethod_$Method$_, " + "context, response, reactor);\n" + "}\n\n"); + for (auto async_prefix : async_prefixes) { (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; @@ -1999,21 +1999,21 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "rpcmethod_$Method$_, " "context, request);\n" "}\n\n"); - - printer->Print( - *vars, - "void $ns$$Service$::Stub::experimental_async::$Method$(::grpc::" - "ClientContext* context, " - "$Request$* request, " - "::grpc::experimental::ClientReadReactor< $Response$>* reactor) {\n"); - printer->Print(*vars, + + printer->Print( + *vars, + "void $ns$$Service$::Stub::experimental_async::$Method$(::grpc::" + "ClientContext* context, " + "$Request$* request, " + "::grpc::experimental::ClientReadReactor< $Response$>* reactor) {\n"); + printer->Print(*vars, " ::grpc::internal::ClientCallbackReaderFactory< " - "$Response$>::Create(" - "stub_->channel_.get(), " - "stub_->rpcmethod_$Method$_, " - "context, request, reactor);\n" - "}\n\n"); - + "$Response$>::Create(" + "stub_->channel_.get(), " + "stub_->rpcmethod_$Method$_, " + "context, request, reactor);\n" + "}\n\n"); + for (auto async_prefix : async_prefixes) { (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; @@ -2045,13 +2045,13 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "rpcmethod_$Method$_, " "context);\n" "}\n\n"); - - printer->Print( - *vars, - "void $ns$$Service$::Stub::experimental_async::$Method$(::grpc::" - "ClientContext* context, " - "::grpc::experimental::ClientBidiReactor< $Request$,$Response$>* " - "reactor) {\n"); + + printer->Print( + *vars, + "void $ns$$Service$::Stub::experimental_async::$Method$(::grpc::" + "ClientContext* context, " + "::grpc::experimental::ClientBidiReactor< $Request$,$Response$>* " + "reactor) {\n"); printer->Print(*vars, " ::grpc::internal::ClientCallbackReaderWriterFactory< " "$Request$,$Response$>::Create(" @@ -2059,7 +2059,7 @@ void PrintSourceClientMethod(grpc_generator::Printer* printer, "stub_->rpcmethod_$Method$_, " "context, reactor);\n" "}\n\n"); - + for (auto async_prefix : async_prefixes) { (*vars)["AsyncPrefix"] = async_prefix.prefix; (*vars)["AsyncStart"] = async_prefix.start; @@ -2150,7 +2150,7 @@ void PrintSourceService(grpc_generator::Printer* printer, printer->Print(*vars, "static const char* $prefix$$Service$_method_names[] = {\n"); for (int i = 0; i < service->method_count(); ++i) { - (*vars)["Method"] = service->method(i)->name(); + (*vars)["Method"] = service->method(i)->name(); printer->Print(*vars, " \"/$Package$$Service$/$Method$\",\n"); } printer->Print(*vars, "};\n\n"); diff --git a/contrib/libs/grpc/src/compiler/csharp_generator.cc b/contrib/libs/grpc/src/compiler/csharp_generator.cc index 3b7107c4c4..ccffd6c601 100644 --- a/contrib/libs/grpc/src/compiler/csharp_generator.cc +++ b/contrib/libs/grpc/src/compiler/csharp_generator.cc @@ -200,25 +200,25 @@ TString GetCSharpMethodType(MethodType method_type) { } TString GetCSharpServerMethodType(MethodType method_type) { - switch (method_type) { - case METHODTYPE_NO_STREAMING: - return "grpc::UnaryServerMethod"; - case METHODTYPE_CLIENT_STREAMING: - return "grpc::ClientStreamingServerMethod"; - case METHODTYPE_SERVER_STREAMING: - return "grpc::ServerStreamingServerMethod"; - case METHODTYPE_BIDI_STREAMING: - return "grpc::DuplexStreamingServerMethod"; - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; -} - + switch (method_type) { + case METHODTYPE_NO_STREAMING: + return "grpc::UnaryServerMethod"; + case METHODTYPE_CLIENT_STREAMING: + return "grpc::ClientStreamingServerMethod"; + case METHODTYPE_SERVER_STREAMING: + return "grpc::ServerStreamingServerMethod"; + case METHODTYPE_BIDI_STREAMING: + return "grpc::DuplexStreamingServerMethod"; + } + GOOGLE_LOG(FATAL) << "Can't get here."; + return ""; +} + TString GetServiceNameFieldName() { return "__ServiceName"; } TString GetMarshallerFieldName(const Descriptor* message) { - return "__Marshaller_" + - grpc_generator::StringReplace(message->full_name(), ".", "_", true); + return "__Marshaller_" + + grpc_generator::StringReplace(message->full_name(), ".", "_", true); } TString GetMethodFieldName(const MethodDescriptor* method) { @@ -673,65 +673,65 @@ void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor* service) { out->Print("{\n"); out->Indent(); - out->Print("return grpc::ServerServiceDefinition.CreateBuilder()"); + out->Print("return grpc::ServerServiceDefinition.CreateBuilder()"); out->Indent(); out->Indent(); for (int i = 0; i < service->method_count(); i++) { const MethodDescriptor* method = service->method(i); - out->Print("\n.AddMethod($methodfield$, serviceImpl.$methodname$)", + out->Print("\n.AddMethod($methodfield$, serviceImpl.$methodname$)", "methodfield", GetMethodFieldName(method), "methodname", method->name()); } - out->Print(".Build();\n"); - out->Outdent(); + out->Print(".Build();\n"); out->Outdent(); - out->Outdent(); - out->Print("}\n"); - out->Print("\n"); -} - -void GenerateBindServiceWithBinderMethod(Printer* out, - const ServiceDescriptor* service) { - out->Print( - "/// <summary>Register service method with a service " - "binder with or without implementation. Useful when customizing the " - "service binding logic.\n" - "/// Note: this method is part of an experimental API that can change or " - "be " - "removed without any prior notice.</summary>\n"); - out->Print( - "/// <param name=\"serviceBinder\">Service methods will be bound by " - "calling <c>AddMethod</c> on this object." - "</param>\n"); - out->Print( - "/// <param name=\"serviceImpl\">An object implementing the server-side" - " handling logic.</param>\n"); - out->Print( - "public static void BindService(grpc::ServiceBinderBase serviceBinder, " - "$implclass$ " - "serviceImpl)\n", - "implclass", GetServerClassName(service)); - out->Print("{\n"); - out->Indent(); - - for (int i = 0; i < service->method_count(); i++) { - const MethodDescriptor* method = service->method(i); - out->Print( - "serviceBinder.AddMethod($methodfield$, serviceImpl == null ? null : " - "new $servermethodtype$<$inputtype$, $outputtype$>(" - "serviceImpl.$methodname$));\n", - "methodfield", GetMethodFieldName(method), "servermethodtype", - GetCSharpServerMethodType(GetMethodType(method)), "inputtype", - GetClassName(method->input_type()), "outputtype", - GetClassName(method->output_type()), "methodname", method->name()); - } out->Outdent(); out->Print("}\n"); out->Print("\n"); } +void GenerateBindServiceWithBinderMethod(Printer* out, + const ServiceDescriptor* service) { + out->Print( + "/// <summary>Register service method with a service " + "binder with or without implementation. Useful when customizing the " + "service binding logic.\n" + "/// Note: this method is part of an experimental API that can change or " + "be " + "removed without any prior notice.</summary>\n"); + out->Print( + "/// <param name=\"serviceBinder\">Service methods will be bound by " + "calling <c>AddMethod</c> on this object." + "</param>\n"); + out->Print( + "/// <param name=\"serviceImpl\">An object implementing the server-side" + " handling logic.</param>\n"); + out->Print( + "public static void BindService(grpc::ServiceBinderBase serviceBinder, " + "$implclass$ " + "serviceImpl)\n", + "implclass", GetServerClassName(service)); + out->Print("{\n"); + out->Indent(); + + for (int i = 0; i < service->method_count(); i++) { + const MethodDescriptor* method = service->method(i); + out->Print( + "serviceBinder.AddMethod($methodfield$, serviceImpl == null ? null : " + "new $servermethodtype$<$inputtype$, $outputtype$>(" + "serviceImpl.$methodname$));\n", + "methodfield", GetMethodFieldName(method), "servermethodtype", + GetCSharpServerMethodType(GetMethodType(method)), "inputtype", + GetClassName(method->input_type()), "outputtype", + GetClassName(method->output_type()), "methodname", method->name()); + } + + out->Outdent(); + out->Print("}\n"); + out->Print("\n"); +} + void GenerateService(Printer* out, const ServiceDescriptor* service, bool generate_client, bool generate_server, bool internal_access) { @@ -760,7 +760,7 @@ void GenerateService(Printer* out, const ServiceDescriptor* service, } if (generate_server) { GenerateBindServiceMethod(out, service); - GenerateBindServiceWithBinderMethod(out, service); + GenerateBindServiceWithBinderMethod(out, service); } out->Outdent(); @@ -798,26 +798,26 @@ TString GetServices(const FileDescriptor* file, bool generate_client, out.PrintRaw(leading_comments.c_str()); } - out.Print("#pragma warning disable 0414, 1591\n"); - + out.Print("#pragma warning disable 0414, 1591\n"); + out.Print("#region Designer generated code\n"); out.Print("\n"); out.Print("using grpc = global::Grpc.Core;\n"); out.Print("\n"); TString file_namespace = GetFileNamespace(file); - if (file_namespace != "") { - out.Print("namespace $namespace$ {\n", "namespace", file_namespace); - out.Indent(); - } + if (file_namespace != "") { + out.Print("namespace $namespace$ {\n", "namespace", file_namespace); + out.Indent(); + } for (int i = 0; i < file->service_count(); i++) { GenerateService(&out, file->service(i), generate_client, generate_server, internal_access); } - if (file_namespace != "") { - out.Outdent(); - out.Print("}\n"); - } + if (file_namespace != "") { + out.Outdent(); + out.Print("}\n"); + } out.Print("#endregion\n"); } return output; diff --git a/contrib/libs/grpc/src/compiler/objective_c_generator.cc b/contrib/libs/grpc/src/compiler/objective_c_generator.cc index 07826b6a8d..ce2e9f0869 100644 --- a/contrib/libs/grpc/src/compiler/objective_c_generator.cc +++ b/contrib/libs/grpc/src/compiler/objective_c_generator.cc @@ -120,29 +120,29 @@ void PrintAdvancedSignature(Printer* printer, const MethodDescriptor* method, PrintMethodSignature(printer, method, vars); } -void PrintV2Signature(Printer* printer, const MethodDescriptor* method, +void PrintV2Signature(Printer* printer, const MethodDescriptor* method, map< ::TString, ::TString> vars) { - if (method->client_streaming()) { - vars["return_type"] = "GRPCStreamingProtoCall *"; - } else { - vars["return_type"] = "GRPCUnaryProtoCall *"; - } - vars["method_name"] = - grpc_generator::LowercaseFirstLetter(vars["method_name"]); - - PrintAllComments(method, printer); - - printer->Print(vars, "- ($return_type$)$method_name$With"); - if (method->client_streaming()) { - printer->Print("ResponseHandler:(id<GRPCProtoResponseHandler>)handler"); - } else { - printer->Print(vars, - "Message:($request_class$ *)message " - "responseHandler:(id<GRPCProtoResponseHandler>)handler"); - } - printer->Print(" callOptions:(GRPCCallOptions *_Nullable)callOptions"); -} - + if (method->client_streaming()) { + vars["return_type"] = "GRPCStreamingProtoCall *"; + } else { + vars["return_type"] = "GRPCUnaryProtoCall *"; + } + vars["method_name"] = + grpc_generator::LowercaseFirstLetter(vars["method_name"]); + + PrintAllComments(method, printer); + + printer->Print(vars, "- ($return_type$)$method_name$With"); + if (method->client_streaming()) { + printer->Print("ResponseHandler:(id<GRPCProtoResponseHandler>)handler"); + } else { + printer->Print(vars, + "Message:($request_class$ *)message " + "responseHandler:(id<GRPCProtoResponseHandler>)handler"); + } + printer->Print(" callOptions:(GRPCCallOptions *_Nullable)callOptions"); +} + inline map< ::TString, ::TString> GetMethodVars( const MethodDescriptor* method) { map< ::TString, ::TString> res; @@ -165,16 +165,16 @@ void PrintMethodDeclarations(Printer* printer, const MethodDescriptor* method) { printer->Print(";\n\n\n"); } -void PrintV2MethodDeclarations(Printer* printer, - const MethodDescriptor* method) { +void PrintV2MethodDeclarations(Printer* printer, + const MethodDescriptor* method) { map< ::TString, ::TString> vars = GetMethodVars(method); - - PrintProtoRpcDeclarationAsPragma(printer, method, vars); - - PrintV2Signature(printer, method, vars); - printer->Print(";\n\n"); -} - + + PrintProtoRpcDeclarationAsPragma(printer, method, vars); + + PrintV2Signature(printer, method, vars); + printer->Print(";\n\n"); +} + void PrintSimpleImplementation(Printer* printer, const MethodDescriptor* method, map< ::TString, ::TString> vars) { printer->Print("{\n"); @@ -217,25 +217,25 @@ void PrintAdvancedImplementation(Printer* printer, printer->Print("}\n"); } -void PrintV2Implementation(Printer* printer, const MethodDescriptor* method, +void PrintV2Implementation(Printer* printer, const MethodDescriptor* method, map< ::TString, ::TString> vars) { - printer->Print(" {\n"); - if (method->client_streaming()) { - printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n"); - printer->Print(" responseHandler:handler\n"); - printer->Print(" callOptions:callOptions\n"); - printer->Print( - vars, " responseClass:[$response_class$ class]];\n}\n\n"); - } else { - printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n"); - printer->Print(" message:message\n"); - printer->Print(" responseHandler:handler\n"); - printer->Print(" callOptions:callOptions\n"); - printer->Print( - vars, " responseClass:[$response_class$ class]];\n}\n\n"); - } -} - + printer->Print(" {\n"); + if (method->client_streaming()) { + printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n"); + printer->Print(" responseHandler:handler\n"); + printer->Print(" callOptions:callOptions\n"); + printer->Print( + vars, " responseClass:[$response_class$ class]];\n}\n\n"); + } else { + printer->Print(vars, " return [self RPCToMethod:@\"$method_name$\"\n"); + printer->Print(" message:message\n"); + printer->Print(" responseHandler:handler\n"); + printer->Print(" callOptions:callOptions\n"); + printer->Print( + vars, " responseClass:[$response_class$ class]];\n}\n\n"); + } +} + void PrintMethodImplementations(Printer* printer, const MethodDescriptor* method, const Parameters& generator_params) { @@ -252,9 +252,9 @@ void PrintMethodImplementations(Printer* printer, PrintAdvancedSignature(printer, method, vars); PrintAdvancedImplementation(printer, method, vars); } - - PrintV2Signature(printer, method, vars); - PrintV2Implementation(printer, method, vars); + + PrintV2Signature(printer, method, vars); + PrintV2Implementation(printer, method, vars); } } // namespace @@ -297,7 +297,7 @@ void PrintMethodImplementations(Printer* printer, " * recognize call options provided in the initializer. Using " "the v2 protocol is recommended.\n" " */\n"); - printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n"); + printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n"); for (int i = 0; i < service->method_count(); i++) { PrintMethodDeclarations(&printer, service->method(i)); } @@ -308,23 +308,23 @@ void PrintMethodImplementations(Printer* printer, ::TString GetV2Protocol(const ServiceDescriptor* service) { ::TString output; - - // Scope the output stream so it closes and finalizes output to the string. - grpc::protobuf::io::StringOutputStream output_stream(&output); - Printer printer(&output_stream, '$'); - + + // Scope the output stream so it closes and finalizes output to the string. + grpc::protobuf::io::StringOutputStream output_stream(&output); + Printer printer(&output_stream, '$'); + map< ::TString, ::TString> vars = { - {"service_class", ServiceClassName(service) + "2"}}; - - printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n"); - for (int i = 0; i < service->method_count(); i++) { - PrintV2MethodDeclarations(&printer, service->method(i)); - } - printer.Print("@end\n\n"); - - return output; -} - + {"service_class", ServiceClassName(service) + "2"}}; + + printer.Print(vars, "@protocol $service_class$ <NSObject>\n\n"); + for (int i = 0; i < service->method_count(); i++) { + PrintV2MethodDeclarations(&printer, service->method(i)); + } + printer.Print("@end\n\n"); + + return output; +} + ::TString GetInterface(const ServiceDescriptor* service, const Parameters& generator_params) { ::TString output; @@ -349,13 +349,13 @@ void PrintMethodImplementations(Printer* printer, } printer.Print(">\n"); printer.Print( - "- (instancetype)initWithHost:(NSString *)host " - "callOptions:(GRPCCallOptions " - "*_Nullable)callOptions" + "- (instancetype)initWithHost:(NSString *)host " + "callOptions:(GRPCCallOptions " + "*_Nullable)callOptions" " NS_DESIGNATED_INITIALIZER;\n"); - printer.Print( - "+ (instancetype)serviceWithHost:(NSString *)host " - "callOptions:(GRPCCallOptions *_Nullable)callOptions;\n"); + printer.Print( + "+ (instancetype)serviceWithHost:(NSString *)host " + "callOptions:(GRPCCallOptions *_Nullable)callOptions;\n"); if (!generator_params.no_v1_compatibility) { printer.Print( "// The following methods belong to a set of old APIs that have been " @@ -383,16 +383,16 @@ void PrintMethodImplementations(Printer* printer, printer.Print(vars, "@implementation $service_class$\n\n" - "#pragma clang diagnostic push\n" - "#pragma clang diagnostic ignored " - "\"-Wobjc-designated-initializers\"\n\n" + "#pragma clang diagnostic push\n" + "#pragma clang diagnostic ignored " + "\"-Wobjc-designated-initializers\"\n\n" "// Designated initializer\n" - "- (instancetype)initWithHost:(NSString *)host " - "callOptions:(GRPCCallOptions *_Nullable)callOptions {\n" - " return [super initWithHost:host\n" - " packageName:@\"$package$\"\n" - " serviceName:@\"$service_name$\"\n" - " callOptions:callOptions];\n" + "- (instancetype)initWithHost:(NSString *)host " + "callOptions:(GRPCCallOptions *_Nullable)callOptions {\n" + " return [super initWithHost:host\n" + " packageName:@\"$package$\"\n" + " serviceName:@\"$service_name$\"\n" + " callOptions:callOptions];\n" "}\n\n"); if (!generator_params.no_v1_compatibility) { printer.Print(vars, @@ -417,9 +417,9 @@ void PrintMethodImplementations(Printer* printer, printer.Print( "- (instancetype)initWithHost:(NSString *)host\n" " packageName:(NSString *)packageName\n" - " serviceName:(NSString *)serviceName\n" - " callOptions:(GRPCCallOptions *)callOptions {\n" - " return [self initWithHost:host callOptions:callOptions];\n" + " serviceName:(NSString *)serviceName\n" + " callOptions:(GRPCCallOptions *)callOptions {\n" + " return [self initWithHost:host callOptions:callOptions];\n" "}\n\n"); printer.Print("#pragma mark - Class Methods\n\n"); @@ -430,9 +430,9 @@ void PrintMethodImplementations(Printer* printer, "}\n\n"); } printer.Print( - "+ (instancetype)serviceWithHost:(NSString *)host " - "callOptions:(GRPCCallOptions *_Nullable)callOptions {\n" - " return [[self alloc] initWithHost:host callOptions:callOptions];\n" + "+ (instancetype)serviceWithHost:(NSString *)host " + "callOptions:(GRPCCallOptions *_Nullable)callOptions {\n" + " return [[self alloc] initWithHost:host callOptions:callOptions];\n" "}\n\n"); printer.Print("#pragma mark - Method Implementations\n\n"); diff --git a/contrib/libs/grpc/src/compiler/objective_c_generator.h b/contrib/libs/grpc/src/compiler/objective_c_generator.h index 9770f65436..2a7753e23c 100644 --- a/contrib/libs/grpc/src/compiler/objective_c_generator.h +++ b/contrib/libs/grpc/src/compiler/objective_c_generator.h @@ -36,15 +36,15 @@ using ::TString; string GetAllMessageClasses(const FileDescriptor* file); // Returns the content to be included defining the @protocol segment at the -// insertion point of the generated implementation file. This interface is -// legacy and for backwards compatibility. +// insertion point of the generated implementation file. This interface is +// legacy and for backwards compatibility. string GetProtocol(const ServiceDescriptor* service, const Parameters& generator_params); -// Returns the content to be included defining the @protocol segment at the -// insertion point of the generated implementation file. -string GetV2Protocol(const ServiceDescriptor* service); - +// Returns the content to be included defining the @protocol segment at the +// insertion point of the generated implementation file. +string GetV2Protocol(const ServiceDescriptor* service); + // Returns the content to be included defining the @interface segment at the // insertion point of the generated implementation file. string GetInterface(const ServiceDescriptor* service, diff --git a/contrib/libs/grpc/src/compiler/ruby_generator.cc b/contrib/libs/grpc/src/compiler/ruby_generator.cc index c82e78fd64..ab90716cd8 100644 --- a/contrib/libs/grpc/src/compiler/ruby_generator.cc +++ b/contrib/libs/grpc/src/compiler/ruby_generator.cc @@ -157,13 +157,13 @@ TString GetServices(const FileDescriptor* file) { } TString package_name = RubyPackage(file); - + // Write out a file header. std::map<TString, TString> header_comment_vars = ListToDict({ "file.name", file->name(), "file.package", - package_name, + package_name, }); out.Print("# Generated by the protocol buffer compiler. DO NOT EDIT!\n"); out.Print(header_comment_vars, diff --git a/contrib/libs/grpc/src/core/ext/filters/census/grpc_context.cc b/contrib/libs/grpc/src/core/ext/filters/census/grpc_context.cc index 599a798dda..70ea3f6782 100644 --- a/contrib/libs/grpc/src/core/ext/filters/census/grpc_context.cc +++ b/contrib/libs/grpc/src/core/ext/filters/census/grpc_context.cc @@ -1,38 +1,38 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include <grpc/census.h> -#include <grpc/grpc.h> -#include "src/core/lib/surface/api_trace.h" -#include "src/core/lib/surface/call.h" - -void grpc_census_call_set_context(grpc_call* call, census_context* context) { - GRPC_API_TRACE("grpc_census_call_set_context(call=%p, census_context=%p)", 2, - (call, context)); - if (context != nullptr) { - grpc_call_context_set(call, GRPC_CONTEXT_TRACING, context, nullptr); - } -} - -census_context* grpc_census_call_get_context(grpc_call* call) { - GRPC_API_TRACE("grpc_census_call_get_context(call=%p)", 1, (call)); - return static_cast<census_context*>( - grpc_call_context_get(call, GRPC_CONTEXT_TRACING)); -} +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include <grpc/census.h> +#include <grpc/grpc.h> +#include "src/core/lib/surface/api_trace.h" +#include "src/core/lib/surface/call.h" + +void grpc_census_call_set_context(grpc_call* call, census_context* context) { + GRPC_API_TRACE("grpc_census_call_set_context(call=%p, census_context=%p)", 2, + (call, context)); + if (context != nullptr) { + grpc_call_context_set(call, GRPC_CONTEXT_TRACING, context, nullptr); + } +} + +census_context* grpc_census_call_get_context(grpc_call* call) { + GRPC_API_TRACE("grpc_census_call_get_context(call=%p)", 1, (call)); + return static_cast<census_context*>( + grpc_call_context_get(call, GRPC_CONTEXT_TRACING)); +} diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md b/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md index ffb09fd34e..5cf9116d51 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/README.md @@ -46,4 +46,4 @@ concrete subchannel instances. Naming for GRPC =============== -See [/doc/naming.md](gRPC name resolution). +See [/doc/naming.md](gRPC name resolution). diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc index 4ebb976efe..9978ada0b0 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/channel_connectivity.cc @@ -35,13 +35,13 @@ grpc_connectivity_state grpc_channel_check_connectivity_state( /* forward through to the underlying client channel */ grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel)); - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; grpc_connectivity_state state; GRPC_API_TRACE( "grpc_channel_check_connectivity_state(channel=%p, try_to_connect=%d)", 2, (channel, try_to_connect)); - if (GPR_LIKELY(client_channel_elem->filter == &grpc_client_channel_filter)) { + if (GPR_LIKELY(client_channel_elem->filter == &grpc_client_channel_filter)) { state = grpc_client_channel_check_connectivity_state(client_channel_elem, try_to_connect); @@ -217,7 +217,7 @@ void grpc_channel_watch_connectivity_state( gpr_timespec deadline, grpc_completion_queue* cq, void* tag) { grpc_channel_element* client_channel_elem = grpc_channel_stack_last_element(grpc_channel_get_channel_stack(channel)); - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; state_watcher* w = static_cast<state_watcher*>(gpr_malloc(sizeof(*w))); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc index 908a05248c..1d6e1d4689 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.cc @@ -49,7 +49,7 @@ #include "src/core/ext/filters/client_channel/local_subchannel_pool.h" #include "src/core/ext/filters/client_channel/proxy_mapper_registry.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" -#include "src/core/ext/filters/client_channel/resolver_result_parsing.h" +#include "src/core/ext/filters/client_channel/resolver_result_parsing.h" #include "src/core/ext/filters/client_channel/resolving_lb_policy.h" #include "src/core/ext/filters/client_channel/retry_throttle.h" #include "src/core/ext/filters/client_channel/service_config.h" @@ -2182,7 +2182,7 @@ CallData::CallData(grpc_call_element* elem, const ChannelData& chand, enable_retries_(chand.enable_retries()), retry_committed_(false), last_attempt_got_server_pushback_(false) {} - + CallData::~CallData() { grpc_slice_unref_internal(path_); GRPC_ERROR_UNREF(cancel_error_); @@ -2195,14 +2195,14 @@ CallData::~CallData() { GPR_ASSERT(pending_batches_[i].batch == nullptr); } } - + grpc_error* CallData::Init(grpc_call_element* elem, const grpc_call_element_args* args) { ChannelData* chand = static_cast<ChannelData*>(elem->channel_data); new (elem->call_data) CallData(elem, *chand, *args); return GRPC_ERROR_NONE; } - + void CallData::Destroy(grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* then_schedule_closure) { @@ -2216,7 +2216,7 @@ void CallData::Destroy(grpc_call_element* elem, ExecCtx::Run(DEBUG_LOCATION, then_schedule_closure, GRPC_ERROR_NONE); } } - + void CallData::StartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { GPR_TIMER_SCOPE("cc_start_transport_stream_op_batch", 0); @@ -2230,7 +2230,7 @@ void CallData::StartTransportStreamOpBatch( if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { gpr_log(GPR_INFO, "chand=%p calld=%p: failing batch with error: %s", chand, calld, grpc_error_string(calld->cancel_error_)); - } + } // Note: This will release the call combiner. grpc_transport_stream_op_batch_finish_with_failure( batch, GRPC_ERROR_REF(calld->cancel_error_), calld->call_combiner_); @@ -2249,7 +2249,7 @@ void CallData::StartTransportStreamOpBatch( if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { gpr_log(GPR_INFO, "chand=%p calld=%p: recording cancel_error=%s", chand, calld, grpc_error_string(calld->cancel_error_)); - } + } // If we do not have a subchannel call (i.e., a pick has not yet // been started), fail all pending batches. Otherwise, send the // cancellation down to the subchannel call. @@ -2266,7 +2266,7 @@ void CallData::StartTransportStreamOpBatch( calld->subchannel_call_->StartTransportStreamOpBatch(batch); } return; - } + } // Add the batch to the pending list. calld->PendingBatchesAdd(elem, batch); // Check if we've already gotten a subchannel call. @@ -2303,7 +2303,7 @@ void CallData::StartTransportStreamOpBatch( "batch does not include send_initial_metadata"); } } - + void CallData::SetPollent(grpc_call_element* elem, grpc_polling_entity* pollent) { CallData* calld = static_cast<CallData*>(elem->call_data); @@ -2408,9 +2408,9 @@ void CallData::FreeCachedSendOpDataForCompletedBatch( } // -// LB recv_trailing_metadata_ready handling -// - +// LB recv_trailing_metadata_ready handling +// + void CallData::RecvTrailingMetadataReadyForLoadBalancingPolicy( void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(arg); @@ -2446,21 +2446,21 @@ void CallData::RecvTrailingMetadataReadyForLoadBalancingPolicy( } void CallData::MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy( - grpc_transport_stream_op_batch* batch) { + grpc_transport_stream_op_batch* batch) { if (lb_recv_trailing_metadata_ready_ != nullptr) { recv_trailing_metadata_ = batch->payload->recv_trailing_metadata.recv_trailing_metadata; original_recv_trailing_metadata_ready_ = - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, RecvTrailingMetadataReadyForLoadBalancingPolicy, this, grpc_schedule_on_exec_ctx); - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = &recv_trailing_metadata_ready_; - } -} - -// + } +} + +// // pending_batches management // @@ -2603,19 +2603,19 @@ void CallData::PendingBatchesFail( if (batch != nullptr) { if (batch->recv_trailing_metadata) { MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch); - } + } batch->handler_private.extra_arg = this; - GRPC_CLOSURE_INIT(&batch->handler_private.closure, + GRPC_CLOSURE_INIT(&batch->handler_private.closure, FailPendingBatchInCallCombiner, batch, - grpc_schedule_on_exec_ctx); - closures.Add(&batch->handler_private.closure, GRPC_ERROR_REF(error), + grpc_schedule_on_exec_ctx); + closures.Add(&batch->handler_private.closure, GRPC_ERROR_REF(error), "PendingBatchesFail"); PendingBatchClear(pending); } } if (yield_call_combiner_predicate(closures)) { closures.RunClosures(call_combiner_); - } else { + } else { closures.RunClosuresWithoutYielding(call_combiner_); } GRPC_ERROR_UNREF(error); @@ -2629,7 +2629,7 @@ void CallData::ResumePendingBatchInCallCombiner(void* arg, SubchannelCall* subchannel_call = static_cast<SubchannelCall*>(batch->handler_private.extra_arg); // Note: This will release the call combiner. - subchannel_call->StartTransportStreamOpBatch(batch); + subchannel_call->StartTransportStreamOpBatch(batch); } // This is called via the call combiner, so access to calld is synchronized. @@ -2655,14 +2655,14 @@ void CallData::PendingBatchesResume(grpc_call_element* elem) { PendingBatch* pending = &pending_batches_[i]; grpc_transport_stream_op_batch* batch = pending->batch; if (batch != nullptr) { - if (batch->recv_trailing_metadata) { + if (batch->recv_trailing_metadata) { MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy(batch); - } + } batch->handler_private.extra_arg = subchannel_call_.get(); - GRPC_CLOSURE_INIT(&batch->handler_private.closure, + GRPC_CLOSURE_INIT(&batch->handler_private.closure, ResumePendingBatchInCallCombiner, batch, - grpc_schedule_on_exec_ctx); - closures.Add(&batch->handler_private.closure, GRPC_ERROR_NONE, + grpc_schedule_on_exec_ctx); + closures.Add(&batch->handler_private.closure, GRPC_ERROR_NONE, "PendingBatchesResume"); PendingBatchClear(pending); } @@ -2671,24 +2671,24 @@ void CallData::PendingBatchesResume(grpc_call_element* elem) { closures.RunClosures(call_combiner_); } -template <typename Predicate> +template <typename Predicate> CallData::PendingBatch* CallData::PendingBatchFind(grpc_call_element* elem, const char* log_message, Predicate predicate) { ChannelData* chand = static_cast<ChannelData*>(elem->channel_data); for (size_t i = 0; i < GPR_ARRAY_SIZE(pending_batches_); ++i) { PendingBatch* pending = &pending_batches_[i]; - grpc_transport_stream_op_batch* batch = pending->batch; - if (batch != nullptr && predicate(batch)) { + grpc_transport_stream_op_batch* batch = pending->batch; + if (batch != nullptr && predicate(batch)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { - gpr_log(GPR_INFO, - "chand=%p calld=%p: %s pending batch at index %" PRIuPTR, chand, + gpr_log(GPR_INFO, + "chand=%p calld=%p: %s pending batch at index %" PRIuPTR, chand, this, log_message, i); - } - return pending; - } + } + return pending; + } } - return nullptr; + return nullptr; } // @@ -2736,7 +2736,7 @@ void CallData::DoRetry(grpc_call_element* elem, } if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { gpr_log(GPR_INFO, - "chand=%p calld=%p: retrying failed call in %" PRId64 " ms", chand, + "chand=%p calld=%p: retrying failed call in %" PRId64 " ms", chand, this, next_attempt_time - ExecCtx::Get()->Now()); } // Schedule retry after computed delay. @@ -2762,7 +2762,7 @@ bool CallData::MaybeRetry(grpc_call_element* elem, SubchannelCallRetryState* retry_state = nullptr; if (batch_data != nullptr) { retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); + batch_data->subchannel_call->GetParentData()); if (retry_state->retry_dispatched) { if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { gpr_log(GPR_INFO, "chand=%p calld=%p: retry already dispatched", chand, @@ -2772,7 +2772,7 @@ bool CallData::MaybeRetry(grpc_call_element* elem, } } // Check status. - if (GPR_LIKELY(status == GRPC_STATUS_OK)) { + if (GPR_LIKELY(status == GRPC_STATUS_OK)) { if (retry_throttle_data_ != nullptr) { retry_throttle_data_->RecordSuccess(); } @@ -2864,7 +2864,7 @@ CallData::SubchannelCallBatchData* CallData::SubchannelCallBatchData::Create( return calld->arena_->New<SubchannelCallBatchData>(elem, calld, refcount, set_on_complete); } - + CallData::SubchannelCallBatchData::SubchannelCallBatchData( grpc_call_element* elem, CallData* calld, int refcount, bool set_on_complete) @@ -2872,36 +2872,36 @@ CallData::SubchannelCallBatchData::SubchannelCallBatchData( SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( calld->subchannel_call_->GetParentData()); - batch.payload = &retry_state->batch_payload; - gpr_ref_init(&refs, refcount); - if (set_on_complete) { + batch.payload = &retry_state->batch_payload; + gpr_ref_init(&refs, refcount); + if (set_on_complete) { GRPC_CLOSURE_INIT(&on_complete, CallData::OnComplete, this, - grpc_schedule_on_exec_ctx); - batch.on_complete = &on_complete; - } + grpc_schedule_on_exec_ctx); + batch.on_complete = &on_complete; + } GRPC_CALL_STACK_REF(calld->owning_call_, "batch_data"); -} - +} + void CallData::SubchannelCallBatchData::Destroy() { SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>(subchannel_call->GetParentData()); - if (batch.send_initial_metadata) { - grpc_metadata_batch_destroy(&retry_state->send_initial_metadata); - } - if (batch.send_trailing_metadata) { - grpc_metadata_batch_destroy(&retry_state->send_trailing_metadata); - } - if (batch.recv_initial_metadata) { - grpc_metadata_batch_destroy(&retry_state->recv_initial_metadata); - } - if (batch.recv_trailing_metadata) { - grpc_metadata_batch_destroy(&retry_state->recv_trailing_metadata); - } - subchannel_call.reset(); + if (batch.send_initial_metadata) { + grpc_metadata_batch_destroy(&retry_state->send_initial_metadata); + } + if (batch.send_trailing_metadata) { + grpc_metadata_batch_destroy(&retry_state->send_trailing_metadata); + } + if (batch.recv_initial_metadata) { + grpc_metadata_batch_destroy(&retry_state->recv_initial_metadata); + } + if (batch.recv_trailing_metadata) { + grpc_metadata_batch_destroy(&retry_state->recv_trailing_metadata); + } + subchannel_call.reset(); CallData* calld = static_cast<CallData*>(elem->call_data); GRPC_CALL_STACK_UNREF(calld->owning_call_, "batch_data"); -} - +} + // // recv_initial_metadata callback handling // @@ -2912,19 +2912,19 @@ void CallData::InvokeRecvInitialMetadataCallback(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(batch_data->elem->call_data); // Find pending batch. PendingBatch* pending = calld->PendingBatchFind( - batch_data->elem, "invoking recv_initial_metadata_ready for", - [](grpc_transport_stream_op_batch* batch) { - return batch->recv_initial_metadata && - batch->payload->recv_initial_metadata - .recv_initial_metadata_ready != nullptr; - }); + batch_data->elem, "invoking recv_initial_metadata_ready for", + [](grpc_transport_stream_op_batch* batch) { + return batch->recv_initial_metadata && + batch->payload->recv_initial_metadata + .recv_initial_metadata_ready != nullptr; + }); GPR_ASSERT(pending != nullptr); // Return metadata. SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); + batch_data->subchannel_call->GetParentData()); grpc_metadata_batch_move( - &retry_state->recv_initial_metadata, + &retry_state->recv_initial_metadata, pending->batch->payload->recv_initial_metadata.recv_initial_metadata); // Update bookkeeping. // Note: Need to do this before invoking the callback, since invoking @@ -2954,23 +2954,23 @@ void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) { } SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); - retry_state->completed_recv_initial_metadata = true; - // If a retry was already dispatched, then we're not going to use the - // result of this recv_initial_metadata op, so do nothing. - if (retry_state->retry_dispatched) { - GRPC_CALL_COMBINER_STOP( + batch_data->subchannel_call->GetParentData()); + retry_state->completed_recv_initial_metadata = true; + // If a retry was already dispatched, then we're not going to use the + // result of this recv_initial_metadata op, so do nothing. + if (retry_state->retry_dispatched) { + GRPC_CALL_COMBINER_STOP( calld->call_combiner_, - "recv_initial_metadata_ready after retry dispatched"); - return; - } + "recv_initial_metadata_ready after retry dispatched"); + return; + } // If we got an error or a Trailers-Only response and have not yet gotten - // the recv_trailing_metadata_ready callback, then defer propagating this - // callback back to the surface. We can evaluate whether to retry when - // recv_trailing_metadata comes back. - if (GPR_UNLIKELY((retry_state->trailing_metadata_available || - error != GRPC_ERROR_NONE) && - !retry_state->completed_recv_trailing_metadata)) { + // the recv_trailing_metadata_ready callback, then defer propagating this + // callback back to the surface. We can evaluate whether to retry when + // recv_trailing_metadata comes back. + if (GPR_UNLIKELY((retry_state->trailing_metadata_available || + error != GRPC_ERROR_NONE) && + !retry_state->completed_recv_trailing_metadata)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { gpr_log(GPR_INFO, "chand=%p calld=%p: deferring recv_initial_metadata_ready " @@ -2993,7 +2993,7 @@ void CallData::RecvInitialMetadataReady(void* arg, grpc_error* error) { // Received valid initial metadata, so commit the call. calld->RetryCommit(elem, retry_state); calld->MaybeInvokeConfigSelectorCommitCallback(); - // Invoke the callback to return the result to the surface. + // Invoke the callback to return the result to the surface. // Manually invoking a callback function; it does not take ownership of error. calld->InvokeRecvInitialMetadataCallback(batch_data, error); } @@ -3008,18 +3008,18 @@ void CallData::InvokeRecvMessageCallback(void* arg, grpc_error* error) { CallData* calld = static_cast<CallData*>(batch_data->elem->call_data); // Find pending op. PendingBatch* pending = calld->PendingBatchFind( - batch_data->elem, "invoking recv_message_ready for", - [](grpc_transport_stream_op_batch* batch) { - return batch->recv_message && - batch->payload->recv_message.recv_message_ready != nullptr; - }); + batch_data->elem, "invoking recv_message_ready for", + [](grpc_transport_stream_op_batch* batch) { + return batch->recv_message && + batch->payload->recv_message.recv_message_ready != nullptr; + }); GPR_ASSERT(pending != nullptr); // Return payload. SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); + batch_data->subchannel_call->GetParentData()); *pending->batch->payload->recv_message.recv_message = - std::move(retry_state->recv_message); + std::move(retry_state->recv_message); // Update bookkeeping. // Note: Need to do this before invoking the callback, since invoking // the callback will result in yielding the call combiner. @@ -3044,22 +3044,22 @@ void CallData::RecvMessageReady(void* arg, grpc_error* error) { } SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); - ++retry_state->completed_recv_message_count; - // If a retry was already dispatched, then we're not going to use the - // result of this recv_message op, so do nothing. - if (retry_state->retry_dispatched) { + batch_data->subchannel_call->GetParentData()); + ++retry_state->completed_recv_message_count; + // If a retry was already dispatched, then we're not going to use the + // result of this recv_message op, so do nothing. + if (retry_state->retry_dispatched) { GRPC_CALL_COMBINER_STOP(calld->call_combiner_, - "recv_message_ready after retry dispatched"); - return; - } + "recv_message_ready after retry dispatched"); + return; + } // If we got an error or the payload was nullptr and we have not yet gotten - // the recv_trailing_metadata_ready callback, then defer propagating this - // callback back to the surface. We can evaluate whether to retry when - // recv_trailing_metadata comes back. - if (GPR_UNLIKELY( - (retry_state->recv_message == nullptr || error != GRPC_ERROR_NONE) && - !retry_state->completed_recv_trailing_metadata)) { + // the recv_trailing_metadata_ready callback, then defer propagating this + // callback back to the surface. We can evaluate whether to retry when + // recv_trailing_metadata comes back. + if (GPR_UNLIKELY( + (retry_state->recv_message == nullptr || error != GRPC_ERROR_NONE) && + !retry_state->completed_recv_trailing_metadata)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { gpr_log(GPR_INFO, "chand=%p calld=%p: deferring recv_message_ready (nullptr " @@ -3080,63 +3080,63 @@ void CallData::RecvMessageReady(void* arg, grpc_error* error) { // Received a valid message, so commit the call. calld->RetryCommit(elem, retry_state); calld->MaybeInvokeConfigSelectorCommitCallback(); - // Invoke the callback to return the result to the surface. + // Invoke the callback to return the result to the surface. // Manually invoking a callback function; it does not take ownership of error. calld->InvokeRecvMessageCallback(batch_data, error); } // -// recv_trailing_metadata handling +// recv_trailing_metadata handling // void CallData::GetCallStatus(grpc_metadata_batch* md_batch, grpc_error* error, grpc_status_code* status, grpc_mdelem** server_pushback_md) { - if (error != GRPC_ERROR_NONE) { + if (error != GRPC_ERROR_NONE) { grpc_error_get_status(error, deadline_, status, nullptr, nullptr, nullptr); } else { - GPR_ASSERT(md_batch->idx.named.grpc_status != nullptr); - *status = - grpc_get_status_code_from_metadata(md_batch->idx.named.grpc_status->md); - if (server_pushback_md != nullptr && - md_batch->idx.named.grpc_retry_pushback_ms != nullptr) { - *server_pushback_md = &md_batch->idx.named.grpc_retry_pushback_ms->md; + GPR_ASSERT(md_batch->idx.named.grpc_status != nullptr); + *status = + grpc_get_status_code_from_metadata(md_batch->idx.named.grpc_status->md); + if (server_pushback_md != nullptr && + md_batch->idx.named.grpc_retry_pushback_ms != nullptr) { + *server_pushback_md = &md_batch->idx.named.grpc_retry_pushback_ms->md; } } - GRPC_ERROR_UNREF(error); + GRPC_ERROR_UNREF(error); } void CallData::AddClosureForRecvTrailingMetadataReady( grpc_call_element* elem, SubchannelCallBatchData* batch_data, grpc_error* error, CallCombinerClosureList* closures) { - // Find pending batch. + // Find pending batch. PendingBatch* pending = PendingBatchFind( - elem, "invoking recv_trailing_metadata for", - [](grpc_transport_stream_op_batch* batch) { - return batch->recv_trailing_metadata && - batch->payload->recv_trailing_metadata - .recv_trailing_metadata_ready != nullptr; - }); - // If we generated the recv_trailing_metadata op internally via + elem, "invoking recv_trailing_metadata for", + [](grpc_transport_stream_op_batch* batch) { + return batch->recv_trailing_metadata && + batch->payload->recv_trailing_metadata + .recv_trailing_metadata_ready != nullptr; + }); + // If we generated the recv_trailing_metadata op internally via // StartInternalRecvTrailingMetadata(), then there will be no pending batch. - if (pending == nullptr) { - GRPC_ERROR_UNREF(error); - return; + if (pending == nullptr) { + GRPC_ERROR_UNREF(error); + return; } - // Return metadata. + // Return metadata. SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); - grpc_metadata_batch_move( - &retry_state->recv_trailing_metadata, - pending->batch->payload->recv_trailing_metadata.recv_trailing_metadata); - // Add closure. - closures->Add(pending->batch->payload->recv_trailing_metadata - .recv_trailing_metadata_ready, - error, "recv_trailing_metadata_ready for pending batch"); - // Update bookkeeping. - pending->batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - nullptr; + batch_data->subchannel_call->GetParentData()); + grpc_metadata_batch_move( + &retry_state->recv_trailing_metadata, + pending->batch->payload->recv_trailing_metadata.recv_trailing_metadata); + // Add closure. + closures->Add(pending->batch->payload->recv_trailing_metadata + .recv_trailing_metadata_ready, + error, "recv_trailing_metadata_ready for pending batch"); + // Update bookkeeping. + pending->batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + nullptr; MaybeClearPendingBatch(elem, pending); } @@ -3145,27 +3145,27 @@ void CallData::AddClosuresForDeferredRecvCallbacks( CallCombinerClosureList* closures) { if (batch_data->batch.recv_trailing_metadata) { // Add closure for deferred recv_initial_metadata_ready. - if (GPR_UNLIKELY(retry_state->recv_initial_metadata_ready_deferred_batch != - nullptr)) { - GRPC_CLOSURE_INIT(&retry_state->recv_initial_metadata_ready, + if (GPR_UNLIKELY(retry_state->recv_initial_metadata_ready_deferred_batch != + nullptr)) { + GRPC_CLOSURE_INIT(&retry_state->recv_initial_metadata_ready, InvokeRecvInitialMetadataCallback, - retry_state->recv_initial_metadata_ready_deferred_batch, - grpc_schedule_on_exec_ctx); - closures->Add(&retry_state->recv_initial_metadata_ready, - retry_state->recv_initial_metadata_error, - "resuming recv_initial_metadata_ready"); + retry_state->recv_initial_metadata_ready_deferred_batch, + grpc_schedule_on_exec_ctx); + closures->Add(&retry_state->recv_initial_metadata_ready, + retry_state->recv_initial_metadata_error, + "resuming recv_initial_metadata_ready"); retry_state->recv_initial_metadata_ready_deferred_batch = nullptr; } // Add closure for deferred recv_message_ready. - if (GPR_UNLIKELY(retry_state->recv_message_ready_deferred_batch != - nullptr)) { - GRPC_CLOSURE_INIT(&retry_state->recv_message_ready, + if (GPR_UNLIKELY(retry_state->recv_message_ready_deferred_batch != + nullptr)) { + GRPC_CLOSURE_INIT(&retry_state->recv_message_ready, InvokeRecvMessageCallback, - retry_state->recv_message_ready_deferred_batch, - grpc_schedule_on_exec_ctx); - closures->Add(&retry_state->recv_message_ready, - retry_state->recv_message_error, - "resuming recv_message_ready"); + retry_state->recv_message_ready_deferred_batch, + grpc_schedule_on_exec_ctx); + closures->Add(&retry_state->recv_message_ready, + retry_state->recv_message_error, + "resuming recv_message_ready"); retry_state->recv_message_ready_deferred_batch = nullptr; } } @@ -3173,24 +3173,24 @@ void CallData::AddClosuresForDeferredRecvCallbacks( bool CallData::PendingBatchIsUnstarted(PendingBatch* pending, SubchannelCallRetryState* retry_state) { - if (pending->batch == nullptr || pending->batch->on_complete == nullptr) { - return false; - } - if (pending->batch->send_initial_metadata && - !retry_state->started_send_initial_metadata) { - return true; - } - if (pending->batch->send_message && + if (pending->batch == nullptr || pending->batch->on_complete == nullptr) { + return false; + } + if (pending->batch->send_initial_metadata && + !retry_state->started_send_initial_metadata) { + return true; + } + if (pending->batch->send_message && retry_state->started_send_message_count < send_messages_.size()) { - return true; - } - if (pending->batch->send_trailing_metadata && - !retry_state->started_send_trailing_metadata) { - return true; - } - return false; -} - + return true; + } + if (pending->batch->send_trailing_metadata && + !retry_state->started_send_trailing_metadata) { + return true; + } + return false; +} + void CallData::AddClosuresToFailUnstartedPendingBatches( grpc_call_element* elem, SubchannelCallRetryState* retry_state, grpc_error* error, CallCombinerClosureList* closures) { @@ -3199,124 +3199,124 @@ void CallData::AddClosuresToFailUnstartedPendingBatches( PendingBatch* pending = &pending_batches_[i]; if (PendingBatchIsUnstarted(pending, retry_state)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { - gpr_log(GPR_INFO, - "chand=%p calld=%p: failing unstarted pending batch at index " - "%" PRIuPTR, + gpr_log(GPR_INFO, + "chand=%p calld=%p: failing unstarted pending batch at index " + "%" PRIuPTR, chand, this, i); - } - closures->Add(pending->batch->on_complete, GRPC_ERROR_REF(error), - "failing on_complete for pending batch"); - pending->batch->on_complete = nullptr; + } + closures->Add(pending->batch->on_complete, GRPC_ERROR_REF(error), + "failing on_complete for pending batch"); + pending->batch->on_complete = nullptr; MaybeClearPendingBatch(elem, pending); - } - } - GRPC_ERROR_UNREF(error); -} - + } + } + GRPC_ERROR_UNREF(error); +} + void CallData::RunClosuresForCompletedCall(SubchannelCallBatchData* batch_data, grpc_error* error) { - grpc_call_element* elem = batch_data->elem; + grpc_call_element* elem = batch_data->elem; SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); - // Construct list of closures to execute. + batch_data->subchannel_call->GetParentData()); + // Construct list of closures to execute. CallCombinerClosureList closures; - // First, add closure for recv_trailing_metadata_ready. + // First, add closure for recv_trailing_metadata_ready. AddClosureForRecvTrailingMetadataReady(elem, batch_data, GRPC_ERROR_REF(error), &closures); - // If there are deferred recv_initial_metadata_ready or recv_message_ready - // callbacks, add them to closures. + // If there are deferred recv_initial_metadata_ready or recv_message_ready + // callbacks, add them to closures. AddClosuresForDeferredRecvCallbacks(batch_data, retry_state, &closures); - // Add closures to fail any pending batches that have not yet been started. + // Add closures to fail any pending batches that have not yet been started. AddClosuresToFailUnstartedPendingBatches(elem, retry_state, GRPC_ERROR_REF(error), &closures); - // Don't need batch_data anymore. + // Don't need batch_data anymore. batch_data->Unref(); - // Schedule all of the closures identified above. - // Note: This will release the call combiner. + // Schedule all of the closures identified above. + // Note: This will release the call combiner. closures.RunClosures(call_combiner_); - GRPC_ERROR_UNREF(error); -} - + GRPC_ERROR_UNREF(error); +} + void CallData::RecvTrailingMetadataReady(void* arg, grpc_error* error) { SubchannelCallBatchData* batch_data = static_cast<SubchannelCallBatchData*>(arg); - grpc_call_element* elem = batch_data->elem; + grpc_call_element* elem = batch_data->elem; ChannelData* chand = static_cast<ChannelData*>(elem->channel_data); CallData* calld = static_cast<CallData*>(elem->call_data); if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { - gpr_log(GPR_INFO, - "chand=%p calld=%p: got recv_trailing_metadata_ready, error=%s", - chand, calld, grpc_error_string(error)); - } + gpr_log(GPR_INFO, + "chand=%p calld=%p: got recv_trailing_metadata_ready, error=%s", + chand, calld, grpc_error_string(error)); + } SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); - retry_state->completed_recv_trailing_metadata = true; - // Get the call's status and check for server pushback metadata. - grpc_status_code status = GRPC_STATUS_OK; - grpc_mdelem* server_pushback_md = nullptr; - grpc_metadata_batch* md_batch = - batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata; + batch_data->subchannel_call->GetParentData()); + retry_state->completed_recv_trailing_metadata = true; + // Get the call's status and check for server pushback metadata. + grpc_status_code status = GRPC_STATUS_OK; + grpc_mdelem* server_pushback_md = nullptr; + grpc_metadata_batch* md_batch = + batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata; calld->GetCallStatus(md_batch, GRPC_ERROR_REF(error), &status, &server_pushback_md); if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { - gpr_log(GPR_INFO, "chand=%p calld=%p: call finished, status=%s", chand, - calld, grpc_status_code_to_string(status)); - } - // Check if we should retry. + gpr_log(GPR_INFO, "chand=%p calld=%p: call finished, status=%s", chand, + calld, grpc_status_code_to_string(status)); + } + // Check if we should retry. if (calld->MaybeRetry(elem, batch_data, status, server_pushback_md)) { - // Unref batch_data for deferred recv_initial_metadata_ready or - // recv_message_ready callbacks, if any. - if (retry_state->recv_initial_metadata_ready_deferred_batch != nullptr) { + // Unref batch_data for deferred recv_initial_metadata_ready or + // recv_message_ready callbacks, if any. + if (retry_state->recv_initial_metadata_ready_deferred_batch != nullptr) { batch_data->Unref(); - GRPC_ERROR_UNREF(retry_state->recv_initial_metadata_error); - } - if (retry_state->recv_message_ready_deferred_batch != nullptr) { + GRPC_ERROR_UNREF(retry_state->recv_initial_metadata_error); + } + if (retry_state->recv_message_ready_deferred_batch != nullptr) { batch_data->Unref(); - GRPC_ERROR_UNREF(retry_state->recv_message_error); - } + GRPC_ERROR_UNREF(retry_state->recv_message_error); + } batch_data->Unref(); - return; - } - // Not retrying, so commit the call. + return; + } + // Not retrying, so commit the call. calld->RetryCommit(elem, retry_state); calld->MaybeInvokeConfigSelectorCommitCallback(); - // Run any necessary closures. + // Run any necessary closures. calld->RunClosuresForCompletedCall(batch_data, GRPC_ERROR_REF(error)); -} - -// -// on_complete callback handling -// - +} + +// +// on_complete callback handling +// + void CallData::AddClosuresForCompletedPendingBatch( grpc_call_element* elem, SubchannelCallBatchData* batch_data, grpc_error* error, CallCombinerClosureList* closures) { PendingBatch* pending = PendingBatchFind( - elem, "completed", [batch_data](grpc_transport_stream_op_batch* batch) { - // Match the pending batch with the same set of send ops as the - // subchannel batch we've just completed. - return batch->on_complete != nullptr && - batch_data->batch.send_initial_metadata == - batch->send_initial_metadata && - batch_data->batch.send_message == batch->send_message && - batch_data->batch.send_trailing_metadata == - batch->send_trailing_metadata; - }); - // If batch_data is a replay batch, then there will be no pending - // batch to complete. - if (pending == nullptr) { - GRPC_ERROR_UNREF(error); - return; - } - // Add closure. - closures->Add(pending->batch->on_complete, error, - "on_complete for pending batch"); - pending->batch->on_complete = nullptr; + elem, "completed", [batch_data](grpc_transport_stream_op_batch* batch) { + // Match the pending batch with the same set of send ops as the + // subchannel batch we've just completed. + return batch->on_complete != nullptr && + batch_data->batch.send_initial_metadata == + batch->send_initial_metadata && + batch_data->batch.send_message == batch->send_message && + batch_data->batch.send_trailing_metadata == + batch->send_trailing_metadata; + }); + // If batch_data is a replay batch, then there will be no pending + // batch to complete. + if (pending == nullptr) { + GRPC_ERROR_UNREF(error); + return; + } + // Add closure. + closures->Add(pending->batch->on_complete, error, + "on_complete for pending batch"); + pending->batch->on_complete = nullptr; MaybeClearPendingBatch(elem, pending); -} - +} + void CallData::AddClosuresForReplayOrPendingSendOps( grpc_call_element* elem, SubchannelCallBatchData* batch_data, SubchannelCallRetryState* retry_state, CallCombinerClosureList* closures) { @@ -3344,11 +3344,11 @@ void CallData::AddClosuresForReplayOrPendingSendOps( "chand=%p calld=%p: starting next batch for pending send op(s)", chand, this); } - GRPC_CLOSURE_INIT(&batch_data->batch.handler_private.closure, + GRPC_CLOSURE_INIT(&batch_data->batch.handler_private.closure, StartRetriableSubchannelBatches, elem, - grpc_schedule_on_exec_ctx); - closures->Add(&batch_data->batch.handler_private.closure, GRPC_ERROR_NONE, - "starting next batch for send_* op(s)"); + grpc_schedule_on_exec_ctx); + closures->Add(&batch_data->batch.handler_private.closure, GRPC_ERROR_NONE, + "starting next batch for send_* op(s)"); } } @@ -3365,52 +3365,52 @@ void CallData::OnComplete(void* arg, grpc_error* error) { } SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>( - batch_data->subchannel_call->GetParentData()); + batch_data->subchannel_call->GetParentData()); // Update bookkeeping in retry_state. - if (batch_data->batch.send_initial_metadata) { - retry_state->completed_send_initial_metadata = true; - } - if (batch_data->batch.send_message) { - ++retry_state->completed_send_message_count; - } - if (batch_data->batch.send_trailing_metadata) { - retry_state->completed_send_trailing_metadata = true; - } - // If the call is committed, free cached data for send ops that we've just - // completed. + if (batch_data->batch.send_initial_metadata) { + retry_state->completed_send_initial_metadata = true; + } + if (batch_data->batch.send_message) { + ++retry_state->completed_send_message_count; + } + if (batch_data->batch.send_trailing_metadata) { + retry_state->completed_send_trailing_metadata = true; + } + // If the call is committed, free cached data for send ops that we've just + // completed. if (calld->retry_committed_) { calld->FreeCachedSendOpDataForCompletedBatch(elem, batch_data, retry_state); } // Construct list of closures to execute. CallCombinerClosureList closures; - // If a retry was already dispatched, that means we saw - // recv_trailing_metadata before this, so we do nothing here. - // Otherwise, invoke the callback to return the result to the surface. - if (!retry_state->retry_dispatched) { - // Add closure for the completed pending batch, if any. + // If a retry was already dispatched, that means we saw + // recv_trailing_metadata before this, so we do nothing here. + // Otherwise, invoke the callback to return the result to the surface. + if (!retry_state->retry_dispatched) { + // Add closure for the completed pending batch, if any. calld->AddClosuresForCompletedPendingBatch( elem, batch_data, GRPC_ERROR_REF(error), &closures); - // If needed, add a callback to start any replay or pending send ops on - // the subchannel call. - if (!retry_state->completed_recv_trailing_metadata) { + // If needed, add a callback to start any replay or pending send ops on + // the subchannel call. + if (!retry_state->completed_recv_trailing_metadata) { calld->AddClosuresForReplayOrPendingSendOps(elem, batch_data, retry_state, - &closures); - } + &closures); + } } - // Track number of pending subchannel send batches and determine if this - // was the last one. + // Track number of pending subchannel send batches and determine if this + // was the last one. --calld->num_pending_retriable_subchannel_send_batches_; - const bool last_send_batch_complete = + const bool last_send_batch_complete = calld->num_pending_retriable_subchannel_send_batches_ == 0; // Don't need batch_data anymore. batch_data->Unref(); // Schedule all of the closures identified above. - // Note: This yeilds the call combiner. + // Note: This yeilds the call combiner. closures.RunClosures(calld->call_combiner_); - // If this was the last subchannel send batch, unref the call stack. - if (last_send_batch_complete) { + // If this was the last subchannel send batch, unref the call stack. + if (last_send_batch_complete) { GRPC_CALL_STACK_UNREF(calld->owning_call_, "subchannel_send_batches"); - } + } } // @@ -3423,22 +3423,22 @@ void CallData::StartBatchInCallCombiner(void* arg, grpc_error* /*ignored*/) { SubchannelCall* subchannel_call = static_cast<SubchannelCall*>(batch->handler_private.extra_arg); // Note: This will release the call combiner. - subchannel_call->StartTransportStreamOpBatch(batch); + subchannel_call->StartTransportStreamOpBatch(batch); } void CallData::AddClosureForSubchannelBatch( - grpc_call_element* elem, grpc_transport_stream_op_batch* batch, + grpc_call_element* elem, grpc_transport_stream_op_batch* batch, CallCombinerClosureList* closures) { ChannelData* chand = static_cast<ChannelData*>(elem->channel_data); batch->handler_private.extra_arg = subchannel_call_.get(); GRPC_CLOSURE_INIT(&batch->handler_private.closure, StartBatchInCallCombiner, batch, grpc_schedule_on_exec_ctx); if (GRPC_TRACE_FLAG_ENABLED(grpc_client_channel_call_trace)) { - gpr_log(GPR_INFO, "chand=%p calld=%p: starting subchannel batch: %s", chand, + gpr_log(GPR_INFO, "chand=%p calld=%p: starting subchannel batch: %s", chand, this, grpc_transport_stream_op_batch_string(batch).c_str()); } - closures->Add(&batch->handler_private.closure, GRPC_ERROR_NONE, - "start_subchannel_batch"); + closures->Add(&batch->handler_private.closure, GRPC_ERROR_NONE, + "start_subchannel_batch"); } void CallData::AddRetriableSendInitialMetadataOp( @@ -3453,28 +3453,28 @@ void CallData::AddRetriableSendInitialMetadataOp( // // If we've already completed one or more attempts, add the // grpc-retry-attempts header. - retry_state->send_initial_metadata_storage = + retry_state->send_initial_metadata_storage = static_cast<grpc_linked_mdelem*>(arena_->Alloc( sizeof(grpc_linked_mdelem) * (send_initial_metadata_.list.count + (num_attempts_completed_ > 0)))); grpc_metadata_batch_copy(&send_initial_metadata_, - &retry_state->send_initial_metadata, - retry_state->send_initial_metadata_storage); - if (GPR_UNLIKELY(retry_state->send_initial_metadata.idx.named - .grpc_previous_rpc_attempts != nullptr)) { - grpc_metadata_batch_remove(&retry_state->send_initial_metadata, + &retry_state->send_initial_metadata, + retry_state->send_initial_metadata_storage); + if (GPR_UNLIKELY(retry_state->send_initial_metadata.idx.named + .grpc_previous_rpc_attempts != nullptr)) { + grpc_metadata_batch_remove(&retry_state->send_initial_metadata, GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS); } if (GPR_UNLIKELY(num_attempts_completed_ > 0)) { - grpc_mdelem retry_md = grpc_mdelem_create( + grpc_mdelem retry_md = grpc_mdelem_create( GRPC_MDSTR_GRPC_PREVIOUS_RPC_ATTEMPTS, *retry_count_strings[num_attempts_completed_ - 1], nullptr); grpc_error* error = grpc_metadata_batch_add_tail( - &retry_state->send_initial_metadata, + &retry_state->send_initial_metadata, &retry_state ->send_initial_metadata_storage[send_initial_metadata_.list.count], retry_md, GRPC_BATCH_GRPC_PREVIOUS_RPC_ATTEMPTS); - if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) { + if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) { gpr_log(GPR_ERROR, "error adding retry metadata: %s", grpc_error_string(error)); GPR_ASSERT(false); @@ -3483,7 +3483,7 @@ void CallData::AddRetriableSendInitialMetadataOp( retry_state->started_send_initial_metadata = true; batch_data->batch.send_initial_metadata = true; batch_data->batch.payload->send_initial_metadata.send_initial_metadata = - &retry_state->send_initial_metadata; + &retry_state->send_initial_metadata; batch_data->batch.payload->send_initial_metadata.send_initial_metadata_flags = send_initial_metadata_flags_; batch_data->batch.payload->send_initial_metadata.peer_string = peer_string_; @@ -3501,10 +3501,10 @@ void CallData::AddRetriableSendMessageOp(grpc_call_element* elem, ByteStreamCache* cache = send_messages_[retry_state->started_send_message_count]; ++retry_state->started_send_message_count; - retry_state->send_message.Init(cache); + retry_state->send_message.Init(cache); batch_data->batch.send_message = true; batch_data->batch.payload->send_message.send_message.reset( - retry_state->send_message.get()); + retry_state->send_message.get()); } void CallData::AddRetriableSendTrailingMetadataOp( @@ -3513,16 +3513,16 @@ void CallData::AddRetriableSendTrailingMetadataOp( // We need to make a copy of the metadata batch for each attempt, since // the filters in the subchannel stack may modify this batch, and we don't // want those modifications to be passed forward to subsequent attempts. - retry_state->send_trailing_metadata_storage = + retry_state->send_trailing_metadata_storage = static_cast<grpc_linked_mdelem*>(arena_->Alloc( sizeof(grpc_linked_mdelem) * send_trailing_metadata_.list.count)); grpc_metadata_batch_copy(&send_trailing_metadata_, - &retry_state->send_trailing_metadata, - retry_state->send_trailing_metadata_storage); + &retry_state->send_trailing_metadata, + retry_state->send_trailing_metadata_storage); retry_state->started_send_trailing_metadata = true; batch_data->batch.send_trailing_metadata = true; batch_data->batch.payload->send_trailing_metadata.send_trailing_metadata = - &retry_state->send_trailing_metadata; + &retry_state->send_trailing_metadata; } void CallData::AddRetriableRecvInitialMetadataOp( @@ -3530,16 +3530,16 @@ void CallData::AddRetriableRecvInitialMetadataOp( SubchannelCallBatchData* batch_data) { retry_state->started_recv_initial_metadata = true; batch_data->batch.recv_initial_metadata = true; - grpc_metadata_batch_init(&retry_state->recv_initial_metadata); + grpc_metadata_batch_init(&retry_state->recv_initial_metadata); batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata = - &retry_state->recv_initial_metadata; + &retry_state->recv_initial_metadata; batch_data->batch.payload->recv_initial_metadata.trailing_metadata_available = - &retry_state->trailing_metadata_available; - GRPC_CLOSURE_INIT(&retry_state->recv_initial_metadata_ready, + &retry_state->trailing_metadata_available; + GRPC_CLOSURE_INIT(&retry_state->recv_initial_metadata_ready, RecvInitialMetadataReady, batch_data, grpc_schedule_on_exec_ctx); batch_data->batch.payload->recv_initial_metadata.recv_initial_metadata_ready = - &retry_state->recv_initial_metadata_ready; + &retry_state->recv_initial_metadata_ready; } void CallData::AddRetriableRecvMessageOp(SubchannelCallRetryState* retry_state, @@ -3547,11 +3547,11 @@ void CallData::AddRetriableRecvMessageOp(SubchannelCallRetryState* retry_state, ++retry_state->started_recv_message_count; batch_data->batch.recv_message = true; batch_data->batch.payload->recv_message.recv_message = - &retry_state->recv_message; + &retry_state->recv_message; GRPC_CLOSURE_INIT(&retry_state->recv_message_ready, RecvMessageReady, batch_data, grpc_schedule_on_exec_ctx); batch_data->batch.payload->recv_message.recv_message_ready = - &retry_state->recv_message_ready; + &retry_state->recv_message_ready; } void CallData::AddRetriableRecvTrailingMetadataOp( @@ -3559,17 +3559,17 @@ void CallData::AddRetriableRecvTrailingMetadataOp( SubchannelCallBatchData* batch_data) { retry_state->started_recv_trailing_metadata = true; batch_data->batch.recv_trailing_metadata = true; - grpc_metadata_batch_init(&retry_state->recv_trailing_metadata); + grpc_metadata_batch_init(&retry_state->recv_trailing_metadata); batch_data->batch.payload->recv_trailing_metadata.recv_trailing_metadata = - &retry_state->recv_trailing_metadata; - batch_data->batch.payload->recv_trailing_metadata.collect_stats = - &retry_state->collect_stats; - GRPC_CLOSURE_INIT(&retry_state->recv_trailing_metadata_ready, + &retry_state->recv_trailing_metadata; + batch_data->batch.payload->recv_trailing_metadata.collect_stats = + &retry_state->collect_stats; + GRPC_CLOSURE_INIT(&retry_state->recv_trailing_metadata_ready, RecvTrailingMetadataReady, batch_data, - grpc_schedule_on_exec_ctx); - batch_data->batch.payload->recv_trailing_metadata - .recv_trailing_metadata_ready = - &retry_state->recv_trailing_metadata_ready; + grpc_schedule_on_exec_ctx); + batch_data->batch.payload->recv_trailing_metadata + .recv_trailing_metadata_ready = + &retry_state->recv_trailing_metadata_ready; MaybeInjectRecvTrailingMetadataReadyForLoadBalancingPolicy( &batch_data->batch); } @@ -3585,9 +3585,9 @@ void CallData::StartInternalRecvTrailingMetadata(grpc_call_element* elem) { SubchannelCallRetryState* retry_state = static_cast<SubchannelCallRetryState*>(subchannel_call_->GetParentData()); // Create batch_data with 2 refs, since this batch will be unreffed twice: - // once for the recv_trailing_metadata_ready callback when the subchannel - // batch returns, and again when we actually get a recv_trailing_metadata - // op from the surface. + // once for the recv_trailing_metadata_ready callback when the subchannel + // batch returns, and again when we actually get a recv_trailing_metadata + // op from the surface. SubchannelCallBatchData* batch_data = SubchannelCallBatchData::Create(elem, 2, false /* set_on_complete */); AddRetriableRecvTrailingMetadataOp(retry_state, batch_data); @@ -3631,7 +3631,7 @@ CallData::MaybeCreateSubchannelBatchForReplay( chand, this); } if (replay_batch_data == nullptr) { - replay_batch_data = + replay_batch_data = SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */); } AddRetriableSendMessageOp(elem, retry_state, replay_batch_data); @@ -3651,7 +3651,7 @@ CallData::MaybeCreateSubchannelBatchForReplay( chand, this); } if (replay_batch_data == nullptr) { - replay_batch_data = + replay_batch_data = SubchannelCallBatchData::Create(elem, 1, true /* set_on_complete */); } AddRetriableSendTrailingMetadataOp(retry_state, replay_batch_data); @@ -3706,8 +3706,8 @@ void CallData::AddSubchannelBatchesForPendingBatches( // If we previously completed a recv_trailing_metadata op // initiated by StartInternalRecvTrailingMetadata(), use the // result of that instead of trying to re-start this op. - if (GPR_UNLIKELY((retry_state->recv_trailing_metadata_internal_batch != - nullptr))) { + if (GPR_UNLIKELY((retry_state->recv_trailing_metadata_internal_batch != + nullptr))) { // If the batch completed, then trigger the completion callback // directly, so that we return the previously returned results to // the application. Otherwise, just unref the internally @@ -3715,10 +3715,10 @@ void CallData::AddSubchannelBatchesForPendingBatches( // completion when it completes. if (retry_state->completed_recv_trailing_metadata) { // Batches containing recv_trailing_metadata always succeed. - closures->Add( - &retry_state->recv_trailing_metadata_ready, GRPC_ERROR_NONE, - "re-executing recv_trailing_metadata_ready to propagate " - "internally triggered result"); + closures->Add( + &retry_state->recv_trailing_metadata_ready, GRPC_ERROR_NONE, + "re-executing recv_trailing_metadata_ready to propagate " + "internally triggered result"); } else { retry_state->recv_trailing_metadata_internal_batch->Unref(); } @@ -3736,14 +3736,14 @@ void CallData::AddSubchannelBatchesForPendingBatches( continue; } // Create batch with the right number of callbacks. - const bool has_send_ops = batch->send_initial_metadata || - batch->send_message || - batch->send_trailing_metadata; - const int num_callbacks = has_send_ops + batch->recv_initial_metadata + - batch->recv_message + - batch->recv_trailing_metadata; + const bool has_send_ops = batch->send_initial_metadata || + batch->send_message || + batch->send_trailing_metadata; + const int num_callbacks = has_send_ops + batch->recv_initial_metadata + + batch->recv_message + + batch->recv_trailing_metadata; SubchannelCallBatchData* batch_data = SubchannelCallBatchData::Create( - elem, num_callbacks, has_send_ops /* set_on_complete */); + elem, num_callbacks, has_send_ops /* set_on_complete */); // Cache send ops if needed. MaybeCacheSendOpsForBatch(pending); // send_initial_metadata. @@ -3773,15 +3773,15 @@ void CallData::AddSubchannelBatchesForPendingBatches( AddRetriableRecvTrailingMetadataOp(retry_state, batch_data); } AddClosureForSubchannelBatch(elem, &batch_data->batch, closures); - // Track number of pending subchannel send batches. - // If this is the first one, take a ref to the call stack. - if (batch->send_initial_metadata || batch->send_message || - batch->send_trailing_metadata) { + // Track number of pending subchannel send batches. + // If this is the first one, take a ref to the call stack. + if (batch->send_initial_metadata || batch->send_message || + batch->send_trailing_metadata) { if (num_pending_retriable_subchannel_send_batches_ == 0) { GRPC_CALL_STACK_REF(owning_call_, "subchannel_send_batches"); - } + } ++num_pending_retriable_subchannel_send_batches_; - } + } } } @@ -3805,11 +3805,11 @@ void CallData::StartRetriableSubchannelBatches(void* arg, if (replay_batch_data != nullptr) { calld->AddClosureForSubchannelBatch(elem, &replay_batch_data->batch, &closures); - // Track number of pending subchannel send batches. - // If this is the first one, take a ref to the call stack. + // Track number of pending subchannel send batches. + // If this is the first one, take a ref to the call stack. if (calld->num_pending_retriable_subchannel_send_batches_ == 0) { GRPC_CALL_STACK_REF(calld->owning_call_, "subchannel_send_batches"); - } + } ++calld->num_pending_retriable_subchannel_send_batches_; } // Now add pending batches. @@ -3821,7 +3821,7 @@ void CallData::StartRetriableSubchannelBatches(void* arg, " retriable batches on subchannel_call=%p", chand, calld, closures.size(), calld->subchannel_call_.get()); } - // Note: This will yield the call combiner. + // Note: This will yield the call combiner. closures.RunClosures(calld->call_combiner_); } @@ -3999,7 +3999,7 @@ grpc_error* CallData::ApplyServiceConfigToCallLocked( } else { *send_initial_metadata_flags &= ~GRPC_INITIAL_METADATA_WAIT_FOR_READY; } - } + } } // Set retry throttle data for call. retry_throttle_data_ = chand->retry_throttle_data(); @@ -4115,16 +4115,16 @@ bool CallData::PickSubchannelLocked(grpc_call_element* elem, *error = ApplyServiceConfigToCallLocked(elem, initial_metadata_batch); if (*error != GRPC_ERROR_NONE) return true; } - // If this is a retry, use the send_initial_metadata payload that - // we've cached; otherwise, use the pending batch. The - // send_initial_metadata batch will be the first pending batch in the + // If this is a retry, use the send_initial_metadata payload that + // we've cached; otherwise, use the pending batch. The + // send_initial_metadata batch will be the first pending batch in the // list, as set by GetBatchIndex() above. - // TODO(roth): What if the LB policy needs to add something to the - // call's initial metadata, and then there's a retry? We don't want - // the new metadata to be added twice. We might need to somehow - // allocate the subchannel batch earlier so that we can give the - // subchannel's copy of the metadata batch (which is copied for each - // attempt) to the LB policy instead the one from the parent channel. + // TODO(roth): What if the LB policy needs to add something to the + // call's initial metadata, and then there's a retry? We don't want + // the new metadata to be added twice. We might need to somehow + // allocate the subchannel batch earlier so that we can give the + // subchannel's copy of the metadata batch (which is copied for each + // attempt) to the LB policy instead the one from the parent channel. LoadBalancingPolicy::PickArgs pick_args; pick_args.path = StringViewFromSlice(path_); pick_args.call_state = &lb_call_state_; @@ -4271,8 +4271,8 @@ void grpc_client_channel_stop_connectivity_watch( chand->RemoveConnectivityWatcher(watcher); } -grpc_core::RefCountedPtr<grpc_core::SubchannelCall> -grpc_client_channel_get_subchannel_call(grpc_call_element* elem) { +grpc_core::RefCountedPtr<grpc_core::SubchannelCall> +grpc_client_channel_get_subchannel_call(grpc_call_element* elem) { auto* calld = static_cast<CallData*>(elem->call_data); return calld->subchannel_call(); } diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h index 35c2a2af6b..8be55d511c 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel.h @@ -21,7 +21,7 @@ #include <grpc/support/port_platform.h> -#include "src/core/ext/filters/client_channel/client_channel_channelz.h" +#include "src/core/ext/filters/client_channel/client_channel_channelz.h" #include "src/core/ext/filters/client_channel/client_channel_factory.h" #include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/lib/channel/channel_stack.h" @@ -76,7 +76,7 @@ void grpc_client_channel_stop_connectivity_watch( grpc_core::AsyncConnectivityStateWatcherInterface* watcher); /* Debug helper: pull the subchannel call from a call stack element */ -grpc_core::RefCountedPtr<grpc_core::SubchannelCall> -grpc_client_channel_get_subchannel_call(grpc_call_element* elem); +grpc_core::RefCountedPtr<grpc_core::SubchannelCall> +grpc_client_channel_get_subchannel_call(grpc_call_element* elem); #endif // GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_H diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc index a7799e449a..b09bab5aa3 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.cc @@ -1,54 +1,54 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/client_channel.h" -#include "src/core/ext/filters/client_channel/client_channel_channelz.h" -#include "src/core/lib/channel/channelz_registry.h" -#include "src/core/lib/gpr/useful.h" -#include "src/core/lib/surface/channel.h" -#include "src/core/lib/transport/connectivity_state.h" - -#include <grpc/support/string_util.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/client_channel.h" +#include "src/core/ext/filters/client_channel/client_channel_channelz.h" +#include "src/core/lib/channel/channelz_registry.h" +#include "src/core/lib/gpr/useful.h" +#include "src/core/lib/surface/channel.h" +#include "src/core/lib/transport/connectivity_state.h" + +#include <grpc/support/string_util.h> + #include <util/string/cast.h> -namespace grpc_core { -namespace channelz { - +namespace grpc_core { +namespace channelz { + SubchannelNode::SubchannelNode(TString target_address, size_t channel_tracer_max_nodes) : BaseNode(EntityType::kSubchannel, target_address), target_(std::move(target_address)), trace_(channel_tracer_max_nodes) {} - + SubchannelNode::~SubchannelNode() {} - + void SubchannelNode::UpdateConnectivityState(grpc_connectivity_state state) { connectivity_state_.Store(state, MemoryOrder::RELAXED); -} - +} + void SubchannelNode::SetChildSocket(RefCountedPtr<SocketNode> socket) { MutexLock lock(&socket_mu_); child_socket_ = std::move(socket); -} - +} + Json SubchannelNode::RenderJson() { // Create and fill the data child. grpc_connectivity_state state = @@ -60,12 +60,12 @@ Json SubchannelNode::RenderJson() { }}, {"target", target_}, }; - + // Fill in the channel trace if applicable Json trace_json = trace_.RenderJson(); if (trace_json.type() != Json::Type::JSON_NULL) { data["trace"] = std::move(trace_json); - } + } // Ask CallCountingHelper to populate call count data. call_counter_.PopulateCallCounts(&data); // Construct top-level object. @@ -89,9 +89,9 @@ Json SubchannelNode::RenderJson() { {"name", child_socket->name()}, }, }; - } + } return object; -} - -} // namespace channelz -} // namespace grpc_core +} + +} // namespace channelz +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h index cc463e26b9..bdc96a9d0f 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_channelz.h @@ -1,75 +1,75 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_CHANNELZ_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_CHANNELZ_H - -#include <grpc/support/port_platform.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_CHANNELZ_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_CHANNELZ_H + +#include <grpc/support/port_platform.h> + #include <util/generic/string.h> -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/channel/channel_stack.h" -#include "src/core/lib/channel/channel_trace.h" -#include "src/core/lib/channel/channelz.h" - -namespace grpc_core { -namespace channelz { - -class SubchannelNode : public BaseNode { - public: +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/channel/channel_stack.h" +#include "src/core/lib/channel/channel_trace.h" +#include "src/core/lib/channel/channelz.h" + +namespace grpc_core { +namespace channelz { + +class SubchannelNode : public BaseNode { + public: SubchannelNode(TString target_address, size_t channel_tracer_max_nodes); - ~SubchannelNode() override; - + ~SubchannelNode() override; + // Sets the subchannel's connectivity state without health checking. void UpdateConnectivityState(grpc_connectivity_state state); - + // Used when the subchannel's child socket changes. This should be set when // the subchannel's transport is created and set to nullptr when the // subchannel unrefs the transport. void SetChildSocket(RefCountedPtr<SocketNode> socket); Json RenderJson() override; - - // proxy methods to composed classes. + + // proxy methods to composed classes. void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) { - trace_.AddTraceEvent(severity, data); - } - void AddTraceEventWithReference(ChannelTrace::Severity severity, + trace_.AddTraceEvent(severity, data); + } + void AddTraceEventWithReference(ChannelTrace::Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_channel) { - trace_.AddTraceEventWithReference(severity, data, - std::move(referenced_channel)); - } - void RecordCallStarted() { call_counter_.RecordCallStarted(); } - void RecordCallFailed() { call_counter_.RecordCallFailed(); } - void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); } - - private: + RefCountedPtr<BaseNode> referenced_channel) { + trace_.AddTraceEventWithReference(severity, data, + std::move(referenced_channel)); + } + void RecordCallStarted() { call_counter_.RecordCallStarted(); } + void RecordCallFailed() { call_counter_.RecordCallFailed(); } + void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); } + + private: Atomic<grpc_connectivity_state> connectivity_state_{GRPC_CHANNEL_IDLE}; Mutex socket_mu_; RefCountedPtr<SocketNode> child_socket_; TString target_; - CallCountingHelper call_counter_; - ChannelTrace trace_; -}; - -} // namespace channelz -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_CHANNELZ_H */ + CallCountingHelper call_counter_; + ChannelTrace trace_; +}; + +} // namespace channelz +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_CLIENT_CHANNEL_CHANNELZ_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc index 2358415fc2..17e2b0ad71 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/client_channel_plugin.cc @@ -26,8 +26,8 @@ #include "src/core/ext/filters/client_channel/backup_poller.h" #include "src/core/ext/filters/client_channel/client_channel.h" -#include "src/core/ext/filters/client_channel/client_channel_channelz.h" -#include "src/core/ext/filters/client_channel/global_subchannel_pool.h" +#include "src/core/ext/filters/client_channel/client_channel_channelz.h" +#include "src/core/ext/filters/client_channel/global_subchannel_pool.h" #include "src/core/ext/filters/client_channel/http_connect_handshaker.h" #include "src/core/ext/filters/client_channel/http_proxy.h" #include "src/core/ext/filters/client_channel/lb_policy_registry.h" @@ -51,7 +51,7 @@ void grpc_client_channel_init(void) { grpc_core::internal::ServerRetryThrottleMap::Init(); grpc_core::ProxyMapperRegistry::Init(); grpc_core::RegisterHttpProxyMapper(); - grpc_core::GlobalSubchannelPool::Init(); + grpc_core::GlobalSubchannelPool::Init(); grpc_channel_init_register_stage( GRPC_CLIENT_CHANNEL, GRPC_CHANNEL_INIT_BUILTIN_PRIORITY, append_filter, (void*)&grpc_client_channel_filter); @@ -60,7 +60,7 @@ void grpc_client_channel_init(void) { } void grpc_client_channel_shutdown(void) { - grpc_core::GlobalSubchannelPool::Shutdown(); + grpc_core::GlobalSubchannelPool::Shutdown(); grpc_channel_init_shutdown(); grpc_core::ProxyMapperRegistry::Shutdown(); grpc_core::internal::ServerRetryThrottleMap::Shutdown(); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h index 256471456e..c23341e1da 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/connector.h @@ -63,7 +63,7 @@ class SubchannelConnector : public InternallyRefCounted<SubchannelConnector> { // Only one connection attempt may be in progress at any one time. virtual void Connect(const Args& args, Result* result, grpc_closure* notify) = 0; - + // Cancels any in-flight connection attempt and shuts down the // connector. virtual void Shutdown(grpc_error* error) = 0; diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc index 546d1c4416..6a15ab11be 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.cc @@ -1,76 +1,76 @@ -// -// -// Copyright 2018 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/global_subchannel_pool.h" - -#include "src/core/ext/filters/client_channel/subchannel.h" - -namespace grpc_core { - +// +// +// Copyright 2018 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/global_subchannel_pool.h" + +#include "src/core/ext/filters/client_channel/subchannel.h" + +namespace grpc_core { + #define GRPC_REGISTER_SUBCHANNEL_CALM_DOWN_AFTER_ATTEMPTS 100 #define GRPC_REGISTER_SUBCHANNEL_CALM_DOWN_MICROS 10 -GlobalSubchannelPool::GlobalSubchannelPool() { - subchannel_map_ = grpc_avl_create(&subchannel_avl_vtable_); - gpr_mu_init(&mu_); -} - -GlobalSubchannelPool::~GlobalSubchannelPool() { - gpr_mu_destroy(&mu_); - grpc_avl_unref(subchannel_map_, nullptr); -} - -void GlobalSubchannelPool::Init() { +GlobalSubchannelPool::GlobalSubchannelPool() { + subchannel_map_ = grpc_avl_create(&subchannel_avl_vtable_); + gpr_mu_init(&mu_); +} + +GlobalSubchannelPool::~GlobalSubchannelPool() { + gpr_mu_destroy(&mu_); + grpc_avl_unref(subchannel_map_, nullptr); +} + +void GlobalSubchannelPool::Init() { instance_ = new RefCountedPtr<GlobalSubchannelPool>( - MakeRefCounted<GlobalSubchannelPool>()); -} - -void GlobalSubchannelPool::Shutdown() { - // To ensure Init() was called before. - GPR_ASSERT(instance_ != nullptr); - // To ensure Shutdown() was not called before. - GPR_ASSERT(*instance_ != nullptr); - instance_->reset(); + MakeRefCounted<GlobalSubchannelPool>()); +} + +void GlobalSubchannelPool::Shutdown() { + // To ensure Init() was called before. + GPR_ASSERT(instance_ != nullptr); + // To ensure Shutdown() was not called before. + GPR_ASSERT(*instance_ != nullptr); + instance_->reset(); delete instance_; -} - -RefCountedPtr<GlobalSubchannelPool> GlobalSubchannelPool::instance() { - GPR_ASSERT(instance_ != nullptr); - GPR_ASSERT(*instance_ != nullptr); - return *instance_; -} - -Subchannel* GlobalSubchannelPool::RegisterSubchannel(SubchannelKey* key, - Subchannel* constructed) { - Subchannel* c = nullptr; - // Compare and swap (CAS) loop: +} + +RefCountedPtr<GlobalSubchannelPool> GlobalSubchannelPool::instance() { + GPR_ASSERT(instance_ != nullptr); + GPR_ASSERT(*instance_ != nullptr); + return *instance_; +} + +Subchannel* GlobalSubchannelPool::RegisterSubchannel(SubchannelKey* key, + Subchannel* constructed) { + Subchannel* c = nullptr; + // Compare and swap (CAS) loop: for (int attempt_count = 0; c == nullptr; attempt_count++) { - // Ref the shared map to have a local copy. - gpr_mu_lock(&mu_); - grpc_avl old_map = grpc_avl_ref(subchannel_map_, nullptr); - gpr_mu_unlock(&mu_); - // Check to see if a subchannel already exists. - c = static_cast<Subchannel*>(grpc_avl_get(old_map, key, nullptr)); - if (c != nullptr) { + // Ref the shared map to have a local copy. + gpr_mu_lock(&mu_); + grpc_avl old_map = grpc_avl_ref(subchannel_map_, nullptr); + gpr_mu_unlock(&mu_); + // Check to see if a subchannel already exists. + c = static_cast<Subchannel*>(grpc_avl_get(old_map, key, nullptr)); + if (c != nullptr) { // The subchannel already exists. Try to reuse it. - c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "subchannel_register+reuse"); + c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "subchannel_register+reuse"); if (c != nullptr) { GRPC_SUBCHANNEL_UNREF(constructed, "subchannel_register+found_existing"); @@ -95,107 +95,107 @@ Subchannel* GlobalSubchannelPool::RegisterSubchannel(SubchannelKey* key, GPR_TIMESPAN))); } } - } else { - // There hasn't been such subchannel. Add one. - // Note that we should ref the old map first because grpc_avl_add() will - // unref it while we still need to access it later. - grpc_avl new_map = grpc_avl_add( + } else { + // There hasn't been such subchannel. Add one. + // Note that we should ref the old map first because grpc_avl_add() will + // unref it while we still need to access it later. + grpc_avl new_map = grpc_avl_add( grpc_avl_ref(old_map, nullptr), new SubchannelKey(*key), - GRPC_SUBCHANNEL_WEAK_REF(constructed, "subchannel_register+new"), - nullptr); - // Try to publish the change to the shared map. It may happen (but - // unlikely) that some other thread has changed the shared map, so compare - // to make sure it's unchanged before swapping. Retry if it's changed. - gpr_mu_lock(&mu_); - if (old_map.root == subchannel_map_.root) { - GPR_SWAP(grpc_avl, new_map, subchannel_map_); - c = constructed; - } - gpr_mu_unlock(&mu_); - grpc_avl_unref(new_map, nullptr); - } - grpc_avl_unref(old_map, nullptr); - } - return c; -} - -void GlobalSubchannelPool::UnregisterSubchannel(SubchannelKey* key) { - bool done = false; - // Compare and swap (CAS) loop: - while (!done) { - // Ref the shared map to have a local copy. - gpr_mu_lock(&mu_); - grpc_avl old_map = grpc_avl_ref(subchannel_map_, nullptr); - gpr_mu_unlock(&mu_); - // Remove the subchannel. - // Note that we should ref the old map first because grpc_avl_remove() will - // unref it while we still need to access it later. - grpc_avl new_map = - grpc_avl_remove(grpc_avl_ref(old_map, nullptr), key, nullptr); - // Try to publish the change to the shared map. It may happen (but - // unlikely) that some other thread has changed the shared map, so compare - // to make sure it's unchanged before swapping. Retry if it's changed. - gpr_mu_lock(&mu_); - if (old_map.root == subchannel_map_.root) { - GPR_SWAP(grpc_avl, new_map, subchannel_map_); - done = true; - } - gpr_mu_unlock(&mu_); - grpc_avl_unref(new_map, nullptr); - grpc_avl_unref(old_map, nullptr); - } -} - -Subchannel* GlobalSubchannelPool::FindSubchannel(SubchannelKey* key) { - // Lock, and take a reference to the subchannel map. - // We don't need to do the search under a lock as AVL's are immutable. - gpr_mu_lock(&mu_); - grpc_avl index = grpc_avl_ref(subchannel_map_, nullptr); - gpr_mu_unlock(&mu_); - Subchannel* c = static_cast<Subchannel*>(grpc_avl_get(index, key, nullptr)); + GRPC_SUBCHANNEL_WEAK_REF(constructed, "subchannel_register+new"), + nullptr); + // Try to publish the change to the shared map. It may happen (but + // unlikely) that some other thread has changed the shared map, so compare + // to make sure it's unchanged before swapping. Retry if it's changed. + gpr_mu_lock(&mu_); + if (old_map.root == subchannel_map_.root) { + GPR_SWAP(grpc_avl, new_map, subchannel_map_); + c = constructed; + } + gpr_mu_unlock(&mu_); + grpc_avl_unref(new_map, nullptr); + } + grpc_avl_unref(old_map, nullptr); + } + return c; +} + +void GlobalSubchannelPool::UnregisterSubchannel(SubchannelKey* key) { + bool done = false; + // Compare and swap (CAS) loop: + while (!done) { + // Ref the shared map to have a local copy. + gpr_mu_lock(&mu_); + grpc_avl old_map = grpc_avl_ref(subchannel_map_, nullptr); + gpr_mu_unlock(&mu_); + // Remove the subchannel. + // Note that we should ref the old map first because grpc_avl_remove() will + // unref it while we still need to access it later. + grpc_avl new_map = + grpc_avl_remove(grpc_avl_ref(old_map, nullptr), key, nullptr); + // Try to publish the change to the shared map. It may happen (but + // unlikely) that some other thread has changed the shared map, so compare + // to make sure it's unchanged before swapping. Retry if it's changed. + gpr_mu_lock(&mu_); + if (old_map.root == subchannel_map_.root) { + GPR_SWAP(grpc_avl, new_map, subchannel_map_); + done = true; + } + gpr_mu_unlock(&mu_); + grpc_avl_unref(new_map, nullptr); + grpc_avl_unref(old_map, nullptr); + } +} + +Subchannel* GlobalSubchannelPool::FindSubchannel(SubchannelKey* key) { + // Lock, and take a reference to the subchannel map. + // We don't need to do the search under a lock as AVL's are immutable. + gpr_mu_lock(&mu_); + grpc_avl index = grpc_avl_ref(subchannel_map_, nullptr); + gpr_mu_unlock(&mu_); + Subchannel* c = static_cast<Subchannel*>(grpc_avl_get(index, key, nullptr)); if (c != nullptr) c = GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(c, "found_from_pool"); - grpc_avl_unref(index, nullptr); - return c; -} - -RefCountedPtr<GlobalSubchannelPool>* GlobalSubchannelPool::instance_ = nullptr; - -namespace { - + grpc_avl_unref(index, nullptr); + return c; +} + +RefCountedPtr<GlobalSubchannelPool>* GlobalSubchannelPool::instance_ = nullptr; + +namespace { + void sck_avl_destroy(void* p, void* /*user_data*/) { - SubchannelKey* key = static_cast<SubchannelKey*>(p); + SubchannelKey* key = static_cast<SubchannelKey*>(p); delete key; -} - +} + void* sck_avl_copy(void* p, void* /*unused*/) { - const SubchannelKey* key = static_cast<const SubchannelKey*>(p); + const SubchannelKey* key = static_cast<const SubchannelKey*>(p); auto* new_key = new SubchannelKey(*key); - return static_cast<void*>(new_key); -} - + return static_cast<void*>(new_key); +} + long sck_avl_compare(void* a, void* b, void* /*unused*/) { - const SubchannelKey* key_a = static_cast<const SubchannelKey*>(a); - const SubchannelKey* key_b = static_cast<const SubchannelKey*>(b); - return key_a->Cmp(*key_b); -} - + const SubchannelKey* key_a = static_cast<const SubchannelKey*>(a); + const SubchannelKey* key_b = static_cast<const SubchannelKey*>(b); + return key_a->Cmp(*key_b); +} + void scv_avl_destroy(void* p, void* /*user_data*/) { - GRPC_SUBCHANNEL_WEAK_UNREF((Subchannel*)p, "global_subchannel_pool"); -} - + GRPC_SUBCHANNEL_WEAK_UNREF((Subchannel*)p, "global_subchannel_pool"); +} + void* scv_avl_copy(void* p, void* /*unused*/) { - GRPC_SUBCHANNEL_WEAK_REF((Subchannel*)p, "global_subchannel_pool"); - return p; -} - -} // namespace - -const grpc_avl_vtable GlobalSubchannelPool::subchannel_avl_vtable_ = { - sck_avl_destroy, // destroy_key - sck_avl_copy, // copy_key - sck_avl_compare, // compare_keys - scv_avl_destroy, // destroy_value - scv_avl_copy // copy_value -}; - -} // namespace grpc_core + GRPC_SUBCHANNEL_WEAK_REF((Subchannel*)p, "global_subchannel_pool"); + return p; +} + +} // namespace + +const grpc_avl_vtable GlobalSubchannelPool::subchannel_avl_vtable_ = { + sck_avl_destroy, // destroy_key + sck_avl_copy, // copy_key + sck_avl_compare, // compare_keys + scv_avl_destroy, // destroy_value + scv_avl_copy // copy_value +}; + +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.h index 96dc8d7b3a..b786d80339 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/global_subchannel_pool.h @@ -1,68 +1,68 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_GLOBAL_SUBCHANNEL_POOL_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_GLOBAL_SUBCHANNEL_POOL_H - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" - -namespace grpc_core { - -// The global subchannel pool. It shares subchannels among channels. There -// should be only one instance of this class. Init() should be called once at -// the filter initialization time; Shutdown() should be called once at the -// filter shutdown time. -// TODO(juanlishen): Enable subchannel retention. -class GlobalSubchannelPool final : public SubchannelPoolInterface { - public: - // The ctor and dtor are not intended to use directly. - GlobalSubchannelPool(); - ~GlobalSubchannelPool() override; - - // Should be called exactly once at filter initialization time. - static void Init(); - // Should be called exactly once at filter shutdown time. - static void Shutdown(); - - // Gets the singleton instance. - static RefCountedPtr<GlobalSubchannelPool> instance(); - - // Implements interface methods. - Subchannel* RegisterSubchannel(SubchannelKey* key, - Subchannel* constructed) override; - void UnregisterSubchannel(SubchannelKey* key) override; - Subchannel* FindSubchannel(SubchannelKey* key) override; - - private: - // The singleton instance. (It's a pointer to RefCountedPtr so that this - // non-local static object can be trivially destructible.) - static RefCountedPtr<GlobalSubchannelPool>* instance_; - - // The vtable for subchannel operations in an AVL tree. - static const grpc_avl_vtable subchannel_avl_vtable_; - // A map from subchannel key to subchannel. - grpc_avl subchannel_map_; - // To protect subchannel_map_. - gpr_mu mu_; -}; - -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_GLOBAL_SUBCHANNEL_POOL_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_GLOBAL_SUBCHANNEL_POOL_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_GLOBAL_SUBCHANNEL_POOL_H + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" + +namespace grpc_core { + +// The global subchannel pool. It shares subchannels among channels. There +// should be only one instance of this class. Init() should be called once at +// the filter initialization time; Shutdown() should be called once at the +// filter shutdown time. +// TODO(juanlishen): Enable subchannel retention. +class GlobalSubchannelPool final : public SubchannelPoolInterface { + public: + // The ctor and dtor are not intended to use directly. + GlobalSubchannelPool(); + ~GlobalSubchannelPool() override; + + // Should be called exactly once at filter initialization time. + static void Init(); + // Should be called exactly once at filter shutdown time. + static void Shutdown(); + + // Gets the singleton instance. + static RefCountedPtr<GlobalSubchannelPool> instance(); + + // Implements interface methods. + Subchannel* RegisterSubchannel(SubchannelKey* key, + Subchannel* constructed) override; + void UnregisterSubchannel(SubchannelKey* key) override; + Subchannel* FindSubchannel(SubchannelKey* key) override; + + private: + // The singleton instance. (It's a pointer to RefCountedPtr so that this + // non-local static object can be trivially destructible.) + static RefCountedPtr<GlobalSubchannelPool>* instance_; + + // The vtable for subchannel operations in an AVL tree. + static const grpc_avl_vtable subchannel_avl_vtable_; + // A map from subchannel key to subchannel. + grpc_avl subchannel_map_; + // To protect subchannel_map_. + gpr_mu mu_; +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_GLOBAL_SUBCHANNEL_POOL_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc index 7995185c13..905aa3f7f1 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.cc @@ -1,184 +1,184 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include <stdint.h> -#include <stdio.h> - -#include "src/core/ext/filters/client_channel/health/health_check_client.h" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include <stdint.h> +#include <stdio.h> + +#include "src/core/ext/filters/client_channel/health/health_check_client.h" + #include "upb/upb.hpp" -#include "src/core/lib/debug/trace.h" +#include "src/core/lib/debug/trace.h" #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/transport/error_utils.h" -#include "src/core/lib/transport/status_metadata.h" +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/transport/error_utils.h" +#include "src/core/lib/transport/status_metadata.h" #include "src/proto/grpc/health/v1/health.upb.h" - -#define HEALTH_CHECK_INITIAL_CONNECT_BACKOFF_SECONDS 1 -#define HEALTH_CHECK_RECONNECT_BACKOFF_MULTIPLIER 1.6 -#define HEALTH_CHECK_RECONNECT_MAX_BACKOFF_SECONDS 120 -#define HEALTH_CHECK_RECONNECT_JITTER 0.2 - -namespace grpc_core { - + +#define HEALTH_CHECK_INITIAL_CONNECT_BACKOFF_SECONDS 1 +#define HEALTH_CHECK_RECONNECT_BACKOFF_MULTIPLIER 1.6 +#define HEALTH_CHECK_RECONNECT_MAX_BACKOFF_SECONDS 120 +#define HEALTH_CHECK_RECONNECT_JITTER 0.2 + +namespace grpc_core { + TraceFlag grpc_health_check_client_trace(false, "health_check_client"); -// -// HealthCheckClient -// - -HealthCheckClient::HealthCheckClient( - const char* service_name, - RefCountedPtr<ConnectedSubchannel> connected_subchannel, - grpc_pollset_set* interested_parties, +// +// HealthCheckClient +// + +HealthCheckClient::HealthCheckClient( + const char* service_name, + RefCountedPtr<ConnectedSubchannel> connected_subchannel, + grpc_pollset_set* interested_parties, RefCountedPtr<channelz::SubchannelNode> channelz_node, RefCountedPtr<ConnectivityStateWatcherInterface> watcher) - : InternallyRefCounted<HealthCheckClient>(&grpc_health_check_client_trace), - service_name_(service_name), - connected_subchannel_(std::move(connected_subchannel)), - interested_parties_(interested_parties), - channelz_node_(std::move(channelz_node)), + : InternallyRefCounted<HealthCheckClient>(&grpc_health_check_client_trace), + service_name_(service_name), + connected_subchannel_(std::move(connected_subchannel)), + interested_parties_(interested_parties), + channelz_node_(std::move(channelz_node)), watcher_(std::move(watcher)), - retry_backoff_( - BackOff::Options() - .set_initial_backoff( - HEALTH_CHECK_INITIAL_CONNECT_BACKOFF_SECONDS * 1000) - .set_multiplier(HEALTH_CHECK_RECONNECT_BACKOFF_MULTIPLIER) - .set_jitter(HEALTH_CHECK_RECONNECT_JITTER) - .set_max_backoff(HEALTH_CHECK_RECONNECT_MAX_BACKOFF_SECONDS * - 1000)) { + retry_backoff_( + BackOff::Options() + .set_initial_backoff( + HEALTH_CHECK_INITIAL_CONNECT_BACKOFF_SECONDS * 1000) + .set_multiplier(HEALTH_CHECK_RECONNECT_BACKOFF_MULTIPLIER) + .set_jitter(HEALTH_CHECK_RECONNECT_JITTER) + .set_max_backoff(HEALTH_CHECK_RECONNECT_MAX_BACKOFF_SECONDS * + 1000)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "created HealthCheckClient %p", this); - } - GRPC_CLOSURE_INIT(&retry_timer_callback_, OnRetryTimer, this, - grpc_schedule_on_exec_ctx); - StartCall(); -} - -HealthCheckClient::~HealthCheckClient() { + gpr_log(GPR_INFO, "created HealthCheckClient %p", this); + } + GRPC_CLOSURE_INIT(&retry_timer_callback_, OnRetryTimer, this, + grpc_schedule_on_exec_ctx); + StartCall(); +} + +HealthCheckClient::~HealthCheckClient() { if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "destroying HealthCheckClient %p", this); - } -} - -void HealthCheckClient::SetHealthStatus(grpc_connectivity_state state, + gpr_log(GPR_INFO, "destroying HealthCheckClient %p", this); + } +} + +void HealthCheckClient::SetHealthStatus(grpc_connectivity_state state, const char* reason) { - MutexLock lock(&mu_); + MutexLock lock(&mu_); SetHealthStatusLocked(state, reason); -} - -void HealthCheckClient::SetHealthStatusLocked(grpc_connectivity_state state, +} + +void HealthCheckClient::SetHealthStatusLocked(grpc_connectivity_state state, const char* reason) { if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { gpr_log(GPR_INFO, "HealthCheckClient %p: setting state=%s reason=%s", this, ConnectivityStateName(state), reason); - } + } if (watcher_ != nullptr) { watcher_->Notify(state, state == GRPC_CHANNEL_TRANSIENT_FAILURE ? y_absl::Status(y_absl::StatusCode::kUnavailable, reason) : y_absl::Status()); } -} - -void HealthCheckClient::Orphan() { +} + +void HealthCheckClient::Orphan() { if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "HealthCheckClient %p: shutting down", this); - } - { - MutexLock lock(&mu_); - shutting_down_ = true; + gpr_log(GPR_INFO, "HealthCheckClient %p: shutting down", this); + } + { + MutexLock lock(&mu_); + shutting_down_ = true; watcher_.reset(); - call_state_.reset(); - if (retry_timer_callback_pending_) { - grpc_timer_cancel(&retry_timer_); - } - } - Unref(DEBUG_LOCATION, "orphan"); -} - -void HealthCheckClient::StartCall() { - MutexLock lock(&mu_); - StartCallLocked(); -} - -void HealthCheckClient::StartCallLocked() { - if (shutting_down_) return; - GPR_ASSERT(call_state_ == nullptr); + call_state_.reset(); + if (retry_timer_callback_pending_) { + grpc_timer_cancel(&retry_timer_); + } + } + Unref(DEBUG_LOCATION, "orphan"); +} + +void HealthCheckClient::StartCall() { + MutexLock lock(&mu_); + StartCallLocked(); +} + +void HealthCheckClient::StartCallLocked() { + if (shutting_down_) return; + GPR_ASSERT(call_state_ == nullptr); SetHealthStatusLocked(GRPC_CHANNEL_CONNECTING, "starting health watch"); - call_state_ = MakeOrphanable<CallState>(Ref(), interested_parties_); + call_state_ = MakeOrphanable<CallState>(Ref(), interested_parties_); if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "HealthCheckClient %p: created CallState %p", this, - call_state_.get()); - } - call_state_->StartCall(); -} - + gpr_log(GPR_INFO, "HealthCheckClient %p: created CallState %p", this, + call_state_.get()); + } + call_state_->StartCall(); +} + void HealthCheckClient::StartRetryTimerLocked() { SetHealthStatusLocked(GRPC_CHANNEL_TRANSIENT_FAILURE, "health check call failed; will retry after backoff"); - grpc_millis next_try = retry_backoff_.NextAttemptTime(); + grpc_millis next_try = retry_backoff_.NextAttemptTime(); if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "HealthCheckClient %p: health check call lost...", this); - grpc_millis timeout = next_try - ExecCtx::Get()->Now(); - if (timeout > 0) { - gpr_log(GPR_INFO, - "HealthCheckClient %p: ... will retry in %" PRId64 "ms.", this, - timeout); - } else { - gpr_log(GPR_INFO, "HealthCheckClient %p: ... retrying immediately.", - this); - } - } - // Ref for callback, tracked manually. - Ref(DEBUG_LOCATION, "health_retry_timer").release(); - retry_timer_callback_pending_ = true; - grpc_timer_init(&retry_timer_, next_try, &retry_timer_callback_); -} - -void HealthCheckClient::OnRetryTimer(void* arg, grpc_error* error) { - HealthCheckClient* self = static_cast<HealthCheckClient*>(arg); - { - MutexLock lock(&self->mu_); - self->retry_timer_callback_pending_ = false; - if (!self->shutting_down_ && error == GRPC_ERROR_NONE && - self->call_state_ == nullptr) { + gpr_log(GPR_INFO, "HealthCheckClient %p: health check call lost...", this); + grpc_millis timeout = next_try - ExecCtx::Get()->Now(); + if (timeout > 0) { + gpr_log(GPR_INFO, + "HealthCheckClient %p: ... will retry in %" PRId64 "ms.", this, + timeout); + } else { + gpr_log(GPR_INFO, "HealthCheckClient %p: ... retrying immediately.", + this); + } + } + // Ref for callback, tracked manually. + Ref(DEBUG_LOCATION, "health_retry_timer").release(); + retry_timer_callback_pending_ = true; + grpc_timer_init(&retry_timer_, next_try, &retry_timer_callback_); +} + +void HealthCheckClient::OnRetryTimer(void* arg, grpc_error* error) { + HealthCheckClient* self = static_cast<HealthCheckClient*>(arg); + { + MutexLock lock(&self->mu_); + self->retry_timer_callback_pending_ = false; + if (!self->shutting_down_ && error == GRPC_ERROR_NONE && + self->call_state_ == nullptr) { if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "HealthCheckClient %p: restarting health check call", - self); - } - self->StartCallLocked(); - } - } - self->Unref(DEBUG_LOCATION, "health_retry_timer"); -} - -// -// protobuf helpers -// - -namespace { - -void EncodeRequest(const char* service_name, - ManualConstructor<SliceBufferByteStream>* send_message) { + gpr_log(GPR_INFO, "HealthCheckClient %p: restarting health check call", + self); + } + self->StartCallLocked(); + } + } + self->Unref(DEBUG_LOCATION, "health_retry_timer"); +} + +// +// protobuf helpers +// + +namespace { + +void EncodeRequest(const char* service_name, + ManualConstructor<SliceBufferByteStream>* send_message) { upb::Arena arena; grpc_health_v1_HealthCheckRequest* request_struct = grpc_health_v1_HealthCheckRequest_new(arena.ptr()); @@ -189,212 +189,212 @@ void EncodeRequest(const char* service_name, request_struct, arena.ptr(), &buf_length); grpc_slice request_slice = GRPC_SLICE_MALLOC(buf_length); memcpy(GRPC_SLICE_START_PTR(request_slice), buf, buf_length); - grpc_slice_buffer slice_buffer; - grpc_slice_buffer_init(&slice_buffer); - grpc_slice_buffer_add(&slice_buffer, request_slice); - send_message->Init(&slice_buffer, 0); - grpc_slice_buffer_destroy_internal(&slice_buffer); -} - -// Returns true if healthy. -// If there was an error parsing the response, sets *error and returns false. -bool DecodeResponse(grpc_slice_buffer* slice_buffer, grpc_error** error) { - // If message is empty, assume unhealthy. - if (slice_buffer->length == 0) { - *error = - GRPC_ERROR_CREATE_FROM_STATIC_STRING("health check response was empty"); - return false; - } - // Concatenate the slices to form a single string. + grpc_slice_buffer slice_buffer; + grpc_slice_buffer_init(&slice_buffer); + grpc_slice_buffer_add(&slice_buffer, request_slice); + send_message->Init(&slice_buffer, 0); + grpc_slice_buffer_destroy_internal(&slice_buffer); +} + +// Returns true if healthy. +// If there was an error parsing the response, sets *error and returns false. +bool DecodeResponse(grpc_slice_buffer* slice_buffer, grpc_error** error) { + // If message is empty, assume unhealthy. + if (slice_buffer->length == 0) { + *error = + GRPC_ERROR_CREATE_FROM_STATIC_STRING("health check response was empty"); + return false; + } + // Concatenate the slices to form a single string. std::unique_ptr<uint8_t> recv_message_deleter; - uint8_t* recv_message; - if (slice_buffer->count == 1) { - recv_message = GRPC_SLICE_START_PTR(slice_buffer->slices[0]); - } else { - recv_message = static_cast<uint8_t*>(gpr_malloc(slice_buffer->length)); - recv_message_deleter.reset(recv_message); - size_t offset = 0; - for (size_t i = 0; i < slice_buffer->count; ++i) { - memcpy(recv_message + offset, - GRPC_SLICE_START_PTR(slice_buffer->slices[i]), - GRPC_SLICE_LENGTH(slice_buffer->slices[i])); - offset += GRPC_SLICE_LENGTH(slice_buffer->slices[i]); - } - } - // Deserialize message. + uint8_t* recv_message; + if (slice_buffer->count == 1) { + recv_message = GRPC_SLICE_START_PTR(slice_buffer->slices[0]); + } else { + recv_message = static_cast<uint8_t*>(gpr_malloc(slice_buffer->length)); + recv_message_deleter.reset(recv_message); + size_t offset = 0; + for (size_t i = 0; i < slice_buffer->count; ++i) { + memcpy(recv_message + offset, + GRPC_SLICE_START_PTR(slice_buffer->slices[i]), + GRPC_SLICE_LENGTH(slice_buffer->slices[i])); + offset += GRPC_SLICE_LENGTH(slice_buffer->slices[i]); + } + } + // Deserialize message. upb::Arena arena; grpc_health_v1_HealthCheckResponse* response_struct = grpc_health_v1_HealthCheckResponse_parse( reinterpret_cast<char*>(recv_message), slice_buffer->length, arena.ptr()); if (response_struct == nullptr) { - // Can't parse message; assume unhealthy. - *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "cannot parse health check response"); - return false; - } + // Can't parse message; assume unhealthy. + *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "cannot parse health check response"); + return false; + } int32_t status = grpc_health_v1_HealthCheckResponse_status(response_struct); return status == grpc_health_v1_HealthCheckResponse_SERVING; -} - -} // namespace - -// -// HealthCheckClient::CallState -// - -HealthCheckClient::CallState::CallState( - RefCountedPtr<HealthCheckClient> health_check_client, - grpc_pollset_set* interested_parties) +} + +} // namespace + +// +// HealthCheckClient::CallState +// + +HealthCheckClient::CallState::CallState( + RefCountedPtr<HealthCheckClient> health_check_client, + grpc_pollset_set* interested_parties) : health_check_client_(std::move(health_check_client)), - pollent_(grpc_polling_entity_create_from_pollset_set(interested_parties)), + pollent_(grpc_polling_entity_create_from_pollset_set(interested_parties)), arena_(Arena::Create(health_check_client_->connected_subchannel_ ->GetInitialCallSizeEstimate(0))), payload_(context_) {} - -HealthCheckClient::CallState::~CallState() { + +HealthCheckClient::CallState::~CallState() { if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, "HealthCheckClient %p: destroying CallState %p", - health_check_client_.get(), this); - } - for (size_t i = 0; i < GRPC_CONTEXT_COUNT; i++) { - if (context_[i].destroy != nullptr) { - context_[i].destroy(context_[i].value); - } - } - // Unset the call combiner cancellation closure. This has the - // effect of scheduling the previously set cancellation closure, if - // any, so that it can release any internal references it may be - // holding to the call stack. Also flush the closures on exec_ctx so that - // filters that schedule cancel notification closures on exec_ctx do not - // need to take a ref of the call stack to guarantee closure liveness. + gpr_log(GPR_INFO, "HealthCheckClient %p: destroying CallState %p", + health_check_client_.get(), this); + } + for (size_t i = 0; i < GRPC_CONTEXT_COUNT; i++) { + if (context_[i].destroy != nullptr) { + context_[i].destroy(context_[i].value); + } + } + // Unset the call combiner cancellation closure. This has the + // effect of scheduling the previously set cancellation closure, if + // any, so that it can release any internal references it may be + // holding to the call stack. Also flush the closures on exec_ctx so that + // filters that schedule cancel notification closures on exec_ctx do not + // need to take a ref of the call stack to guarantee closure liveness. call_combiner_.SetNotifyOnCancel(nullptr); ExecCtx::Get()->Flush(); arena_->Destroy(); -} - -void HealthCheckClient::CallState::Orphan() { +} + +void HealthCheckClient::CallState::Orphan() { call_combiner_.Cancel(GRPC_ERROR_CANCELLED); - Cancel(); -} - -void HealthCheckClient::CallState::StartCall() { + Cancel(); +} + +void HealthCheckClient::CallState::StartCall() { SubchannelCall::Args args = { health_check_client_->connected_subchannel_, - &pollent_, - GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH, + &pollent_, + GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH, gpr_get_cycle_counter(), // start_time GRPC_MILLIS_INF_FUTURE, // deadline - arena_, - context_, - &call_combiner_, - 0, // parent_data_size - }; - grpc_error* error = GRPC_ERROR_NONE; + arena_, + context_, + &call_combiner_, + 0, // parent_data_size + }; + grpc_error* error = GRPC_ERROR_NONE; call_ = SubchannelCall::Create(std::move(args), &error).release(); // Register after-destruction callback. GRPC_CLOSURE_INIT(&after_call_stack_destruction_, AfterCallStackDestruction, this, grpc_schedule_on_exec_ctx); call_->SetAfterCallStackDestroy(&after_call_stack_destruction_); // Check if creation failed. - if (error != GRPC_ERROR_NONE) { - gpr_log(GPR_ERROR, - "HealthCheckClient %p CallState %p: error creating health " - "checking call on subchannel (%s); will retry", - health_check_client_.get(), this, grpc_error_string(error)); - GRPC_ERROR_UNREF(error); + if (error != GRPC_ERROR_NONE) { + gpr_log(GPR_ERROR, + "HealthCheckClient %p CallState %p: error creating health " + "checking call on subchannel (%s); will retry", + health_check_client_.get(), this, grpc_error_string(error)); + GRPC_ERROR_UNREF(error); CallEndedLocked(/*retry=*/true); - return; - } - // Initialize payload and batch. - payload_.context = context_; - batch_.payload = &payload_; - // on_complete callback takes ref, handled manually. + return; + } + // Initialize payload and batch. + payload_.context = context_; + batch_.payload = &payload_; + // on_complete callback takes ref, handled manually. call_->Ref(DEBUG_LOCATION, "on_complete").release(); - batch_.on_complete = GRPC_CLOSURE_INIT(&on_complete_, OnComplete, this, - grpc_schedule_on_exec_ctx); - // Add send_initial_metadata op. - grpc_metadata_batch_init(&send_initial_metadata_); - error = grpc_metadata_batch_add_head( - &send_initial_metadata_, &path_metadata_storage_, - grpc_mdelem_from_slices( - GRPC_MDSTR_PATH, + batch_.on_complete = GRPC_CLOSURE_INIT(&on_complete_, OnComplete, this, + grpc_schedule_on_exec_ctx); + // Add send_initial_metadata op. + grpc_metadata_batch_init(&send_initial_metadata_); + error = grpc_metadata_batch_add_head( + &send_initial_metadata_, &path_metadata_storage_, + grpc_mdelem_from_slices( + GRPC_MDSTR_PATH, GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH), GRPC_BATCH_PATH); - GPR_ASSERT(error == GRPC_ERROR_NONE); - payload_.send_initial_metadata.send_initial_metadata = - &send_initial_metadata_; - payload_.send_initial_metadata.send_initial_metadata_flags = 0; - payload_.send_initial_metadata.peer_string = nullptr; - batch_.send_initial_metadata = true; - // Add send_message op. - EncodeRequest(health_check_client_->service_name_, &send_message_); - payload_.send_message.send_message.reset(send_message_.get()); - batch_.send_message = true; - // Add send_trailing_metadata op. - grpc_metadata_batch_init(&send_trailing_metadata_); - payload_.send_trailing_metadata.send_trailing_metadata = - &send_trailing_metadata_; - batch_.send_trailing_metadata = true; - // Add recv_initial_metadata op. - grpc_metadata_batch_init(&recv_initial_metadata_); - payload_.recv_initial_metadata.recv_initial_metadata = - &recv_initial_metadata_; - payload_.recv_initial_metadata.recv_flags = nullptr; - payload_.recv_initial_metadata.trailing_metadata_available = nullptr; - payload_.recv_initial_metadata.peer_string = nullptr; - // recv_initial_metadata_ready callback takes ref, handled manually. + GPR_ASSERT(error == GRPC_ERROR_NONE); + payload_.send_initial_metadata.send_initial_metadata = + &send_initial_metadata_; + payload_.send_initial_metadata.send_initial_metadata_flags = 0; + payload_.send_initial_metadata.peer_string = nullptr; + batch_.send_initial_metadata = true; + // Add send_message op. + EncodeRequest(health_check_client_->service_name_, &send_message_); + payload_.send_message.send_message.reset(send_message_.get()); + batch_.send_message = true; + // Add send_trailing_metadata op. + grpc_metadata_batch_init(&send_trailing_metadata_); + payload_.send_trailing_metadata.send_trailing_metadata = + &send_trailing_metadata_; + batch_.send_trailing_metadata = true; + // Add recv_initial_metadata op. + grpc_metadata_batch_init(&recv_initial_metadata_); + payload_.recv_initial_metadata.recv_initial_metadata = + &recv_initial_metadata_; + payload_.recv_initial_metadata.recv_flags = nullptr; + payload_.recv_initial_metadata.trailing_metadata_available = nullptr; + payload_.recv_initial_metadata.peer_string = nullptr; + // recv_initial_metadata_ready callback takes ref, handled manually. call_->Ref(DEBUG_LOCATION, "recv_initial_metadata_ready").release(); - payload_.recv_initial_metadata.recv_initial_metadata_ready = - GRPC_CLOSURE_INIT(&recv_initial_metadata_ready_, RecvInitialMetadataReady, - this, grpc_schedule_on_exec_ctx); - batch_.recv_initial_metadata = true; - // Add recv_message op. - payload_.recv_message.recv_message = &recv_message_; - // recv_message callback takes ref, handled manually. + payload_.recv_initial_metadata.recv_initial_metadata_ready = + GRPC_CLOSURE_INIT(&recv_initial_metadata_ready_, RecvInitialMetadataReady, + this, grpc_schedule_on_exec_ctx); + batch_.recv_initial_metadata = true; + // Add recv_message op. + payload_.recv_message.recv_message = &recv_message_; + // recv_message callback takes ref, handled manually. call_->Ref(DEBUG_LOCATION, "recv_message_ready").release(); - payload_.recv_message.recv_message_ready = GRPC_CLOSURE_INIT( - &recv_message_ready_, RecvMessageReady, this, grpc_schedule_on_exec_ctx); - batch_.recv_message = true; - // Start batch. - StartBatch(&batch_); - // Initialize recv_trailing_metadata batch. - recv_trailing_metadata_batch_.payload = &payload_; - // Add recv_trailing_metadata op. - grpc_metadata_batch_init(&recv_trailing_metadata_); - payload_.recv_trailing_metadata.recv_trailing_metadata = - &recv_trailing_metadata_; - payload_.recv_trailing_metadata.collect_stats = &collect_stats_; - // This callback signals the end of the call, so it relies on the - // initial ref instead of taking a new ref. When it's invoked, the - // initial ref is released. - payload_.recv_trailing_metadata.recv_trailing_metadata_ready = - GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, - RecvTrailingMetadataReady, this, - grpc_schedule_on_exec_ctx); - recv_trailing_metadata_batch_.recv_trailing_metadata = true; - // Start recv_trailing_metadata batch. - StartBatch(&recv_trailing_metadata_batch_); -} - + payload_.recv_message.recv_message_ready = GRPC_CLOSURE_INIT( + &recv_message_ready_, RecvMessageReady, this, grpc_schedule_on_exec_ctx); + batch_.recv_message = true; + // Start batch. + StartBatch(&batch_); + // Initialize recv_trailing_metadata batch. + recv_trailing_metadata_batch_.payload = &payload_; + // Add recv_trailing_metadata op. + grpc_metadata_batch_init(&recv_trailing_metadata_); + payload_.recv_trailing_metadata.recv_trailing_metadata = + &recv_trailing_metadata_; + payload_.recv_trailing_metadata.collect_stats = &collect_stats_; + // This callback signals the end of the call, so it relies on the + // initial ref instead of taking a new ref. When it's invoked, the + // initial ref is released. + payload_.recv_trailing_metadata.recv_trailing_metadata_ready = + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, + RecvTrailingMetadataReady, this, + grpc_schedule_on_exec_ctx); + recv_trailing_metadata_batch_.recv_trailing_metadata = true; + // Start recv_trailing_metadata batch. + StartBatch(&recv_trailing_metadata_batch_); +} + void HealthCheckClient::CallState::StartBatchInCallCombiner( void* arg, grpc_error* /*error*/) { - grpc_transport_stream_op_batch* batch = - static_cast<grpc_transport_stream_op_batch*>(arg); - SubchannelCall* call = - static_cast<SubchannelCall*>(batch->handler_private.extra_arg); - call->StartTransportStreamOpBatch(batch); -} - -void HealthCheckClient::CallState::StartBatch( - grpc_transport_stream_op_batch* batch) { + grpc_transport_stream_op_batch* batch = + static_cast<grpc_transport_stream_op_batch*>(arg); + SubchannelCall* call = + static_cast<SubchannelCall*>(batch->handler_private.extra_arg); + call->StartTransportStreamOpBatch(batch); +} + +void HealthCheckClient::CallState::StartBatch( + grpc_transport_stream_op_batch* batch) { batch->handler_private.extra_arg = call_; - GRPC_CLOSURE_INIT(&batch->handler_private.closure, StartBatchInCallCombiner, - batch, grpc_schedule_on_exec_ctx); - GRPC_CALL_COMBINER_START(&call_combiner_, &batch->handler_private.closure, - GRPC_ERROR_NONE, "start_subchannel_batch"); -} - + GRPC_CLOSURE_INIT(&batch->handler_private.closure, StartBatchInCallCombiner, + batch, grpc_schedule_on_exec_ctx); + GRPC_CALL_COMBINER_START(&call_combiner_, &batch->handler_private.closure, + GRPC_ERROR_NONE, "start_subchannel_batch"); +} + void HealthCheckClient::CallState::AfterCallStackDestruction( void* arg, grpc_error* /*error*/) { HealthCheckClient::CallState* self = @@ -402,212 +402,212 @@ void HealthCheckClient::CallState::AfterCallStackDestruction( delete self; } -void HealthCheckClient::CallState::OnCancelComplete(void* arg, +void HealthCheckClient::CallState::OnCancelComplete(void* arg, grpc_error* /*error*/) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "health_cancel"); + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "health_cancel"); self->call_->Unref(DEBUG_LOCATION, "cancel"); -} - +} + void HealthCheckClient::CallState::StartCancel(void* arg, grpc_error* /*error*/) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - auto* batch = grpc_make_transport_stream_op( - GRPC_CLOSURE_CREATE(OnCancelComplete, self, grpc_schedule_on_exec_ctx)); - batch->cancel_stream = true; - batch->payload->cancel_stream.cancel_error = GRPC_ERROR_CANCELLED; - self->call_->StartTransportStreamOpBatch(batch); -} - -void HealthCheckClient::CallState::Cancel() { + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + auto* batch = grpc_make_transport_stream_op( + GRPC_CLOSURE_CREATE(OnCancelComplete, self, grpc_schedule_on_exec_ctx)); + batch->cancel_stream = true; + batch->payload->cancel_stream.cancel_error = GRPC_ERROR_CANCELLED; + self->call_->StartTransportStreamOpBatch(batch); +} + +void HealthCheckClient::CallState::Cancel() { bool expected = false; if (cancelled_.CompareExchangeStrong(&expected, true, MemoryOrder::ACQ_REL, MemoryOrder::ACQUIRE)) { call_->Ref(DEBUG_LOCATION, "cancel").release(); - GRPC_CALL_COMBINER_START( - &call_combiner_, - GRPC_CLOSURE_CREATE(StartCancel, this, grpc_schedule_on_exec_ctx), - GRPC_ERROR_NONE, "health_cancel"); - } -} - + GRPC_CALL_COMBINER_START( + &call_combiner_, + GRPC_CLOSURE_CREATE(StartCancel, this, grpc_schedule_on_exec_ctx), + GRPC_ERROR_NONE, "health_cancel"); + } +} + void HealthCheckClient::CallState::OnComplete(void* arg, grpc_error* /*error*/) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "on_complete"); - grpc_metadata_batch_destroy(&self->send_initial_metadata_); - grpc_metadata_batch_destroy(&self->send_trailing_metadata_); + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "on_complete"); + grpc_metadata_batch_destroy(&self->send_initial_metadata_); + grpc_metadata_batch_destroy(&self->send_trailing_metadata_); self->call_->Unref(DEBUG_LOCATION, "on_complete"); -} - +} + void HealthCheckClient::CallState::RecvInitialMetadataReady( void* arg, grpc_error* /*error*/) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "recv_initial_metadata_ready"); - grpc_metadata_batch_destroy(&self->recv_initial_metadata_); + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "recv_initial_metadata_ready"); + grpc_metadata_batch_destroy(&self->recv_initial_metadata_); self->call_->Unref(DEBUG_LOCATION, "recv_initial_metadata_ready"); -} - -void HealthCheckClient::CallState::DoneReadingRecvMessage(grpc_error* error) { - recv_message_.reset(); - if (error != GRPC_ERROR_NONE) { - GRPC_ERROR_UNREF(error); - Cancel(); - grpc_slice_buffer_destroy_internal(&recv_message_buffer_); +} + +void HealthCheckClient::CallState::DoneReadingRecvMessage(grpc_error* error) { + recv_message_.reset(); + if (error != GRPC_ERROR_NONE) { + GRPC_ERROR_UNREF(error); + Cancel(); + grpc_slice_buffer_destroy_internal(&recv_message_buffer_); call_->Unref(DEBUG_LOCATION, "recv_message_ready"); - return; - } - const bool healthy = DecodeResponse(&recv_message_buffer_, &error); - const grpc_connectivity_state state = - healthy ? GRPC_CHANNEL_READY : GRPC_CHANNEL_TRANSIENT_FAILURE; + return; + } + const bool healthy = DecodeResponse(&recv_message_buffer_, &error); + const grpc_connectivity_state state = + healthy ? GRPC_CHANNEL_READY : GRPC_CHANNEL_TRANSIENT_FAILURE; const char* reason = error == GRPC_ERROR_NONE && !healthy ? "backend unhealthy" : grpc_error_string(error); health_check_client_->SetHealthStatus(state, reason); seen_response_.Store(true, MemoryOrder::RELEASE); - grpc_slice_buffer_destroy_internal(&recv_message_buffer_); - // Start another recv_message batch. - // This re-uses the ref we're holding. - // Note: Can't just reuse batch_ here, since we don't know that all - // callbacks from the original batch have completed yet. - recv_message_batch_.payload = &payload_; - payload_.recv_message.recv_message = &recv_message_; - payload_.recv_message.recv_message_ready = GRPC_CLOSURE_INIT( - &recv_message_ready_, RecvMessageReady, this, grpc_schedule_on_exec_ctx); - recv_message_batch_.recv_message = true; - StartBatch(&recv_message_batch_); -} - -grpc_error* HealthCheckClient::CallState::PullSliceFromRecvMessage() { - grpc_slice slice; - grpc_error* error = recv_message_->Pull(&slice); - if (error == GRPC_ERROR_NONE) { - grpc_slice_buffer_add(&recv_message_buffer_, slice); - } - return error; -} - -void HealthCheckClient::CallState::ContinueReadingRecvMessage() { - while (recv_message_->Next(SIZE_MAX, &recv_message_ready_)) { - grpc_error* error = PullSliceFromRecvMessage(); - if (error != GRPC_ERROR_NONE) { - DoneReadingRecvMessage(error); - return; - } - if (recv_message_buffer_.length == recv_message_->length()) { - DoneReadingRecvMessage(GRPC_ERROR_NONE); - break; - } - } -} - -void HealthCheckClient::CallState::OnByteStreamNext(void* arg, - grpc_error* error) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - if (error != GRPC_ERROR_NONE) { - self->DoneReadingRecvMessage(GRPC_ERROR_REF(error)); - return; - } - error = self->PullSliceFromRecvMessage(); - if (error != GRPC_ERROR_NONE) { - self->DoneReadingRecvMessage(error); - return; - } - if (self->recv_message_buffer_.length == self->recv_message_->length()) { - self->DoneReadingRecvMessage(GRPC_ERROR_NONE); - } else { - self->ContinueReadingRecvMessage(); - } -} - -void HealthCheckClient::CallState::RecvMessageReady(void* arg, + grpc_slice_buffer_destroy_internal(&recv_message_buffer_); + // Start another recv_message batch. + // This re-uses the ref we're holding. + // Note: Can't just reuse batch_ here, since we don't know that all + // callbacks from the original batch have completed yet. + recv_message_batch_.payload = &payload_; + payload_.recv_message.recv_message = &recv_message_; + payload_.recv_message.recv_message_ready = GRPC_CLOSURE_INIT( + &recv_message_ready_, RecvMessageReady, this, grpc_schedule_on_exec_ctx); + recv_message_batch_.recv_message = true; + StartBatch(&recv_message_batch_); +} + +grpc_error* HealthCheckClient::CallState::PullSliceFromRecvMessage() { + grpc_slice slice; + grpc_error* error = recv_message_->Pull(&slice); + if (error == GRPC_ERROR_NONE) { + grpc_slice_buffer_add(&recv_message_buffer_, slice); + } + return error; +} + +void HealthCheckClient::CallState::ContinueReadingRecvMessage() { + while (recv_message_->Next(SIZE_MAX, &recv_message_ready_)) { + grpc_error* error = PullSliceFromRecvMessage(); + if (error != GRPC_ERROR_NONE) { + DoneReadingRecvMessage(error); + return; + } + if (recv_message_buffer_.length == recv_message_->length()) { + DoneReadingRecvMessage(GRPC_ERROR_NONE); + break; + } + } +} + +void HealthCheckClient::CallState::OnByteStreamNext(void* arg, + grpc_error* error) { + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + if (error != GRPC_ERROR_NONE) { + self->DoneReadingRecvMessage(GRPC_ERROR_REF(error)); + return; + } + error = self->PullSliceFromRecvMessage(); + if (error != GRPC_ERROR_NONE) { + self->DoneReadingRecvMessage(error); + return; + } + if (self->recv_message_buffer_.length == self->recv_message_->length()) { + self->DoneReadingRecvMessage(GRPC_ERROR_NONE); + } else { + self->ContinueReadingRecvMessage(); + } +} + +void HealthCheckClient::CallState::RecvMessageReady(void* arg, grpc_error* /*error*/) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "recv_message_ready"); - if (self->recv_message_ == nullptr) { + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + GRPC_CALL_COMBINER_STOP(&self->call_combiner_, "recv_message_ready"); + if (self->recv_message_ == nullptr) { self->call_->Unref(DEBUG_LOCATION, "recv_message_ready"); - return; - } - grpc_slice_buffer_init(&self->recv_message_buffer_); - GRPC_CLOSURE_INIT(&self->recv_message_ready_, OnByteStreamNext, self, - grpc_schedule_on_exec_ctx); - self->ContinueReadingRecvMessage(); - // Ref will continue to be held until we finish draining the byte stream. -} - -void HealthCheckClient::CallState::RecvTrailingMetadataReady( - void* arg, grpc_error* error) { - HealthCheckClient::CallState* self = - static_cast<HealthCheckClient::CallState*>(arg); - GRPC_CALL_COMBINER_STOP(&self->call_combiner_, - "recv_trailing_metadata_ready"); - // Get call status. - grpc_status_code status = GRPC_STATUS_UNKNOWN; - if (error != GRPC_ERROR_NONE) { - grpc_error_get_status(error, GRPC_MILLIS_INF_FUTURE, &status, - nullptr /* slice */, nullptr /* http_error */, - nullptr /* error_string */); - } else if (self->recv_trailing_metadata_.idx.named.grpc_status != nullptr) { - status = grpc_get_status_code_from_metadata( - self->recv_trailing_metadata_.idx.named.grpc_status->md); - } + return; + } + grpc_slice_buffer_init(&self->recv_message_buffer_); + GRPC_CLOSURE_INIT(&self->recv_message_ready_, OnByteStreamNext, self, + grpc_schedule_on_exec_ctx); + self->ContinueReadingRecvMessage(); + // Ref will continue to be held until we finish draining the byte stream. +} + +void HealthCheckClient::CallState::RecvTrailingMetadataReady( + void* arg, grpc_error* error) { + HealthCheckClient::CallState* self = + static_cast<HealthCheckClient::CallState*>(arg); + GRPC_CALL_COMBINER_STOP(&self->call_combiner_, + "recv_trailing_metadata_ready"); + // Get call status. + grpc_status_code status = GRPC_STATUS_UNKNOWN; + if (error != GRPC_ERROR_NONE) { + grpc_error_get_status(error, GRPC_MILLIS_INF_FUTURE, &status, + nullptr /* slice */, nullptr /* http_error */, + nullptr /* error_string */); + } else if (self->recv_trailing_metadata_.idx.named.grpc_status != nullptr) { + status = grpc_get_status_code_from_metadata( + self->recv_trailing_metadata_.idx.named.grpc_status->md); + } if (GRPC_TRACE_FLAG_ENABLED(grpc_health_check_client_trace)) { - gpr_log(GPR_INFO, - "HealthCheckClient %p CallState %p: health watch failed with " - "status %d", - self->health_check_client_.get(), self, status); - } - // Clean up. - grpc_metadata_batch_destroy(&self->recv_trailing_metadata_); - // For status UNIMPLEMENTED, give up and assume always healthy. - bool retry = true; - if (status == GRPC_STATUS_UNIMPLEMENTED) { - static const char kErrorMessage[] = - "health checking Watch method returned UNIMPLEMENTED; " - "disabling health checks but assuming server is healthy"; - gpr_log(GPR_ERROR, kErrorMessage); - if (self->health_check_client_->channelz_node_ != nullptr) { - self->health_check_client_->channelz_node_->AddTraceEvent( - channelz::ChannelTrace::Error, - grpc_slice_from_static_string(kErrorMessage)); - } - self->health_check_client_->SetHealthStatus(GRPC_CHANNEL_READY, + gpr_log(GPR_INFO, + "HealthCheckClient %p CallState %p: health watch failed with " + "status %d", + self->health_check_client_.get(), self, status); + } + // Clean up. + grpc_metadata_batch_destroy(&self->recv_trailing_metadata_); + // For status UNIMPLEMENTED, give up and assume always healthy. + bool retry = true; + if (status == GRPC_STATUS_UNIMPLEMENTED) { + static const char kErrorMessage[] = + "health checking Watch method returned UNIMPLEMENTED; " + "disabling health checks but assuming server is healthy"; + gpr_log(GPR_ERROR, kErrorMessage); + if (self->health_check_client_->channelz_node_ != nullptr) { + self->health_check_client_->channelz_node_->AddTraceEvent( + channelz::ChannelTrace::Error, + grpc_slice_from_static_string(kErrorMessage)); + } + self->health_check_client_->SetHealthStatus(GRPC_CHANNEL_READY, kErrorMessage); - retry = false; - } + retry = false; + } MutexLock lock(&self->health_check_client_->mu_); self->CallEndedLocked(retry); -} - +} + void HealthCheckClient::CallState::CallEndedLocked(bool retry) { - // If this CallState is still in use, this call ended because of a failure, - // so we need to stop using it and optionally create a new one. - // Otherwise, we have deliberately ended this call, and no further action - // is required. - if (this == health_check_client_->call_state_.get()) { - health_check_client_->call_state_.reset(); - if (retry) { - GPR_ASSERT(!health_check_client_->shutting_down_); + // If this CallState is still in use, this call ended because of a failure, + // so we need to stop using it and optionally create a new one. + // Otherwise, we have deliberately ended this call, and no further action + // is required. + if (this == health_check_client_->call_state_.get()) { + health_check_client_->call_state_.reset(); + if (retry) { + GPR_ASSERT(!health_check_client_->shutting_down_); if (seen_response_.Load(MemoryOrder::ACQUIRE)) { - // If the call fails after we've gotten a successful response, reset - // the backoff and restart the call immediately. - health_check_client_->retry_backoff_.Reset(); + // If the call fails after we've gotten a successful response, reset + // the backoff and restart the call immediately. + health_check_client_->retry_backoff_.Reset(); health_check_client_->StartCallLocked(); - } else { - // If the call failed without receiving any messages, retry later. + } else { + // If the call failed without receiving any messages, retry later. health_check_client_->StartRetryTimerLocked(); - } - } - } + } + } + } // When the last ref to the call stack goes away, the CallState object // will be automatically destroyed. call_->Unref(DEBUG_LOCATION, "call_ended"); -} - -} // namespace grpc_core +} + +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h index e9555b5f95..ef64f9ee64 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/health/health_check_client.h @@ -1,175 +1,175 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HEALTH_HEALTH_CHECK_CLIENT_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HEALTH_HEALTH_CHECK_CLIENT_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc.h> -#include <grpc/support/sync.h> - -#include "src/core/ext/filters/client_channel/client_channel_channelz.h" -#include "src/core/ext/filters/client_channel/subchannel.h" -#include "src/core/lib/backoff/backoff.h" +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HEALTH_HEALTH_CHECK_CLIENT_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HEALTH_HEALTH_CHECK_CLIENT_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc.h> +#include <grpc/support/sync.h> + +#include "src/core/ext/filters/client_channel/client_channel_channelz.h" +#include "src/core/ext/filters/client_channel/subchannel.h" +#include "src/core/lib/backoff/backoff.h" #include "src/core/lib/gprpp/arena.h" #include "src/core/lib/gprpp/atomic.h" -#include "src/core/lib/gprpp/orphanable.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/orphanable.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/iomgr/call_combiner.h" -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/polling_entity.h" -#include "src/core/lib/iomgr/timer.h" -#include "src/core/lib/transport/byte_stream.h" -#include "src/core/lib/transport/metadata_batch.h" -#include "src/core/lib/transport/transport.h" - -namespace grpc_core { - -class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> { - public: - HealthCheckClient(const char* service_name, - RefCountedPtr<ConnectedSubchannel> connected_subchannel, - grpc_pollset_set* interested_parties, +#include "src/core/lib/iomgr/call_combiner.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/polling_entity.h" +#include "src/core/lib/iomgr/timer.h" +#include "src/core/lib/transport/byte_stream.h" +#include "src/core/lib/transport/metadata_batch.h" +#include "src/core/lib/transport/transport.h" + +namespace grpc_core { + +class HealthCheckClient : public InternallyRefCounted<HealthCheckClient> { + public: + HealthCheckClient(const char* service_name, + RefCountedPtr<ConnectedSubchannel> connected_subchannel, + grpc_pollset_set* interested_parties, RefCountedPtr<channelz::SubchannelNode> channelz_node, RefCountedPtr<ConnectivityStateWatcherInterface> watcher); - - ~HealthCheckClient(); - - void Orphan() override; - - private: - // Contains a call to the backend and all the data related to the call. + + ~HealthCheckClient(); + + void Orphan() override; + + private: + // Contains a call to the backend and all the data related to the call. class CallState : public Orphanable { - public: - CallState(RefCountedPtr<HealthCheckClient> health_check_client, - grpc_pollset_set* interested_parties_); - ~CallState(); - - void Orphan() override; - - void StartCall(); - - private: - void Cancel(); - - void StartBatch(grpc_transport_stream_op_batch* batch); - static void StartBatchInCallCombiner(void* arg, grpc_error* error); - + public: + CallState(RefCountedPtr<HealthCheckClient> health_check_client, + grpc_pollset_set* interested_parties_); + ~CallState(); + + void Orphan() override; + + void StartCall(); + + private: + void Cancel(); + + void StartBatch(grpc_transport_stream_op_batch* batch); + static void StartBatchInCallCombiner(void* arg, grpc_error* error); + // Requires holding health_check_client_->mu_. void CallEndedLocked(bool retry); - - static void OnComplete(void* arg, grpc_error* error); - static void RecvInitialMetadataReady(void* arg, grpc_error* error); - static void RecvMessageReady(void* arg, grpc_error* error); - static void RecvTrailingMetadataReady(void* arg, grpc_error* error); - static void StartCancel(void* arg, grpc_error* error); - static void OnCancelComplete(void* arg, grpc_error* error); - - static void OnByteStreamNext(void* arg, grpc_error* error); - void ContinueReadingRecvMessage(); - grpc_error* PullSliceFromRecvMessage(); - void DoneReadingRecvMessage(grpc_error* error); - + + static void OnComplete(void* arg, grpc_error* error); + static void RecvInitialMetadataReady(void* arg, grpc_error* error); + static void RecvMessageReady(void* arg, grpc_error* error); + static void RecvTrailingMetadataReady(void* arg, grpc_error* error); + static void StartCancel(void* arg, grpc_error* error); + static void OnCancelComplete(void* arg, grpc_error* error); + + static void OnByteStreamNext(void* arg, grpc_error* error); + void ContinueReadingRecvMessage(); + grpc_error* PullSliceFromRecvMessage(); + void DoneReadingRecvMessage(grpc_error* error); + static void AfterCallStackDestruction(void* arg, grpc_error* error); - RefCountedPtr<HealthCheckClient> health_check_client_; - grpc_polling_entity pollent_; - + RefCountedPtr<HealthCheckClient> health_check_client_; + grpc_polling_entity pollent_; + Arena* arena_; grpc_core::CallCombiner call_combiner_; - grpc_call_context_element context_[GRPC_CONTEXT_COUNT] = {}; - + grpc_call_context_element context_[GRPC_CONTEXT_COUNT] = {}; + // The streaming call to the backend. Always non-null. // Refs are tracked manually; when the last ref is released, the // CallState object will be automatically destroyed. SubchannelCall* call_; - - grpc_transport_stream_op_batch_payload payload_; - grpc_transport_stream_op_batch batch_; - grpc_transport_stream_op_batch recv_message_batch_; - grpc_transport_stream_op_batch recv_trailing_metadata_batch_; - - grpc_closure on_complete_; - - // send_initial_metadata - grpc_metadata_batch send_initial_metadata_; - grpc_linked_mdelem path_metadata_storage_; - - // send_message - ManualConstructor<SliceBufferByteStream> send_message_; - - // send_trailing_metadata - grpc_metadata_batch send_trailing_metadata_; - - // recv_initial_metadata - grpc_metadata_batch recv_initial_metadata_; - grpc_closure recv_initial_metadata_ready_; - - // recv_message - OrphanablePtr<ByteStream> recv_message_; - grpc_closure recv_message_ready_; - grpc_slice_buffer recv_message_buffer_; + + grpc_transport_stream_op_batch_payload payload_; + grpc_transport_stream_op_batch batch_; + grpc_transport_stream_op_batch recv_message_batch_; + grpc_transport_stream_op_batch recv_trailing_metadata_batch_; + + grpc_closure on_complete_; + + // send_initial_metadata + grpc_metadata_batch send_initial_metadata_; + grpc_linked_mdelem path_metadata_storage_; + + // send_message + ManualConstructor<SliceBufferByteStream> send_message_; + + // send_trailing_metadata + grpc_metadata_batch send_trailing_metadata_; + + // recv_initial_metadata + grpc_metadata_batch recv_initial_metadata_; + grpc_closure recv_initial_metadata_ready_; + + // recv_message + OrphanablePtr<ByteStream> recv_message_; + grpc_closure recv_message_ready_; + grpc_slice_buffer recv_message_buffer_; Atomic<bool> seen_response_{false}; - - // recv_trailing_metadata - grpc_metadata_batch recv_trailing_metadata_; - grpc_transport_stream_stats collect_stats_; - grpc_closure recv_trailing_metadata_ready_; + + // recv_trailing_metadata + grpc_metadata_batch recv_trailing_metadata_; + grpc_transport_stream_stats collect_stats_; + grpc_closure recv_trailing_metadata_ready_; // True if the cancel_stream batch has been started. Atomic<bool> cancelled_{false}; // Closure for call stack destruction. grpc_closure after_call_stack_destruction_; - }; - - void StartCall(); - void StartCallLocked(); // Requires holding mu_. - + }; + + void StartCall(); + void StartCallLocked(); // Requires holding mu_. + void StartRetryTimerLocked(); // Requires holding mu_. - static void OnRetryTimer(void* arg, grpc_error* error); - + static void OnRetryTimer(void* arg, grpc_error* error); + void SetHealthStatus(grpc_connectivity_state state, const char* reason); - void SetHealthStatusLocked(grpc_connectivity_state state, + void SetHealthStatusLocked(grpc_connectivity_state state, const char* reason); // Requires holding mu_. - - const char* service_name_; // Do not own. - RefCountedPtr<ConnectedSubchannel> connected_subchannel_; - grpc_pollset_set* interested_parties_; // Do not own. - RefCountedPtr<channelz::SubchannelNode> channelz_node_; - + + const char* service_name_; // Do not own. + RefCountedPtr<ConnectedSubchannel> connected_subchannel_; + grpc_pollset_set* interested_parties_; // Do not own. + RefCountedPtr<channelz::SubchannelNode> channelz_node_; + Mutex mu_; RefCountedPtr<ConnectivityStateWatcherInterface> watcher_; - bool shutting_down_ = false; - - // The data associated with the current health check call. It holds a ref - // to this HealthCheckClient object. - OrphanablePtr<CallState> call_state_; - - // Call retry state. - BackOff retry_backoff_; - grpc_timer retry_timer_; - grpc_closure retry_timer_callback_; - bool retry_timer_callback_pending_ = false; -}; - -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HEALTH_HEALTH_CHECK_CLIENT_H */ + bool shutting_down_ = false; + + // The data associated with the current health check call. It holds a ref + // to this HealthCheckClient object. + OrphanablePtr<CallState> call_state_; + + // Call retry state. + BackOff retry_backoff_; + grpc_timer retry_timer_; + grpc_closure retry_timer_callback_; + bool retry_timer_callback_pending_ = false; +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_HEALTH_HEALTH_CHECK_CLIENT_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc index 190baabd0a..fffd415459 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_connect_handshaker.cc @@ -38,94 +38,94 @@ #include "src/core/lib/http/format_request.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/uri/uri_parser.h" +#include "src/core/lib/uri/uri_parser.h" -namespace grpc_core { +namespace grpc_core { -namespace { +namespace { -class HttpConnectHandshaker : public Handshaker { - public: - HttpConnectHandshaker(); - void Shutdown(grpc_error* why) override; - void DoHandshake(grpc_tcp_server_acceptor* acceptor, - grpc_closure* on_handshake_done, - HandshakerArgs* args) override; - const char* name() const override { return "http_connect"; } - - private: - virtual ~HttpConnectHandshaker(); - void CleanupArgsForFailureLocked(); - void HandshakeFailedLocked(grpc_error* error); - static void OnWriteDone(void* arg, grpc_error* error); - static void OnReadDone(void* arg, grpc_error* error); +class HttpConnectHandshaker : public Handshaker { + public: + HttpConnectHandshaker(); + void Shutdown(grpc_error* why) override; + void DoHandshake(grpc_tcp_server_acceptor* acceptor, + grpc_closure* on_handshake_done, + HandshakerArgs* args) override; + const char* name() const override { return "http_connect"; } + + private: + virtual ~HttpConnectHandshaker(); + void CleanupArgsForFailureLocked(); + void HandshakeFailedLocked(grpc_error* error); + static void OnWriteDone(void* arg, grpc_error* error); + static void OnReadDone(void* arg, grpc_error* error); static void OnWriteDoneScheduler(void* arg, grpc_error* error); static void OnReadDoneScheduler(void* arg, grpc_error* error); - + Mutex mu_; - - bool is_shutdown_ = false; + + bool is_shutdown_ = false; // Endpoint and read buffer to destroy after a shutdown. - grpc_endpoint* endpoint_to_destroy_ = nullptr; - grpc_slice_buffer* read_buffer_to_destroy_ = nullptr; + grpc_endpoint* endpoint_to_destroy_ = nullptr; + grpc_slice_buffer* read_buffer_to_destroy_ = nullptr; // State saved while performing the handshake. - HandshakerArgs* args_ = nullptr; - grpc_closure* on_handshake_done_ = nullptr; + HandshakerArgs* args_ = nullptr; + grpc_closure* on_handshake_done_ = nullptr; // Objects for processing the HTTP CONNECT request and response. - grpc_slice_buffer write_buffer_; - grpc_closure request_done_closure_; - grpc_closure response_read_closure_; - grpc_http_parser http_parser_; - grpc_http_response http_response_; -}; + grpc_slice_buffer write_buffer_; + grpc_closure request_done_closure_; + grpc_closure response_read_closure_; + grpc_http_parser http_parser_; + grpc_http_response http_response_; +}; -HttpConnectHandshaker::~HttpConnectHandshaker() { - if (endpoint_to_destroy_ != nullptr) { - grpc_endpoint_destroy(endpoint_to_destroy_); - } - if (read_buffer_to_destroy_ != nullptr) { - grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_); - gpr_free(read_buffer_to_destroy_); +HttpConnectHandshaker::~HttpConnectHandshaker() { + if (endpoint_to_destroy_ != nullptr) { + grpc_endpoint_destroy(endpoint_to_destroy_); } - grpc_slice_buffer_destroy_internal(&write_buffer_); - grpc_http_parser_destroy(&http_parser_); - grpc_http_response_destroy(&http_response_); + if (read_buffer_to_destroy_ != nullptr) { + grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_); + gpr_free(read_buffer_to_destroy_); + } + grpc_slice_buffer_destroy_internal(&write_buffer_); + grpc_http_parser_destroy(&http_parser_); + grpc_http_response_destroy(&http_response_); } // Set args fields to nullptr, saving the endpoint and read buffer for // later destruction. -void HttpConnectHandshaker::CleanupArgsForFailureLocked() { - endpoint_to_destroy_ = args_->endpoint; - args_->endpoint = nullptr; - read_buffer_to_destroy_ = args_->read_buffer; - args_->read_buffer = nullptr; - grpc_channel_args_destroy(args_->args); - args_->args = nullptr; +void HttpConnectHandshaker::CleanupArgsForFailureLocked() { + endpoint_to_destroy_ = args_->endpoint; + args_->endpoint = nullptr; + read_buffer_to_destroy_ = args_->read_buffer; + args_->read_buffer = nullptr; + grpc_channel_args_destroy(args_->args); + args_->args = nullptr; } // If the handshake failed or we're shutting down, clean up and invoke the // callback with the error. -void HttpConnectHandshaker::HandshakeFailedLocked(grpc_error* error) { +void HttpConnectHandshaker::HandshakeFailedLocked(grpc_error* error) { if (error == GRPC_ERROR_NONE) { // If we were shut down after an endpoint operation succeeded but // before the endpoint callback was invoked, we need to generate our // own error. error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown"); } - if (!is_shutdown_) { + if (!is_shutdown_) { // TODO(ctiller): It is currently necessary to shutdown endpoints // before destroying them, even if we know that there are no // pending read/write callbacks. This should be fixed, at which // point this can be removed. - grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(error)); + grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(error)); // Not shutting down, so the handshake failed. Clean up before // invoking the callback. - CleanupArgsForFailureLocked(); + CleanupArgsForFailureLocked(); // Set shutdown to true so that subsequent calls to // http_connect_handshaker_shutdown() do nothing. - is_shutdown_ = true; + is_shutdown_ = true; } // Invoke callback. ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, error); @@ -144,15 +144,15 @@ void HttpConnectHandshaker::OnWriteDoneScheduler(void* arg, grpc_error* error) { } // Callback invoked when finished writing HTTP CONNECT request. -void HttpConnectHandshaker::OnWriteDone(void* arg, grpc_error* error) { - auto* handshaker = static_cast<HttpConnectHandshaker*>(arg); +void HttpConnectHandshaker::OnWriteDone(void* arg, grpc_error* error) { + auto* handshaker = static_cast<HttpConnectHandshaker*>(arg); ReleasableMutexLock lock(&handshaker->mu_); - if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) { + if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) { // If the write failed or we're shutting down, clean up and invoke the // callback with the error. - handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error)); + handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error)); lock.Unlock(); - handshaker->Unref(); + handshaker->Unref(); } else { // Otherwise, read the response. // The read callback inherits our ref to the handshaker. @@ -178,42 +178,42 @@ void HttpConnectHandshaker::OnReadDoneScheduler(void* arg, grpc_error* error) { } // Callback invoked for reading HTTP CONNECT response. -void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) { - auto* handshaker = static_cast<HttpConnectHandshaker*>(arg); +void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) { + auto* handshaker = static_cast<HttpConnectHandshaker*>(arg); ReleasableMutexLock lock(&handshaker->mu_); - if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) { + if (error != GRPC_ERROR_NONE || handshaker->is_shutdown_) { // If the read failed or we're shutting down, clean up and invoke the // callback with the error. - handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error)); + handshaker->HandshakeFailedLocked(GRPC_ERROR_REF(error)); goto done; } // Add buffer to parser. - for (size_t i = 0; i < handshaker->args_->read_buffer->count; ++i) { - if (GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i]) > 0) { + for (size_t i = 0; i < handshaker->args_->read_buffer->count; ++i) { + if (GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i]) > 0) { size_t body_start_offset = 0; - error = grpc_http_parser_parse(&handshaker->http_parser_, - handshaker->args_->read_buffer->slices[i], + error = grpc_http_parser_parse(&handshaker->http_parser_, + handshaker->args_->read_buffer->slices[i], &body_start_offset); if (error != GRPC_ERROR_NONE) { - handshaker->HandshakeFailedLocked(error); + handshaker->HandshakeFailedLocked(error); goto done; } - if (handshaker->http_parser_.state == GRPC_HTTP_BODY) { + if (handshaker->http_parser_.state == GRPC_HTTP_BODY) { // Remove the data we've already read from the read buffer, // leaving only the leftover bytes (if any). grpc_slice_buffer tmp_buffer; grpc_slice_buffer_init(&tmp_buffer); if (body_start_offset < - GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i])) { + GRPC_SLICE_LENGTH(handshaker->args_->read_buffer->slices[i])) { grpc_slice_buffer_add( &tmp_buffer, - grpc_slice_split_tail(&handshaker->args_->read_buffer->slices[i], + grpc_slice_split_tail(&handshaker->args_->read_buffer->slices[i], body_start_offset)); } grpc_slice_buffer_addn(&tmp_buffer, - &handshaker->args_->read_buffer->slices[i + 1], - handshaker->args_->read_buffer->count - i - 1); - grpc_slice_buffer_swap(handshaker->args_->read_buffer, &tmp_buffer); + &handshaker->args_->read_buffer->slices[i + 1], + handshaker->args_->read_buffer->count - i - 1); + grpc_slice_buffer_swap(handshaker->args_->read_buffer, &tmp_buffer); grpc_slice_buffer_destroy_internal(&tmp_buffer); break; } @@ -230,8 +230,8 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) { // need to fix the HTTP parser to understand when the body is // complete (e.g., handling chunked transfer encoding or looking // at the Content-Length: header). - if (handshaker->http_parser_.state != GRPC_HTTP_BODY) { - grpc_slice_buffer_reset_and_unref_internal(handshaker->args_->read_buffer); + if (handshaker->http_parser_.state != GRPC_HTTP_BODY) { + grpc_slice_buffer_reset_and_unref_internal(handshaker->args_->read_buffer); grpc_endpoint_read( handshaker->args_->endpoint, handshaker->args_->read_buffer, GRPC_CLOSURE_INIT(&handshaker->response_read_closure_, @@ -241,13 +241,13 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) { return; } // Make sure we got a 2xx response. - if (handshaker->http_response_.status < 200 || - handshaker->http_response_.status >= 300) { + if (handshaker->http_response_.status < 200 || + handshaker->http_response_.status >= 300) { error = GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("HTTP proxy returned response code ", handshaker->http_response_.status) .c_str()); - handshaker->HandshakeFailedLocked(error); + handshaker->HandshakeFailedLocked(error); goto done; } // Success. Invoke handshake-done callback. @@ -255,16 +255,16 @@ void HttpConnectHandshaker::OnReadDone(void* arg, grpc_error* error) { done: // Set shutdown to true so that subsequent calls to // http_connect_handshaker_shutdown() do nothing. - handshaker->is_shutdown_ = true; + handshaker->is_shutdown_ = true; lock.Unlock(); - handshaker->Unref(); + handshaker->Unref(); } // // Public handshaker methods // -void HttpConnectHandshaker::Shutdown(grpc_error* why) { +void HttpConnectHandshaker::Shutdown(grpc_error* why) { { MutexLock lock(&mu_); if (!is_shutdown_) { @@ -277,8 +277,8 @@ void HttpConnectHandshaker::Shutdown(grpc_error* why) { } void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, - grpc_closure* on_handshake_done, - HandshakerArgs* args) { + grpc_closure* on_handshake_done, + HandshakerArgs* args) { // Check for HTTP CONNECT channel arg. // If not found, invoke on_handshake_done without doing anything. const grpc_arg* arg = @@ -308,7 +308,7 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, gpr_malloc(sizeof(grpc_http_header) * num_header_strings)); for (size_t i = 0; i < num_header_strings; ++i) { char* sep = strchr(header_strings[i], ':'); - + if (sep == nullptr) { gpr_log(GPR_ERROR, "skipping unparseable HTTP CONNECT header: %s", header_strings[i]); @@ -321,9 +321,9 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, } } // Save state in the handshaker object. - MutexLock lock(&mu_); - args_ = args; - on_handshake_done_ = on_handshake_done; + MutexLock lock(&mu_); + args_ = args; + on_handshake_done_ = on_handshake_done; // Log connection via proxy. TString proxy_name(grpc_endpoint_get_peer(args->endpoint)); gpr_log(GPR_INFO, "Connecting to server %s via HTTP proxy %s", server_name, @@ -331,17 +331,17 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, // Construct HTTP CONNECT request. grpc_httpcli_request request; request.host = server_name; - request.ssl_host_override = nullptr; + request.ssl_host_override = nullptr; request.http.method = (char*)"CONNECT"; request.http.path = server_name; - request.http.version = GRPC_HTTP_HTTP10; // Set by OnReadDone + request.http.version = GRPC_HTTP_HTTP10; // Set by OnReadDone request.http.hdrs = headers; request.http.hdr_count = num_headers; - request.http.body_length = 0; - request.http.body = nullptr; + request.http.body_length = 0; + request.http.body = nullptr; request.handshaker = &grpc_httpcli_plaintext; grpc_slice request_slice = grpc_httpcli_format_connect_request(&request); - grpc_slice_buffer_add(&write_buffer_, request_slice); + grpc_slice_buffer_add(&write_buffer_, request_slice); // Clean up. gpr_free(headers); for (size_t i = 0; i < num_header_strings; ++i) { @@ -349,7 +349,7 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, } gpr_free(header_strings); // Take a new ref to be held by the write callback. - Ref().release(); + Ref().release(); grpc_endpoint_write( args->endpoint, &write_buffer_, GRPC_CLOSURE_INIT(&request_done_closure_, @@ -358,32 +358,32 @@ void HttpConnectHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, nullptr); } -HttpConnectHandshaker::HttpConnectHandshaker() { - grpc_slice_buffer_init(&write_buffer_); - grpc_http_parser_init(&http_parser_, GRPC_HTTP_RESPONSE, &http_response_); +HttpConnectHandshaker::HttpConnectHandshaker() { + grpc_slice_buffer_init(&write_buffer_); + grpc_http_parser_init(&http_parser_, GRPC_HTTP_RESPONSE, &http_response_); } // // handshaker factory // -class HttpConnectHandshakerFactory : public HandshakerFactory { - public: +class HttpConnectHandshakerFactory : public HandshakerFactory { + public: void AddHandshakers(const grpc_channel_args* /*args*/, grpc_pollset_set* /*interested_parties*/, - HandshakeManager* handshake_mgr) override { - handshake_mgr->Add(MakeRefCounted<HttpConnectHandshaker>()); - } - ~HttpConnectHandshakerFactory() override = default; -}; + HandshakeManager* handshake_mgr) override { + handshake_mgr->Add(MakeRefCounted<HttpConnectHandshaker>()); + } + ~HttpConnectHandshakerFactory() override = default; +}; -} // namespace +} // namespace -} // namespace grpc_core +} // namespace grpc_core void grpc_http_connect_register_handshaker_factory() { - using namespace grpc_core; - HandshakerRegistry::RegisterHandshakerFactory( - true /* at_start */, HANDSHAKER_CLIENT, + using namespace grpc_core; + HandshakerRegistry::RegisterHandshakerFactory( + true /* at_start */, HANDSHAKER_CLIENT, y_absl::make_unique<HttpConnectHandshakerFactory>()); } diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc index 2187682526..1fb980dcb4 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/http_proxy.cc @@ -36,16 +36,16 @@ #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/host_port.h" #include "src/core/lib/slice/b64.h" -#include "src/core/lib/uri/uri_parser.h" +#include "src/core/lib/uri/uri_parser.h" namespace grpc_core { namespace { /** - * Parses the 'https_proxy' env var (fallback on 'http_proxy') and returns the - * proxy hostname to resolve or nullptr on error. Also sets 'user_cred' to user - * credentials if present in the 'http_proxy' env var, otherwise leaves it - * unchanged. It is caller's responsibility to gpr_free user_cred. + * Parses the 'https_proxy' env var (fallback on 'http_proxy') and returns the + * proxy hostname to resolve or nullptr on error. Also sets 'user_cred' to user + * credentials if present in the 'http_proxy' env var, otherwise leaves it + * unchanged. It is caller's responsibility to gpr_free user_cred. */ char* GetHttpProxyServer(const grpc_channel_args* args, char** user_cred) { GPR_ASSERT(user_cred != nullptr); @@ -60,12 +60,12 @@ char* GetHttpProxyServer(const grpc_channel_args* args, char** user_cred) { * 3. https_proxy environment variable * 4. http_proxy environment variable * If none of the above are set, then no HTTP proxy will be used. - */ + */ char* uri_str = gpr_strdup(grpc_channel_args_find_string(args, GRPC_ARG_HTTP_PROXY)); if (uri_str == nullptr) uri_str = gpr_getenv("grpc_proxy"); if (uri_str == nullptr) uri_str = gpr_getenv("https_proxy"); - if (uri_str == nullptr) uri_str = gpr_getenv("http_proxy"); + if (uri_str == nullptr) uri_str = gpr_getenv("http_proxy"); if (uri_str == nullptr) return nullptr; // an emtpy value means "don't use proxy" if (uri_str[0] == '\0') goto done; diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc index 6c639ef86c..deaedf3aa7 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.cc @@ -19,14 +19,14 @@ #include <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/lb_policy.h" - -#include "src/core/ext/filters/client_channel/lb_policy_registry.h" + +#include "src/core/ext/filters/client_channel/lb_policy_registry.h" #include "src/core/lib/iomgr/combiner.h" namespace grpc_core { DebugOnlyTraceFlag grpc_trace_lb_policy_refcount(false, "lb_policy_refcount"); - + // // LoadBalancingPolicy // diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h index 1cbc074484..f70bd89bf0 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy.h @@ -80,7 +80,7 @@ extern DebugOnlyTraceFlag grpc_trace_lb_policy_refcount; /// returned by \a interested_parties(). // TODO(roth): Once we move to EventManager-based polling, remove the // interested_parties() hooks from the API. -class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> { +class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> { public: // Represents backend metrics reported by the backend to the client. struct BackendMetricData { @@ -347,14 +347,14 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> { LoadBalancingPolicy(const LoadBalancingPolicy&) = delete; LoadBalancingPolicy& operator=(const LoadBalancingPolicy&) = delete; - /// Returns the name of the LB policy. + /// Returns the name of the LB policy. virtual const char* name() const = 0; /// Updates the policy with new data from the resolver. Will be invoked /// immediately after LB policy is constructed, and then again whenever /// the resolver returns a new result. virtual void UpdateLocked(UpdateArgs) = 0; // NOLINT - + /// Tries to enter a READY connectivity state. /// This is a no-op by default, since most LB policies never go into /// IDLE state. @@ -384,7 +384,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> { RefCountedPtr<LoadBalancingPolicy> parent_; bool exit_idle_called_ = false; }; - + // A picker that returns PICK_TRANSIENT_FAILURE for all picks. class TransientFailurePicker : public SubchannelPicker { public: @@ -392,7 +392,7 @@ class LoadBalancingPolicy : public InternallyRefCounted<LoadBalancingPolicy> { ~TransientFailurePicker() override { GRPC_ERROR_UNREF(error_); } PickResult Pick(PickArgs args) override; - + private: grpc_error* error_; }; diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc index c8d1b1d7af..cd72178b2b 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc @@ -38,20 +38,20 @@ static grpc_error* clr_init_channel_elem(grpc_channel_element* /*elem*/, static void clr_destroy_channel_elem(grpc_channel_element* /*elem*/) {} namespace { - + struct call_data { // Stats object to update. - grpc_core::RefCountedPtr<grpc_core::GrpcLbClientStats> client_stats; + grpc_core::RefCountedPtr<grpc_core::GrpcLbClientStats> client_stats; // State for intercepting send_initial_metadata. grpc_closure on_complete_for_send; grpc_closure* original_on_complete_for_send; - bool send_initial_metadata_succeeded = false; + bool send_initial_metadata_succeeded = false; // State for intercepting recv_initial_metadata. grpc_closure recv_initial_metadata_ready; grpc_closure* original_recv_initial_metadata_ready; - bool recv_initial_metadata_succeeded = false; + bool recv_initial_metadata_succeeded = false; }; - + } // namespace static void on_complete_for_send(void* arg, grpc_error* error) { @@ -87,11 +87,11 @@ static void clr_destroy_call_elem(grpc_call_element* elem, if (calld->client_stats != nullptr) { // Record call finished, optionally setting client_failed_to_send and // received. - calld->client_stats->AddCallFinished( + calld->client_stats->AddCallFinished( !calld->send_initial_metadata_succeeded /* client_failed_to_send */, - calld->recv_initial_metadata_succeeded /* known_received */); + calld->recv_initial_metadata_succeeded /* known_received */); } - calld->~call_data(); + calld->~call_data(); } static void clr_start_transport_stream_op_batch( diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc index ccfdb5f215..23efac12d4 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc @@ -80,7 +80,7 @@ #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/lb_policy/child_policy_handler.h" #include "src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.h" -#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h" +#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h" #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h" #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h" #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h" @@ -88,7 +88,7 @@ #include "src/core/ext/filters/client_channel/lb_policy_factory.h" #include "src/core/ext/filters/client_channel/lb_policy_registry.h" #include "src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/backoff/backoff.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_stack.h" @@ -114,9 +114,9 @@ #define GRPC_GRPCLB_RECONNECT_JITTER 0.2 #define GRPC_GRPCLB_DEFAULT_FALLBACK_TIMEOUT_MS 10000 -#define GRPC_ARG_GRPCLB_ADDRESS_LB_TOKEN "grpc.grpclb_address_lb_token" +#define GRPC_ARG_GRPCLB_ADDRESS_LB_TOKEN "grpc.grpclb_address_lb_token" #define GRPC_ARG_GRPCLB_ADDRESS_CLIENT_STATS "grpc.grpclb_address_client_stats" - + namespace grpc_core { TraceFlag grpc_lb_glb_trace(false, "glb"); @@ -128,8 +128,8 @@ const char kGrpcLbAddressAttributeKey[] = "grpclb"; namespace { -constexpr char kGrpclb[] = "grpclb"; - +constexpr char kGrpclb[] = "grpclb"; + class GrpcLbConfig : public LoadBalancingPolicy::Config { public: GrpcLbConfig(RefCountedPtr<LoadBalancingPolicy::Config> child_policy, @@ -151,16 +151,16 @@ class GrpcLbConfig : public LoadBalancingPolicy::Config { class GrpcLb : public LoadBalancingPolicy { public: - explicit GrpcLb(Args args); - - const char* name() const override { return kGrpclb; } + explicit GrpcLb(Args args); + const char* name() const override { return kGrpclb; } + void UpdateLocked(UpdateArgs args) override; - void ResetBackoffLocked() override; + void ResetBackoffLocked() override; private: /// Contains a call to the LB server and all the data related to the call. - class BalancerCallState : public InternallyRefCounted<BalancerCallState> { + class BalancerCallState : public InternallyRefCounted<BalancerCallState> { public: explicit BalancerCallState( RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy); @@ -172,8 +172,8 @@ class GrpcLb : public LoadBalancingPolicy { void StartQuery(); - GrpcLbClientStats* client_stats() const { return client_stats_.get(); } - + GrpcLbClientStats* client_stats() const { return client_stats_.get(); } + bool seen_initial_response() const { return seen_initial_response_; } bool seen_serverlist() const { return seen_serverlist_; } @@ -224,7 +224,7 @@ class GrpcLb : public LoadBalancingPolicy { // The stats for client-side load reporting associated with this LB call. // Created after the first serverlist is received. - RefCountedPtr<GrpcLbClientStats> client_stats_; + RefCountedPtr<GrpcLbClientStats> client_stats_; grpc_millis client_stats_report_interval_ = 0; grpc_timer client_load_report_timer_; bool client_load_report_timer_callback_pending_ = false; @@ -540,14 +540,14 @@ ServerAddressList GrpcLb::Serverlist::GetServerAddressList( GrpcLbClientStats* client_stats) const { RefCountedPtr<GrpcLbClientStats> stats; if (client_stats != nullptr) stats = client_stats->Ref(); - ServerAddressList addresses; + ServerAddressList addresses; for (size_t i = 0; i < serverlist_.size(); ++i) { const GrpcLbServer& server = serverlist_[i]; if (!IsServerValid(server, i, false)) continue; - // Address processing. + // Address processing. grpc_resolved_address addr; ParseServer(server, &addr); - // LB token processing. + // LB token processing. const size_t lb_token_length = strnlen( server.load_balance_token, GPR_ARRAY_SIZE(server.load_balance_token)); TString lb_token(server.load_balance_token, lb_token_length); @@ -563,10 +563,10 @@ ServerAddressList GrpcLb::Serverlist::GetServerAddressList( attributes[kGrpcLbAddressAttributeKey] = y_absl::make_unique<TokenAndClientStatsAttribute>(std::move(lb_token), stats); - // Add address. + // Add address. addresses.emplace_back(addr, /*args=*/nullptr, std::move(attributes)); } - return addresses; + return addresses; } bool GrpcLb::Serverlist::ContainsAllDropEntries() const { @@ -738,7 +738,7 @@ void GrpcLb::Helper::AddTraceEvent(TraceSeverity severity, GrpcLb::BalancerCallState::BalancerCallState( RefCountedPtr<LoadBalancingPolicy> parent_grpclb_policy) - : InternallyRefCounted<BalancerCallState>(&grpc_lb_glb_trace), + : InternallyRefCounted<BalancerCallState>(&grpc_lb_glb_trace), grpclb_policy_(std::move(parent_grpclb_policy)) { GPR_ASSERT(grpclb_policy_ != nullptr); GPR_ASSERT(!grpclb_policy()->shutting_down_); @@ -808,7 +808,7 @@ void GrpcLb::BalancerCallState::Orphan() { void GrpcLb::BalancerCallState::StartQuery() { GPR_ASSERT(lb_call_ != nullptr); if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) { - gpr_log(GPR_INFO, "[grpclb %p] lb_calld=%p: Starting LB call %p", + gpr_log(GPR_INFO, "[grpclb %p] lb_calld=%p: Starting LB call %p", grpclb_policy_.get(), this, lb_call_); } // Create the ops. @@ -959,10 +959,10 @@ void GrpcLb::BalancerCallState::SendClientLoadReportLocked() { grpc_schedule_on_exec_ctx); grpc_call_error call_error = grpc_call_start_batch_and_execute( lb_call_, &op, 1, &client_load_report_closure_); - if (GPR_UNLIKELY(call_error != GRPC_CALL_OK)) { - gpr_log(GPR_ERROR, - "[grpclb %p] lb_calld=%p call_error=%d sending client load report", - grpclb_policy_.get(), this, call_error); + if (GPR_UNLIKELY(call_error != GRPC_CALL_OK)) { + gpr_log(GPR_ERROR, + "[grpclb %p] lb_calld=%p call_error=%d sending client load report", + grpclb_policy_.get(), this, call_error); GPR_ASSERT(GRPC_CALL_OK == call_error); } } @@ -1015,7 +1015,7 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceived( } void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() { - // Null payload means the LB call was cancelled. + // Null payload means the LB call was cancelled. if (this != grpclb_policy()->lb_calld_.get() || recv_message_payload_ == nullptr) { Unref(DEBUG_LOCATION, "on_message_received"); @@ -1031,13 +1031,13 @@ void GrpcLb::BalancerCallState::OnBalancerMessageReceivedLocked() { upb::Arena arena; if (!GrpcLbResponseParse(response_slice, arena.ptr(), &response) || (response.type == response.INITIAL && seen_initial_response_)) { - char* response_slice_str = - grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX); + char* response_slice_str = + grpc_dump_slice(response_slice, GPR_DUMP_ASCII | GPR_DUMP_HEX); gpr_log(GPR_ERROR, - "[grpclb %p] lb_calld=%p: Invalid LB response received: '%s'. " - "Ignoring.", + "[grpclb %p] lb_calld=%p: Invalid LB response received: '%s'. " + "Ignoring.", grpclb_policy(), this, response_slice_str); - gpr_free(response_slice_str); + gpr_free(response_slice_str); } else { switch (response.type) { case response.INITIAL: { @@ -1184,8 +1184,8 @@ void GrpcLb::BalancerCallState::OnBalancerStatusReceivedLocked( if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) { char* status_details = grpc_slice_to_c_string(lb_call_status_details_); gpr_log(GPR_INFO, - "[grpclb %p] lb_calld=%p: Status from LB server received. " - "Status = %d, details = '%s', (lb_call: %p), error '%s'", + "[grpclb %p] lb_calld=%p: Status from LB server received. " + "Status = %d, details = '%s', (lb_call: %p), error '%s'", grpclb_policy(), this, lb_call_status_, status_details, lb_call_, grpc_error_string(error)); gpr_free(status_details); @@ -1250,7 +1250,7 @@ ServerAddressList ExtractBalancerAddresses(const grpc_channel_args& args) { * above the grpclb policy. * - \a args: other args inherited from the grpclb policy. */ grpc_channel_args* BuildBalancerChannelArgs( - const ServerAddressList& addresses, + const ServerAddressList& addresses, FakeResolverResponseGenerator* response_generator, const grpc_channel_args* args) { // Channel args to remove. @@ -1258,9 +1258,9 @@ grpc_channel_args* BuildBalancerChannelArgs( // LB policy name, since we want to use the default (pick_first) in // the LB channel. GRPC_ARG_LB_POLICY_NAME, - // Strip out the service config, since we don't want the LB policy - // config specified for the parent channel to affect the LB channel. - GRPC_ARG_SERVICE_CONFIG, + // Strip out the service config, since we don't want the LB policy + // config specified for the parent channel to affect the LB channel. + GRPC_ARG_SERVICE_CONFIG, // The channel arg for the server URI, since that will be different for // the LB channel than for the parent channel. The client channel // factory will re-add this arg with the right value. @@ -1307,7 +1307,7 @@ grpc_channel_args* BuildBalancerChannelArgs( // GrpcLb::GrpcLb(Args args) - : LoadBalancingPolicy(std::move(args)), + : LoadBalancingPolicy(std::move(args)), response_generator_(MakeRefCounted<FakeResolverResponseGenerator>()), lb_call_backoff_( BackOff::Options() @@ -1385,13 +1385,13 @@ void GrpcLb::ShutdownLocked() { // public methods // -void GrpcLb::ResetBackoffLocked() { - if (lb_channel_ != nullptr) { - grpc_channel_reset_connect_backoff(lb_channel_); - } +void GrpcLb::ResetBackoffLocked() { + if (lb_channel_ != nullptr) { + grpc_channel_reset_connect_backoff(lb_channel_); + } if (child_policy_ != nullptr) { child_policy_->ResetBackoffLocked(); - } + } } void GrpcLb::UpdateLocked(UpdateArgs args) { @@ -1422,7 +1422,7 @@ void GrpcLb::UpdateLocked(UpdateArgs args) { OrphanablePtr<AsyncConnectivityStateWatcherInterface>(watcher_)); // Start balancer call. StartBalancerCallLocked(); - } + } } // @@ -1436,10 +1436,10 @@ ServerAddressList GrpcLb::AddNullLbTokenToAddresses( addresses_out.emplace_back(address.WithAttribute( kGrpcLbAddressAttributeKey, y_absl::make_unique<TokenAndClientStatsAttribute>("", nullptr))); - } + } return addresses_out; -} - +} + void GrpcLb::ProcessAddressesAndChannelArgsLocked( const ServerAddressList& addresses, const grpc_channel_args& args) { // Update fallback address list. @@ -1512,7 +1512,7 @@ void GrpcLb::StartBalancerCallRetryTimerLocked() { gpr_log(GPR_INFO, "[grpclb %p] Connection to LB server lost...", this); grpc_millis timeout = next_try - ExecCtx::Get()->Now(); if (timeout > 0) { - gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active in %" PRId64 "ms.", + gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active in %" PRId64 "ms.", this, timeout); } else { gpr_log(GPR_INFO, "[grpclb %p] ... retry_timer_active immediately.", @@ -1628,7 +1628,7 @@ OrphanablePtr<LoadBalancingPolicy> GrpcLb::CreateChildPolicyLocked( if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_glb_trace)) { gpr_log(GPR_INFO, "[grpclb %p] Created new child policy handler (%p)", this, lb_policy.get()); - } + } // Add the gRPC LB's interested_parties pollset_set to that of the newly // created child policy. This will make the child policy progress upon // activity on gRPC LB, which in turn is tied to the application's call. @@ -1641,7 +1641,7 @@ void GrpcLb::CreateOrUpdateChildPolicyLocked() { if (shutting_down_) return; // Construct update args. UpdateArgs update_args; - bool is_backend_from_grpclb_load_balancer = false; + bool is_backend_from_grpclb_load_balancer = false; if (fallback_mode_) { // If CreateOrUpdateChildPolicyLocked() is invoked when we haven't // received any serverlist from the balancer, we use the fallback backends @@ -1677,7 +1677,7 @@ void GrpcLb::CreateOrUpdateChildPolicyLocked() { class GrpcLbFactory : public LoadBalancingPolicyFactory { public: OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy( - LoadBalancingPolicy::Args args) const override { + LoadBalancingPolicy::Args args) const override { return MakeOrphanable<GrpcLb>(std::move(args)); } diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h index a032b5dbf1..d1e6b170ef 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h @@ -1,37 +1,37 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H - -#include <grpc/support/port_platform.h> - -/** Channel arg indicating if a target corresponding to the address is grpclb - * loadbalancer. The type of this arg is an integer and the value is treated as - * a bool. */ -#define GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER \ - "grpc.address_is_grpclb_load_balancer" -/** Channel arg indicating if a target corresponding to the address is a backend - * received from a balancer. The type of this arg is an integer and the value is - * treated as a bool. */ -#define GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER \ - "grpc.address_is_backend_from_grpclb_load_balancer" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H + +#include <grpc/support/port_platform.h> + +/** Channel arg indicating if a target corresponding to the address is grpclb + * loadbalancer. The type of this arg is an integer and the value is treated as + * a bool. */ +#define GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER \ + "grpc.address_is_grpclb_load_balancer" +/** Channel arg indicating if a target corresponding to the address is a backend + * received from a balancer. The type of this arg is an integer and the value is + * treated as a bool. */ +#define GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER \ + "grpc.address_is_backend_from_grpclb_load_balancer" + namespace grpc_core { extern const char kGrpcLbClientStatsMetadataKey[]; @@ -39,5 +39,5 @@ extern const char kGrpcLbLbTokenMetadataKey[]; } // namespace grpc_core -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H \ - */ +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_H \ + */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h index 1458233022..5d2512d826 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel.h @@ -21,7 +21,7 @@ #include <grpc/support/port_platform.h> -#include <grpc/impl/codegen/grpc_types.h> +#include <grpc/impl/codegen/grpc_types.h> #include "src/core/ext/filters/client_channel/server_address.h" diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc index e918ee0836..18c3e56105 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc @@ -30,7 +30,7 @@ #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/sockaddr_utils.h" @@ -51,7 +51,7 @@ grpc_channel_args* ModifyGrpclbBalancerChannelArgs( RefCountedPtr<grpc_channel_credentials> creds_sans_call_creds; if (channel_credentials != nullptr) { creds_sans_call_creds = - channel_credentials->duplicate_without_call_credentials(); + channel_credentials->duplicate_without_call_credentials(); GPR_ASSERT(creds_sans_call_creds != nullptr); args_to_remove.emplace_back(GRPC_ARG_CHANNEL_CREDENTIALS); args_to_add.emplace_back( diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc index 1566e7b5f1..3406651fde 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc @@ -27,65 +27,65 @@ #include "src/core/lib/gprpp/sync.h" -namespace grpc_core { +namespace grpc_core { -void GrpcLbClientStats::AddCallStarted() { - gpr_atm_full_fetch_add(&num_calls_started_, (gpr_atm)1); +void GrpcLbClientStats::AddCallStarted() { + gpr_atm_full_fetch_add(&num_calls_started_, (gpr_atm)1); } -void GrpcLbClientStats::AddCallFinished( - bool finished_with_client_failed_to_send, bool finished_known_received) { - gpr_atm_full_fetch_add(&num_calls_finished_, (gpr_atm)1); +void GrpcLbClientStats::AddCallFinished( + bool finished_with_client_failed_to_send, bool finished_known_received) { + gpr_atm_full_fetch_add(&num_calls_finished_, (gpr_atm)1); if (finished_with_client_failed_to_send) { - gpr_atm_full_fetch_add(&num_calls_finished_with_client_failed_to_send_, - (gpr_atm)1); + gpr_atm_full_fetch_add(&num_calls_finished_with_client_failed_to_send_, + (gpr_atm)1); } if (finished_known_received) { - gpr_atm_full_fetch_add(&num_calls_finished_known_received_, (gpr_atm)1); + gpr_atm_full_fetch_add(&num_calls_finished_known_received_, (gpr_atm)1); } } void GrpcLbClientStats::AddCallDropped(const char* token) { // Increment num_calls_started and num_calls_finished. - gpr_atm_full_fetch_add(&num_calls_started_, (gpr_atm)1); - gpr_atm_full_fetch_add(&num_calls_finished_, (gpr_atm)1); + gpr_atm_full_fetch_add(&num_calls_started_, (gpr_atm)1); + gpr_atm_full_fetch_add(&num_calls_finished_, (gpr_atm)1); // Record the drop. MutexLock lock(&drop_count_mu_); - if (drop_token_counts_ == nullptr) { + if (drop_token_counts_ == nullptr) { drop_token_counts_.reset(new DroppedCallCounts()); } - for (size_t i = 0; i < drop_token_counts_->size(); ++i) { - if (strcmp((*drop_token_counts_)[i].token.get(), token) == 0) { - ++(*drop_token_counts_)[i].count; + for (size_t i = 0; i < drop_token_counts_->size(); ++i) { + if (strcmp((*drop_token_counts_)[i].token.get(), token) == 0) { + ++(*drop_token_counts_)[i].count; return; } } - // Not found, so add a new entry. + // Not found, so add a new entry. drop_token_counts_->emplace_back( grpc_core::UniquePtr<char>(gpr_strdup(token)), 1); } -namespace { - -void AtomicGetAndResetCounter(int64_t* value, gpr_atm* counter) { - *value = static_cast<int64_t>(gpr_atm_full_xchg(counter, (gpr_atm)0)); +namespace { + +void AtomicGetAndResetCounter(int64_t* value, gpr_atm* counter) { + *value = static_cast<int64_t>(gpr_atm_full_xchg(counter, (gpr_atm)0)); } -} // namespace - +} // namespace + void GrpcLbClientStats::Get( - int64_t* num_calls_started, int64_t* num_calls_finished, + int64_t* num_calls_started, int64_t* num_calls_finished, int64_t* num_calls_finished_with_client_failed_to_send, int64_t* num_calls_finished_known_received, std::unique_ptr<DroppedCallCounts>* drop_token_counts) { - AtomicGetAndResetCounter(num_calls_started, &num_calls_started_); - AtomicGetAndResetCounter(num_calls_finished, &num_calls_finished_); - AtomicGetAndResetCounter(num_calls_finished_with_client_failed_to_send, - &num_calls_finished_with_client_failed_to_send_); - AtomicGetAndResetCounter(num_calls_finished_known_received, - &num_calls_finished_known_received_); + AtomicGetAndResetCounter(num_calls_started, &num_calls_started_); + AtomicGetAndResetCounter(num_calls_finished, &num_calls_finished_); + AtomicGetAndResetCounter(num_calls_finished_with_client_failed_to_send, + &num_calls_finished_with_client_failed_to_send_); + AtomicGetAndResetCounter(num_calls_finished_known_received, + &num_calls_finished_known_received_); MutexLock lock(&drop_count_mu_); - *drop_token_counts = std::move(drop_token_counts_); + *drop_token_counts = std::move(drop_token_counts_); } -} // namespace grpc_core +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h index e5304fda6b..52abde35db 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h @@ -21,31 +21,31 @@ #include <grpc/support/port_platform.h> -#include <grpc/support/atm.h> +#include <grpc/support/atm.h> #include "y_absl/container/inlined_vector.h" -#include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/gprpp/sync.h" -namespace grpc_core { +namespace grpc_core { -class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> { - public: - struct DropTokenCount { +class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> { + public: + struct DropTokenCount { grpc_core::UniquePtr<char> token; - int64_t count; + int64_t count; DropTokenCount(grpc_core::UniquePtr<char> token, int64_t count) - : token(std::move(token)), count(count) {} - }; + : token(std::move(token)), count(count) {} + }; typedef y_absl::InlinedVector<DropTokenCount, 10> DroppedCallCounts; - void AddCallStarted(); - void AddCallFinished(bool finished_with_client_failed_to_send, - bool finished_known_received); + void AddCallStarted(); + void AddCallFinished(bool finished_with_client_failed_to_send, + bool finished_known_received); void AddCallDropped(const char* token); @@ -60,16 +60,16 @@ class GrpcLbClientStats : public RefCounted<GrpcLbClientStats> { static_cast<GrpcLbClientStats*>(arg)->Unref(); } - private: - gpr_atm num_calls_started_ = 0; - gpr_atm num_calls_finished_ = 0; - gpr_atm num_calls_finished_with_client_failed_to_send_ = 0; - gpr_atm num_calls_finished_known_received_ = 0; + private: + gpr_atm num_calls_started_ = 0; + gpr_atm num_calls_finished_ = 0; + gpr_atm num_calls_finished_with_client_failed_to_send_ = 0; + gpr_atm num_calls_finished_known_received_ = 0; Mutex drop_count_mu_; // Guards drop_token_counts_. std::unique_ptr<DroppedCallCounts> drop_token_counts_; -}; - -} // namespace grpc_core - +}; + +} // namespace grpc_core + #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_GRPCLB_GRPCLB_CLIENT_STATS_H \ */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc index 3185b993c4..551b0a5e79 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc @@ -18,7 +18,7 @@ #include <grpc/support/port_platform.h> -#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h" +#include "src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h" #include "src/core/lib/gpr/useful.h" #include "google/protobuf/duration.upb.h" diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h index 6caa120f58..8b7070add0 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.h @@ -26,7 +26,7 @@ #include <grpc/slice_buffer.h> #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.h" -#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/exec_ctx.h" #include "src/proto/grpc/lb/v1/load_balancer.upb.h" #define GRPC_GRPCLB_SERVICE_NAME_MAX_LENGTH 128 diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc index ab78053008..de5023af81 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc @@ -24,7 +24,7 @@ #include "src/core/ext/filters/client_channel/lb_policy/subchannel_list.h" #include "src/core/ext/filters/client_channel/lb_policy_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/ext/filters/client_channel/subchannel.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gprpp/sync.h" @@ -42,17 +42,17 @@ namespace { // pick_first LB policy // -constexpr char kPickFirst[] = "pick_first"; - +constexpr char kPickFirst[] = "pick_first"; + class PickFirst : public LoadBalancingPolicy { public: - explicit PickFirst(Args args); - - const char* name() const override { return kPickFirst; } + explicit PickFirst(Args args); + const char* name() const override { return kPickFirst; } + void UpdateLocked(UpdateArgs args) override; void ExitIdleLocked() override; - void ResetBackoffLocked() override; + void ResetBackoffLocked() override; private: ~PickFirst(); @@ -63,20 +63,20 @@ class PickFirst : public LoadBalancingPolicy { : public SubchannelData<PickFirstSubchannelList, PickFirstSubchannelData> { public: - PickFirstSubchannelData( - SubchannelList<PickFirstSubchannelList, PickFirstSubchannelData>* - subchannel_list, + PickFirstSubchannelData( + SubchannelList<PickFirstSubchannelList, PickFirstSubchannelData>* + subchannel_list, const ServerAddress& address, RefCountedPtr<SubchannelInterface> subchannel) : SubchannelData(subchannel_list, address, std::move(subchannel)) {} void ProcessConnectivityChangeLocked( grpc_connectivity_state connectivity_state) override; - - // Processes the connectivity change to READY for an unselected subchannel. - void ProcessUnselectedReadyLocked(); - - void CheckConnectivityStateAndStartWatchingLocked(); + + // Processes the connectivity change to READY for an unselected subchannel. + void ProcessUnselectedReadyLocked(); + + void CheckConnectivityStateAndStartWatchingLocked(); }; class PickFirstSubchannelList @@ -109,10 +109,10 @@ class PickFirst : public LoadBalancingPolicy { }; class Picker : public SubchannelPicker { - public: + public: explicit Picker(RefCountedPtr<SubchannelInterface> subchannel) : subchannel_(std::move(subchannel)) {} - + PickResult Pick(PickArgs /*args*/) override { PickResult result; result.type = PickResult::PICK_COMPLETE; @@ -120,10 +120,10 @@ class PickFirst : public LoadBalancingPolicy { return result; } - private: + private: RefCountedPtr<SubchannelInterface> subchannel_; - }; - + }; + void ShutdownLocked() override; void AttemptToConnectUsingLatestUpdateArgsLocked(); @@ -142,7 +142,7 @@ class PickFirst : public LoadBalancingPolicy { bool shutdown_ = false; }; -PickFirst::PickFirst(Args args) : LoadBalancingPolicy(std::move(args)) { +PickFirst::PickFirst(Args args) : LoadBalancingPolicy(std::move(args)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) { gpr_log(GPR_INFO, "Pick First %p created.", this); } @@ -176,13 +176,13 @@ void PickFirst::ExitIdleLocked() { } } -void PickFirst::ResetBackoffLocked() { +void PickFirst::ResetBackoffLocked() { if (subchannel_list_ != nullptr) subchannel_list_->ResetBackoffLocked(); - if (latest_pending_subchannel_list_ != nullptr) { - latest_pending_subchannel_list_->ResetBackoffLocked(); - } -} - + if (latest_pending_subchannel_list_ != nullptr) { + latest_pending_subchannel_list_->ResetBackoffLocked(); + } +} + void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() { // Create a subchannel list from the latest_update_args_. auto subchannel_list = MakeOrphanable<PickFirstSubchannelList>( @@ -205,25 +205,25 @@ void PickFirst::AttemptToConnectUsingLatestUpdateArgsLocked() { y_absl::make_unique<TransientFailurePicker>(error)); return; } - // If one of the subchannels in the new list is already in state - // READY, then select it immediately. This can happen when the - // currently selected subchannel is also present in the update. It - // can also happen if one of the subchannels in the update is already + // If one of the subchannels in the new list is already in state + // READY, then select it immediately. This can happen when the + // currently selected subchannel is also present in the update. It + // can also happen if one of the subchannels in the update is already // in the global subchannel pool because it's in use by another channel. - for (size_t i = 0; i < subchannel_list->num_subchannels(); ++i) { - PickFirstSubchannelData* sd = subchannel_list->subchannel(i); + for (size_t i = 0; i < subchannel_list->num_subchannels(); ++i) { + PickFirstSubchannelData* sd = subchannel_list->subchannel(i); grpc_connectivity_state state = sd->CheckConnectivityStateLocked(); - if (state == GRPC_CHANNEL_READY) { - subchannel_list_ = std::move(subchannel_list); + if (state == GRPC_CHANNEL_READY) { + subchannel_list_ = std::move(subchannel_list); sd->StartConnectivityWatchLocked(); - sd->ProcessUnselectedReadyLocked(); - // If there was a previously pending update (which may or may - // not have contained the currently selected subchannel), drop - // it, so that it doesn't override what we've done here. - latest_pending_subchannel_list_.reset(); - return; - } - } + sd->ProcessUnselectedReadyLocked(); + // If there was a previously pending update (which may or may + // not have contained the currently selected subchannel), drop + // it, so that it doesn't override what we've done here. + latest_pending_subchannel_list_.reset(); + return; + } + } if (selected_ == nullptr) { // We don't yet have a selected subchannel, so replace the current // subchannel list immediately. @@ -289,7 +289,7 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked( // latest pending subchannel lists. GPR_ASSERT(subchannel_list() == p->subchannel_list_.get() || subchannel_list() == p->latest_pending_subchannel_list_.get()); - GPR_ASSERT(connectivity_state != GRPC_CHANNEL_SHUTDOWN); + GPR_ASSERT(connectivity_state != GRPC_CHANNEL_SHUTDOWN); // Handle updates for the currently selected subchannel. if (p->selected_ == this) { if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) { @@ -373,15 +373,15 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked( subchannel_list()->set_in_transient_failure(false); switch (connectivity_state) { case GRPC_CHANNEL_READY: { - ProcessUnselectedReadyLocked(); + ProcessUnselectedReadyLocked(); break; } case GRPC_CHANNEL_TRANSIENT_FAILURE: { CancelConnectivityWatchLocked("connection attempt failed"); PickFirstSubchannelData* sd = this; - size_t next_index = - (sd->Index() + 1) % subchannel_list()->num_subchannels(); - sd = subchannel_list()->subchannel(next_index); + size_t next_index = + (sd->Index() + 1) % subchannel_list()->num_subchannels(); + sd = subchannel_list()->subchannel(next_index); // If we're tried all subchannels, set state to TRANSIENT_FAILURE. if (sd->Index() == 0) { // Re-resolve if this is the most recent subchannel list. @@ -402,7 +402,7 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked( y_absl::make_unique<TransientFailurePicker>(error)); } } - sd->CheckConnectivityStateAndStartWatchingLocked(); + sd->CheckConnectivityStateAndStartWatchingLocked(); break; } case GRPC_CHANNEL_CONNECTING: @@ -421,34 +421,34 @@ void PickFirst::PickFirstSubchannelData::ProcessConnectivityChangeLocked( } } -void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() { - PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy()); - // If we get here, there are two possible cases: - // 1. We do not currently have a selected subchannel, and the update is - // for a subchannel in p->subchannel_list_ that we're trying to - // connect to. The goal here is to find a subchannel that we can - // select. - // 2. We do currently have a selected subchannel, and the update is - // for a subchannel in p->latest_pending_subchannel_list_. The - // goal here is to find a subchannel from the update that we can - // select in place of the current one. - GPR_ASSERT(subchannel_list() == p->subchannel_list_.get() || - subchannel_list() == p->latest_pending_subchannel_list_.get()); - // Case 2. Promote p->latest_pending_subchannel_list_ to p->subchannel_list_. - if (subchannel_list() == p->latest_pending_subchannel_list_.get()) { +void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() { + PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy()); + // If we get here, there are two possible cases: + // 1. We do not currently have a selected subchannel, and the update is + // for a subchannel in p->subchannel_list_ that we're trying to + // connect to. The goal here is to find a subchannel that we can + // select. + // 2. We do currently have a selected subchannel, and the update is + // for a subchannel in p->latest_pending_subchannel_list_. The + // goal here is to find a subchannel from the update that we can + // select in place of the current one. + GPR_ASSERT(subchannel_list() == p->subchannel_list_.get() || + subchannel_list() == p->latest_pending_subchannel_list_.get()); + // Case 2. Promote p->latest_pending_subchannel_list_ to p->subchannel_list_. + if (subchannel_list() == p->latest_pending_subchannel_list_.get()) { if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) { - gpr_log(GPR_INFO, - "Pick First %p promoting pending subchannel list %p to " - "replace %p", - p, p->latest_pending_subchannel_list_.get(), - p->subchannel_list_.get()); - } - p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_); - } - // Cases 1 and 2. + gpr_log(GPR_INFO, + "Pick First %p promoting pending subchannel list %p to " + "replace %p", + p, p->latest_pending_subchannel_list_.get(), + p->subchannel_list_.get()); + } + p->subchannel_list_ = std::move(p->latest_pending_subchannel_list_); + } + // Cases 1 and 2. if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_pick_first_trace)) { - gpr_log(GPR_INFO, "Pick First %p selected subchannel %p", p, subchannel()); - } + gpr_log(GPR_INFO, "Pick First %p selected subchannel %p", p, subchannel()); + } p->selected_ = this; p->channel_control_helper()->UpdateState( GRPC_CHANNEL_READY, y_absl::Status(), @@ -456,13 +456,13 @@ void PickFirst::PickFirstSubchannelData::ProcessUnselectedReadyLocked() { for (size_t i = 0; i < subchannel_list()->num_subchannels(); ++i) { if (i != Index()) { subchannel_list()->subchannel(i)->ShutdownLocked(); - } - } -} - -void PickFirst::PickFirstSubchannelData:: - CheckConnectivityStateAndStartWatchingLocked() { - PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy()); + } + } +} + +void PickFirst::PickFirstSubchannelData:: + CheckConnectivityStateAndStartWatchingLocked() { + PickFirst* p = static_cast<PickFirst*>(subchannel_list()->policy()); // Check current state. grpc_connectivity_state current_state = CheckConnectivityStateLocked(); // Start watch. @@ -475,9 +475,9 @@ void PickFirst::PickFirstSubchannelData:: if (p->selected_ != this) ProcessUnselectedReadyLocked(); } else { subchannel()->AttemptToConnect(); - } -} - + } +} + class PickFirstConfig : public LoadBalancingPolicy::Config { public: const char* name() const override { return kPickFirst; } @@ -490,11 +490,11 @@ class PickFirstConfig : public LoadBalancingPolicy::Config { class PickFirstFactory : public LoadBalancingPolicyFactory { public: OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy( - LoadBalancingPolicy::Args args) const override { + LoadBalancingPolicy::Args args) const override { return MakeOrphanable<PickFirst>(std::move(args)); } - const char* name() const override { return kPickFirst; } + const char* name() const override { return kPickFirst; } RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig( const Json& json, grpc_error** /*error*/) const override { diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc index b277add32a..bf180cf620 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc @@ -53,16 +53,16 @@ namespace { // round_robin LB policy // -constexpr char kRoundRobin[] = "round_robin"; - +constexpr char kRoundRobin[] = "round_robin"; + class RoundRobin : public LoadBalancingPolicy { public: - explicit RoundRobin(Args args); - - const char* name() const override { return kRoundRobin; } + explicit RoundRobin(Args args); + const char* name() const override { return kRoundRobin; } + void UpdateLocked(UpdateArgs args) override; - void ResetBackoffLocked() override; + void ResetBackoffLocked() override; private: ~RoundRobin(); @@ -78,9 +78,9 @@ class RoundRobin : public LoadBalancingPolicy { : public SubchannelData<RoundRobinSubchannelList, RoundRobinSubchannelData> { public: - RoundRobinSubchannelData( - SubchannelList<RoundRobinSubchannelList, RoundRobinSubchannelData>* - subchannel_list, + RoundRobinSubchannelData( + SubchannelList<RoundRobinSubchannelList, RoundRobinSubchannelData>* + subchannel_list, const ServerAddress& address, RefCountedPtr<SubchannelInterface> subchannel) : SubchannelData(subchannel_list, address, std::move(subchannel)) {} @@ -151,19 +151,19 @@ class RoundRobin : public LoadBalancingPolicy { }; class Picker : public SubchannelPicker { - public: + public: Picker(RoundRobin* parent, RoundRobinSubchannelList* subchannel_list); - + PickResult Pick(PickArgs args) override; - private: + private: // Using pointer value only, no ref held -- do not dereference! RoundRobin* parent_; size_t last_picked_index_; y_absl::InlinedVector<RefCountedPtr<SubchannelInterface>, 10> subchannels_; - }; - + }; + void ShutdownLocked() override; /** list of subchannels */ @@ -223,7 +223,7 @@ RoundRobin::PickResult RoundRobin::Picker::Pick(PickArgs /*args*/) { // RoundRobin // -RoundRobin::RoundRobin(Args args) : LoadBalancingPolicy(std::move(args)) { +RoundRobin::RoundRobin(Args args) : LoadBalancingPolicy(std::move(args)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_lb_round_robin_trace)) { gpr_log(GPR_INFO, "[RR %p] Created", this); } @@ -246,13 +246,13 @@ void RoundRobin::ShutdownLocked() { latest_pending_subchannel_list_.reset(); } -void RoundRobin::ResetBackoffLocked() { - subchannel_list_->ResetBackoffLocked(); - if (latest_pending_subchannel_list_ != nullptr) { - latest_pending_subchannel_list_->ResetBackoffLocked(); - } -} - +void RoundRobin::ResetBackoffLocked() { + subchannel_list_->ResetBackoffLocked(); + if (latest_pending_subchannel_list_ != nullptr) { + latest_pending_subchannel_list_->ResetBackoffLocked(); + } +} + void RoundRobin::RoundRobinSubchannelList::StartWatchingLocked() { if (num_subchannels() == 0) return; // Check current state of each subchannel synchronously, since any @@ -480,11 +480,11 @@ class RoundRobinConfig : public LoadBalancingPolicy::Config { class RoundRobinFactory : public LoadBalancingPolicyFactory { public: OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy( - LoadBalancingPolicy::Args args) const override { + LoadBalancingPolicy::Args args) const override { return MakeOrphanable<RoundRobin>(std::move(args)); } - const char* name() const override { return kRoundRobin; } + const char* name() const override { return kRoundRobin; } RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig( const Json& /*json*/, grpc_error** /*error*/) const override { diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h index db46cd1104..1c13a72f7b 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/subchannel_list.h @@ -29,7 +29,7 @@ #include "y_absl/container/inlined_vector.h" #include "src/core/ext/filters/client_channel/lb_policy_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" // TODO(roth): Should not need the include of subchannel.h here, since // that implementation should be hidden from the LB policy API. #include "src/core/ext/filters/client_channel/subchannel.h" @@ -68,10 +68,10 @@ class MySubchannelList namespace grpc_core { -// Forward declaration. -template <typename SubchannelListType, typename SubchannelDataType> -class SubchannelList; - +// Forward declaration. +template <typename SubchannelListType, typename SubchannelDataType> +class SubchannelList; + // Stores data for a particular subchannel in a subchannel list. // Callers must create a subclass that implements the // ProcessConnectivityChangeLocked() method. @@ -79,9 +79,9 @@ template <typename SubchannelListType, typename SubchannelDataType> class SubchannelData { public: // Returns a pointer to the subchannel list containing this object. - SubchannelListType* subchannel_list() const { - return static_cast<SubchannelListType*>(subchannel_list_); - } + SubchannelListType* subchannel_list() const { + return static_cast<SubchannelListType*>(subchannel_list_); + } // Returns the index into the subchannel list of this object. size_t Index() const { @@ -102,10 +102,10 @@ class SubchannelData { return connectivity_state_; } - // Resets the connection backoff. - // TODO(roth): This method should go away when we move the backoff - // code out of the subchannel and into the LB policies. - void ResetBackoffLocked(); + // Resets the connection backoff. + // TODO(roth): This method should go away when we move the backoff + // code out of the subchannel and into the LB policies. + void ResetBackoffLocked(); // Starts watching the connectivity state of the subchannel. // ProcessConnectivityChangeLocked() will be called whenever the @@ -119,8 +119,8 @@ class SubchannelData { void ShutdownLocked(); protected: - SubchannelData( - SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list, + SubchannelData( + SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list, const ServerAddress& address, RefCountedPtr<SubchannelInterface> subchannel); @@ -156,11 +156,11 @@ class SubchannelData { RefCountedPtr<SubchannelListType> subchannel_list_; }; - // Unrefs the subchannel. - void UnrefSubchannelLocked(const char* reason); - + // Unrefs the subchannel. + void UnrefSubchannelLocked(const char* reason); + // Backpointer to owning subchannel list. Not owned. - SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list_; + SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list_; // The subchannel. RefCountedPtr<SubchannelInterface> subchannel_; // Will be non-null when the subchannel's state is being watched. @@ -172,7 +172,7 @@ class SubchannelData { // A list of subchannels. template <typename SubchannelListType, typename SubchannelDataType> -class SubchannelList : public InternallyRefCounted<SubchannelListType> { +class SubchannelList : public InternallyRefCounted<SubchannelListType> { public: typedef y_absl::InlinedVector<SubchannelDataType, 10> SubchannelVector; @@ -189,14 +189,14 @@ class SubchannelList : public InternallyRefCounted<SubchannelListType> { LoadBalancingPolicy* policy() const { return policy_; } TraceFlag* tracer() const { return tracer_; } - // Resets connection backoff of all subchannels. - // TODO(roth): We will probably need to rethink this as part of moving - // the backoff code out of subchannels and into LB policies. - void ResetBackoffLocked(); - + // Resets connection backoff of all subchannels. + // TODO(roth): We will probably need to rethink this as part of moving + // the backoff code out of subchannels and into LB policies. + void ResetBackoffLocked(); + void Orphan() override { ShutdownLocked(); - InternallyRefCounted<SubchannelListType>::Unref(DEBUG_LOCATION, "shutdown"); + InternallyRefCounted<SubchannelListType>::Unref(DEBUG_LOCATION, "shutdown"); } protected: @@ -264,7 +264,7 @@ void SubchannelData<SubchannelListType, SubchannelDataType>::Watcher:: template <typename SubchannelListType, typename SubchannelDataType> SubchannelData<SubchannelListType, SubchannelDataType>::SubchannelData( - SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list, + SubchannelList<SubchannelListType, SubchannelDataType>* subchannel_list, const ServerAddress& /*address*/, RefCountedPtr<SubchannelInterface> subchannel) : subchannel_list_(subchannel_list), @@ -296,14 +296,14 @@ void SubchannelData<SubchannelListType, SubchannelDataType>:: template <typename SubchannelListType, typename SubchannelDataType> void SubchannelData<SubchannelListType, - SubchannelDataType>::ResetBackoffLocked() { - if (subchannel_ != nullptr) { - subchannel_->ResetBackoff(); - } -} - -template <typename SubchannelListType, typename SubchannelDataType> -void SubchannelData<SubchannelListType, + SubchannelDataType>::ResetBackoffLocked() { + if (subchannel_ != nullptr) { + subchannel_->ResetBackoff(); + } +} + +template <typename SubchannelListType, typename SubchannelDataType> +void SubchannelData<SubchannelListType, SubchannelDataType>::StartConnectivityWatchLocked() { if (GRPC_TRACE_FLAG_ENABLED(*subchannel_list_->tracer())) { gpr_log(GPR_INFO, @@ -354,15 +354,15 @@ SubchannelList<SubchannelListType, SubchannelDataType>::SubchannelList( LoadBalancingPolicy* policy, TraceFlag* tracer, ServerAddressList addresses, LoadBalancingPolicy::ChannelControlHelper* helper, const grpc_channel_args& args) Y_NO_SANITIZE("undefined") - : InternallyRefCounted<SubchannelListType>(tracer), + : InternallyRefCounted<SubchannelListType>(tracer), policy_(policy), tracer_(tracer) { if (GRPC_TRACE_FLAG_ENABLED(*tracer_)) { gpr_log(GPR_INFO, "[%s %p] Creating subchannel list %p for %" PRIuPTR " subchannels", - tracer_->name(), policy, this, addresses.size()); + tracer_->name(), policy, this, addresses.size()); } - subchannels_.reserve(addresses.size()); + subchannels_.reserve(addresses.size()); // Create a subchannel for each address. for (const ServerAddress& address : addresses) { RefCountedPtr<SubchannelInterface> subchannel = @@ -410,15 +410,15 @@ void SubchannelList<SubchannelListType, SubchannelDataType>::ShutdownLocked() { } } -template <typename SubchannelListType, typename SubchannelDataType> -void SubchannelList<SubchannelListType, - SubchannelDataType>::ResetBackoffLocked() { - for (size_t i = 0; i < subchannels_.size(); i++) { - SubchannelDataType* sd = &subchannels_[i]; - sd->ResetBackoffLocked(); - } -} - +template <typename SubchannelListType, typename SubchannelDataType> +void SubchannelList<SubchannelListType, + SubchannelDataType>::ResetBackoffLocked() { + for (size_t i = 0; i < subchannels_.size(); i++) { + SubchannelDataType* sd = &subchannels_[i]; + sd->ResetBackoffLocked(); + } +} + } // namespace grpc_core #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_SUBCHANNEL_LIST_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h index 1de3472a3a..6d45369a87 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy/xds/xds.h @@ -1,32 +1,32 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_XDS_XDS_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_XDS_XDS_H - -#include <grpc/support/port_platform.h> - -/** Channel arg indicating if a target corresponding to the address is a backend - * received from a balancer. The type of this arg is an integer and the value is - * treated as a bool. */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_XDS_XDS_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_XDS_XDS_H + +#include <grpc/support/port_platform.h> + +/** Channel arg indicating if a target corresponding to the address is a backend + * received from a balancer. The type of this arg is an integer and the value is + * treated as a bool. */ // TODO(roth): Depending on how we ultimately decide to handle fallback, // this may no longer be needed. -#define GRPC_ARG_ADDRESS_IS_BACKEND_FROM_XDS_LOAD_BALANCER \ - "grpc.address_is_backend_from_xds_load_balancer" - +#define GRPC_ARG_ADDRESS_IS_BACKEND_FROM_XDS_LOAD_BALANCER \ + "grpc.address_is_backend_from_xds_load_balancer" + #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LB_POLICY_XDS_XDS_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h index 9e4425fa44..c6a55cc65e 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_factory.h @@ -22,7 +22,7 @@ #include <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/lb_policy.h" -#include "src/core/lib/gprpp/orphanable.h" +#include "src/core/lib/gprpp/orphanable.h" namespace grpc_core { diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc index 463e54a2e6..2974a57979 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.cc @@ -91,19 +91,19 @@ void LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory( OrphanablePtr<LoadBalancingPolicy> LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy( - const char* name, LoadBalancingPolicy::Args args) { + const char* name, LoadBalancingPolicy::Args args) { GPR_ASSERT(g_state != nullptr); // Find factory. LoadBalancingPolicyFactory* factory = g_state->GetLoadBalancingPolicyFactory(name); if (factory == nullptr) return nullptr; // Specified name not found. // Create policy via factory. - return factory->CreateLoadBalancingPolicy(std::move(args)); + return factory->CreateLoadBalancingPolicy(std::move(args)); } bool LoadBalancingPolicyRegistry::LoadBalancingPolicyExists( const char* name, bool* requires_config) { - GPR_ASSERT(g_state != nullptr); + GPR_ASSERT(g_state != nullptr); auto* factory = g_state->GetLoadBalancingPolicyFactory(name); if (factory == nullptr) { return false; @@ -116,8 +116,8 @@ bool LoadBalancingPolicyRegistry::LoadBalancingPolicyExists( GRPC_ERROR_UNREF(error); } return true; -} - +} + namespace { // Returns the JSON node of policy (with both policy name and config content) diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h index 8d2e3e395d..c518ec4a98 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/lb_policy_registry.h @@ -46,9 +46,9 @@ class LoadBalancingPolicyRegistry { /// Creates an LB policy of the type specified by \a name. static OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy( - const char* name, LoadBalancingPolicy::Args args); - - /// Returns true if the LB policy factory specified by \a name exists in this + const char* name, LoadBalancingPolicy::Args args); + + /// Returns true if the LB policy factory specified by \a name exists in this /// registry. If the load balancing policy requires a config to be specified /// then sets \a requires_config to true. static bool LoadBalancingPolicyExists(const char* name, diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc index e57599962a..7b0e3e2bf1 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.cc @@ -1,96 +1,96 @@ -// -// -// Copyright 2018 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/local_subchannel_pool.h" - -#include "src/core/ext/filters/client_channel/subchannel.h" - -namespace grpc_core { - -LocalSubchannelPool::LocalSubchannelPool() { - subchannel_map_ = grpc_avl_create(&subchannel_avl_vtable_); -} - -LocalSubchannelPool::~LocalSubchannelPool() { - grpc_avl_unref(subchannel_map_, nullptr); -} - -Subchannel* LocalSubchannelPool::RegisterSubchannel(SubchannelKey* key, - Subchannel* constructed) { - // Check to see if a subchannel already exists. - Subchannel* c = - static_cast<Subchannel*>(grpc_avl_get(subchannel_map_, key, nullptr)); - if (c != nullptr) { - // The subchannel already exists. Reuse it. - c = GRPC_SUBCHANNEL_REF(c, "subchannel_register+reuse"); - GRPC_SUBCHANNEL_UNREF(constructed, "subchannel_register+found_existing"); - } else { - // There hasn't been such subchannel. Add one. +// +// +// Copyright 2018 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/local_subchannel_pool.h" + +#include "src/core/ext/filters/client_channel/subchannel.h" + +namespace grpc_core { + +LocalSubchannelPool::LocalSubchannelPool() { + subchannel_map_ = grpc_avl_create(&subchannel_avl_vtable_); +} + +LocalSubchannelPool::~LocalSubchannelPool() { + grpc_avl_unref(subchannel_map_, nullptr); +} + +Subchannel* LocalSubchannelPool::RegisterSubchannel(SubchannelKey* key, + Subchannel* constructed) { + // Check to see if a subchannel already exists. + Subchannel* c = + static_cast<Subchannel*>(grpc_avl_get(subchannel_map_, key, nullptr)); + if (c != nullptr) { + // The subchannel already exists. Reuse it. + c = GRPC_SUBCHANNEL_REF(c, "subchannel_register+reuse"); + GRPC_SUBCHANNEL_UNREF(constructed, "subchannel_register+found_existing"); + } else { + // There hasn't been such subchannel. Add one. subchannel_map_ = grpc_avl_add(subchannel_map_, new SubchannelKey(*key), - constructed, nullptr); - c = constructed; - } - return c; -} - -void LocalSubchannelPool::UnregisterSubchannel(SubchannelKey* key) { - subchannel_map_ = grpc_avl_remove(subchannel_map_, key, nullptr); -} - -Subchannel* LocalSubchannelPool::FindSubchannel(SubchannelKey* key) { - Subchannel* c = - static_cast<Subchannel*>(grpc_avl_get(subchannel_map_, key, nullptr)); - return c == nullptr ? c : GRPC_SUBCHANNEL_REF(c, "found_from_pool"); -} - -namespace { - + constructed, nullptr); + c = constructed; + } + return c; +} + +void LocalSubchannelPool::UnregisterSubchannel(SubchannelKey* key) { + subchannel_map_ = grpc_avl_remove(subchannel_map_, key, nullptr); +} + +Subchannel* LocalSubchannelPool::FindSubchannel(SubchannelKey* key) { + Subchannel* c = + static_cast<Subchannel*>(grpc_avl_get(subchannel_map_, key, nullptr)); + return c == nullptr ? c : GRPC_SUBCHANNEL_REF(c, "found_from_pool"); +} + +namespace { + void sck_avl_destroy(void* p, void* /*user_data*/) { - SubchannelKey* key = static_cast<SubchannelKey*>(p); + SubchannelKey* key = static_cast<SubchannelKey*>(p); delete key; -} - +} + void* sck_avl_copy(void* p, void* /*unused*/) { - const SubchannelKey* key = static_cast<const SubchannelKey*>(p); + const SubchannelKey* key = static_cast<const SubchannelKey*>(p); auto new_key = new SubchannelKey(*key); - return static_cast<void*>(new_key); -} - + return static_cast<void*>(new_key); +} + long sck_avl_compare(void* a, void* b, void* /*unused*/) { - const SubchannelKey* key_a = static_cast<const SubchannelKey*>(a); - const SubchannelKey* key_b = static_cast<const SubchannelKey*>(b); - return key_a->Cmp(*key_b); -} - + const SubchannelKey* key_a = static_cast<const SubchannelKey*>(a); + const SubchannelKey* key_b = static_cast<const SubchannelKey*>(b); + return key_a->Cmp(*key_b); +} + void scv_avl_destroy(void* /*p*/, void* /*user_data*/) {} - + void* scv_avl_copy(void* p, void* /*unused*/) { return p; } - -} // namespace - -const grpc_avl_vtable LocalSubchannelPool::subchannel_avl_vtable_ = { - sck_avl_destroy, // destroy_key - sck_avl_copy, // copy_key - sck_avl_compare, // compare_keys - scv_avl_destroy, // destroy_value - scv_avl_copy // copy_value -}; - -} // namespace grpc_core + +} // namespace + +const grpc_avl_vtable LocalSubchannelPool::subchannel_avl_vtable_ = { + sck_avl_destroy, // destroy_key + sck_avl_copy, // copy_key + sck_avl_compare, // compare_keys + scv_avl_destroy, // destroy_value + scv_avl_copy // copy_value +}; + +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.h index 7d18d9b53f..0ace0ddabe 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/local_subchannel_pool.h @@ -1,57 +1,57 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LOCAL_SUBCHANNEL_POOL_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LOCAL_SUBCHANNEL_POOL_H - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" - -namespace grpc_core { - -// The local subchannel pool that is owned by a single channel. It doesn't -// support subchannel sharing with other channels by nature. Nor does it support -// subchannel retention when a subchannel is not used. The only real purpose of -// using this subchannel pool is to allow subchannel reuse within the channel -// when an incoming resolver update contains some addresses for which the -// channel has already created subchannels. -// Thread-unsafe. -class LocalSubchannelPool final : public SubchannelPoolInterface { - public: - LocalSubchannelPool(); - ~LocalSubchannelPool() override; - - // Implements interface methods. +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LOCAL_SUBCHANNEL_POOL_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LOCAL_SUBCHANNEL_POOL_H + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" + +namespace grpc_core { + +// The local subchannel pool that is owned by a single channel. It doesn't +// support subchannel sharing with other channels by nature. Nor does it support +// subchannel retention when a subchannel is not used. The only real purpose of +// using this subchannel pool is to allow subchannel reuse within the channel +// when an incoming resolver update contains some addresses for which the +// channel has already created subchannels. +// Thread-unsafe. +class LocalSubchannelPool final : public SubchannelPoolInterface { + public: + LocalSubchannelPool(); + ~LocalSubchannelPool() override; + + // Implements interface methods. // Thread-unsafe. Intended to be invoked within the client_channel work // serializer. - Subchannel* RegisterSubchannel(SubchannelKey* key, - Subchannel* constructed) override; - void UnregisterSubchannel(SubchannelKey* key) override; - Subchannel* FindSubchannel(SubchannelKey* key) override; - - private: - // The vtable for subchannel operations in an AVL tree. - static const grpc_avl_vtable subchannel_avl_vtable_; - // A map from subchannel key to subchannel. - grpc_avl subchannel_map_; -}; - -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LOCAL_SUBCHANNEL_POOL_H */ + Subchannel* RegisterSubchannel(SubchannelKey* key, + Subchannel* constructed) override; + void UnregisterSubchannel(SubchannelKey* key) override; + Subchannel* FindSubchannel(SubchannelKey* key) override; + + private: + // The vtable for subchannel operations in an AVL tree. + static const grpc_avl_vtable subchannel_avl_vtable_; + // A map from subchannel key to subchannel. + grpc_avl subchannel_map_; +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_LOCAL_SUBCHANNEL_POOL_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc index 4a76a7d7bd..91b4fccc74 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.cc @@ -31,7 +31,7 @@ namespace grpc_core { Resolver::Resolver(std::shared_ptr<WorkSerializer> work_serializer, std::unique_ptr<ResultHandler> result_handler) - : InternallyRefCounted(&grpc_trace_resolver_refcount), + : InternallyRefCounted(&grpc_trace_resolver_refcount), work_serializer_(std::move(work_serializer)), result_handler_(std::move(result_handler)) {} diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h index de941a063b..1376b67c9c 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver.h @@ -46,7 +46,7 @@ namespace grpc_core { /// /// Note: All methods with a "Locked" suffix must be called from the /// work_serializer passed to the constructor. -class Resolver : public InternallyRefCounted<Resolver> { +class Resolver : public InternallyRefCounted<Resolver> { public: /// Results returned by the resolver. struct Result { @@ -105,16 +105,16 @@ class Resolver : public InternallyRefCounted<Resolver> { /// /// Note: Implementations must not invoke any method on the /// ResultHandler from within this call. - virtual void RequestReresolutionLocked() {} - - /// Resets the re-resolution backoff, if any. - /// This needs to be implemented only by pull-based implementations; - /// for push-based implementations, it will be a no-op. - /// TODO(roth): Pull the backoff code out of resolver and into - /// client_channel, so that it can be shared across resolver - /// implementations. At that point, this method can go away. - virtual void ResetBackoffLocked() {} - + virtual void RequestReresolutionLocked() {} + + /// Resets the re-resolution backoff, if any. + /// This needs to be implemented only by pull-based implementations; + /// for push-based implementations, it will be a no-op. + /// TODO(roth): Pull the backoff code out of resolver and into + /// client_channel, so that it can be shared across resolver + /// implementations. At that point, this method can go away. + virtual void ResetBackoffLocked() {} + // Note: This must be invoked while holding the work_serializer. void Orphan() override { ShutdownLocked(); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc index 43d638ab3f..8e2a770e51 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc @@ -38,7 +38,7 @@ #include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" #include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/ext/filters/client_channel/service_config.h" #include "src/core/lib/backoff/backoff.h" #include "src/core/lib/channel/channel_args.h" @@ -70,8 +70,8 @@ class AresDnsResolver : public Resolver { void RequestReresolutionLocked() override; - void ResetBackoffLocked() override; - + void ResetBackoffLocked() override; + void ShutdownLocked() override; private: @@ -117,12 +117,12 @@ class AresDnsResolver : public Resolver { std::unique_ptr<ServerAddressList> balancer_addresses_; /// currently resolving service config char* service_config_json_ = nullptr; - // has shutdown been initiated - bool shutdown_initiated_ = false; - // timeout in milliseconds for active DNS queries - int query_timeout_ms_; - // whether or not to enable SRV DNS queries - bool enable_srv_queries_; + // has shutdown been initiated + bool shutdown_initiated_ = false; + // timeout in milliseconds for active DNS queries + int query_timeout_ms_; + // whether or not to enable SRV DNS queries + bool enable_srv_queries_; }; AresDnsResolver::AresDnsResolver(ResolverArgs args) @@ -148,32 +148,32 @@ AresDnsResolver::AresDnsResolver(ResolverArgs args) dns_server_ = gpr_strdup(args.uri->authority); } channel_args_ = grpc_channel_args_copy(args.args); - // Disable service config option + // Disable service config option const grpc_arg* arg = grpc_channel_args_find( channel_args_, GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION); - request_service_config_ = !grpc_channel_arg_get_bool(arg, true); - // Min time b/t resolutions option + request_service_config_ = !grpc_channel_arg_get_bool(arg, true); + // Min time b/t resolutions option arg = grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_MIN_TIME_BETWEEN_RESOLUTIONS_MS); min_time_between_resolutions_ = grpc_channel_arg_get_integer(arg, {1000 * 30, 0, INT_MAX}); - // Enable SRV queries option - arg = grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_ENABLE_SRV_QUERIES); - enable_srv_queries_ = grpc_channel_arg_get_bool(arg, false); + // Enable SRV queries option + arg = grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_ENABLE_SRV_QUERIES); + enable_srv_queries_ = grpc_channel_arg_get_bool(arg, false); interested_parties_ = grpc_pollset_set_create(); if (args.pollset_set != nullptr) { grpc_pollset_set_add_pollset_set(interested_parties_, args.pollset_set); } - const grpc_arg* query_timeout_ms_arg = - grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS); - query_timeout_ms_ = grpc_channel_arg_get_integer( - query_timeout_ms_arg, - {GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS, 0, INT_MAX}); + const grpc_arg* query_timeout_ms_arg = + grpc_channel_args_find(channel_args_, GRPC_ARG_DNS_ARES_QUERY_TIMEOUT_MS); + query_timeout_ms_ = grpc_channel_arg_get_integer( + query_timeout_ms_arg, + {GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS, 0, INT_MAX}); } AresDnsResolver::~AresDnsResolver() { - GRPC_CARES_TRACE_LOG("resolver:%p destroying AresDnsResolver", this); + GRPC_CARES_TRACE_LOG("resolver:%p destroying AresDnsResolver", this); grpc_pollset_set_destroy(interested_parties_); gpr_free(dns_server_); gpr_free(name_to_resolve_); @@ -182,7 +182,7 @@ AresDnsResolver::~AresDnsResolver() { void AresDnsResolver::StartLocked() { GRPC_CARES_TRACE_LOG("resolver:%p AresDnsResolver::StartLocked() is called.", - this); + this); MaybeStartResolvingLocked(); } @@ -192,20 +192,20 @@ void AresDnsResolver::RequestReresolutionLocked() { } } -void AresDnsResolver::ResetBackoffLocked() { - if (have_next_resolution_timer_) { - grpc_timer_cancel(&next_resolution_timer_); - } - backoff_.Reset(); -} - +void AresDnsResolver::ResetBackoffLocked() { + if (have_next_resolution_timer_) { + grpc_timer_cancel(&next_resolution_timer_); + } + backoff_.Reset(); +} + void AresDnsResolver::ShutdownLocked() { - shutdown_initiated_ = true; + shutdown_initiated_ = true; if (have_next_resolution_timer_) { grpc_timer_cancel(&next_resolution_timer_); } if (pending_request_ != nullptr) { - grpc_cancel_ares_request_locked(pending_request_); + grpc_cancel_ares_request_locked(pending_request_); } } @@ -217,14 +217,14 @@ void AresDnsResolver::OnNextResolution(void* arg, grpc_error* error) { } void AresDnsResolver::OnNextResolutionLocked(grpc_error* error) { - GRPC_CARES_TRACE_LOG( - "resolver:%p re-resolution timer fired. error: %s. shutdown_initiated_: " - "%d", + GRPC_CARES_TRACE_LOG( + "resolver:%p re-resolution timer fired. error: %s. shutdown_initiated_: " + "%d", this, grpc_error_string(error), shutdown_initiated_); have_next_resolution_timer_ = false; if (error == GRPC_ERROR_NONE && !shutdown_initiated_) { if (!resolving_) { - GRPC_CARES_TRACE_LOG( + GRPC_CARES_TRACE_LOG( "resolver:%p start resolving due to re-resolution timer", this); StartResolvingLocked(); } @@ -349,7 +349,7 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) { gpr_free(service_config_json_); if (result.service_config_error == GRPC_ERROR_NONE && !service_config_string.empty()) { - GRPC_CARES_TRACE_LOG("resolver:%p selected service config choice: %s", + GRPC_CARES_TRACE_LOG("resolver:%p selected service config choice: %s", this, service_config_string.c_str()); result.service_config = ServiceConfig::Create( channel_args_, service_config_string, &result.service_config_error); @@ -380,7 +380,7 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) { // Set retry timer. grpc_millis next_try = backoff_.NextAttemptTime(); grpc_millis timeout = next_try - ExecCtx::Get()->Now(); - GRPC_CARES_TRACE_LOG("resolver:%p dns resolution failed (will retry): %s", + GRPC_CARES_TRACE_LOG("resolver:%p dns resolution failed (will retry): %s", this, grpc_error_string(error)); GPR_ASSERT(!have_next_resolution_timer_); have_next_resolution_timer_ = true; @@ -389,7 +389,7 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) { // callback as part of the type system. Ref(DEBUG_LOCATION, "retry-timer").release(); if (timeout > 0) { - GRPC_CARES_TRACE_LOG("resolver:%p retrying in %" PRId64 " milliseconds", + GRPC_CARES_TRACE_LOG("resolver:%p retrying in %" PRId64 " milliseconds", this, timeout); } else { GRPC_CARES_TRACE_LOG("resolver:%p retrying immediately", this); @@ -403,7 +403,7 @@ void AresDnsResolver::OnResolvedLocked(grpc_error* error) { void AresDnsResolver::MaybeStartResolvingLocked() { // If there is an existing timer, the time it fires is the earliest time we // can start the next resolution. - if (have_next_resolution_timer_) return; + if (have_next_resolution_timer_) return; if (last_resolution_timestamp_ >= 0) { const grpc_millis earliest_next_resolution = last_resolution_timestamp_ + min_time_between_resolutions_; @@ -412,10 +412,10 @@ void AresDnsResolver::MaybeStartResolvingLocked() { if (ms_until_next_resolution > 0) { const grpc_millis last_resolution_ago = grpc_core::ExecCtx::Get()->Now() - last_resolution_timestamp_; - GRPC_CARES_TRACE_LOG( - "resolver:%p In cooldown from last resolution (from %" PRId64 - " ms ago). Will resolve again in %" PRId64 " ms", - this, last_resolution_ago, ms_until_next_resolution); + GRPC_CARES_TRACE_LOG( + "resolver:%p In cooldown from last resolution (from %" PRId64 + " ms ago). Will resolve again in %" PRId64 " ms", + this, last_resolution_ago, ms_until_next_resolution); have_next_resolution_timer_ = true; // TODO(roth): We currently deal with this ref manually. Once the // new closure API is done, find a way to track this ref with the timer @@ -438,15 +438,15 @@ void AresDnsResolver::StartResolvingLocked() { GPR_ASSERT(!resolving_); resolving_ = true; service_config_json_ = nullptr; - pending_request_ = grpc_dns_lookup_ares_locked( + pending_request_ = grpc_dns_lookup_ares_locked( dns_server_, name_to_resolve_, kDefaultPort, interested_parties_, &on_resolved_, &addresses_, enable_srv_queries_ ? &balancer_addresses_ : nullptr, - request_service_config_ ? &service_config_json_ : nullptr, + request_service_config_ ? &service_config_json_ : nullptr, query_timeout_ms_, work_serializer()); last_resolution_timestamp_ = grpc_core::ExecCtx::Get()->Now(); - GRPC_CARES_TRACE_LOG("resolver:%p Started resolving. pending_request_:%p", - this, pending_request_); + GRPC_CARES_TRACE_LOG("resolver:%p Started resolving. pending_request_:%p", + this, pending_request_); } // @@ -484,9 +484,9 @@ static grpc_address_resolver_vtable ares_resolver = { #ifdef GRPC_UV /* TODO(murgatroid99): Remove this when we want the cares resolver to be the * default when using libuv */ -static bool should_use_ares(const char* resolver_env) { +static bool should_use_ares(const char* resolver_env) { return resolver_env != nullptr && gpr_stricmp(resolver_env, "ares") == 0; -} +} #else /* GRPC_UV */ static bool should_use_ares(const char* resolver_env) { // TODO(lidiz): Remove the "g_custom_iomgr_enabled" flag once c-ares support @@ -494,7 +494,7 @@ static bool should_use_ares(const char* resolver_env) { return !g_custom_iomgr_enabled && resolver_env != nullptr && (gpr_stricmp(resolver_env, "ares") == 0); } #endif /* GRPC_UV */ - + static bool g_use_ares_dns_resolver; void grpc_resolver_dns_ares_init() { @@ -502,16 +502,16 @@ void grpc_resolver_dns_ares_init() { GPR_GLOBAL_CONFIG_GET(grpc_dns_resolver); if (should_use_ares(resolver.get())) { g_use_ares_dns_resolver = true; - gpr_log(GPR_DEBUG, "Using ares dns resolver"); + gpr_log(GPR_DEBUG, "Using ares dns resolver"); address_sorting_init(); grpc_error* error = grpc_ares_init(); if (error != GRPC_ERROR_NONE) { GRPC_LOG_IF_ERROR("grpc_ares_init() failed", error); return; } - if (default_resolver == nullptr) { - default_resolver = grpc_resolve_address_impl; - } + if (default_resolver == nullptr) { + default_resolver = grpc_resolve_address_impl; + } grpc_set_resolver_impl(&ares_resolver); grpc_core::ResolverRegistry::Builder::RegisterResolverFactory( y_absl::make_unique<grpc_core::AresDnsResolverFactory>()); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc index 9e6bd87622..1a811e84b8 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.cc @@ -1,140 +1,140 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" #if GRPC_ARES == 1 - -#include <ares.h> -#include <string.h> - + +#include <ares.h> +#include <string.h> + #include "y_absl/strings/str_cat.h" -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h" - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> -#include <grpc/support/time.h> -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/iomgr/iomgr_internal.h" -#include "src/core/lib/iomgr/sockaddr_utils.h" -#include "src/core/lib/iomgr/timer.h" - -typedef struct fd_node { - /** the owner of this fd node */ - grpc_ares_ev_driver* ev_driver; - /** a closure wrapping on_readable_locked, which should be - invoked when the grpc_fd in this node becomes readable. */ - grpc_closure read_closure; - /** a closure wrapping on_writable_locked, which should be - invoked when the grpc_fd in this node becomes writable. */ - grpc_closure write_closure; - /** next fd node in the list */ - struct fd_node* next; - - /** wrapped fd that's polled by grpc's poller for the current platform */ - grpc_core::GrpcPolledFd* grpc_polled_fd; - /** if the readable closure has been registered */ - bool readable_registered; - /** if the writable closure has been registered */ - bool writable_registered; - /** if the fd has been shutdown yet from grpc iomgr perspective */ - bool already_shutdown; -} fd_node; - -struct grpc_ares_ev_driver { - /** the ares_channel owned by this event driver */ - ares_channel channel; - /** pollset set for driving the IO events of the channel */ - grpc_pollset_set* pollset_set; - /** refcount of the event driver */ - gpr_refcount refs; - +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h" + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> +#include <grpc/support/time.h> +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/iomgr/iomgr_internal.h" +#include "src/core/lib/iomgr/sockaddr_utils.h" +#include "src/core/lib/iomgr/timer.h" + +typedef struct fd_node { + /** the owner of this fd node */ + grpc_ares_ev_driver* ev_driver; + /** a closure wrapping on_readable_locked, which should be + invoked when the grpc_fd in this node becomes readable. */ + grpc_closure read_closure; + /** a closure wrapping on_writable_locked, which should be + invoked when the grpc_fd in this node becomes writable. */ + grpc_closure write_closure; + /** next fd node in the list */ + struct fd_node* next; + + /** wrapped fd that's polled by grpc's poller for the current platform */ + grpc_core::GrpcPolledFd* grpc_polled_fd; + /** if the readable closure has been registered */ + bool readable_registered; + /** if the writable closure has been registered */ + bool writable_registered; + /** if the fd has been shutdown yet from grpc iomgr perspective */ + bool already_shutdown; +} fd_node; + +struct grpc_ares_ev_driver { + /** the ares_channel owned by this event driver */ + ares_channel channel; + /** pollset set for driving the IO events of the channel */ + grpc_pollset_set* pollset_set; + /** refcount of the event driver */ + gpr_refcount refs; + /** work_serializer to synchronize c-ares and I/O callbacks on */ std::shared_ptr<grpc_core::WorkSerializer> work_serializer; - /** a list of grpc_fd that this event driver is currently using. */ - fd_node* fds; - /** is this event driver currently working? */ - bool working; - /** is this event driver being shut down */ - bool shutting_down; - /** request object that's using this ev driver */ - grpc_ares_request* request; - /** Owned by the ev_driver. Creates new GrpcPolledFd's */ + /** a list of grpc_fd that this event driver is currently using. */ + fd_node* fds; + /** is this event driver currently working? */ + bool working; + /** is this event driver being shut down */ + bool shutting_down; + /** request object that's using this ev driver */ + grpc_ares_request* request; + /** Owned by the ev_driver. Creates new GrpcPolledFd's */ std::unique_ptr<grpc_core::GrpcPolledFdFactory> polled_fd_factory; - /** query timeout in milliseconds */ - int query_timeout_ms; - /** alarm to cancel active queries */ - grpc_timer query_timeout; - /** cancels queries on a timeout */ - grpc_closure on_timeout_locked; + /** query timeout in milliseconds */ + int query_timeout_ms; + /** alarm to cancel active queries */ + grpc_timer query_timeout; + /** cancels queries on a timeout */ + grpc_closure on_timeout_locked; /** alarm to poll ares_process on in case fd events don't happen */ grpc_timer ares_backup_poll_alarm; /** polls ares_process on a periodic timer */ grpc_closure on_ares_backup_poll_alarm_locked; -}; - -static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver); - -static grpc_ares_ev_driver* grpc_ares_ev_driver_ref( - grpc_ares_ev_driver* ev_driver) { - GRPC_CARES_TRACE_LOG("request:%p Ref ev_driver %p", ev_driver->request, - ev_driver); - gpr_ref(&ev_driver->refs); - return ev_driver; -} - -static void grpc_ares_ev_driver_unref(grpc_ares_ev_driver* ev_driver) { - GRPC_CARES_TRACE_LOG("request:%p Unref ev_driver %p", ev_driver->request, - ev_driver); - if (gpr_unref(&ev_driver->refs)) { - GRPC_CARES_TRACE_LOG("request:%p destroy ev_driver %p", ev_driver->request, - ev_driver); - GPR_ASSERT(ev_driver->fds == nullptr); - ares_destroy(ev_driver->channel); - grpc_ares_complete_request_locked(ev_driver->request); +}; + +static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver); + +static grpc_ares_ev_driver* grpc_ares_ev_driver_ref( + grpc_ares_ev_driver* ev_driver) { + GRPC_CARES_TRACE_LOG("request:%p Ref ev_driver %p", ev_driver->request, + ev_driver); + gpr_ref(&ev_driver->refs); + return ev_driver; +} + +static void grpc_ares_ev_driver_unref(grpc_ares_ev_driver* ev_driver) { + GRPC_CARES_TRACE_LOG("request:%p Unref ev_driver %p", ev_driver->request, + ev_driver); + if (gpr_unref(&ev_driver->refs)) { + GRPC_CARES_TRACE_LOG("request:%p destroy ev_driver %p", ev_driver->request, + ev_driver); + GPR_ASSERT(ev_driver->fds == nullptr); + ares_destroy(ev_driver->channel); + grpc_ares_complete_request_locked(ev_driver->request); delete ev_driver; - } -} - -static void fd_node_destroy_locked(fd_node* fdn) { - GRPC_CARES_TRACE_LOG("request:%p delete fd: %s", fdn->ev_driver->request, - fdn->grpc_polled_fd->GetName()); - GPR_ASSERT(!fdn->readable_registered); - GPR_ASSERT(!fdn->writable_registered); - GPR_ASSERT(fdn->already_shutdown); + } +} + +static void fd_node_destroy_locked(fd_node* fdn) { + GRPC_CARES_TRACE_LOG("request:%p delete fd: %s", fdn->ev_driver->request, + fdn->grpc_polled_fd->GetName()); + GPR_ASSERT(!fdn->readable_registered); + GPR_ASSERT(!fdn->writable_registered); + GPR_ASSERT(fdn->already_shutdown); delete fdn->grpc_polled_fd; - gpr_free(fdn); -} - -static void fd_node_shutdown_locked(fd_node* fdn, const char* reason) { - if (!fdn->already_shutdown) { - fdn->already_shutdown = true; - fdn->grpc_polled_fd->ShutdownLocked( - GRPC_ERROR_CREATE_FROM_STATIC_STRING(reason)); - } -} - + gpr_free(fdn); +} + +static void fd_node_shutdown_locked(fd_node* fdn, const char* reason) { + if (!fdn->already_shutdown) { + fdn->already_shutdown = true; + fdn->grpc_polled_fd->ShutdownLocked( + GRPC_ERROR_CREATE_FROM_STATIC_STRING(reason)); + } +} + static void on_timeout(void* arg, grpc_error* error); static void on_timeout_locked(grpc_ares_ev_driver* arg, grpc_error* error); - + static void on_ares_backup_poll_alarm(void* arg, grpc_error* error); static void on_ares_backup_poll_alarm_locked(grpc_ares_ev_driver* arg, grpc_error* error); @@ -150,73 +150,73 @@ grpc_error* grpc_ares_ev_driver_create_locked( std::shared_ptr<grpc_core::WorkSerializer> work_serializer, grpc_ares_request* request) { *ev_driver = new grpc_ares_ev_driver(); - ares_options opts; - memset(&opts, 0, sizeof(opts)); - opts.flags |= ARES_FLAG_STAYOPEN; - int status = ares_init_options(&(*ev_driver)->channel, &opts, ARES_OPT_FLAGS); + ares_options opts; + memset(&opts, 0, sizeof(opts)); + opts.flags |= ARES_FLAG_STAYOPEN; + int status = ares_init_options(&(*ev_driver)->channel, &opts, ARES_OPT_FLAGS); grpc_ares_test_only_inject_config((*ev_driver)->channel); - GRPC_CARES_TRACE_LOG("request:%p grpc_ares_ev_driver_create_locked", request); - if (status != ARES_SUCCESS) { + GRPC_CARES_TRACE_LOG("request:%p grpc_ares_ev_driver_create_locked", request); + if (status != ARES_SUCCESS) { grpc_error* err = GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("Failed to init ares channel. C-ares error: ", ares_strerror(status)) .c_str()); - gpr_free(*ev_driver); - return err; - } + gpr_free(*ev_driver); + return err; + } (*ev_driver)->work_serializer = std::move(work_serializer); - gpr_ref_init(&(*ev_driver)->refs, 1); - (*ev_driver)->pollset_set = pollset_set; - (*ev_driver)->fds = nullptr; - (*ev_driver)->working = false; - (*ev_driver)->shutting_down = false; - (*ev_driver)->request = request; - (*ev_driver)->polled_fd_factory = + gpr_ref_init(&(*ev_driver)->refs, 1); + (*ev_driver)->pollset_set = pollset_set; + (*ev_driver)->fds = nullptr; + (*ev_driver)->working = false; + (*ev_driver)->shutting_down = false; + (*ev_driver)->request = request; + (*ev_driver)->polled_fd_factory = grpc_core::NewGrpcPolledFdFactory((*ev_driver)->work_serializer); - (*ev_driver) - ->polled_fd_factory->ConfigureAresChannelLocked((*ev_driver)->channel); - (*ev_driver)->query_timeout_ms = query_timeout_ms; - return GRPC_ERROR_NONE; -} - -void grpc_ares_ev_driver_on_queries_complete_locked( - grpc_ares_ev_driver* ev_driver) { - // We mark the event driver as being shut down. If the event driver - // is working, grpc_ares_notify_on_event_locked will shut down the - // fds; if it's not working, there are no fds to shut down. - ev_driver->shutting_down = true; - grpc_timer_cancel(&ev_driver->query_timeout); + (*ev_driver) + ->polled_fd_factory->ConfigureAresChannelLocked((*ev_driver)->channel); + (*ev_driver)->query_timeout_ms = query_timeout_ms; + return GRPC_ERROR_NONE; +} + +void grpc_ares_ev_driver_on_queries_complete_locked( + grpc_ares_ev_driver* ev_driver) { + // We mark the event driver as being shut down. If the event driver + // is working, grpc_ares_notify_on_event_locked will shut down the + // fds; if it's not working, there are no fds to shut down. + ev_driver->shutting_down = true; + grpc_timer_cancel(&ev_driver->query_timeout); grpc_timer_cancel(&ev_driver->ares_backup_poll_alarm); - grpc_ares_ev_driver_unref(ev_driver); -} - -void grpc_ares_ev_driver_shutdown_locked(grpc_ares_ev_driver* ev_driver) { - ev_driver->shutting_down = true; - fd_node* fn = ev_driver->fds; - while (fn != nullptr) { - fd_node_shutdown_locked(fn, "grpc_ares_ev_driver_shutdown"); - fn = fn->next; - } -} - -// Search fd in the fd_node list head. This is an O(n) search, the max possible -// value of n is ARES_GETSOCK_MAXNUM (16). n is typically 1 - 2 in our tests. -static fd_node* pop_fd_node_locked(fd_node** head, ares_socket_t as) { - fd_node dummy_head; - dummy_head.next = *head; - fd_node* node = &dummy_head; - while (node->next != nullptr) { - if (node->next->grpc_polled_fd->GetWrappedAresSocketLocked() == as) { - fd_node* ret = node->next; - node->next = node->next->next; - *head = dummy_head.next; - return ret; - } - node = node->next; - } - return nullptr; -} - + grpc_ares_ev_driver_unref(ev_driver); +} + +void grpc_ares_ev_driver_shutdown_locked(grpc_ares_ev_driver* ev_driver) { + ev_driver->shutting_down = true; + fd_node* fn = ev_driver->fds; + while (fn != nullptr) { + fd_node_shutdown_locked(fn, "grpc_ares_ev_driver_shutdown"); + fn = fn->next; + } +} + +// Search fd in the fd_node list head. This is an O(n) search, the max possible +// value of n is ARES_GETSOCK_MAXNUM (16). n is typically 1 - 2 in our tests. +static fd_node* pop_fd_node_locked(fd_node** head, ares_socket_t as) { + fd_node dummy_head; + dummy_head.next = *head; + fd_node* node = &dummy_head; + while (node->next != nullptr) { + if (node->next->grpc_polled_fd->GetWrappedAresSocketLocked() == as) { + fd_node* ret = node->next; + node->next = node->next->next; + *head = dummy_head.next; + return ret; + } + node = node->next; + } + return nullptr; +} + static grpc_millis calculate_next_ares_backup_poll_alarm_ms( grpc_ares_ev_driver* driver) { // An alternative here could be to use ares_timeout to try to be more @@ -240,17 +240,17 @@ static void on_timeout(void* arg, grpc_error* error) { } static void on_timeout_locked(grpc_ares_ev_driver* driver, grpc_error* error) { - GRPC_CARES_TRACE_LOG( - "request:%p ev_driver=%p on_timeout_locked. driver->shutting_down=%d. " - "err=%s", - driver->request, driver, driver->shutting_down, grpc_error_string(error)); - if (!driver->shutting_down && error == GRPC_ERROR_NONE) { - grpc_ares_ev_driver_shutdown_locked(driver); - } - grpc_ares_ev_driver_unref(driver); + GRPC_CARES_TRACE_LOG( + "request:%p ev_driver=%p on_timeout_locked. driver->shutting_down=%d. " + "err=%s", + driver->request, driver, driver->shutting_down, grpc_error_string(error)); + if (!driver->shutting_down && error == GRPC_ERROR_NONE) { + grpc_ares_ev_driver_shutdown_locked(driver); + } + grpc_ares_ev_driver_unref(driver); GRPC_ERROR_UNREF(error); -} - +} + static void on_ares_backup_poll_alarm(void* arg, grpc_error* error) { grpc_ares_ev_driver* driver = static_cast<grpc_ares_ev_driver*>(arg); GRPC_ERROR_REF(error); @@ -306,29 +306,29 @@ static void on_ares_backup_poll_alarm_locked(grpc_ares_ev_driver* driver, static void on_readable_locked(fd_node* fdn, grpc_error* error) { GPR_ASSERT(fdn->readable_registered); - grpc_ares_ev_driver* ev_driver = fdn->ev_driver; - const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked(); - fdn->readable_registered = false; - GRPC_CARES_TRACE_LOG("request:%p readable on %s", fdn->ev_driver->request, - fdn->grpc_polled_fd->GetName()); - if (error == GRPC_ERROR_NONE) { - do { - ares_process_fd(ev_driver->channel, as, ARES_SOCKET_BAD); - } while (fdn->grpc_polled_fd->IsFdStillReadableLocked()); - } else { - // If error is not GRPC_ERROR_NONE, it means the fd has been shutdown or - // timed out. The pending lookups made on this ev_driver will be cancelled - // by the following ares_cancel() and the on_done callbacks will be invoked - // with a status of ARES_ECANCELLED. The remaining file descriptors in this - // ev_driver will be cleaned up in the follwing - // grpc_ares_notify_on_event_locked(). - ares_cancel(ev_driver->channel); - } - grpc_ares_notify_on_event_locked(ev_driver); - grpc_ares_ev_driver_unref(ev_driver); + grpc_ares_ev_driver* ev_driver = fdn->ev_driver; + const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked(); + fdn->readable_registered = false; + GRPC_CARES_TRACE_LOG("request:%p readable on %s", fdn->ev_driver->request, + fdn->grpc_polled_fd->GetName()); + if (error == GRPC_ERROR_NONE) { + do { + ares_process_fd(ev_driver->channel, as, ARES_SOCKET_BAD); + } while (fdn->grpc_polled_fd->IsFdStillReadableLocked()); + } else { + // If error is not GRPC_ERROR_NONE, it means the fd has been shutdown or + // timed out. The pending lookups made on this ev_driver will be cancelled + // by the following ares_cancel() and the on_done callbacks will be invoked + // with a status of ARES_ECANCELLED. The remaining file descriptors in this + // ev_driver will be cleaned up in the follwing + // grpc_ares_notify_on_event_locked(). + ares_cancel(ev_driver->channel); + } + grpc_ares_notify_on_event_locked(ev_driver); + grpc_ares_ev_driver_unref(ev_driver); GRPC_ERROR_UNREF(error); -} - +} + static void on_readable(void* arg, grpc_error* error) { fd_node* fdn = static_cast<fd_node*>(arg); GRPC_ERROR_REF(error); /* ref owned by lambda */ @@ -338,27 +338,27 @@ static void on_readable(void* arg, grpc_error* error) { static void on_writable_locked(fd_node* fdn, grpc_error* error) { GPR_ASSERT(fdn->writable_registered); - grpc_ares_ev_driver* ev_driver = fdn->ev_driver; - const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked(); - fdn->writable_registered = false; - GRPC_CARES_TRACE_LOG("request:%p writable on %s", ev_driver->request, - fdn->grpc_polled_fd->GetName()); - if (error == GRPC_ERROR_NONE) { - ares_process_fd(ev_driver->channel, ARES_SOCKET_BAD, as); - } else { - // If error is not GRPC_ERROR_NONE, it means the fd has been shutdown or - // timed out. The pending lookups made on this ev_driver will be cancelled - // by the following ares_cancel() and the on_done callbacks will be invoked - // with a status of ARES_ECANCELLED. The remaining file descriptors in this - // ev_driver will be cleaned up in the follwing - // grpc_ares_notify_on_event_locked(). - ares_cancel(ev_driver->channel); - } - grpc_ares_notify_on_event_locked(ev_driver); - grpc_ares_ev_driver_unref(ev_driver); + grpc_ares_ev_driver* ev_driver = fdn->ev_driver; + const ares_socket_t as = fdn->grpc_polled_fd->GetWrappedAresSocketLocked(); + fdn->writable_registered = false; + GRPC_CARES_TRACE_LOG("request:%p writable on %s", ev_driver->request, + fdn->grpc_polled_fd->GetName()); + if (error == GRPC_ERROR_NONE) { + ares_process_fd(ev_driver->channel, ARES_SOCKET_BAD, as); + } else { + // If error is not GRPC_ERROR_NONE, it means the fd has been shutdown or + // timed out. The pending lookups made on this ev_driver will be cancelled + // by the following ares_cancel() and the on_done callbacks will be invoked + // with a status of ARES_ECANCELLED. The remaining file descriptors in this + // ev_driver will be cleaned up in the follwing + // grpc_ares_notify_on_event_locked(). + ares_cancel(ev_driver->channel); + } + grpc_ares_notify_on_event_locked(ev_driver); + grpc_ares_ev_driver_unref(ev_driver); GRPC_ERROR_UNREF(error); -} - +} + static void on_writable(void* arg, grpc_error* error) { fd_node* fdn = static_cast<fd_node*>(arg); GRPC_ERROR_REF(error); /* ref owned by lambda */ @@ -366,109 +366,109 @@ static void on_writable(void* arg, grpc_error* error) { [fdn, error]() { on_writable_locked(fdn, error); }, DEBUG_LOCATION); } -ares_channel* grpc_ares_ev_driver_get_channel_locked( - grpc_ares_ev_driver* ev_driver) { - return &ev_driver->channel; -} - -// Get the file descriptors used by the ev_driver's ares channel, register -// driver_closure with these filedescriptors. -static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver) { - fd_node* new_list = nullptr; - if (!ev_driver->shutting_down) { - ares_socket_t socks[ARES_GETSOCK_MAXNUM]; - int socks_bitmask = - ares_getsock(ev_driver->channel, socks, ARES_GETSOCK_MAXNUM); - for (size_t i = 0; i < ARES_GETSOCK_MAXNUM; i++) { - if (ARES_GETSOCK_READABLE(socks_bitmask, i) || - ARES_GETSOCK_WRITABLE(socks_bitmask, i)) { - fd_node* fdn = pop_fd_node_locked(&ev_driver->fds, socks[i]); - // Create a new fd_node if sock[i] is not in the fd_node list. - if (fdn == nullptr) { - fdn = static_cast<fd_node*>(gpr_malloc(sizeof(fd_node))); - fdn->grpc_polled_fd = - ev_driver->polled_fd_factory->NewGrpcPolledFdLocked( +ares_channel* grpc_ares_ev_driver_get_channel_locked( + grpc_ares_ev_driver* ev_driver) { + return &ev_driver->channel; +} + +// Get the file descriptors used by the ev_driver's ares channel, register +// driver_closure with these filedescriptors. +static void grpc_ares_notify_on_event_locked(grpc_ares_ev_driver* ev_driver) { + fd_node* new_list = nullptr; + if (!ev_driver->shutting_down) { + ares_socket_t socks[ARES_GETSOCK_MAXNUM]; + int socks_bitmask = + ares_getsock(ev_driver->channel, socks, ARES_GETSOCK_MAXNUM); + for (size_t i = 0; i < ARES_GETSOCK_MAXNUM; i++) { + if (ARES_GETSOCK_READABLE(socks_bitmask, i) || + ARES_GETSOCK_WRITABLE(socks_bitmask, i)) { + fd_node* fdn = pop_fd_node_locked(&ev_driver->fds, socks[i]); + // Create a new fd_node if sock[i] is not in the fd_node list. + if (fdn == nullptr) { + fdn = static_cast<fd_node*>(gpr_malloc(sizeof(fd_node))); + fdn->grpc_polled_fd = + ev_driver->polled_fd_factory->NewGrpcPolledFdLocked( socks[i], ev_driver->pollset_set, ev_driver->work_serializer); - GRPC_CARES_TRACE_LOG("request:%p new fd: %s", ev_driver->request, - fdn->grpc_polled_fd->GetName()); - fdn->ev_driver = ev_driver; - fdn->readable_registered = false; - fdn->writable_registered = false; - fdn->already_shutdown = false; - } - fdn->next = new_list; - new_list = fdn; - // Register read_closure if the socket is readable and read_closure has - // not been registered with this socket. - if (ARES_GETSOCK_READABLE(socks_bitmask, i) && - !fdn->readable_registered) { - grpc_ares_ev_driver_ref(ev_driver); - GRPC_CARES_TRACE_LOG("request:%p notify read on: %s", - ev_driver->request, - fdn->grpc_polled_fd->GetName()); + GRPC_CARES_TRACE_LOG("request:%p new fd: %s", ev_driver->request, + fdn->grpc_polled_fd->GetName()); + fdn->ev_driver = ev_driver; + fdn->readable_registered = false; + fdn->writable_registered = false; + fdn->already_shutdown = false; + } + fdn->next = new_list; + new_list = fdn; + // Register read_closure if the socket is readable and read_closure has + // not been registered with this socket. + if (ARES_GETSOCK_READABLE(socks_bitmask, i) && + !fdn->readable_registered) { + grpc_ares_ev_driver_ref(ev_driver); + GRPC_CARES_TRACE_LOG("request:%p notify read on: %s", + ev_driver->request, + fdn->grpc_polled_fd->GetName()); GRPC_CLOSURE_INIT(&fdn->read_closure, on_readable, fdn, grpc_schedule_on_exec_ctx); - fdn->grpc_polled_fd->RegisterForOnReadableLocked(&fdn->read_closure); - fdn->readable_registered = true; - } - // Register write_closure if the socket is writable and write_closure - // has not been registered with this socket. - if (ARES_GETSOCK_WRITABLE(socks_bitmask, i) && - !fdn->writable_registered) { - GRPC_CARES_TRACE_LOG("request:%p notify write on: %s", - ev_driver->request, - fdn->grpc_polled_fd->GetName()); - grpc_ares_ev_driver_ref(ev_driver); + fdn->grpc_polled_fd->RegisterForOnReadableLocked(&fdn->read_closure); + fdn->readable_registered = true; + } + // Register write_closure if the socket is writable and write_closure + // has not been registered with this socket. + if (ARES_GETSOCK_WRITABLE(socks_bitmask, i) && + !fdn->writable_registered) { + GRPC_CARES_TRACE_LOG("request:%p notify write on: %s", + ev_driver->request, + fdn->grpc_polled_fd->GetName()); + grpc_ares_ev_driver_ref(ev_driver); GRPC_CLOSURE_INIT(&fdn->write_closure, on_writable, fdn, grpc_schedule_on_exec_ctx); - fdn->grpc_polled_fd->RegisterForOnWriteableLocked( - &fdn->write_closure); - fdn->writable_registered = true; - } - } - } - } - // Any remaining fds in ev_driver->fds were not returned by ares_getsock() and - // are therefore no longer in use, so they can be shut down and removed from - // the list. - while (ev_driver->fds != nullptr) { - fd_node* cur = ev_driver->fds; - ev_driver->fds = ev_driver->fds->next; - fd_node_shutdown_locked(cur, "c-ares fd shutdown"); - if (!cur->readable_registered && !cur->writable_registered) { - fd_node_destroy_locked(cur); - } else { - cur->next = new_list; - new_list = cur; - } - } - ev_driver->fds = new_list; - // If the ev driver has no working fd, all the tasks are done. - if (new_list == nullptr) { - ev_driver->working = false; - GRPC_CARES_TRACE_LOG("request:%p ev driver stop working", - ev_driver->request); - } -} - -void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver) { - if (!ev_driver->working) { - ev_driver->working = true; - grpc_ares_notify_on_event_locked(ev_driver); + fdn->grpc_polled_fd->RegisterForOnWriteableLocked( + &fdn->write_closure); + fdn->writable_registered = true; + } + } + } + } + // Any remaining fds in ev_driver->fds were not returned by ares_getsock() and + // are therefore no longer in use, so they can be shut down and removed from + // the list. + while (ev_driver->fds != nullptr) { + fd_node* cur = ev_driver->fds; + ev_driver->fds = ev_driver->fds->next; + fd_node_shutdown_locked(cur, "c-ares fd shutdown"); + if (!cur->readable_registered && !cur->writable_registered) { + fd_node_destroy_locked(cur); + } else { + cur->next = new_list; + new_list = cur; + } + } + ev_driver->fds = new_list; + // If the ev driver has no working fd, all the tasks are done. + if (new_list == nullptr) { + ev_driver->working = false; + GRPC_CARES_TRACE_LOG("request:%p ev driver stop working", + ev_driver->request); + } +} + +void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver) { + if (!ev_driver->working) { + ev_driver->working = true; + grpc_ares_notify_on_event_locked(ev_driver); // Initialize overall DNS resolution timeout alarm - grpc_millis timeout = - ev_driver->query_timeout_ms == 0 - ? GRPC_MILLIS_INF_FUTURE - : ev_driver->query_timeout_ms + grpc_core::ExecCtx::Get()->Now(); - GRPC_CARES_TRACE_LOG( - "request:%p ev_driver=%p grpc_ares_ev_driver_start_locked. timeout in " - "%" PRId64 " ms", - ev_driver->request, ev_driver, timeout); - grpc_ares_ev_driver_ref(ev_driver); + grpc_millis timeout = + ev_driver->query_timeout_ms == 0 + ? GRPC_MILLIS_INF_FUTURE + : ev_driver->query_timeout_ms + grpc_core::ExecCtx::Get()->Now(); + GRPC_CARES_TRACE_LOG( + "request:%p ev_driver=%p grpc_ares_ev_driver_start_locked. timeout in " + "%" PRId64 " ms", + ev_driver->request, ev_driver, timeout); + grpc_ares_ev_driver_ref(ev_driver); GRPC_CLOSURE_INIT(&ev_driver->on_timeout_locked, on_timeout, ev_driver, grpc_schedule_on_exec_ctx); - grpc_timer_init(&ev_driver->query_timeout, timeout, - &ev_driver->on_timeout_locked); + grpc_timer_init(&ev_driver->query_timeout, timeout, + &ev_driver->on_timeout_locked); // Initialize the backup poll alarm grpc_millis next_ares_backup_poll_alarm = calculate_next_ares_backup_poll_alarm_ms(ev_driver); @@ -479,7 +479,7 @@ void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver) { grpc_timer_init(&ev_driver->ares_backup_poll_alarm, next_ares_backup_poll_alarm, &ev_driver->on_ares_backup_poll_alarm_locked); - } -} - + } +} + #endif /* GRPC_ARES == 1 */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h index cedf0c3970..de5a310620 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h @@ -22,7 +22,7 @@ #include <grpc/support/port_platform.h> #include <ares.h> -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" #include "src/core/lib/iomgr/pollset_set.h" typedef struct grpc_ares_ev_driver grpc_ares_ev_driver; @@ -30,13 +30,13 @@ typedef struct grpc_ares_ev_driver grpc_ares_ev_driver; /* Start \a ev_driver. It will keep working until all IO on its ares_channel is done, or grpc_ares_ev_driver_destroy() is called. It may notify the callbacks bound to its ares_channel when necessary. */ -void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver); +void grpc_ares_ev_driver_start_locked(grpc_ares_ev_driver* ev_driver); /* Returns the ares_channel owned by \a ev_driver. To bind a c-ares query to \a ev_driver, use the ares_channel owned by \a ev_driver as the arg of the query. */ -ares_channel* grpc_ares_ev_driver_get_channel_locked( - grpc_ares_ev_driver* ev_driver); +ares_channel* grpc_ares_ev_driver_get_channel_locked( + grpc_ares_ev_driver* ev_driver); /* Creates a new grpc_ares_ev_driver. Returns GRPC_ERROR_NONE if \a ev_driver is created successfully. */ @@ -46,59 +46,59 @@ grpc_error* grpc_ares_ev_driver_create_locked( std::shared_ptr<grpc_core::WorkSerializer> work_serializer, grpc_ares_request* request); -/* Called back when all DNS lookups have completed. */ -void grpc_ares_ev_driver_on_queries_complete_locked( - grpc_ares_ev_driver* ev_driver); +/* Called back when all DNS lookups have completed. */ +void grpc_ares_ev_driver_on_queries_complete_locked( + grpc_ares_ev_driver* ev_driver); /* Shutdown all the grpc_fds used by \a ev_driver */ -void grpc_ares_ev_driver_shutdown_locked(grpc_ares_ev_driver* ev_driver); +void grpc_ares_ev_driver_shutdown_locked(grpc_ares_ev_driver* ev_driver); /* Exposed in this header for C-core tests only */ extern void (*grpc_ares_test_only_inject_config)(ares_channel channel); -namespace grpc_core { - -/* A wrapped fd that integrates with the grpc iomgr of the current platform. - * A GrpcPolledFd knows how to create grpc platform-specific iomgr endpoints - * from "ares_socket_t" sockets, and then sign up for readability/writeability - * with that poller, and do shutdown and destruction. */ -class GrpcPolledFd { - public: - virtual ~GrpcPolledFd() {} - /* Called when c-ares library is interested and there's no pending callback */ +namespace grpc_core { + +/* A wrapped fd that integrates with the grpc iomgr of the current platform. + * A GrpcPolledFd knows how to create grpc platform-specific iomgr endpoints + * from "ares_socket_t" sockets, and then sign up for readability/writeability + * with that poller, and do shutdown and destruction. */ +class GrpcPolledFd { + public: + virtual ~GrpcPolledFd() {} + /* Called when c-ares library is interested and there's no pending callback */ virtual void RegisterForOnReadableLocked(grpc_closure* read_closure) = 0; - /* Called when c-ares library is interested and there's no pending callback */ + /* Called when c-ares library is interested and there's no pending callback */ virtual void RegisterForOnWriteableLocked(grpc_closure* write_closure) = 0; - /* Indicates if there is data left even after just being read from */ + /* Indicates if there is data left even after just being read from */ virtual bool IsFdStillReadableLocked() = 0; - /* Called once and only once. Must cause cancellation of any pending - * read/write callbacks. */ + /* Called once and only once. Must cause cancellation of any pending + * read/write callbacks. */ virtual void ShutdownLocked(grpc_error* error) = 0; - /* Get the underlying ares_socket_t that this was created from */ + /* Get the underlying ares_socket_t that this was created from */ virtual ares_socket_t GetWrappedAresSocketLocked() = 0; - /* A unique name, for logging */ + /* A unique name, for logging */ virtual const char* GetName() = 0; -}; - -/* A GrpcPolledFdFactory is 1-to-1 with and owned by the - * ares event driver. It knows how to create GrpcPolledFd's - * for the current platform, and the ares driver uses it for all of - * its fd's. */ -class GrpcPolledFdFactory { - public: - virtual ~GrpcPolledFdFactory() {} - /* Creates a new wrapped fd for the current platform */ - virtual GrpcPolledFd* NewGrpcPolledFdLocked( - ares_socket_t as, grpc_pollset_set* driver_pollset_set, +}; + +/* A GrpcPolledFdFactory is 1-to-1 with and owned by the + * ares event driver. It knows how to create GrpcPolledFd's + * for the current platform, and the ares driver uses it for all of + * its fd's. */ +class GrpcPolledFdFactory { + public: + virtual ~GrpcPolledFdFactory() {} + /* Creates a new wrapped fd for the current platform */ + virtual GrpcPolledFd* NewGrpcPolledFdLocked( + ares_socket_t as, grpc_pollset_set* driver_pollset_set, std::shared_ptr<grpc_core::WorkSerializer> work_serializer) = 0; - /* Optionally configures the ares channel after creation */ + /* Optionally configures the ares channel after creation */ virtual void ConfigureAresChannelLocked(ares_channel channel) = 0; -}; - +}; + std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory( std::shared_ptr<grpc_core::WorkSerializer> work_serializer); - -} // namespace grpc_core - + +} // namespace grpc_core + #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_EV_DRIVER_H \ */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc index e1fcaa5090..807ea85fc5 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc @@ -18,10 +18,10 @@ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" -#if GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) +#if GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) #include <ares.h> -#include <string.h> +#include <string.h> #include <sys/ioctl.h> #include "y_absl/strings/str_cat.h" @@ -38,57 +38,57 @@ #include "src/core/lib/iomgr/iomgr_internal.h" #include "src/core/lib/iomgr/sockaddr_utils.h" -namespace grpc_core { +namespace grpc_core { -class GrpcPolledFdPosix : public GrpcPolledFd { - public: - GrpcPolledFdPosix(ares_socket_t as, grpc_pollset_set* driver_pollset_set) +class GrpcPolledFdPosix : public GrpcPolledFd { + public: + GrpcPolledFdPosix(ares_socket_t as, grpc_pollset_set* driver_pollset_set) : name_(y_absl::StrCat("c-ares fd: ", (int)as)), as_(as) { fd_ = grpc_fd_create((int)as, name_.c_str(), false); - driver_pollset_set_ = driver_pollset_set; - grpc_pollset_set_add_fd(driver_pollset_set_, fd_); + driver_pollset_set_ = driver_pollset_set; + grpc_pollset_set_add_fd(driver_pollset_set_, fd_); + } + + ~GrpcPolledFdPosix() { + grpc_pollset_set_del_fd(driver_pollset_set_, fd_); + /* c-ares library will close the fd inside grpc_fd. This fd may be picked up + immediately by another thread, and should not be closed by the following + grpc_fd_orphan. */ + int dummy_release_fd; + grpc_fd_orphan(fd_, nullptr, &dummy_release_fd, "c-ares query finished"); } - ~GrpcPolledFdPosix() { - grpc_pollset_set_del_fd(driver_pollset_set_, fd_); - /* c-ares library will close the fd inside grpc_fd. This fd may be picked up - immediately by another thread, and should not be closed by the following - grpc_fd_orphan. */ - int dummy_release_fd; - grpc_fd_orphan(fd_, nullptr, &dummy_release_fd, "c-ares query finished"); + void RegisterForOnReadableLocked(grpc_closure* read_closure) override { + grpc_fd_notify_on_read(fd_, read_closure); } - void RegisterForOnReadableLocked(grpc_closure* read_closure) override { - grpc_fd_notify_on_read(fd_, read_closure); + void RegisterForOnWriteableLocked(grpc_closure* write_closure) override { + grpc_fd_notify_on_write(fd_, write_closure); } - void RegisterForOnWriteableLocked(grpc_closure* write_closure) override { - grpc_fd_notify_on_write(fd_, write_closure); + bool IsFdStillReadableLocked() override { + size_t bytes_available = 0; + return ioctl(grpc_fd_wrapped_fd(fd_), FIONREAD, &bytes_available) == 0 && + bytes_available > 0; } - bool IsFdStillReadableLocked() override { - size_t bytes_available = 0; - return ioctl(grpc_fd_wrapped_fd(fd_), FIONREAD, &bytes_available) == 0 && - bytes_available > 0; + void ShutdownLocked(grpc_error* error) override { + grpc_fd_shutdown(fd_, error); } - void ShutdownLocked(grpc_error* error) override { - grpc_fd_shutdown(fd_, error); - } - - ares_socket_t GetWrappedAresSocketLocked() override { return as_; } + ares_socket_t GetWrappedAresSocketLocked() override { return as_; } const char* GetName() override { return name_.c_str(); } private: TString name_; - ares_socket_t as_; - grpc_fd* fd_; - grpc_pollset_set* driver_pollset_set_; -}; + ares_socket_t as_; + grpc_fd* fd_; + grpc_pollset_set* driver_pollset_set_; +}; -class GrpcPolledFdFactoryPosix : public GrpcPolledFdFactory { - public: +class GrpcPolledFdFactoryPosix : public GrpcPolledFdFactory { + public: GrpcPolledFd* NewGrpcPolledFdLocked( ares_socket_t as, grpc_pollset_set* driver_pollset_set, std::shared_ptr<WorkSerializer> /*work_serializer*/) override { @@ -96,7 +96,7 @@ class GrpcPolledFdFactoryPosix : public GrpcPolledFdFactory { } void ConfigureAresChannelLocked(ares_channel /*channel*/) override {} -}; +}; std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory( std::shared_ptr<WorkSerializer> work_serializer) { @@ -104,6 +104,6 @@ std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory( return y_absl::make_unique<GrpcPolledFdFactoryPosix>(); } -} // namespace grpc_core +} // namespace grpc_core -#endif /* GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) */ +#endif /* GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc index e228469517..6b780ac8e8 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc @@ -1,60 +1,60 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" #if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER) - + #include "y_absl/strings/str_format.h" -#include <ares.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/log_windows.h> -#include <grpc/support/string_util.h> -#include <grpc/support/time.h> -#include <string.h> -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/gprpp/memory.h" +#include <ares.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/log_windows.h> +#include <grpc/support/string_util.h> +#include <grpc/support/time.h> +#include <string.h> +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/iocp_windows.h" #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/iomgr/sockaddr_windows.h" -#include "src/core/lib/iomgr/socket_windows.h" -#include "src/core/lib/iomgr/tcp_windows.h" +#include "src/core/lib/iomgr/socket_windows.h" +#include "src/core/lib/iomgr/tcp_windows.h" #include "src/core/lib/iomgr/work_serializer.h" -#include "src/core/lib/slice/slice_internal.h" - -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h" -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" - -/* TODO(apolcyn): remove this hack after fixing upstream. - * Our grpc/c-ares code on Windows uses the ares_set_socket_functions API, - * which uses "struct iovec" type, which on Windows is defined inside of - * a c-ares header that is not public. - * See https://github.com/c-ares/c-ares/issues/206. */ -struct iovec { - void* iov_base; - size_t iov_len; -}; - -namespace grpc_core { - +#include "src/core/lib/slice/slice_internal.h" + +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver.h" +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" + +/* TODO(apolcyn): remove this hack after fixing upstream. + * Our grpc/c-ares code on Windows uses the ares_set_socket_functions API, + * which uses "struct iovec" type, which on Windows is defined inside of + * a c-ares header that is not public. + * See https://github.com/c-ares/c-ares/issues/206. */ +struct iovec { + void* iov_base; + size_t iov_len; +}; + +namespace grpc_core { + /* c-ares reads and takes action on the error codes of the * "virtual socket operations" in this file, via the WSAGetLastError * APIs. If code in this file wants to set a specific WSA error that @@ -81,30 +81,30 @@ class WSAErrorContext { int error_ = 0; }; -/* c-ares creates its own sockets and is meant to read them when readable and - * write them when writeable. To fit this socket usage model into the grpc - * windows poller (which gives notifications when attempted reads and writes are - * actually fulfilled rather than possible), this GrpcPolledFdWindows class - * takes advantage of the ares_set_socket_functions API and acts as a virtual - * socket. It holds its own read and write buffers which are written to and read - * from c-ares and are used with the grpc windows poller, and it, e.g., - * manufactures virtual socket error codes when it e.g. needs to tell the c-ares - * library to wait for an async read. */ +/* c-ares creates its own sockets and is meant to read them when readable and + * write them when writeable. To fit this socket usage model into the grpc + * windows poller (which gives notifications when attempted reads and writes are + * actually fulfilled rather than possible), this GrpcPolledFdWindows class + * takes advantage of the ares_set_socket_functions API and acts as a virtual + * socket. It holds its own read and write buffers which are written to and read + * from c-ares and are used with the grpc windows poller, and it, e.g., + * manufactures virtual socket error codes when it e.g. needs to tell the c-ares + * library to wait for an async read. */ class GrpcPolledFdWindows { - public: - enum WriteState { - WRITE_IDLE, - WRITE_REQUESTED, - WRITE_PENDING, - WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY, - }; - + public: + enum WriteState { + WRITE_IDLE, + WRITE_REQUESTED, + WRITE_PENDING, + WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY, + }; + GrpcPolledFdWindows(ares_socket_t as, std::shared_ptr<WorkSerializer> work_serializer, int address_family, int socket_type) : work_serializer_(std::move(work_serializer)), read_buf_(grpc_empty_slice()), - write_buf_(grpc_empty_slice()), + write_buf_(grpc_empty_slice()), tcp_write_state_(WRITE_IDLE), name_(y_absl::StrFormat("c-ares socket: %" PRIdPTR, as)), gotten_into_driver_list_(false), @@ -121,33 +121,33 @@ class GrpcPolledFdWindows { &GrpcPolledFdWindows::OnTcpConnect, this, grpc_schedule_on_exec_ctx); winsocket_ = grpc_winsocket_create(as, name_.c_str()); - } - - ~GrpcPolledFdWindows() { - grpc_slice_unref_internal(read_buf_); - grpc_slice_unref_internal(write_buf_); - GPR_ASSERT(read_closure_ == nullptr); - GPR_ASSERT(write_closure_ == nullptr); - grpc_winsocket_destroy(winsocket_); - } - - void ScheduleAndNullReadClosure(grpc_error* error) { + } + + ~GrpcPolledFdWindows() { + grpc_slice_unref_internal(read_buf_); + grpc_slice_unref_internal(write_buf_); + GPR_ASSERT(read_closure_ == nullptr); + GPR_ASSERT(write_closure_ == nullptr); + grpc_winsocket_destroy(winsocket_); + } + + void ScheduleAndNullReadClosure(grpc_error* error) { grpc_core::ExecCtx::Run(DEBUG_LOCATION, read_closure_, error); - read_closure_ = nullptr; - } - - void ScheduleAndNullWriteClosure(grpc_error* error) { + read_closure_ = nullptr; + } + + void ScheduleAndNullWriteClosure(grpc_error* error) { grpc_core::ExecCtx::Run(DEBUG_LOCATION, write_closure_, error); - write_closure_ = nullptr; - } - + write_closure_ = nullptr; + } + void RegisterForOnReadableLocked(grpc_closure* read_closure) { - GPR_ASSERT(read_closure_ == nullptr); - read_closure_ = read_closure; - GPR_ASSERT(GRPC_SLICE_LENGTH(read_buf_) == 0); - grpc_slice_unref_internal(read_buf_); + GPR_ASSERT(read_closure_ == nullptr); + read_closure_ = read_closure; + GPR_ASSERT(GRPC_SLICE_LENGTH(read_buf_) == 0); + grpc_slice_unref_internal(read_buf_); GPR_ASSERT(!read_buf_has_data_); - read_buf_ = GRPC_SLICE_MALLOC(4192); + read_buf_ = GRPC_SLICE_MALLOC(4192); if (connect_done_) { work_serializer_->Run([this]() { ContinueRegisterForOnReadableLocked(); }, DEBUG_LOCATION); @@ -167,32 +167,32 @@ class GrpcPolledFdWindows { ScheduleAndNullReadClosure(GRPC_WSA_ERROR(wsa_connect_error_, "connect")); return; } - WSABUF buffer; - buffer.buf = (char*)GRPC_SLICE_START_PTR(read_buf_); - buffer.len = GRPC_SLICE_LENGTH(read_buf_); - memset(&winsocket_->read_info.overlapped, 0, sizeof(OVERLAPPED)); - recv_from_source_addr_len_ = sizeof(recv_from_source_addr_); - DWORD flags = 0; - if (WSARecvFrom(grpc_winsocket_wrapped_socket(winsocket_), &buffer, 1, - nullptr, &flags, (sockaddr*)recv_from_source_addr_, - &recv_from_source_addr_len_, - &winsocket_->read_info.overlapped, nullptr)) { - int wsa_last_error = WSAGetLastError(); - char* msg = gpr_format_message(wsa_last_error); - GRPC_CARES_TRACE_LOG( + WSABUF buffer; + buffer.buf = (char*)GRPC_SLICE_START_PTR(read_buf_); + buffer.len = GRPC_SLICE_LENGTH(read_buf_); + memset(&winsocket_->read_info.overlapped, 0, sizeof(OVERLAPPED)); + recv_from_source_addr_len_ = sizeof(recv_from_source_addr_); + DWORD flags = 0; + if (WSARecvFrom(grpc_winsocket_wrapped_socket(winsocket_), &buffer, 1, + nullptr, &flags, (sockaddr*)recv_from_source_addr_, + &recv_from_source_addr_len_, + &winsocket_->read_info.overlapped, nullptr)) { + int wsa_last_error = WSAGetLastError(); + char* msg = gpr_format_message(wsa_last_error); + GRPC_CARES_TRACE_LOG( "fd:|%s| RegisterForOnReadableLocked WSARecvFrom error code:|%d| " "msg:|%s|", GetName(), wsa_last_error, msg); - gpr_free(msg); - if (wsa_last_error != WSA_IO_PENDING) { + gpr_free(msg); + if (wsa_last_error != WSA_IO_PENDING) { ScheduleAndNullReadClosure( GRPC_WSA_ERROR(wsa_last_error, "WSARecvFrom")); - return; - } - } + return; + } + } grpc_socket_notify_on_read(winsocket_, &outer_read_closure_); - } - + } + void RegisterForOnWriteableLocked(grpc_closure* write_closure) { if (socket_type_ == SOCK_DGRAM) { GRPC_CARES_TRACE_LOG("fd:|%s| RegisterForOnWriteableLocked called", @@ -203,17 +203,17 @@ class GrpcPolledFdWindows { "fd:|%s| RegisterForOnWriteableLocked called tcp_write_state_: %d", GetName(), tcp_write_state_); } - GPR_ASSERT(write_closure_ == nullptr); - write_closure_ = write_closure; + GPR_ASSERT(write_closure_ == nullptr); + write_closure_ = write_closure; if (connect_done_) { work_serializer_->Run( [this]() { ContinueRegisterForOnWriteableLocked(); }, DEBUG_LOCATION); } else { GPR_ASSERT(pending_continue_register_for_on_writeable_locked_ == false); pending_continue_register_for_on_writeable_locked_ = true; - } - } - + } + } + void ContinueRegisterForOnWriteableLocked() { GRPC_CARES_TRACE_LOG( "fd:|%s| InnerContinueRegisterForOnWriteableLocked " @@ -254,79 +254,79 @@ class GrpcPolledFdWindows { bool IsFdStillReadableLocked() { return GRPC_SLICE_LENGTH(read_buf_) > 0; } void ShutdownLocked(grpc_error* error) { - grpc_winsocket_shutdown(winsocket_); - } - + grpc_winsocket_shutdown(winsocket_); + } + ares_socket_t GetWrappedAresSocketLocked() { - return grpc_winsocket_wrapped_socket(winsocket_); - } - + return grpc_winsocket_wrapped_socket(winsocket_); + } + const char* GetName() { return name_.c_str(); } - + ares_ssize_t RecvFrom(WSAErrorContext* wsa_error_ctx, void* data, ares_socket_t data_len, int flags, - struct sockaddr* from, ares_socklen_t* from_len) { - GRPC_CARES_TRACE_LOG( + struct sockaddr* from, ares_socklen_t* from_len) { + GRPC_CARES_TRACE_LOG( "fd:|%s| RecvFrom called read_buf_has_data:%d Current read buf " "length:|%d|", GetName(), read_buf_has_data_, GRPC_SLICE_LENGTH(read_buf_)); if (!read_buf_has_data_) { wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK); - return -1; - } - ares_ssize_t bytes_read = 0; - for (size_t i = 0; i < GRPC_SLICE_LENGTH(read_buf_) && i < data_len; i++) { - ((char*)data)[i] = GRPC_SLICE_START_PTR(read_buf_)[i]; - bytes_read++; - } - read_buf_ = grpc_slice_sub_no_ref(read_buf_, bytes_read, - GRPC_SLICE_LENGTH(read_buf_)); + return -1; + } + ares_ssize_t bytes_read = 0; + for (size_t i = 0; i < GRPC_SLICE_LENGTH(read_buf_) && i < data_len; i++) { + ((char*)data)[i] = GRPC_SLICE_START_PTR(read_buf_)[i]; + bytes_read++; + } + read_buf_ = grpc_slice_sub_no_ref(read_buf_, bytes_read, + GRPC_SLICE_LENGTH(read_buf_)); if (GRPC_SLICE_LENGTH(read_buf_) == 0) { read_buf_has_data_ = false; } - /* c-ares overloads this recv_from virtual socket function to receive - * data on both UDP and TCP sockets, and from is nullptr for TCP. */ - if (from != nullptr) { - GPR_ASSERT(*from_len <= recv_from_source_addr_len_); - memcpy(from, &recv_from_source_addr_, recv_from_source_addr_len_); - *from_len = recv_from_source_addr_len_; - } - return bytes_read; - } - - grpc_slice FlattenIovec(const struct iovec* iov, int iov_count) { - int total = 0; - for (int i = 0; i < iov_count; i++) { - total += iov[i].iov_len; - } - grpc_slice out = GRPC_SLICE_MALLOC(total); - size_t cur = 0; - for (int i = 0; i < iov_count; i++) { - for (int k = 0; k < iov[i].iov_len; k++) { - GRPC_SLICE_START_PTR(out)[cur++] = ((char*)iov[i].iov_base)[k]; - } - } - return out; - } - + /* c-ares overloads this recv_from virtual socket function to receive + * data on both UDP and TCP sockets, and from is nullptr for TCP. */ + if (from != nullptr) { + GPR_ASSERT(*from_len <= recv_from_source_addr_len_); + memcpy(from, &recv_from_source_addr_, recv_from_source_addr_len_); + *from_len = recv_from_source_addr_len_; + } + return bytes_read; + } + + grpc_slice FlattenIovec(const struct iovec* iov, int iov_count) { + int total = 0; + for (int i = 0; i < iov_count; i++) { + total += iov[i].iov_len; + } + grpc_slice out = GRPC_SLICE_MALLOC(total); + size_t cur = 0; + for (int i = 0; i < iov_count; i++) { + for (int k = 0; k < iov[i].iov_len; k++) { + GRPC_SLICE_START_PTR(out)[cur++] = ((char*)iov[i].iov_base)[k]; + } + } + return out; + } + int SendWriteBuf(LPDWORD bytes_sent_ptr, LPWSAOVERLAPPED overlapped, int* wsa_error_code) { - WSABUF buf; - buf.len = GRPC_SLICE_LENGTH(write_buf_); - buf.buf = (char*)GRPC_SLICE_START_PTR(write_buf_); - DWORD flags = 0; - int out = WSASend(grpc_winsocket_wrapped_socket(winsocket_), &buf, 1, - bytes_sent_ptr, flags, overlapped, nullptr); + WSABUF buf; + buf.len = GRPC_SLICE_LENGTH(write_buf_); + buf.buf = (char*)GRPC_SLICE_START_PTR(write_buf_); + DWORD flags = 0; + int out = WSASend(grpc_winsocket_wrapped_socket(winsocket_), &buf, 1, + bytes_sent_ptr, flags, overlapped, nullptr); *wsa_error_code = WSAGetLastError(); - GRPC_CARES_TRACE_LOG( + GRPC_CARES_TRACE_LOG( "fd:|%s| SendWriteBuf WSASend buf.len:%d *bytes_sent_ptr:%d " "overlapped:%p " "return:%d *wsa_error_code:%d", GetName(), buf.len, bytes_sent_ptr != nullptr ? *bytes_sent_ptr : 0, overlapped, out, *wsa_error_code); - return out; - } - + return out; + } + ares_ssize_t SendV(WSAErrorContext* wsa_error_ctx, const struct iovec* iov, int iov_count) { GRPC_CARES_TRACE_LOG( @@ -359,22 +359,22 @@ class GrpcPolledFdWindows { GPR_ASSERT(GRPC_SLICE_LENGTH(write_buf_) == 0); grpc_slice_unref_internal(write_buf_); write_buf_ = FlattenIovec(iov, iov_count); - DWORD bytes_sent = 0; + DWORD bytes_sent = 0; int wsa_error_code = 0; if (SendWriteBuf(&bytes_sent, nullptr, &wsa_error_code) != 0) { wsa_error_ctx->SetWSAError(wsa_error_code); char* msg = gpr_format_message(wsa_error_code); - GRPC_CARES_TRACE_LOG( + GRPC_CARES_TRACE_LOG( "fd:|%s| SendVUDP SendWriteBuf error code:%d msg:|%s|", GetName(), wsa_error_code, msg); - gpr_free(msg); + gpr_free(msg); return -1; - } - write_buf_ = grpc_slice_sub_no_ref(write_buf_, bytes_sent, - GRPC_SLICE_LENGTH(write_buf_)); - return bytes_sent; - } - + } + write_buf_ = grpc_slice_sub_no_ref(write_buf_, bytes_sent, + GRPC_SLICE_LENGTH(write_buf_)); + return bytes_sent; + } + ares_ssize_t SendVTCP(WSAErrorContext* wsa_error_ctx, const struct iovec* iov, int iov_count) { // The "sendv" handler on TCP sockets buffers up write @@ -385,39 +385,39 @@ class GrpcPolledFdWindows { GRPC_CARES_TRACE_LOG("fd:|%s| SendVTCP called tcp_write_state_:%d", GetName(), tcp_write_state_); switch (tcp_write_state_) { - case WRITE_IDLE: + case WRITE_IDLE: tcp_write_state_ = WRITE_REQUESTED; - GPR_ASSERT(GRPC_SLICE_LENGTH(write_buf_) == 0); - grpc_slice_unref_internal(write_buf_); - write_buf_ = FlattenIovec(iov, iov_count); + GPR_ASSERT(GRPC_SLICE_LENGTH(write_buf_) == 0); + grpc_slice_unref_internal(write_buf_); + write_buf_ = FlattenIovec(iov, iov_count); wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK); return -1; - case WRITE_REQUESTED: - case WRITE_PENDING: + case WRITE_REQUESTED: + case WRITE_PENDING: wsa_error_ctx->SetWSAError(WSAEWOULDBLOCK); - return -1; - case WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY: + return -1; + case WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY: // c-ares is retrying a send on data that we previously returned // WSAEWOULDBLOCK for, but then subsequently wrote out in the // background. Right now, we assume that c-ares is retrying the same // send again. If c-ares still needs to send even more data, we'll get // to it eventually. - grpc_slice currently_attempted = FlattenIovec(iov, iov_count); - GPR_ASSERT(GRPC_SLICE_LENGTH(currently_attempted) >= - GRPC_SLICE_LENGTH(write_buf_)); - ares_ssize_t total_sent = 0; - for (size_t i = 0; i < GRPC_SLICE_LENGTH(write_buf_); i++) { - GPR_ASSERT(GRPC_SLICE_START_PTR(currently_attempted)[i] == - GRPC_SLICE_START_PTR(write_buf_)[i]); - total_sent++; - } + grpc_slice currently_attempted = FlattenIovec(iov, iov_count); + GPR_ASSERT(GRPC_SLICE_LENGTH(currently_attempted) >= + GRPC_SLICE_LENGTH(write_buf_)); + ares_ssize_t total_sent = 0; + for (size_t i = 0; i < GRPC_SLICE_LENGTH(write_buf_); i++) { + GPR_ASSERT(GRPC_SLICE_START_PTR(currently_attempted)[i] == + GRPC_SLICE_START_PTR(write_buf_)[i]); + total_sent++; + } grpc_slice_unref_internal(currently_attempted); tcp_write_state_ = WRITE_IDLE; - return total_sent; - } - abort(); - } - + return total_sent; + } + abort(); + } + static void OnTcpConnect(void* arg, grpc_error* error) { GrpcPolledFdWindows* grpc_polled_fd = static_cast<GrpcPolledFdWindows*>(arg); @@ -490,9 +490,9 @@ class GrpcPolledFdWindows { GRPC_CARES_TRACE_LOG("fd:%s ConnectUDP", GetName()); GPR_ASSERT(!connect_done_); GPR_ASSERT(wsa_connect_error_ == 0); - SOCKET s = grpc_winsocket_wrapped_socket(winsocket_); - int out = - WSAConnect(s, target, target_len, nullptr, nullptr, nullptr, nullptr); + SOCKET s = grpc_winsocket_wrapped_socket(winsocket_); + int out = + WSAConnect(s, target, target_len, nullptr, nullptr, nullptr, nullptr); wsa_connect_error_ = WSAGetLastError(); wsa_error_ctx->SetWSAError(wsa_connect_error_); connect_done_ = true; @@ -514,14 +514,14 @@ class GrpcPolledFdWindows { if (WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ConnectEx, sizeof(ConnectEx), &ioctl_num_bytes, nullptr, nullptr) != 0) { - int wsa_last_error = WSAGetLastError(); + int wsa_last_error = WSAGetLastError(); wsa_error_ctx->SetWSAError(wsa_last_error); - char* msg = gpr_format_message(wsa_last_error); + char* msg = gpr_format_message(wsa_last_error); GRPC_CARES_TRACE_LOG( "fd:%s WSAIoctl(SIO_GET_EXTENSION_FUNCTION_POINTER) error code:%d " "msg:|%s|", GetName(), wsa_last_error, msg); - gpr_free(msg); + gpr_free(msg); connect_done_ = true; wsa_connect_error_ = wsa_last_error; return -1; @@ -550,7 +550,7 @@ class GrpcPolledFdWindows { int out = 0; if (ConnectEx(s, target, target_len, nullptr, 0, nullptr, &winsocket_->write_info.overlapped) == 0) { - out = -1; + out = -1; int wsa_last_error = WSAGetLastError(); wsa_error_ctx->SetWSAError(wsa_last_error); char* msg = gpr_format_message(wsa_last_error); @@ -569,13 +569,13 @@ class GrpcPolledFdWindows { wsa_connect_error_ = wsa_last_error; return -1; } - } + } grpc_socket_notify_on_write(winsocket_, &on_tcp_connect_locked_); - return out; - } - - static void OnIocpReadable(void* arg, grpc_error* error) { - GrpcPolledFdWindows* polled_fd = static_cast<GrpcPolledFdWindows*>(arg); + return out; + } + + static void OnIocpReadable(void* arg, grpc_error* error) { + GrpcPolledFdWindows* polled_fd = static_cast<GrpcPolledFdWindows*>(arg); GRPC_ERROR_REF(error); // ref owned by lambda polled_fd->work_serializer_->Run( [polled_fd, error]() { polled_fd->OnIocpReadableLocked(error); }, @@ -588,39 +588,39 @@ class GrpcPolledFdWindows { // the entire resolution attempt. Doing so will allow the "inject broken // nameserver list" test to pass on Windows. void OnIocpReadableLocked(grpc_error* error) { - if (error == GRPC_ERROR_NONE) { - if (winsocket_->read_info.wsa_error != 0) { - /* WSAEMSGSIZE would be due to receiving more data - * than our read buffer's fixed capacity. Assume that - * the connection is TCP and read the leftovers - * in subsequent c-ares reads. */ - if (winsocket_->read_info.wsa_error != WSAEMSGSIZE) { + if (error == GRPC_ERROR_NONE) { + if (winsocket_->read_info.wsa_error != 0) { + /* WSAEMSGSIZE would be due to receiving more data + * than our read buffer's fixed capacity. Assume that + * the connection is TCP and read the leftovers + * in subsequent c-ares reads. */ + if (winsocket_->read_info.wsa_error != WSAEMSGSIZE) { error = GRPC_WSA_ERROR(winsocket_->read_info.wsa_error, "OnIocpReadableInner"); - GRPC_CARES_TRACE_LOG( + GRPC_CARES_TRACE_LOG( "fd:|%s| OnIocpReadableInner winsocket_->read_info.wsa_error " "code:|%d| msg:|%s|", GetName(), winsocket_->read_info.wsa_error, grpc_error_string(error)); - } - } - } - if (error == GRPC_ERROR_NONE) { + } + } + } + if (error == GRPC_ERROR_NONE) { read_buf_ = grpc_slice_sub_no_ref( read_buf_, 0, winsocket_->read_info.bytes_transferred); read_buf_has_data_ = true; - } else { - grpc_slice_unref_internal(read_buf_); - read_buf_ = grpc_empty_slice(); - } - GRPC_CARES_TRACE_LOG( + } else { + grpc_slice_unref_internal(read_buf_); + read_buf_ = grpc_empty_slice(); + } + GRPC_CARES_TRACE_LOG( "fd:|%s| OnIocpReadable finishing. read buf length now:|%d|", GetName(), GRPC_SLICE_LENGTH(read_buf_)); - ScheduleAndNullReadClosure(error); - } - - static void OnIocpWriteable(void* arg, grpc_error* error) { - GrpcPolledFdWindows* polled_fd = static_cast<GrpcPolledFdWindows*>(arg); + ScheduleAndNullReadClosure(error); + } + + static void OnIocpWriteable(void* arg, grpc_error* error) { + GrpcPolledFdWindows* polled_fd = static_cast<GrpcPolledFdWindows*>(arg); GRPC_ERROR_REF(error); // error owned by lambda polled_fd->work_serializer_->Run( [polled_fd, error]() { polled_fd->OnIocpWriteableLocked(error); }, @@ -628,52 +628,52 @@ class GrpcPolledFdWindows { } void OnIocpWriteableLocked(grpc_error* error) { - GRPC_CARES_TRACE_LOG("OnIocpWriteableInner. fd:|%s|", GetName()); + GRPC_CARES_TRACE_LOG("OnIocpWriteableInner. fd:|%s|", GetName()); GPR_ASSERT(socket_type_ == SOCK_STREAM); - if (error == GRPC_ERROR_NONE) { - if (winsocket_->write_info.wsa_error != 0) { + if (error == GRPC_ERROR_NONE) { + if (winsocket_->write_info.wsa_error != 0) { error = GRPC_WSA_ERROR(winsocket_->write_info.wsa_error, "OnIocpWriteableInner"); - GRPC_CARES_TRACE_LOG( + GRPC_CARES_TRACE_LOG( "fd:|%s| OnIocpWriteableInner. winsocket_->write_info.wsa_error " "code:|%d| msg:|%s|", GetName(), winsocket_->write_info.wsa_error, grpc_error_string(error)); - } - } + } + } GPR_ASSERT(tcp_write_state_ == WRITE_PENDING); - if (error == GRPC_ERROR_NONE) { + if (error == GRPC_ERROR_NONE) { tcp_write_state_ = WRITE_WAITING_FOR_VERIFICATION_UPON_RETRY; - write_buf_ = grpc_slice_sub_no_ref( + write_buf_ = grpc_slice_sub_no_ref( write_buf_, 0, winsocket_->write_info.bytes_transferred); GRPC_CARES_TRACE_LOG("fd:|%s| OnIocpWriteableInner. bytes transferred:%d", GetName(), winsocket_->write_info.bytes_transferred); - } else { - grpc_slice_unref_internal(write_buf_); - write_buf_ = grpc_empty_slice(); - } - ScheduleAndNullWriteClosure(error); - } - - bool gotten_into_driver_list() const { return gotten_into_driver_list_; } - void set_gotten_into_driver_list() { gotten_into_driver_list_ = true; } - + } else { + grpc_slice_unref_internal(write_buf_); + write_buf_ = grpc_empty_slice(); + } + ScheduleAndNullWriteClosure(error); + } + + bool gotten_into_driver_list() const { return gotten_into_driver_list_; } + void set_gotten_into_driver_list() { gotten_into_driver_list_ = true; } + private: std::shared_ptr<WorkSerializer> work_serializer_; - char recv_from_source_addr_[200]; - ares_socklen_t recv_from_source_addr_len_; - grpc_slice read_buf_; + char recv_from_source_addr_[200]; + ares_socklen_t recv_from_source_addr_len_; + grpc_slice read_buf_; bool read_buf_has_data_ = false; - grpc_slice write_buf_; - grpc_closure* read_closure_ = nullptr; - grpc_closure* write_closure_ = nullptr; - grpc_closure outer_read_closure_; - grpc_closure outer_write_closure_; - grpc_winsocket* winsocket_; + grpc_slice write_buf_; + grpc_closure* read_closure_ = nullptr; + grpc_closure* write_closure_ = nullptr; + grpc_closure outer_read_closure_; + grpc_closure outer_write_closure_; + grpc_winsocket* winsocket_; // tcp_write_state_ is only used on TCP GrpcPolledFds WriteState tcp_write_state_; TString name_; - bool gotten_into_driver_list_; + bool gotten_into_driver_list_; int address_family_; int socket_type_; grpc_closure on_tcp_connect_locked_; @@ -684,149 +684,149 @@ class GrpcPolledFdWindows { // registrations with the following state. bool pending_continue_register_for_on_readable_locked_ = false; bool pending_continue_register_for_on_writeable_locked_ = false; -}; - -struct SockToPolledFdEntry { - SockToPolledFdEntry(SOCKET s, GrpcPolledFdWindows* fd) - : socket(s), polled_fd(fd) {} - SOCKET socket; - GrpcPolledFdWindows* polled_fd; - SockToPolledFdEntry* next = nullptr; -}; - -/* A SockToPolledFdMap can make ares_socket_t types (SOCKET's on windows) - * to GrpcPolledFdWindow's, and is used to find the appropriate - * GrpcPolledFdWindows to handle a virtual socket call when c-ares makes that - * socket call on the ares_socket_t type. Instances are owned by and one-to-one - * with a GrpcPolledFdWindows factory and event driver */ -class SockToPolledFdMap { - public: +}; + +struct SockToPolledFdEntry { + SockToPolledFdEntry(SOCKET s, GrpcPolledFdWindows* fd) + : socket(s), polled_fd(fd) {} + SOCKET socket; + GrpcPolledFdWindows* polled_fd; + SockToPolledFdEntry* next = nullptr; +}; + +/* A SockToPolledFdMap can make ares_socket_t types (SOCKET's on windows) + * to GrpcPolledFdWindow's, and is used to find the appropriate + * GrpcPolledFdWindows to handle a virtual socket call when c-ares makes that + * socket call on the ares_socket_t type. Instances are owned by and one-to-one + * with a GrpcPolledFdWindows factory and event driver */ +class SockToPolledFdMap { + public: explicit SockToPolledFdMap(std::shared_ptr<WorkSerializer> work_serializer) : work_serializer_(std::move(work_serializer)) {} - + ~SockToPolledFdMap() { GPR_ASSERT(head_ == nullptr); } - - void AddNewSocket(SOCKET s, GrpcPolledFdWindows* polled_fd) { + + void AddNewSocket(SOCKET s, GrpcPolledFdWindows* polled_fd) { SockToPolledFdEntry* new_node = new SockToPolledFdEntry(s, polled_fd); - new_node->next = head_; - head_ = new_node; - } - - GrpcPolledFdWindows* LookupPolledFd(SOCKET s) { - for (SockToPolledFdEntry* node = head_; node != nullptr; - node = node->next) { - if (node->socket == s) { - GPR_ASSERT(node->polled_fd != nullptr); - return node->polled_fd; - } - } - abort(); - } - - void RemoveEntry(SOCKET s) { - GPR_ASSERT(head_ != nullptr); - SockToPolledFdEntry** prev = &head_; - for (SockToPolledFdEntry* node = head_; node != nullptr; - node = node->next) { - if (node->socket == s) { - *prev = node->next; + new_node->next = head_; + head_ = new_node; + } + + GrpcPolledFdWindows* LookupPolledFd(SOCKET s) { + for (SockToPolledFdEntry* node = head_; node != nullptr; + node = node->next) { + if (node->socket == s) { + GPR_ASSERT(node->polled_fd != nullptr); + return node->polled_fd; + } + } + abort(); + } + + void RemoveEntry(SOCKET s) { + GPR_ASSERT(head_ != nullptr); + SockToPolledFdEntry** prev = &head_; + for (SockToPolledFdEntry* node = head_; node != nullptr; + node = node->next) { + if (node->socket == s) { + *prev = node->next; delete node; - return; - } - prev = &node->next; - } - abort(); - } - - /* These virtual socket functions are called from within the c-ares - * library. These methods generally dispatch those socket calls to the - * appropriate methods. The virtual "socket" and "close" methods are - * special and instead create/add and remove/destroy GrpcPolledFdWindows - * objects. - */ - static ares_socket_t Socket(int af, int type, int protocol, void* user_data) { + return; + } + prev = &node->next; + } + abort(); + } + + /* These virtual socket functions are called from within the c-ares + * library. These methods generally dispatch those socket calls to the + * appropriate methods. The virtual "socket" and "close" methods are + * special and instead create/add and remove/destroy GrpcPolledFdWindows + * objects. + */ + static ares_socket_t Socket(int af, int type, int protocol, void* user_data) { if (type != SOCK_DGRAM && type != SOCK_STREAM) { GRPC_CARES_TRACE_LOG("Socket called with invalid socket type:%d", type); return INVALID_SOCKET; } - SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); + SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); SOCKET s = WSASocket(af, type, protocol, nullptr, 0, grpc_get_default_wsa_socket_flags()); - if (s == INVALID_SOCKET) { + if (s == INVALID_SOCKET) { GRPC_CARES_TRACE_LOG( "WSASocket failed with params af:%d type:%d protocol:%d", af, type, protocol); - return s; - } - grpc_tcp_set_non_block(s); - GrpcPolledFdWindows* polled_fd = + return s; + } + grpc_tcp_set_non_block(s); + GrpcPolledFdWindows* polled_fd = new GrpcPolledFdWindows(s, map->work_serializer_, af, type); GRPC_CARES_TRACE_LOG( "fd:|%s| created with params af:%d type:%d protocol:%d", polled_fd->GetName(), af, type, protocol); - map->AddNewSocket(s, polled_fd); - return s; - } - - static int Connect(ares_socket_t as, const struct sockaddr* target, - ares_socklen_t target_len, void* user_data) { + map->AddNewSocket(s, polled_fd); + return s; + } + + static int Connect(ares_socket_t as, const struct sockaddr* target, + ares_socklen_t target_len, void* user_data) { WSAErrorContext wsa_error_ctx; - SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); - GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as); + SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); + GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as); return polled_fd->Connect(&wsa_error_ctx, target, target_len); - } - - static ares_ssize_t SendV(ares_socket_t as, const struct iovec* iov, - int iovec_count, void* user_data) { + } + + static ares_ssize_t SendV(ares_socket_t as, const struct iovec* iov, + int iovec_count, void* user_data) { WSAErrorContext wsa_error_ctx; - SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); - GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as); + SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); + GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as); return polled_fd->SendV(&wsa_error_ctx, iov, iovec_count); - } - - static ares_ssize_t RecvFrom(ares_socket_t as, void* data, size_t data_len, - int flags, struct sockaddr* from, - ares_socklen_t* from_len, void* user_data) { + } + + static ares_ssize_t RecvFrom(ares_socket_t as, void* data, size_t data_len, + int flags, struct sockaddr* from, + ares_socklen_t* from_len, void* user_data) { WSAErrorContext wsa_error_ctx; - SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); - GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as); + SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); + GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(as); return polled_fd->RecvFrom(&wsa_error_ctx, data, data_len, flags, from, from_len); - } - - static int CloseSocket(SOCKET s, void* user_data) { - SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); - GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(s); - map->RemoveEntry(s); + } + + static int CloseSocket(SOCKET s, void* user_data) { + SockToPolledFdMap* map = static_cast<SockToPolledFdMap*>(user_data); + GrpcPolledFdWindows* polled_fd = map->LookupPolledFd(s); + map->RemoveEntry(s); // See https://github.com/grpc/grpc/pull/20284, this trace log is // intentionally placed to attempt to trigger a crash in case of a // use after free on polled_fd. GRPC_CARES_TRACE_LOG("CloseSocket called for socket: %s", polled_fd->GetName()); - // If a gRPC polled fd has not made it in to the driver's list yet, then - // the driver has not and will never see this socket. - if (!polled_fd->gotten_into_driver_list()) { - polled_fd->ShutdownLocked(GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Shut down c-ares fd before without it ever having made it into the " - "driver's list")); - } + // If a gRPC polled fd has not made it in to the driver's list yet, then + // the driver has not and will never see this socket. + if (!polled_fd->gotten_into_driver_list()) { + polled_fd->ShutdownLocked(GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Shut down c-ares fd before without it ever having made it into the " + "driver's list")); + } delete polled_fd; - return 0; - } - - private: - SockToPolledFdEntry* head_ = nullptr; + return 0; + } + + private: + SockToPolledFdEntry* head_ = nullptr; std::shared_ptr<WorkSerializer> work_serializer_; -}; - -const struct ares_socket_functions custom_ares_sock_funcs = { - &SockToPolledFdMap::Socket /* socket */, - &SockToPolledFdMap::CloseSocket /* close */, - &SockToPolledFdMap::Connect /* connect */, - &SockToPolledFdMap::RecvFrom /* recvfrom */, - &SockToPolledFdMap::SendV /* sendv */, -}; - +}; + +const struct ares_socket_functions custom_ares_sock_funcs = { + &SockToPolledFdMap::Socket /* socket */, + &SockToPolledFdMap::CloseSocket /* close */, + &SockToPolledFdMap::Connect /* connect */, + &SockToPolledFdMap::RecvFrom /* recvfrom */, + &SockToPolledFdMap::SendV /* sendv */, +}; + /* A thin wrapper over a GrpcPolledFdWindows object but with a shorter lifetime. This object releases it's GrpcPolledFdWindows upon destruction, so that c-ares can close it via usual socket teardown. */ @@ -863,37 +863,37 @@ class GrpcPolledFdWindowsWrapper : public GrpcPolledFd { GrpcPolledFdWindows* wrapped_; }; -class GrpcPolledFdFactoryWindows : public GrpcPolledFdFactory { - public: +class GrpcPolledFdFactoryWindows : public GrpcPolledFdFactory { + public: explicit GrpcPolledFdFactoryWindows( std::shared_ptr<WorkSerializer> work_serializer) : sock_to_polled_fd_map_(std::move(work_serializer)) {} - + GrpcPolledFd* NewGrpcPolledFdLocked( ares_socket_t as, grpc_pollset_set* driver_pollset_set, std::shared_ptr<WorkSerializer> work_serializer) override { - GrpcPolledFdWindows* polled_fd = sock_to_polled_fd_map_.LookupPolledFd(as); - // Set a flag so that the virtual socket "close" method knows it - // doesn't need to call ShutdownLocked, since now the driver will. - polled_fd->set_gotten_into_driver_list(); + GrpcPolledFdWindows* polled_fd = sock_to_polled_fd_map_.LookupPolledFd(as); + // Set a flag so that the virtual socket "close" method knows it + // doesn't need to call ShutdownLocked, since now the driver will. + polled_fd->set_gotten_into_driver_list(); return new GrpcPolledFdWindowsWrapper(polled_fd); - } - - void ConfigureAresChannelLocked(ares_channel channel) override { - ares_set_socket_functions(channel, &custom_ares_sock_funcs, - &sock_to_polled_fd_map_); - } - - private: - SockToPolledFdMap sock_to_polled_fd_map_; -}; - + } + + void ConfigureAresChannelLocked(ares_channel channel) override { + ares_set_socket_functions(channel, &custom_ares_sock_funcs, + &sock_to_polled_fd_map_); + } + + private: + SockToPolledFdMap sock_to_polled_fd_map_; +}; + std::unique_ptr<GrpcPolledFdFactory> NewGrpcPolledFdFactory( std::shared_ptr<WorkSerializer> work_serializer) { return y_absl::make_unique<GrpcPolledFdFactoryWindows>( std::move(work_serializer)); -} - -} // namespace grpc_core - -#endif /* GRPC_ARES == 1 && defined(GPR_WINDOWS) */ +} + +} // namespace grpc_core + +#endif /* GRPC_ARES == 1 && defined(GPR_WINDOWS) */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc index c3b236af68..ecbae7e8f3 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc @@ -48,14 +48,14 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/transport/authority_override.h" -using grpc_core::ServerAddress; -using grpc_core::ServerAddressList; - +using grpc_core::ServerAddress; +using grpc_core::ServerAddressList; + grpc_core::TraceFlag grpc_trace_cares_address_sorting(false, "cares_address_sorting"); -grpc_core::TraceFlag grpc_trace_cares_resolver(false, "cares_resolver"); - +grpc_core::TraceFlag grpc_trace_cares_resolver(false, "cares_resolver"); + struct grpc_ares_request { /** indicates the DNS server to use, if specified */ struct ares_addr_port_node dns_server_addr; @@ -71,7 +71,7 @@ struct grpc_ares_request { /** the evernt driver used by this request */ grpc_ares_ev_driver* ev_driver; /** number of ongoing queries */ - size_t pending_queries; + size_t pending_queries; /** the errors explaining query failures, appended to in query callbacks */ grpc_error* error; @@ -80,8 +80,8 @@ struct grpc_ares_request { // TODO(apolcyn): make grpc_ares_hostbyname_request a sub-class // of GrpcAresQuery. typedef struct grpc_ares_hostbyname_request { - /** following members are set in create_hostbyname_request_locked - */ + /** following members are set in create_hostbyname_request_locked + */ /** the top-level request instance */ grpc_ares_request* parent_request; /** host to resolve, parsed from the name to resolve */ @@ -124,7 +124,7 @@ class GrpcAresQuery { static void log_address_sorting_list(const grpc_ares_request* r, const ServerAddressList& addresses, const char* input_output_str) { - for (size_t i = 0; i < addresses.size(); i++) { + for (size_t i = 0; i < addresses.size(); i++) { TString addr_str = grpc_sockaddr_to_string(&addresses[i].address(), true); gpr_log(GPR_INFO, @@ -140,43 +140,43 @@ void grpc_cares_wrapper_address_sorting_sort(const grpc_ares_request* r, log_address_sorting_list(r, *addresses, "input"); } address_sorting_sortable* sortables = (address_sorting_sortable*)gpr_zalloc( - sizeof(address_sorting_sortable) * addresses->size()); - for (size_t i = 0; i < addresses->size(); ++i) { - sortables[i].user_data = &(*addresses)[i]; - memcpy(&sortables[i].dest_addr.addr, &(*addresses)[i].address().addr, - (*addresses)[i].address().len); - sortables[i].dest_addr.len = (*addresses)[i].address().len; - } - address_sorting_rfc_6724_sort(sortables, addresses->size()); - ServerAddressList sorted; - sorted.reserve(addresses->size()); - for (size_t i = 0; i < addresses->size(); ++i) { - sorted.emplace_back(*static_cast<ServerAddress*>(sortables[i].user_data)); + sizeof(address_sorting_sortable) * addresses->size()); + for (size_t i = 0; i < addresses->size(); ++i) { + sortables[i].user_data = &(*addresses)[i]; + memcpy(&sortables[i].dest_addr.addr, &(*addresses)[i].address().addr, + (*addresses)[i].address().len); + sortables[i].dest_addr.len = (*addresses)[i].address().len; + } + address_sorting_rfc_6724_sort(sortables, addresses->size()); + ServerAddressList sorted; + sorted.reserve(addresses->size()); + for (size_t i = 0; i < addresses->size(); ++i) { + sorted.emplace_back(*static_cast<ServerAddress*>(sortables[i].user_data)); } gpr_free(sortables); - *addresses = std::move(sorted); + *addresses = std::move(sorted); if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_address_sorting)) { log_address_sorting_list(r, *addresses, "output"); } } -static void grpc_ares_request_ref_locked(grpc_ares_request* r) { - r->pending_queries++; +static void grpc_ares_request_ref_locked(grpc_ares_request* r) { + r->pending_queries++; } -static void grpc_ares_request_unref_locked(grpc_ares_request* r) { - r->pending_queries--; - if (r->pending_queries == 0u) { - grpc_ares_ev_driver_on_queries_complete_locked(r->ev_driver); - } -} - -void grpc_ares_complete_request_locked(grpc_ares_request* r) { - /* Invoke on_done callback and destroy the +static void grpc_ares_request_unref_locked(grpc_ares_request* r) { + r->pending_queries--; + if (r->pending_queries == 0u) { + grpc_ares_ev_driver_on_queries_complete_locked(r->ev_driver); + } +} + +void grpc_ares_complete_request_locked(grpc_ares_request* r) { + /* Invoke on_done callback and destroy the request */ - r->ev_driver = nullptr; - ServerAddressList* addresses = r->addresses_out->get(); - if (addresses != nullptr) { + r->ev_driver = nullptr; + ServerAddressList* addresses = r->addresses_out->get(); + if (addresses != nullptr) { grpc_cares_wrapper_address_sorting_sort(r, addresses); GRPC_ERROR_UNREF(r->error); r->error = GRPC_ERROR_NONE; @@ -194,7 +194,7 @@ void grpc_ares_complete_request_locked(grpc_ares_request* r) { /* Note that the returned object takes a reference to qtype, so * qtype must outlive it. */ -static grpc_ares_hostbyname_request* create_hostbyname_request_locked( +static grpc_ares_hostbyname_request* create_hostbyname_request_locked( grpc_ares_request* parent_request, const char* host, uint16_t port, bool is_balancer, const char* qtype) { GRPC_CARES_TRACE_LOG( @@ -207,19 +207,19 @@ static grpc_ares_hostbyname_request* create_hostbyname_request_locked( hr->port = port; hr->is_balancer = is_balancer; hr->qtype = qtype; - grpc_ares_request_ref_locked(parent_request); + grpc_ares_request_ref_locked(parent_request); return hr; } -static void destroy_hostbyname_request_locked( - grpc_ares_hostbyname_request* hr) { - grpc_ares_request_unref_locked(hr->parent_request); +static void destroy_hostbyname_request_locked( + grpc_ares_hostbyname_request* hr) { + grpc_ares_request_unref_locked(hr->parent_request); gpr_free(hr->host); delete hr; } static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/, - struct hostent* hostent) { + struct hostent* hostent) { grpc_ares_hostbyname_request* hr = static_cast<grpc_ares_hostbyname_request*>(arg); grpc_ares_request* r = hr->parent_request; @@ -233,47 +233,47 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/, *address_list_ptr = y_absl::make_unique<ServerAddressList>(); } ServerAddressList& addresses = **address_list_ptr; - for (size_t i = 0; hostent->h_addr_list[i] != nullptr; ++i) { + for (size_t i = 0; hostent->h_addr_list[i] != nullptr; ++i) { y_absl::InlinedVector<grpc_arg, 1> args_to_add; - if (hr->is_balancer) { + if (hr->is_balancer) { args_to_add.emplace_back( grpc_core::CreateAuthorityOverrideChannelArg(hr->host)); - } - grpc_channel_args* args = grpc_channel_args_copy_and_add( - nullptr, args_to_add.data(), args_to_add.size()); + } + grpc_channel_args* args = grpc_channel_args_copy_and_add( + nullptr, args_to_add.data(), args_to_add.size()); switch (hostent->h_addrtype) { case AF_INET6: { size_t addr_len = sizeof(struct sockaddr_in6); struct sockaddr_in6 addr; memset(&addr, 0, addr_len); - memcpy(&addr.sin6_addr, hostent->h_addr_list[i], + memcpy(&addr.sin6_addr, hostent->h_addr_list[i], sizeof(struct in6_addr)); - addr.sin6_family = static_cast<unsigned char>(hostent->h_addrtype); + addr.sin6_family = static_cast<unsigned char>(hostent->h_addrtype); addr.sin6_port = hr->port; - addresses.emplace_back(&addr, addr_len, args); + addresses.emplace_back(&addr, addr_len, args); char output[INET6_ADDRSTRLEN]; ares_inet_ntop(AF_INET6, &addr.sin6_addr, output, INET6_ADDRSTRLEN); - GRPC_CARES_TRACE_LOG( - "request:%p c-ares resolver gets a AF_INET6 result: \n" - " addr: %s\n port: %d\n sin6_scope_id: %d\n", - r, output, ntohs(hr->port), addr.sin6_scope_id); + GRPC_CARES_TRACE_LOG( + "request:%p c-ares resolver gets a AF_INET6 result: \n" + " addr: %s\n port: %d\n sin6_scope_id: %d\n", + r, output, ntohs(hr->port), addr.sin6_scope_id); break; } case AF_INET: { size_t addr_len = sizeof(struct sockaddr_in); struct sockaddr_in addr; memset(&addr, 0, addr_len); - memcpy(&addr.sin_addr, hostent->h_addr_list[i], + memcpy(&addr.sin_addr, hostent->h_addr_list[i], sizeof(struct in_addr)); - addr.sin_family = static_cast<unsigned char>(hostent->h_addrtype); + addr.sin_family = static_cast<unsigned char>(hostent->h_addrtype); addr.sin_port = hr->port; - addresses.emplace_back(&addr, addr_len, args); + addresses.emplace_back(&addr, addr_len, args); char output[INET_ADDRSTRLEN]; ares_inet_ntop(AF_INET, &addr.sin_addr, output, INET_ADDRSTRLEN); - GRPC_CARES_TRACE_LOG( - "request:%p c-ares resolver gets a AF_INET result: \n" - " addr: %s\n port: %d\n", - r, output, ntohs(hr->port)); + GRPC_CARES_TRACE_LOG( + "request:%p c-ares resolver gets a AF_INET result: \n" + " addr: %s\n port: %d\n", + r, output, ntohs(hr->port)); break; } } @@ -287,11 +287,11 @@ static void on_hostbyname_done_locked(void* arg, int status, int /*timeouts*/, grpc_error* error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_msg.c_str()); r->error = grpc_error_add_child(error, r->error); } - destroy_hostbyname_request_locked(hr); + destroy_hostbyname_request_locked(hr); } static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/, - unsigned char* abuf, int alen) { + unsigned char* abuf, int alen) { GrpcAresQuery* q = static_cast<GrpcAresQuery*>(arg); grpc_ares_request* r = q->parent_request(); if (status == ARES_SUCCESS) { @@ -303,22 +303,22 @@ static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/, GRPC_CARES_TRACE_LOG("request:%p ares_parse_srv_reply: %d", r, parse_status); if (parse_status == ARES_SUCCESS) { - ares_channel* channel = - grpc_ares_ev_driver_get_channel_locked(r->ev_driver); + ares_channel* channel = + grpc_ares_ev_driver_get_channel_locked(r->ev_driver); for (struct ares_srv_reply* srv_it = reply; srv_it != nullptr; srv_it = srv_it->next) { - if (grpc_ares_query_ipv6()) { - grpc_ares_hostbyname_request* hr = create_hostbyname_request_locked( + if (grpc_ares_query_ipv6()) { + grpc_ares_hostbyname_request* hr = create_hostbyname_request_locked( r, srv_it->host, htons(srv_it->port), true /* is_balancer */, "AAAA"); ares_gethostbyname(*channel, hr->host, AF_INET6, - on_hostbyname_done_locked, hr); + on_hostbyname_done_locked, hr); } - grpc_ares_hostbyname_request* hr = create_hostbyname_request_locked( + grpc_ares_hostbyname_request* hr = create_hostbyname_request_locked( r, srv_it->host, htons(srv_it->port), true /* is_balancer */, "A"); - ares_gethostbyname(*channel, hr->host, AF_INET, - on_hostbyname_done_locked, hr); - grpc_ares_ev_driver_start_locked(r->ev_driver); + ares_gethostbyname(*channel, hr->host, AF_INET, + on_hostbyname_done_locked, hr); + grpc_ares_ev_driver_start_locked(r->ev_driver); } } if (reply != nullptr) { @@ -339,7 +339,7 @@ static void on_srv_query_done_locked(void* arg, int status, int /*timeouts*/, static const char g_service_config_attribute_prefix[] = "grpc_config="; static void on_txt_done_locked(void* arg, int status, int /*timeouts*/, - unsigned char* buf, int len) { + unsigned char* buf, int len) { GrpcAresQuery* q = static_cast<GrpcAresQuery*>(arg); std::unique_ptr<GrpcAresQuery> query_deleter(q); grpc_ares_request* r = q->parent_request(); @@ -377,8 +377,8 @@ static void on_txt_done_locked(void* arg, int status, int /*timeouts*/, service_config_len += result->length; } (*r->service_config_json_out)[service_config_len] = '\0'; - GRPC_CARES_TRACE_LOG("request:%p found service config: %s", r, - *r->service_config_json_out); + GRPC_CARES_TRACE_LOG("request:%p found service config: %s", r, + *r->service_config_json_out); } // Clean up. ares_free_data(reply); @@ -393,9 +393,9 @@ fail: r->error = grpc_error_add_child(error, r->error); } -void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( - grpc_ares_request* r, const char* dns_server, const char* name, - const char* default_port, grpc_pollset_set* interested_parties, +void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( + grpc_ares_request* r, const char* dns_server, const char* name, + const char* default_port, grpc_pollset_set* interested_parties, int query_timeout_ms, std::shared_ptr<grpc_core::WorkSerializer> work_serializer) { grpc_error* error = GRPC_ERROR_NONE; @@ -419,14 +419,14 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( } port = default_port; } - error = grpc_ares_ev_driver_create_locked(&r->ev_driver, interested_parties, + error = grpc_ares_ev_driver_create_locked(&r->ev_driver, interested_parties, query_timeout_ms, std::move(work_serializer), r); if (error != GRPC_ERROR_NONE) goto error_cleanup; - channel = grpc_ares_ev_driver_get_channel_locked(r->ev_driver); + channel = grpc_ares_ev_driver_get_channel_locked(r->ev_driver); // If dns_server is specified, use it. if (dns_server != nullptr) { - GRPC_CARES_TRACE_LOG("request:%p Using DNS server %s", r, dns_server); + GRPC_CARES_TRACE_LOG("request:%p Using DNS server %s", r, dns_server); grpc_resolved_address addr; if (grpc_parse_ipv4_hostport(dns_server, &addr, false /* log_errors */)) { r->dns_server_addr.family = AF_INET; @@ -459,19 +459,19 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( goto error_cleanup; } } - r->pending_queries = 1; - if (grpc_ares_query_ipv6()) { + r->pending_queries = 1; + if (grpc_ares_query_ipv6()) { hr = create_hostbyname_request_locked(r, host.c_str(), grpc_strhtons(port.c_str()), /*is_balancer=*/false, "AAAA"); - ares_gethostbyname(*channel, hr->host, AF_INET6, on_hostbyname_done_locked, - hr); + ares_gethostbyname(*channel, hr->host, AF_INET6, on_hostbyname_done_locked, + hr); } hr = create_hostbyname_request_locked(r, host.c_str(), grpc_strhtons(port.c_str()), /*is_balancer=*/false, "A"); - ares_gethostbyname(*channel, hr->host, AF_INET, on_hostbyname_done_locked, - hr); + ares_gethostbyname(*channel, hr->host, AF_INET, on_hostbyname_done_locked, + hr); if (r->balancer_addresses_out != nullptr) { /* Query the SRV record */ TString service_name = y_absl::StrCat("_grpclb._tcp.", host); @@ -479,85 +479,85 @@ void grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( ares_query(*channel, service_name.c_str(), ns_c_in, ns_t_srv, on_srv_query_done_locked, srv_query); } - if (r->service_config_json_out != nullptr) { + if (r->service_config_json_out != nullptr) { TString config_name = y_absl::StrCat("_grpc_config.", host); GrpcAresQuery* txt_query = new GrpcAresQuery(r, config_name); ares_search(*channel, config_name.c_str(), ns_c_in, ns_t_txt, on_txt_done_locked, txt_query); } - grpc_ares_ev_driver_start_locked(r->ev_driver); - grpc_ares_request_unref_locked(r); - return; + grpc_ares_ev_driver_start_locked(r->ev_driver); + grpc_ares_request_unref_locked(r); + return; error_cleanup: grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_done, error); } -static bool inner_resolve_as_ip_literal_locked( - const char* name, const char* default_port, +static bool inner_resolve_as_ip_literal_locked( + const char* name, const char* default_port, std::unique_ptr<grpc_core::ServerAddressList>* addrs, TString* host, TString* port, TString* hostport) { if (!grpc_core::SplitHostPort(name, host, port)) { - gpr_log(GPR_ERROR, - "Failed to parse %s to host:port while attempting to resolve as ip " - "literal.", - name); - return false; - } + gpr_log(GPR_ERROR, + "Failed to parse %s to host:port while attempting to resolve as ip " + "literal.", + name); + return false; + } if (port->empty()) { - if (default_port == nullptr) { - gpr_log(GPR_ERROR, - "No port or default port for %s while attempting to resolve as " - "ip literal.", - name); - return false; - } + if (default_port == nullptr) { + gpr_log(GPR_ERROR, + "No port or default port for %s while attempting to resolve as " + "ip literal.", + name); + return false; + } *port = default_port; - } - grpc_resolved_address addr; + } + grpc_resolved_address addr; *hostport = grpc_core::JoinHostPort(*host, atoi(port->c_str())); if (grpc_parse_ipv4_hostport(hostport->c_str(), &addr, false /* log errors */) || grpc_parse_ipv6_hostport(hostport->c_str(), &addr, false /* log errors */)) { - GPR_ASSERT(*addrs == nullptr); + GPR_ASSERT(*addrs == nullptr); *addrs = y_absl::make_unique<ServerAddressList>(); - (*addrs)->emplace_back(addr.addr, addr.len, nullptr /* args */); - return true; - } - return false; -} - -static bool resolve_as_ip_literal_locked( - const char* name, const char* default_port, + (*addrs)->emplace_back(addr.addr, addr.len, nullptr /* args */); + return true; + } + return false; +} + +static bool resolve_as_ip_literal_locked( + const char* name, const char* default_port, std::unique_ptr<grpc_core::ServerAddressList>* addrs) { TString host; TString port; TString hostport; - bool out = inner_resolve_as_ip_literal_locked(name, default_port, addrs, - &host, &port, &hostport); - return out; -} - + bool out = inner_resolve_as_ip_literal_locked(name, default_port, addrs, + &host, &port, &hostport); + return out; +} + static bool target_matches_localhost_inner(const char* name, TString* host, TString* port) { if (!grpc_core::SplitHostPort(name, host, port)) { - gpr_log(GPR_ERROR, "Unable to split host and port for name: %s", name); - return false; - } + gpr_log(GPR_ERROR, "Unable to split host and port for name: %s", name); + return false; + } if (gpr_stricmp(host->c_str(), "localhost") == 0) { - return true; - } else { - return false; - } -} - -static bool target_matches_localhost(const char* name) { + return true; + } else { + return false; + } +} + +static bool target_matches_localhost(const char* name) { TString host; TString port; return target_matches_localhost_inner(name, &host, &port); -} - +} + #ifdef GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY static bool inner_maybe_resolve_localhost_manually_locked( const grpc_ares_request* r, const char* name, const char* default_port, @@ -626,70 +626,70 @@ static bool grpc_ares_maybe_resolve_localhost_manually_locked( } #endif /* GRPC_ARES_RESOLVE_LOCALHOST_MANUALLY */ -static grpc_ares_request* grpc_dns_lookup_ares_locked_impl( +static grpc_ares_request* grpc_dns_lookup_ares_locked_impl( const char* dns_server, const char* name, const char* default_port, grpc_pollset_set* interested_parties, grpc_closure* on_done, std::unique_ptr<grpc_core::ServerAddressList>* addrs, std::unique_ptr<grpc_core::ServerAddressList>* balancer_addrs, char** service_config_json, int query_timeout_ms, std::shared_ptr<grpc_core::WorkSerializer> work_serializer) { - grpc_ares_request* r = - static_cast<grpc_ares_request*>(gpr_zalloc(sizeof(grpc_ares_request))); - r->ev_driver = nullptr; - r->on_done = on_done; - r->addresses_out = addrs; + grpc_ares_request* r = + static_cast<grpc_ares_request*>(gpr_zalloc(sizeof(grpc_ares_request))); + r->ev_driver = nullptr; + r->on_done = on_done; + r->addresses_out = addrs; r->balancer_addresses_out = balancer_addrs; - r->service_config_json_out = service_config_json; - r->error = GRPC_ERROR_NONE; - r->pending_queries = 0; - GRPC_CARES_TRACE_LOG( - "request:%p c-ares grpc_dns_lookup_ares_locked_impl name=%s, " - "default_port=%s", - r, name, default_port); - // Early out if the target is an ipv4 or ipv6 literal. - if (resolve_as_ip_literal_locked(name, default_port, addrs)) { - grpc_ares_complete_request_locked(r); - return r; - } - // Early out if the target is localhost and we're on Windows. + r->service_config_json_out = service_config_json; + r->error = GRPC_ERROR_NONE; + r->pending_queries = 0; + GRPC_CARES_TRACE_LOG( + "request:%p c-ares grpc_dns_lookup_ares_locked_impl name=%s, " + "default_port=%s", + r, name, default_port); + // Early out if the target is an ipv4 or ipv6 literal. + if (resolve_as_ip_literal_locked(name, default_port, addrs)) { + grpc_ares_complete_request_locked(r); + return r; + } + // Early out if the target is localhost and we're on Windows. if (grpc_ares_maybe_resolve_localhost_manually_locked(r, name, default_port, - addrs)) { - grpc_ares_complete_request_locked(r); - return r; - } - // Don't query for SRV and TXT records if the target is "localhost", so - // as to cut down on lookups over the network, especially in tests: - // https://github.com/grpc/proposal/pull/79 - if (target_matches_localhost(name)) { + addrs)) { + grpc_ares_complete_request_locked(r); + return r; + } + // Don't query for SRV and TXT records if the target is "localhost", so + // as to cut down on lookups over the network, especially in tests: + // https://github.com/grpc/proposal/pull/79 + if (target_matches_localhost(name)) { r->balancer_addresses_out = nullptr; - r->service_config_json_out = nullptr; - } - // Look up name using c-ares lib. - grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( + r->service_config_json_out = nullptr; + } + // Look up name using c-ares lib. + grpc_dns_lookup_ares_continue_after_check_localhost_and_ip_literals_locked( r, dns_server, name, default_port, interested_parties, query_timeout_ms, std::move(work_serializer)); - return r; -} + return r; +} -grpc_ares_request* (*grpc_dns_lookup_ares_locked)( - const char* dns_server, const char* name, const char* default_port, - grpc_pollset_set* interested_parties, grpc_closure* on_done, +grpc_ares_request* (*grpc_dns_lookup_ares_locked)( + const char* dns_server, const char* name, const char* default_port, + grpc_pollset_set* interested_parties, grpc_closure* on_done, std::unique_ptr<grpc_core::ServerAddressList>* addrs, std::unique_ptr<grpc_core::ServerAddressList>* balancer_addrs, char** service_config_json, int query_timeout_ms, std::shared_ptr<grpc_core::WorkSerializer> work_serializer) = grpc_dns_lookup_ares_locked_impl; - -static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) { - GPR_ASSERT(r != nullptr); - if (r->ev_driver != nullptr) { - grpc_ares_ev_driver_shutdown_locked(r->ev_driver); + +static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) { + GPR_ASSERT(r != nullptr); + if (r->ev_driver != nullptr) { + grpc_ares_ev_driver_shutdown_locked(r->ev_driver); } } -void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) = - grpc_cancel_ares_request_locked_impl; - +void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) = + grpc_cancel_ares_request_locked_impl; + // ares_library_init and ares_library_cleanup are currently no-op except under // Windows. Calling them may cause race conditions when other parts of the // binary calls these functions concurrently. @@ -719,39 +719,39 @@ typedef struct grpc_resolve_address_ares_request { std::shared_ptr<grpc_core::WorkSerializer> work_serializer; /** the pointer to receive the resolved addresses */ grpc_resolved_addresses** addrs_out; - /** currently resolving addresses */ + /** currently resolving addresses */ std::unique_ptr<ServerAddressList> addresses; /** closure to call when the resolve_address_ares request completes */ grpc_closure* on_resolve_address_done; - /** a closure wrapping on_resolve_address_done, which should be invoked when - the grpc_dns_lookup_ares_locked operation is done. */ - grpc_closure on_dns_lookup_done_locked; - /* target name */ - const char* name; - /* default port to use if none is specified */ - const char* default_port; - /* pollset_set to be driven by */ - grpc_pollset_set* interested_parties; - /* underlying ares_request that the query is performed on */ - grpc_ares_request* ares_request = nullptr; + /** a closure wrapping on_resolve_address_done, which should be invoked when + the grpc_dns_lookup_ares_locked operation is done. */ + grpc_closure on_dns_lookup_done_locked; + /* target name */ + const char* name; + /* default port to use if none is specified */ + const char* default_port; + /* pollset_set to be driven by */ + grpc_pollset_set* interested_parties; + /* underlying ares_request that the query is performed on */ + grpc_ares_request* ares_request = nullptr; } grpc_resolve_address_ares_request; static void on_dns_lookup_done_locked(grpc_resolve_address_ares_request* r, grpc_error* error) { - gpr_free(r->ares_request); + gpr_free(r->ares_request); grpc_resolved_addresses** resolved_addresses = r->addrs_out; - if (r->addresses == nullptr || r->addresses->empty()) { + if (r->addresses == nullptr || r->addresses->empty()) { *resolved_addresses = nullptr; } else { *resolved_addresses = static_cast<grpc_resolved_addresses*>( gpr_zalloc(sizeof(grpc_resolved_addresses))); - (*resolved_addresses)->naddrs = r->addresses->size(); + (*resolved_addresses)->naddrs = r->addresses->size(); (*resolved_addresses)->addrs = static_cast<grpc_resolved_address*>(gpr_zalloc( sizeof(grpc_resolved_address) * (*resolved_addresses)->naddrs)); - for (size_t i = 0; i < (*resolved_addresses)->naddrs; ++i) { - memcpy(&(*resolved_addresses)->addrs[i], &(*r->addresses)[i].address(), - sizeof(grpc_resolved_address)); + for (size_t i = 0; i < (*resolved_addresses)->naddrs; ++i) { + memcpy(&(*resolved_addresses)->addrs[i], &(*r->addresses)[i].address(), + sizeof(grpc_resolved_address)); } } grpc_core::ExecCtx::Run(DEBUG_LOCATION, r->on_resolve_address_done, error); @@ -767,17 +767,17 @@ static void on_dns_lookup_done(void* arg, grpc_error* error) { } static void grpc_resolve_address_invoke_dns_lookup_ares_locked(void* arg) { - grpc_resolve_address_ares_request* r = - static_cast<grpc_resolve_address_ares_request*>(arg); + grpc_resolve_address_ares_request* r = + static_cast<grpc_resolve_address_ares_request*>(arg); GRPC_CLOSURE_INIT(&r->on_dns_lookup_done_locked, on_dns_lookup_done, r, grpc_schedule_on_exec_ctx); - r->ares_request = grpc_dns_lookup_ares_locked( - nullptr /* dns_server */, r->name, r->default_port, r->interested_parties, + r->ares_request = grpc_dns_lookup_ares_locked( + nullptr /* dns_server */, r->name, r->default_port, r->interested_parties, &r->on_dns_lookup_done_locked, &r->addresses, nullptr /* balancer_addresses */, nullptr /* service_config_json */, GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS, r->work_serializer); -} - +} + static void grpc_resolve_address_ares_impl(const char* name, const char* default_port, grpc_pollset_set* interested_parties, @@ -788,9 +788,9 @@ static void grpc_resolve_address_ares_impl(const char* name, r->work_serializer = std::make_shared<grpc_core::WorkSerializer>(); r->addrs_out = addrs; r->on_resolve_address_done = on_done; - r->name = name; - r->default_port = default_port; - r->interested_parties = interested_parties; + r->name = name; + r->default_port = default_port; + r->interested_parties = interested_parties; r->work_serializer->Run( [r]() { grpc_resolve_address_invoke_dns_lookup_ares_locked(r); }, DEBUG_LOCATION); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h index ddce754934..9c3ae6e047 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h @@ -21,25 +21,25 @@ #include <grpc/support/port_platform.h> -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/iomgr/resolve_address.h" #include "src/core/lib/iomgr/work_serializer.h" #define GRPC_DNS_ARES_DEFAULT_QUERY_TIMEOUT_MS 120000 - + extern grpc_core::TraceFlag grpc_trace_cares_address_sorting; -extern grpc_core::TraceFlag grpc_trace_cares_resolver; - +extern grpc_core::TraceFlag grpc_trace_cares_resolver; + #define GRPC_CARES_TRACE_LOG(format, ...) \ do { \ if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_cares_resolver)) { \ gpr_log(GPR_DEBUG, "(c-ares resolver) " format, __VA_ARGS__); \ } \ } while (0) - + typedef struct grpc_ares_request grpc_ares_request; /* Asynchronously resolve \a name. Use \a default_port if a port isn't @@ -59,9 +59,9 @@ extern void (*grpc_resolve_address_ares)(const char* name, port in \a name. grpc_ares_init() must be called at least once before this function. \a on_done may be called directly in this function without being scheduled with \a exec_ctx, so it must not try to acquire locks that are - being held by the caller. The returned grpc_ares_request object is owned - by the caller and it is safe to free after on_done is called back. */ -extern grpc_ares_request* (*grpc_dns_lookup_ares_locked)( + being held by the caller. The returned grpc_ares_request object is owned + by the caller and it is safe to free after on_done is called back. */ +extern grpc_ares_request* (*grpc_dns_lookup_ares_locked)( const char* dns_server, const char* name, const char* default_port, grpc_pollset_set* interested_parties, grpc_closure* on_done, std::unique_ptr<grpc_core::ServerAddressList>* addresses, @@ -70,7 +70,7 @@ extern grpc_ares_request* (*grpc_dns_lookup_ares_locked)( std::shared_ptr<grpc_core::WorkSerializer> work_serializer); /* Cancel the pending grpc_ares_request \a request */ -extern void (*grpc_cancel_ares_request_locked)(grpc_ares_request* request); +extern void (*grpc_cancel_ares_request_locked)(grpc_ares_request* request); /* Initialize gRPC ares wrapper. Must be called at least once before grpc_resolve_address_ares(). */ @@ -81,17 +81,17 @@ grpc_error* grpc_ares_init(void); it has been called the same number of times as grpc_ares_init(). */ void grpc_ares_cleanup(void); -/** Schedules the desired callback for request completion - * and destroys the grpc_ares_request */ -void grpc_ares_complete_request_locked(grpc_ares_request* request); +/** Schedules the desired callback for request completion + * and destroys the grpc_ares_request */ +void grpc_ares_complete_request_locked(grpc_ares_request* request); -/* Indicates whether or not AAAA queries should be attempted. */ -/* E.g., return false if ipv6 is known to not be available. */ -bool grpc_ares_query_ipv6(); - -/* Sorts destinations in lb_addrs according to RFC 6724. */ -void grpc_cares_wrapper_address_sorting_sort( +/* Indicates whether or not AAAA queries should be attempted. */ +/* E.g., return false if ipv6 is known to not be available. */ +bool grpc_ares_query_ipv6(); + +/* Sorts destinations in lb_addrs according to RFC 6724. */ +void grpc_cares_wrapper_address_sorting_sort( const grpc_ares_request* request, grpc_core::ServerAddressList* addresses); - + #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_DNS_C_ARES_GRPC_ARES_WRAPPER_H \ */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc index 2049f37118..c079dea0d1 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_fallback.cc @@ -26,7 +26,7 @@ struct grpc_ares_request { char val; }; -static grpc_ares_request* grpc_dns_lookup_ares_locked_impl( +static grpc_ares_request* grpc_dns_lookup_ares_locked_impl( const char* dns_server, const char* name, const char* default_port, grpc_pollset_set* interested_parties, grpc_closure* on_done, std::unique_ptr<grpc_core::ServerAddressList>* addrs, @@ -36,7 +36,7 @@ static grpc_ares_request* grpc_dns_lookup_ares_locked_impl( return NULL; } -grpc_ares_request* (*grpc_dns_lookup_ares_locked)( +grpc_ares_request* (*grpc_dns_lookup_ares_locked)( const char* dns_server, const char* name, const char* default_port, grpc_pollset_set* interested_parties, grpc_closure* on_done, std::unique_ptr<grpc_core::ServerAddressList>* addrs, @@ -45,11 +45,11 @@ grpc_ares_request* (*grpc_dns_lookup_ares_locked)( std::shared_ptr<grpc_core::WorkSerializer> work_serializer) = grpc_dns_lookup_ares_locked_impl; -static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) {} - -void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) = - grpc_cancel_ares_request_locked_impl; +static void grpc_cancel_ares_request_locked_impl(grpc_ares_request* r) {} +void (*grpc_cancel_ares_request_locked)(grpc_ares_request* r) = + grpc_cancel_ares_request_locked_impl; + grpc_error* grpc_ares_init(void) { return GRPC_ERROR_NONE; } void grpc_ares_cleanup(void) {} diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc index 23c0fec74f..fb2aa4e04f 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc @@ -1,29 +1,29 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" -#if GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) - -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" -#include "src/core/lib/iomgr/socket_utils_posix.h" - -bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); } - -#endif /* GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) */ +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" +#if GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) + +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" +#include "src/core/lib/iomgr/socket_utils_posix.h" + +bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); } + +#endif /* GRPC_ARES == 1 && defined(GRPC_POSIX_SOCKET_ARES_EV_DRIVER) */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc index df11db3624..ae605ce08c 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc @@ -1,34 +1,34 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" #if GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER) - -#include <grpc/support/string_util.h> - -#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" -#include "src/core/ext/filters/client_channel/server_address.h" -#include "src/core/lib/gpr/string.h" + +#include <grpc/support/string_util.h> + +#include "src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.h" +#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/parse_address.h" -#include "src/core/lib/iomgr/socket_windows.h" - -bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); } - +#include "src/core/lib/iomgr/socket_windows.h" + +bool grpc_ares_query_ipv6() { return grpc_ipv6_loopback_available(); } + #endif /* GRPC_ARES == 1 && defined(GRPC_WINDOWS_SOCKET_ARES_EV_DRIVER) */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc index a0e3566190..d96270f2ef 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc @@ -30,7 +30,7 @@ #include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/backoff/backoff.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" @@ -58,8 +58,8 @@ class NativeDnsResolver : public Resolver { void RequestReresolutionLocked() override; - void ResetBackoffLocked() override; - + void ResetBackoffLocked() override; + void ShutdownLocked() override; private: @@ -135,13 +135,13 @@ void NativeDnsResolver::RequestReresolutionLocked() { } } -void NativeDnsResolver::ResetBackoffLocked() { - if (have_next_resolution_timer_) { - grpc_timer_cancel(&next_resolution_timer_); - } - backoff_.Reset(); -} - +void NativeDnsResolver::ResetBackoffLocked() { + if (have_next_resolution_timer_) { + grpc_timer_cancel(&next_resolution_timer_); + } + backoff_.Reset(); +} + void NativeDnsResolver::ShutdownLocked() { shutdown_ = true; if (have_next_resolution_timer_) { @@ -216,7 +216,7 @@ void NativeDnsResolver::OnResolvedLocked(grpc_error* error) { // callback as part of the type system. Ref(DEBUG_LOCATION, "next_resolution_timer").release(); if (timeout > 0) { - gpr_log(GPR_DEBUG, "retrying in %" PRId64 " milliseconds", timeout); + gpr_log(GPR_DEBUG, "retrying in %" PRId64 " milliseconds", timeout); } else { gpr_log(GPR_DEBUG, "retrying immediately"); } @@ -231,7 +231,7 @@ void NativeDnsResolver::OnResolvedLocked(grpc_error* error) { void NativeDnsResolver::MaybeStartResolvingLocked() { // If there is an existing timer, the time it fires is the earliest time we // can start the next resolution. - if (have_next_resolution_timer_) return; + if (have_next_resolution_timer_) return; if (last_resolution_timestamp_ >= 0) { const grpc_millis earliest_next_resolution = last_resolution_timestamp_ + min_time_between_resolutions_; @@ -241,8 +241,8 @@ void NativeDnsResolver::MaybeStartResolvingLocked() { const grpc_millis last_resolution_ago = grpc_core::ExecCtx::Get()->Now() - last_resolution_timestamp_; gpr_log(GPR_DEBUG, - "In cooldown from last resolution (from %" PRId64 - " ms ago). Will resolve again in %" PRId64 " ms", + "In cooldown from last resolution (from %" PRId64 + " ms ago). Will resolve again in %" PRId64 " ms", last_resolution_ago, ms_until_next_resolution); have_next_resolution_timer_ = true; // TODO(roth): We currently deal with this ref manually. Once the diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc index 792146ed04..a47f0a12ea 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc @@ -29,10 +29,10 @@ #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/resolver_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" -#include "src/core/lib/gpr/useful.h" +#include "src/core/lib/gpr/useful.h" #include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/parse_address.h" #include "src/core/lib/iomgr/resolve_address.h" @@ -280,7 +280,7 @@ void FakeResolverResponseGenerator::SetFailure() { DEBUG_LOCATION); } -void FakeResolverResponseGenerator::SetFailureOnReresolution() { +void FakeResolverResponseGenerator::SetFailureOnReresolution() { RefCountedPtr<FakeResolver> resolver; { MutexLock lock(&mu_); @@ -292,8 +292,8 @@ void FakeResolverResponseGenerator::SetFailureOnReresolution() { false /* immediate */); resolver->work_serializer()->Run([arg]() { arg->SetFailureLocked(); }, DEBUG_LOCATION); -} - +} + void FakeResolverResponseGenerator::SetFakeResolver( RefCountedPtr<FakeResolver> resolver) { MutexLock lock(&mu_); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h index b9fd90c069..7a983bfd1c 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/fake/fake_resolver.h @@ -22,7 +22,7 @@ #include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/error.h" #define GRPC_ARG_FAKE_RESOLVER_RESPONSE_GENERATOR \ "grpc.fake_resolver.response_generator" @@ -64,10 +64,10 @@ class FakeResolverResponseGenerator // Tells the resolver to return a transient failure. void SetFailure(); - // Same as SetFailure(), but instead of returning the error - // immediately, waits for the next call to RequestReresolutionLocked(). - void SetFailureOnReresolution(); - + // Same as SetFailure(), but instead of returning the error + // immediately, waits for the next call to RequestReresolutionLocked(). + void SetFailureOnReresolution(); + // Returns a channel arg containing \a generator. static grpc_arg MakeChannelArg(FakeResolverResponseGenerator* generator); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc index b52bd8afba..885f5ad6ca 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc @@ -27,7 +27,7 @@ #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/resolver_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/parse_address.h" @@ -58,7 +58,7 @@ class SockaddrResolver : public Resolver { SockaddrResolver::SockaddrResolver(ServerAddressList addresses, ResolverArgs args) : Resolver(std::move(args.work_serializer), std::move(args.result_handler)), - addresses_(std::move(addresses)), + addresses_(std::move(addresses)), channel_args_(grpc_channel_args_copy(args.args)) {} SockaddrResolver::~SockaddrResolver() { @@ -95,15 +95,15 @@ bool ParseUri(const grpc_uri* uri, grpc_slice_buffer_init(&path_parts); grpc_slice_split(path_slice, ",", &path_parts); bool errors_found = false; - for (size_t i = 0; i < path_parts.count; i++) { + for (size_t i = 0; i < path_parts.count; i++) { grpc_uri ith_uri = *uri; grpc_core::UniquePtr<char> part_str( grpc_slice_to_c_string(path_parts.slices[i])); - ith_uri.path = part_str.get(); - grpc_resolved_address addr; - if (!parse(&ith_uri, &addr)) { + ith_uri.path = part_str.get(); + grpc_resolved_address addr; + if (!parse(&ith_uri, &addr)) { errors_found = true; - break; + break; } if (addresses != nullptr) { addresses->emplace_back(addr, nullptr /* args */); diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h index d8dd801ae0..7b9de4e649 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_factory.h @@ -27,7 +27,7 @@ #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/gprpp/orphanable.h" #include "src/core/lib/iomgr/pollset_set.h" -#include "src/core/lib/uri/uri_parser.h" +#include "src/core/lib/uri/uri_parser.h" namespace grpc_core { diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc index e800b1e8f3..8d3e15cee7 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.cc @@ -1,68 +1,68 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/resolver_result_parsing.h" - -#include <ctype.h> -#include <stdio.h> -#include <string.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/resolver_result_parsing.h" + +#include <ctype.h> +#include <stdio.h> +#include <string.h> + #include "y_absl/strings/str_cat.h" #include "y_absl/types/optional.h" -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -#include "src/core/ext/filters/client_channel/client_channel.h" -#include "src/core/ext/filters/client_channel/lb_policy_registry.h" -#include "src/core/ext/filters/client_channel/server_address.h" +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +#include "src/core/ext/filters/client_channel/client_channel.h" +#include "src/core/ext/filters/client_channel/lb_policy_registry.h" +#include "src/core/ext/filters/client_channel/server_address.h" #include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/channel/status_util.h" -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/channel/status_util.h" +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/gprpp/memory.h" #include "src/core/lib/json/json_util.h" -#include "src/core/lib/uri/uri_parser.h" - -// As per the retry design, we do not allow more than 5 retry attempts. -#define MAX_MAX_RETRY_ATTEMPTS 5 - -namespace grpc_core { -namespace internal { - +#include "src/core/lib/uri/uri_parser.h" + +// As per the retry design, we do not allow more than 5 retry attempts. +#define MAX_MAX_RETRY_ATTEMPTS 5 + +namespace grpc_core { +namespace internal { + namespace { size_t g_client_channel_service_config_parser_index; -} - +} + size_t ClientChannelServiceConfigParser::ParserIndex() { return g_client_channel_service_config_parser_index; -} - +} + void ClientChannelServiceConfigParser::Register() { g_client_channel_service_config_parser_index = ServiceConfigParser::RegisterParser( y_absl::make_unique<ClientChannelServiceConfigParser>()); -} - -namespace { - +} + +namespace { + std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy( const Json& json, grpc_error** error) { GPR_DEBUG_ASSERT(error != nullptr && *error == GRPC_ERROR_NONE); @@ -87,11 +87,11 @@ std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy( error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "field:maxAttempts error:should be at least 2")); } else if (retry_policy->max_attempts > MAX_MAX_RETRY_ATTEMPTS) { - gpr_log(GPR_ERROR, - "service config: clamped retryPolicy.maxAttempts at %d", - MAX_MAX_RETRY_ATTEMPTS); - retry_policy->max_attempts = MAX_MAX_RETRY_ATTEMPTS; - } + gpr_log(GPR_ERROR, + "service config: clamped retryPolicy.maxAttempts at %d", + MAX_MAX_RETRY_ATTEMPTS); + retry_policy->max_attempts = MAX_MAX_RETRY_ATTEMPTS; + } } } // Parse initialBackoff. @@ -147,22 +147,22 @@ std::unique_ptr<ClientChannelMethodParsedConfig::RetryPolicy> ParseRetryPolicy( "string")); continue; } - grpc_status_code status; + grpc_status_code status; if (!grpc_status_code_from_string(element.string_value().c_str(), &status)) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "field:retryableStatusCodes error:failed to parse status code")); continue; - } - retry_policy->retryable_status_codes.Add(status); - } + } + retry_policy->retryable_status_codes.Add(status); + } if (retry_policy->retryable_status_codes.Empty()) { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "field:retryableStatusCodes error:should be non-empty")); }; - } - } - // Make sure required fields are set. + } + } + // Make sure required fields are set. if (error_list.empty()) { if (retry_policy->max_attempts == 0 || retry_policy->initial_backoff == 0 || retry_policy->max_backoff == 0 || @@ -261,8 +261,8 @@ const char* ParseHealthCheckConfig(const Json& field, grpc_error** error) { if (field.type() != Json::Type::OBJECT) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "field:healthCheckConfig error:should be of type object"); - return nullptr; - } + return nullptr; + } std::vector<grpc_error*> error_list; auto it = field.object_value().find("serviceName"); if (it != field.object_value().end()) { @@ -279,10 +279,10 @@ const char* ParseHealthCheckConfig(const Json& field, grpc_error** error) { *error = GRPC_ERROR_CREATE_FROM_VECTOR("field:healthCheckConfig", &error_list); return service_name; -} - -} // namespace - +} + +} // namespace + std::unique_ptr<ServiceConfigParser::ParsedConfig> ClientChannelServiceConfigParser::ParseGlobalParams( const grpc_channel_args* /*args*/, const Json& json, grpc_error** error) { @@ -380,8 +380,8 @@ ClientChannelServiceConfigParser::ParsePerMethodParams( } else { error_list.push_back(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "field:waitForReady error:Type should be true/false")); - } - } + } + } // Parse timeout. it = json.object_value().find("timeout"); if (it != json.object_value().end()) { @@ -405,7 +405,7 @@ ClientChannelServiceConfigParser::ParsePerMethodParams( timeout, wait_for_ready, std::move(retry_policy)); } return nullptr; -} - -} // namespace internal -} // namespace grpc_core +} + +} // namespace internal +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h index 6149ebe32b..8443fc4bdf 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/resolver_result_parsing.h @@ -1,42 +1,42 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_RESULT_PARSING_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_RESULT_PARSING_H - -#include <grpc/support/port_platform.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_RESULT_PARSING_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_RESULT_PARSING_H + +#include <grpc/support/port_platform.h> + #include "y_absl/types/optional.h" #include "src/core/ext/filters/client_channel/lb_policy.h" #include "src/core/ext/filters/client_channel/lb_policy_factory.h" #include "src/core/ext/filters/client_channel/resolver.h" -#include "src/core/ext/filters/client_channel/retry_throttle.h" +#include "src/core/ext/filters/client_channel/retry_throttle.h" #include "src/core/ext/filters/client_channel/service_config.h" -#include "src/core/lib/channel/status_util.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/iomgr/exec_ctx.h" // for grpc_millis -#include "src/core/lib/json/json.h" - -namespace grpc_core { -namespace internal { - +#include "src/core/lib/channel/status_util.h" +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/iomgr/exec_ctx.h" // for grpc_millis +#include "src/core/lib/json/json.h" + +namespace grpc_core { +namespace internal { + class ClientChannelGlobalParsedConfig : public ServiceConfigParser::ParsedConfig { public: @@ -44,7 +44,7 @@ class ClientChannelGlobalParsedConfig intptr_t max_milli_tokens = 0; intptr_t milli_token_ratio = 0; }; - + ClientChannelGlobalParsedConfig( RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config, TString parsed_deprecated_lb_policy, @@ -54,75 +54,75 @@ class ClientChannelGlobalParsedConfig parsed_deprecated_lb_policy_(std::move(parsed_deprecated_lb_policy)), retry_throttling_(retry_throttling), health_check_service_name_(health_check_service_name) {} - + y_absl::optional<RetryThrottling> retry_throttling() const { return retry_throttling_; } - + RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config() const { return parsed_lb_config_; - } + } const TString& parsed_deprecated_lb_policy() const { return parsed_deprecated_lb_policy_; - } + } const char* health_check_service_name() const { return health_check_service_name_; - } - - private: + } + + private: RefCountedPtr<LoadBalancingPolicy::Config> parsed_lb_config_; TString parsed_deprecated_lb_policy_; y_absl::optional<RetryThrottling> retry_throttling_; const char* health_check_service_name_; -}; - +}; + class ClientChannelMethodParsedConfig : public ServiceConfigParser::ParsedConfig { - public: - struct RetryPolicy { - int max_attempts = 0; - grpc_millis initial_backoff = 0; - grpc_millis max_backoff = 0; - float backoff_multiplier = 0; - StatusCodeSet retryable_status_codes; - }; - + public: + struct RetryPolicy { + int max_attempts = 0; + grpc_millis initial_backoff = 0; + grpc_millis max_backoff = 0; + float backoff_multiplier = 0; + StatusCodeSet retryable_status_codes; + }; + ClientChannelMethodParsedConfig(grpc_millis timeout, const y_absl::optional<bool>& wait_for_ready, std::unique_ptr<RetryPolicy> retry_policy) : timeout_(timeout), wait_for_ready_(wait_for_ready), retry_policy_(std::move(retry_policy)) {} - - grpc_millis timeout() const { return timeout_; } + + grpc_millis timeout() const { return timeout_; } y_absl::optional<bool> wait_for_ready() const { return wait_for_ready_; } - const RetryPolicy* retry_policy() const { return retry_policy_.get(); } - - private: + const RetryPolicy* retry_policy() const { return retry_policy_.get(); } + + private: grpc_millis timeout_ = 0; y_absl::optional<bool> wait_for_ready_; std::unique_ptr<RetryPolicy> retry_policy_; }; - + class ClientChannelServiceConfigParser : public ServiceConfigParser::Parser { public: std::unique_ptr<ServiceConfigParser::ParsedConfig> ParseGlobalParams( const grpc_channel_args* /*args*/, const Json& json, grpc_error** error) override; - + std::unique_ptr<ServiceConfigParser::ParsedConfig> ParsePerMethodParams( const grpc_channel_args* /*args*/, const Json& json, grpc_error** error) override; - + static size_t ParserIndex(); static void Register(); -}; - -} // namespace internal -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_RESULT_PARSING_H */ +}; + +} // namespace internal +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_RESOLVER_RESULT_PARSING_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.cc index 89ea1d9055..b7b90858e7 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.cc @@ -1,25 +1,25 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/server_address.h" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/server_address.h" + #include <memory> #include <util/generic/string.h> #include <vector> @@ -29,25 +29,25 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" -namespace grpc_core { - -// -// ServerAddress -// - +namespace grpc_core { + +// +// ServerAddress +// + ServerAddress::ServerAddress( const grpc_resolved_address& address, grpc_channel_args* args, std::map<const char*, std::unique_ptr<AttributeInterface>> attributes) : address_(address), args_(args), attributes_(std::move(attributes)) {} - + ServerAddress::ServerAddress( const void* address, size_t address_len, grpc_channel_args* args, std::map<const char*, std::unique_ptr<AttributeInterface>> attributes) : args_(args), attributes_(std::move(attributes)) { - memcpy(address_.addr, address, address_len); - address_.len = static_cast<socklen_t>(address_len); -} - + memcpy(address_.addr, address, address_len); + address_.len = static_cast<socklen_t>(address_len); +} + ServerAddress::ServerAddress(const ServerAddress& other) : address_(other.address_), args_(grpc_channel_args_copy(other.args_)) { for (const auto& p : other.attributes_) { @@ -117,8 +117,8 @@ int ServerAddress::Cmp(const ServerAddress& other) const { retval = grpc_channel_args_compare(args_, other.args_); if (retval != 0) return retval; return CompareAttributes(attributes_, other.attributes_); -} - +} + const ServerAddress::AttributeInterface* ServerAddress::GetAttribute( const char* key) const { auto it = attributes_.find(key); @@ -158,4 +158,4 @@ TString ServerAddress::ToString() const { return y_absl::StrJoin(parts, " "); } -} // namespace grpc_core +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.h index f9359730fa..83041cf282 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/server_address.h @@ -1,45 +1,45 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVER_ADDRESS_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVER_ADDRESS_H - -#include <grpc/support/port_platform.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVER_ADDRESS_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVER_ADDRESS_H + +#include <grpc/support/port_platform.h> + #include <map> #include <memory> #include "y_absl/container/inlined_vector.h" -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/iomgr/resolve_address.h" - -namespace grpc_core { - -// -// ServerAddress -// - -// A server address is a grpc_resolved_address with an associated set of -// channel args. Any args present here will be merged into the channel -// args when a subchannel is created for this address. -class ServerAddress { - public: +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/iomgr/resolve_address.h" + +namespace grpc_core { + +// +// ServerAddress +// + +// A server address is a grpc_resolved_address with an associated set of +// channel args. Any args present here will be merged into the channel +// args when a subchannel is created for this address. +class ServerAddress { + public: // Base class for resolver-supplied attributes. // Unlike channel args, these attributes don't affect subchannel // uniqueness or behavior. They are for use by LB policies only. @@ -61,32 +61,32 @@ class ServerAddress { virtual TString ToString() const = 0; }; - // Takes ownership of args. + // Takes ownership of args. ServerAddress(const grpc_resolved_address& address, grpc_channel_args* args, std::map<const char*, std::unique_ptr<AttributeInterface>> attributes = {}); - ServerAddress(const void* address, size_t address_len, + ServerAddress(const void* address, size_t address_len, grpc_channel_args* args, std::map<const char*, std::unique_ptr<AttributeInterface>> attributes = {}); - - ~ServerAddress() { grpc_channel_args_destroy(args_); } - - // Copyable. + + ~ServerAddress() { grpc_channel_args_destroy(args_); } + + // Copyable. ServerAddress(const ServerAddress& other); ServerAddress& operator=(const ServerAddress& other); - - // Movable. + + // Movable. ServerAddress(ServerAddress&& other) noexcept; ServerAddress& operator=(ServerAddress&& other) noexcept; - + bool operator==(const ServerAddress& other) const { return Cmp(other) == 0; } - + int Cmp(const ServerAddress& other) const; - const grpc_resolved_address& address() const { return address_; } - const grpc_channel_args* args() const { return args_; } - + const grpc_resolved_address& address() const { return address_; } + const grpc_channel_args* args() const { return args_; } + const AttributeInterface* GetAttribute(const char* key) const; // Returns a copy of the address with a modified attribute. @@ -96,22 +96,22 @@ class ServerAddress { TString ToString() const; - private: + private: // Allows the channel to access the attributes without knowing the keys. // (We intentionally do not allow LB policies to do this.) friend class ChannelServerAddressPeer; - grpc_resolved_address address_; - grpc_channel_args* args_; + grpc_resolved_address address_; + grpc_channel_args* args_; std::map<const char*, std::unique_ptr<AttributeInterface>> attributes_; -}; - -// -// ServerAddressList -// - +}; + +// +// ServerAddressList +// + typedef y_absl::InlinedVector<ServerAddress, 1> ServerAddressList; - -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVER_ADDRESS_H */ + +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SERVER_ADDRESS_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc index 39800681e0..7fbc21e848 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.cc @@ -32,15 +32,15 @@ #include <grpc/support/string_util.h> #include "src/core/ext/filters/client_channel/client_channel.h" -#include "src/core/ext/filters/client_channel/health/health_check_client.h" +#include "src/core/ext/filters/client_channel/health/health_check_client.h" #include "src/core/ext/filters/client_channel/proxy_mapper_registry.h" #include "src/core/ext/filters/client_channel/service_config.h" -#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" +#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" #include "src/core/lib/backoff/backoff.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/connected_channel.h" #include "src/core/lib/debug/stats.h" -#include "src/core/lib/gpr/alloc.h" +#include "src/core/lib/gpr/alloc.h" #include "src/core/lib/gprpp/debug_location.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" @@ -52,71 +52,71 @@ #include "src/core/lib/surface/channel.h" #include "src/core/lib/surface/channel_init.h" #include "src/core/lib/transport/connectivity_state.h" -#include "src/core/lib/transport/error_utils.h" -#include "src/core/lib/transport/status_metadata.h" -#include "src/core/lib/uri/uri_parser.h" +#include "src/core/lib/transport/error_utils.h" +#include "src/core/lib/transport/status_metadata.h" +#include "src/core/lib/uri/uri_parser.h" -// Strong and weak refs. +// Strong and weak refs. #define INTERNAL_REF_BITS 16 #define STRONG_REF_MASK (~(gpr_atm)((1 << INTERNAL_REF_BITS) - 1)) -// Backoff parameters. +// Backoff parameters. #define GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS 1 #define GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER 1.6 #define GRPC_SUBCHANNEL_RECONNECT_MIN_TIMEOUT_SECONDS 20 #define GRPC_SUBCHANNEL_RECONNECT_MAX_BACKOFF_SECONDS 120 #define GRPC_SUBCHANNEL_RECONNECT_JITTER 0.2 -// Conversion between subchannel call and call stack. -#define SUBCHANNEL_CALL_TO_CALL_STACK(call) \ - (grpc_call_stack*)((char*)(call) + \ - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall))) -#define CALL_STACK_TO_SUBCHANNEL_CALL(callstack) \ - (SubchannelCall*)(((char*)(call_stack)) - \ - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall))) +// Conversion between subchannel call and call stack. +#define SUBCHANNEL_CALL_TO_CALL_STACK(call) \ + (grpc_call_stack*)((char*)(call) + \ + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall))) +#define CALL_STACK_TO_SUBCHANNEL_CALL(callstack) \ + (SubchannelCall*)(((char*)(call_stack)) - \ + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall))) -namespace grpc_core { +namespace grpc_core { TraceFlag grpc_trace_subchannel(false, "subchannel"); DebugOnlyTraceFlag grpc_trace_subchannel_refcount(false, "subchannel_refcount"); -// -// ConnectedSubchannel -// +// +// ConnectedSubchannel +// -ConnectedSubchannel::ConnectedSubchannel( - grpc_channel_stack* channel_stack, const grpc_channel_args* args, +ConnectedSubchannel::ConnectedSubchannel( + grpc_channel_stack* channel_stack, const grpc_channel_args* args, RefCountedPtr<channelz::SubchannelNode> channelz_subchannel) : RefCounted<ConnectedSubchannel>(&grpc_trace_subchannel_refcount), - channel_stack_(channel_stack), - args_(grpc_channel_args_copy(args)), + channel_stack_(channel_stack), + args_(grpc_channel_args_copy(args)), channelz_subchannel_(std::move(channelz_subchannel)) {} -ConnectedSubchannel::~ConnectedSubchannel() { - grpc_channel_args_destroy(args_); - GRPC_CHANNEL_STACK_UNREF(channel_stack_, "connected_subchannel_dtor"); -} +ConnectedSubchannel::~ConnectedSubchannel() { + grpc_channel_args_destroy(args_); + GRPC_CHANNEL_STACK_UNREF(channel_stack_, "connected_subchannel_dtor"); +} void ConnectedSubchannel::StartWatch( grpc_pollset_set* interested_parties, OrphanablePtr<ConnectivityStateWatcherInterface> watcher) { - grpc_transport_op* op = grpc_make_transport_op(nullptr); + grpc_transport_op* op = grpc_make_transport_op(nullptr); op->start_connectivity_watch = std::move(watcher); op->start_connectivity_watch_state = GRPC_CHANNEL_READY; - op->bind_pollset_set = interested_parties; + op->bind_pollset_set = interested_parties; grpc_channel_element* elem = grpc_channel_stack_element(channel_stack_, 0); - elem->filter->start_transport_op(elem, op); -} - -void ConnectedSubchannel::Ping(grpc_closure* on_initiate, - grpc_closure* on_ack) { - grpc_transport_op* op = grpc_make_transport_op(nullptr); - grpc_channel_element* elem; - op->send_ping.on_initiate = on_initiate; - op->send_ping.on_ack = on_ack; - elem = grpc_channel_stack_element(channel_stack_, 0); - elem->filter->start_transport_op(elem, op); -} + elem->filter->start_transport_op(elem, op); +} + +void ConnectedSubchannel::Ping(grpc_closure* on_initiate, + grpc_closure* on_ack) { + grpc_transport_op* op = grpc_make_transport_op(nullptr); + grpc_channel_element* elem; + op->send_ping.on_initiate = on_initiate; + op->send_ping.on_ack = on_ack; + elem = grpc_channel_stack_element(channel_stack_, 0); + elem->filter->start_transport_op(elem, op); +} size_t ConnectedSubchannel::GetInitialCallSizeEstimate( size_t parent_data_size) const { @@ -138,7 +138,7 @@ size_t ConnectedSubchannel::GetInitialCallSizeEstimate( RefCountedPtr<SubchannelCall> SubchannelCall::Create(Args args, grpc_error** error) { - const size_t allocation_size = + const size_t allocation_size = args.connected_subchannel->GetInitialCallSizeEstimate( args.parent_data_size); Arena* arena = args.arena; @@ -150,183 +150,183 @@ SubchannelCall::SubchannelCall(Args args, grpc_error** error) : connected_subchannel_(std::move(args.connected_subchannel)), deadline_(args.deadline) { grpc_call_stack* callstk = SUBCHANNEL_CALL_TO_CALL_STACK(this); - const grpc_call_element_args call_args = { - callstk, /* call_stack */ - nullptr, /* server_transport_data */ - args.context, /* context */ - args.path, /* path */ - args.start_time, /* start_time */ - args.deadline, /* deadline */ - args.arena, /* arena */ - args.call_combiner /* call_combiner */ - }; + const grpc_call_element_args call_args = { + callstk, /* call_stack */ + nullptr, /* server_transport_data */ + args.context, /* context */ + args.path, /* path */ + args.start_time, /* start_time */ + args.deadline, /* deadline */ + args.arena, /* arena */ + args.call_combiner /* call_combiner */ + }; *error = grpc_call_stack_init(connected_subchannel_->channel_stack(), 1, SubchannelCall::Destroy, this, &call_args); - if (GPR_UNLIKELY(*error != GRPC_ERROR_NONE)) { - const char* error_string = grpc_error_string(*error); - gpr_log(GPR_ERROR, "error: %s", error_string); + if (GPR_UNLIKELY(*error != GRPC_ERROR_NONE)) { + const char* error_string = grpc_error_string(*error); + gpr_log(GPR_ERROR, "error: %s", error_string); return; - } - grpc_call_stack_set_pollset_or_pollset_set(callstk, args.pollent); + } + grpc_call_stack_set_pollset_or_pollset_set(callstk, args.pollent); auto* channelz_node = connected_subchannel_->channelz_subchannel(); if (channelz_node != nullptr) { channelz_node->RecordCallStarted(); - } -} - -void SubchannelCall::StartTransportStreamOpBatch( - grpc_transport_stream_op_batch* batch) { - GPR_TIMER_SCOPE("subchannel_call_process_op", 0); - MaybeInterceptRecvTrailingMetadata(batch); - grpc_call_stack* call_stack = SUBCHANNEL_CALL_TO_CALL_STACK(this); - grpc_call_element* top_elem = grpc_call_stack_element(call_stack, 0); - GRPC_CALL_LOG_OP(GPR_INFO, top_elem, batch); - top_elem->filter->start_transport_stream_op_batch(top_elem, batch); -} - -void* SubchannelCall::GetParentData() { - grpc_channel_stack* chanstk = connected_subchannel_->channel_stack(); - return (char*)this + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)) + - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(chanstk->call_stack_size); -} - -grpc_call_stack* SubchannelCall::GetCallStack() { - return SUBCHANNEL_CALL_TO_CALL_STACK(this); -} - -void SubchannelCall::SetAfterCallStackDestroy(grpc_closure* closure) { - GPR_ASSERT(after_call_stack_destroy_ == nullptr); - GPR_ASSERT(closure != nullptr); - after_call_stack_destroy_ = closure; -} - -RefCountedPtr<SubchannelCall> SubchannelCall::Ref() { - IncrementRefCount(); - return RefCountedPtr<SubchannelCall>(this); -} - -RefCountedPtr<SubchannelCall> SubchannelCall::Ref( - const grpc_core::DebugLocation& location, const char* reason) { - IncrementRefCount(location, reason); - return RefCountedPtr<SubchannelCall>(this); -} - -void SubchannelCall::Unref() { - GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), ""); -} + } +} + +void SubchannelCall::StartTransportStreamOpBatch( + grpc_transport_stream_op_batch* batch) { + GPR_TIMER_SCOPE("subchannel_call_process_op", 0); + MaybeInterceptRecvTrailingMetadata(batch); + grpc_call_stack* call_stack = SUBCHANNEL_CALL_TO_CALL_STACK(this); + grpc_call_element* top_elem = grpc_call_stack_element(call_stack, 0); + GRPC_CALL_LOG_OP(GPR_INFO, top_elem, batch); + top_elem->filter->start_transport_stream_op_batch(top_elem, batch); +} + +void* SubchannelCall::GetParentData() { + grpc_channel_stack* chanstk = connected_subchannel_->channel_stack(); + return (char*)this + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(SubchannelCall)) + + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(chanstk->call_stack_size); +} + +grpc_call_stack* SubchannelCall::GetCallStack() { + return SUBCHANNEL_CALL_TO_CALL_STACK(this); +} + +void SubchannelCall::SetAfterCallStackDestroy(grpc_closure* closure) { + GPR_ASSERT(after_call_stack_destroy_ == nullptr); + GPR_ASSERT(closure != nullptr); + after_call_stack_destroy_ = closure; +} + +RefCountedPtr<SubchannelCall> SubchannelCall::Ref() { + IncrementRefCount(); + return RefCountedPtr<SubchannelCall>(this); +} + +RefCountedPtr<SubchannelCall> SubchannelCall::Ref( + const grpc_core::DebugLocation& location, const char* reason) { + IncrementRefCount(location, reason); + return RefCountedPtr<SubchannelCall>(this); +} + +void SubchannelCall::Unref() { + GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), ""); +} void SubchannelCall::Unref(const DebugLocation& /*location*/, const char* reason) { - GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason); -} + GRPC_CALL_STACK_UNREF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason); +} void SubchannelCall::Destroy(void* arg, grpc_error* /*error*/) { - GPR_TIMER_SCOPE("subchannel_call_destroy", 0); - SubchannelCall* self = static_cast<SubchannelCall*>(arg); - // Keep some members before destroying the subchannel call. - grpc_closure* after_call_stack_destroy = self->after_call_stack_destroy_; - RefCountedPtr<ConnectedSubchannel> connected_subchannel = - std::move(self->connected_subchannel_); - // Destroy the subchannel call. - self->~SubchannelCall(); - // Destroy the call stack. This should be after destroying the subchannel - // call, because call->after_call_stack_destroy(), if not null, will free the - // call arena. - grpc_call_stack_destroy(SUBCHANNEL_CALL_TO_CALL_STACK(self), nullptr, - after_call_stack_destroy); - // Automatically reset connected_subchannel. This should be after destroying - // the call stack, because destroying call stack needs access to the channel - // stack. -} - -void SubchannelCall::MaybeInterceptRecvTrailingMetadata( - grpc_transport_stream_op_batch* batch) { - // only intercept payloads with recv trailing. - if (!batch->recv_trailing_metadata) { - return; - } - // only add interceptor is channelz is enabled. - if (connected_subchannel_->channelz_subchannel() == nullptr) { - return; - } - GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, RecvTrailingMetadataReady, - this, grpc_schedule_on_exec_ctx); - // save some state needed for the interception callback. - GPR_ASSERT(recv_trailing_metadata_ == nullptr); - recv_trailing_metadata_ = - batch->payload->recv_trailing_metadata.recv_trailing_metadata; - original_recv_trailing_metadata_ = - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &recv_trailing_metadata_ready_; + GPR_TIMER_SCOPE("subchannel_call_destroy", 0); + SubchannelCall* self = static_cast<SubchannelCall*>(arg); + // Keep some members before destroying the subchannel call. + grpc_closure* after_call_stack_destroy = self->after_call_stack_destroy_; + RefCountedPtr<ConnectedSubchannel> connected_subchannel = + std::move(self->connected_subchannel_); + // Destroy the subchannel call. + self->~SubchannelCall(); + // Destroy the call stack. This should be after destroying the subchannel + // call, because call->after_call_stack_destroy(), if not null, will free the + // call arena. + grpc_call_stack_destroy(SUBCHANNEL_CALL_TO_CALL_STACK(self), nullptr, + after_call_stack_destroy); + // Automatically reset connected_subchannel. This should be after destroying + // the call stack, because destroying call stack needs access to the channel + // stack. +} + +void SubchannelCall::MaybeInterceptRecvTrailingMetadata( + grpc_transport_stream_op_batch* batch) { + // only intercept payloads with recv trailing. + if (!batch->recv_trailing_metadata) { + return; + } + // only add interceptor is channelz is enabled. + if (connected_subchannel_->channelz_subchannel() == nullptr) { + return; + } + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready_, RecvTrailingMetadataReady, + this, grpc_schedule_on_exec_ctx); + // save some state needed for the interception callback. + GPR_ASSERT(recv_trailing_metadata_ == nullptr); + recv_trailing_metadata_ = + batch->payload->recv_trailing_metadata.recv_trailing_metadata; + original_recv_trailing_metadata_ = + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &recv_trailing_metadata_ready_; +} + +namespace { + +// Sets *status based on the rest of the parameters. +void GetCallStatus(grpc_status_code* status, grpc_millis deadline, + grpc_metadata_batch* md_batch, grpc_error* error) { + if (error != GRPC_ERROR_NONE) { + grpc_error_get_status(error, deadline, status, nullptr, nullptr, nullptr); + } else { + if (md_batch->idx.named.grpc_status != nullptr) { + *status = grpc_get_status_code_from_metadata( + md_batch->idx.named.grpc_status->md); + } else { + *status = GRPC_STATUS_UNKNOWN; + } + } + GRPC_ERROR_UNREF(error); } -namespace { - -// Sets *status based on the rest of the parameters. -void GetCallStatus(grpc_status_code* status, grpc_millis deadline, - grpc_metadata_batch* md_batch, grpc_error* error) { - if (error != GRPC_ERROR_NONE) { - grpc_error_get_status(error, deadline, status, nullptr, nullptr, nullptr); - } else { - if (md_batch->idx.named.grpc_status != nullptr) { - *status = grpc_get_status_code_from_metadata( - md_batch->idx.named.grpc_status->md); - } else { - *status = GRPC_STATUS_UNKNOWN; - } - } - GRPC_ERROR_UNREF(error); -} - -} // namespace - -void SubchannelCall::RecvTrailingMetadataReady(void* arg, grpc_error* error) { - SubchannelCall* call = static_cast<SubchannelCall*>(arg); - GPR_ASSERT(call->recv_trailing_metadata_ != nullptr); - grpc_status_code status = GRPC_STATUS_OK; - GetCallStatus(&status, call->deadline_, call->recv_trailing_metadata_, - GRPC_ERROR_REF(error)); - channelz::SubchannelNode* channelz_subchannel = - call->connected_subchannel_->channelz_subchannel(); - GPR_ASSERT(channelz_subchannel != nullptr); - if (status == GRPC_STATUS_OK) { - channelz_subchannel->RecordCallSucceeded(); - } else { - channelz_subchannel->RecordCallFailed(); +} // namespace + +void SubchannelCall::RecvTrailingMetadataReady(void* arg, grpc_error* error) { + SubchannelCall* call = static_cast<SubchannelCall*>(arg); + GPR_ASSERT(call->recv_trailing_metadata_ != nullptr); + grpc_status_code status = GRPC_STATUS_OK; + GetCallStatus(&status, call->deadline_, call->recv_trailing_metadata_, + GRPC_ERROR_REF(error)); + channelz::SubchannelNode* channelz_subchannel = + call->connected_subchannel_->channelz_subchannel(); + GPR_ASSERT(channelz_subchannel != nullptr); + if (status == GRPC_STATUS_OK) { + channelz_subchannel->RecordCallSucceeded(); + } else { + channelz_subchannel->RecordCallFailed(); } Closure::Run(DEBUG_LOCATION, call->original_recv_trailing_metadata_, GRPC_ERROR_REF(error)); } -void SubchannelCall::IncrementRefCount() { - GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), ""); +void SubchannelCall::IncrementRefCount() { + GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), ""); } void SubchannelCall::IncrementRefCount( const grpc_core::DebugLocation& /*location*/, const char* reason) { - GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason); + GRPC_CALL_STACK_REF(SUBCHANNEL_CALL_TO_CALL_STACK(this), reason); } -// -// Subchannel::ConnectedSubchannelStateWatcher -// - -class Subchannel::ConnectedSubchannelStateWatcher +// +// Subchannel::ConnectedSubchannelStateWatcher +// + +class Subchannel::ConnectedSubchannelStateWatcher : public AsyncConnectivityStateWatcherInterface { - public: - // Must be instantiated while holding c->mu. - explicit ConnectedSubchannelStateWatcher(Subchannel* c) : subchannel_(c) { - // Steal subchannel ref for connecting. - GRPC_SUBCHANNEL_WEAK_REF(subchannel_, "state_watcher"); - GRPC_SUBCHANNEL_WEAK_UNREF(subchannel_, "connecting"); - } - - ~ConnectedSubchannelStateWatcher() { - GRPC_SUBCHANNEL_WEAK_UNREF(subchannel_, "state_watcher"); - } - - private: + public: + // Must be instantiated while holding c->mu. + explicit ConnectedSubchannelStateWatcher(Subchannel* c) : subchannel_(c) { + // Steal subchannel ref for connecting. + GRPC_SUBCHANNEL_WEAK_REF(subchannel_, "state_watcher"); + GRPC_SUBCHANNEL_WEAK_UNREF(subchannel_, "connecting"); + } + + ~ConnectedSubchannelStateWatcher() { + GRPC_SUBCHANNEL_WEAK_UNREF(subchannel_, "state_watcher"); + } + + private: void OnConnectivityStateChange(grpc_connectivity_state new_state, const y_absl::Status& status) override { Subchannel* c = subchannel_; @@ -341,11 +341,11 @@ class Subchannel::ConnectedSubchannelStateWatcher "%s. Attempting to reconnect.", c->connected_subchannel_.get(), c, ConnectivityStateName(new_state)); - } + } c->connected_subchannel_.reset(); if (c->channelz_node() != nullptr) { c->channelz_node()->SetChildSocket(nullptr); - } + } // We need to construct our own status if the underlying state was // shutdown since the accompanying status will be StatusCode::OK // otherwise. @@ -357,7 +357,7 @@ class Subchannel::ConnectedSubchannelStateWatcher : status); c->backoff_begun_ = false; c->backoff_.Reset(); - } + } break; } default: { @@ -464,9 +464,9 @@ class Subchannel::HealthWatcherMap::HealthWatcher RefCountedPtr<Subchannel::ConnectivityStateWatcherInterface> watcher) { if (state_ != initial_state) { new AsyncWatcherNotifierLocked(watcher, subchannel_, state_, status_); - } + } watcher_list_.AddWatcherLocked(std::move(watcher)); - } + } void RemoveWatcherLocked( Subchannel::ConnectivityStateWatcherInterface* watcher) { @@ -521,18 +521,18 @@ class Subchannel::HealthWatcherMap::HealthWatcher subchannel_->pollset_set_, subchannel_->channelz_node_, Ref()); } - Subchannel* subchannel_; + Subchannel* subchannel_; grpc_core::UniquePtr<char> health_check_service_name_; - OrphanablePtr<HealthCheckClient> health_check_client_; + OrphanablePtr<HealthCheckClient> health_check_client_; grpc_connectivity_state state_; y_absl::Status status_; ConnectivityStateWatcherList watcher_list_; -}; - -// +}; + +// // Subchannel::HealthWatcherMap -// - +// + void Subchannel::HealthWatcherMap::AddWatcherLocked( Subchannel* subchannel, grpc_connectivity_state initial_state, grpc_core::UniquePtr<char> health_check_service_name, @@ -588,17 +588,17 @@ Subchannel::HealthWatcherMap::CheckConnectivityStateLocked( HealthWatcher* health_watcher = it->second.get(); return health_watcher->state(); } - + void Subchannel::HealthWatcherMap::ShutdownLocked() { map_.clear(); } -// -// Subchannel -// - -namespace { - -BackOff::Options ParseArgsForBackoffValues( - const grpc_channel_args* args, grpc_millis* min_connect_timeout_ms) { +// +// Subchannel +// + +namespace { + +BackOff::Options ParseArgsForBackoffValues( + const grpc_channel_args* args, grpc_millis* min_connect_timeout_ms) { grpc_millis initial_backoff_ms = GRPC_SUBCHANNEL_INITIAL_CONNECT_BACKOFF_SECONDS * 1000; *min_connect_timeout_ms = @@ -635,8 +635,8 @@ BackOff::Options ParseArgsForBackoffValues( } } } - return BackOff::Options() - .set_initial_backoff(initial_backoff_ms) + return BackOff::Options() + .set_initial_backoff(initial_backoff_ms) .set_multiplier(fixed_reconnect_backoff ? 1.0 : GRPC_SUBCHANNEL_RECONNECT_BACKOFF_MULTIPLIER) @@ -645,8 +645,8 @@ BackOff::Options ParseArgsForBackoffValues( .set_max_backoff(max_backoff_ms); } -} // namespace - +} // namespace + void Subchannel::ConnectivityStateWatcherInterface::PushConnectivityStateChange( ConnectivityStateChange state_change) { MutexLock lock(&mu_); @@ -664,16 +664,16 @@ Subchannel::ConnectivityStateWatcherInterface::PopConnectivityStateChange() { Subchannel::Subchannel(SubchannelKey* key, OrphanablePtr<SubchannelConnector> connector, - const grpc_channel_args* args) - : key_(key), + const grpc_channel_args* args) + : key_(key), connector_(std::move(connector)), - backoff_(ParseArgsForBackoffValues(args, &min_connect_timeout_ms_)) { + backoff_(ParseArgsForBackoffValues(args, &min_connect_timeout_ms_)) { GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED(); - gpr_atm_no_barrier_store(&ref_pair_, 1 << INTERNAL_REF_BITS); - pollset_set_ = grpc_pollset_set_create(); + gpr_atm_no_barrier_store(&ref_pair_, 1 << INTERNAL_REF_BITS); + pollset_set_ = grpc_pollset_set_create(); grpc_resolved_address* addr = static_cast<grpc_resolved_address*>(gpr_malloc(sizeof(*addr))); - GetAddressFromSubchannelAddressArg(args, addr); + GetAddressFromSubchannelAddressArg(args, addr); grpc_resolved_address* new_address = nullptr; grpc_channel_args* new_args = nullptr; if (ProxyMapperRegistry::MapAddress(*addr, args, &new_address, &new_args)) { @@ -682,65 +682,65 @@ Subchannel::Subchannel(SubchannelKey* key, addr = new_address; } static const char* keys_to_remove[] = {GRPC_ARG_SUBCHANNEL_ADDRESS}; - grpc_arg new_arg = CreateSubchannelAddressArg(addr); + grpc_arg new_arg = CreateSubchannelAddressArg(addr); gpr_free(addr); - args_ = grpc_channel_args_copy_and_add_and_remove( - new_args != nullptr ? new_args : args, keys_to_remove, + args_ = grpc_channel_args_copy_and_add_and_remove( + new_args != nullptr ? new_args : args, keys_to_remove, GPR_ARRAY_SIZE(keys_to_remove), &new_arg, 1); gpr_free(new_arg.value.string); if (new_args != nullptr) grpc_channel_args_destroy(new_args); - GRPC_CLOSURE_INIT(&on_connecting_finished_, OnConnectingFinished, this, + GRPC_CLOSURE_INIT(&on_connecting_finished_, OnConnectingFinished, this, grpc_schedule_on_exec_ctx); - const grpc_arg* arg = grpc_channel_args_find(args_, GRPC_ARG_ENABLE_CHANNELZ); - const bool channelz_enabled = - grpc_channel_arg_get_bool(arg, GRPC_ENABLE_CHANNELZ_DEFAULT); - arg = grpc_channel_args_find( - args_, GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE); - const grpc_integer_options options = { - GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT, 0, INT_MAX}; - size_t channel_tracer_max_memory = - (size_t)grpc_channel_arg_get_integer(arg, options); - if (channelz_enabled) { - channelz_node_ = MakeRefCounted<channelz::SubchannelNode>( + const grpc_arg* arg = grpc_channel_args_find(args_, GRPC_ARG_ENABLE_CHANNELZ); + const bool channelz_enabled = + grpc_channel_arg_get_bool(arg, GRPC_ENABLE_CHANNELZ_DEFAULT); + arg = grpc_channel_args_find( + args_, GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE); + const grpc_integer_options options = { + GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT, 0, INT_MAX}; + size_t channel_tracer_max_memory = + (size_t)grpc_channel_arg_get_integer(arg, options); + if (channelz_enabled) { + channelz_node_ = MakeRefCounted<channelz::SubchannelNode>( GetTargetAddress(), channel_tracer_max_memory); - channelz_node_->AddTraceEvent( - channelz::ChannelTrace::Severity::Info, - grpc_slice_from_static_string("subchannel created")); - } -} - -Subchannel::~Subchannel() { - if (channelz_node_ != nullptr) { - channelz_node_->AddTraceEvent( - channelz::ChannelTrace::Severity::Info, - grpc_slice_from_static_string("Subchannel destroyed")); + channelz_node_->AddTraceEvent( + channelz::ChannelTrace::Severity::Info, + grpc_slice_from_static_string("subchannel created")); + } +} + +Subchannel::~Subchannel() { + if (channelz_node_ != nullptr) { + channelz_node_->AddTraceEvent( + channelz::ChannelTrace::Severity::Info, + grpc_slice_from_static_string("Subchannel destroyed")); channelz_node_->UpdateConnectivityState(GRPC_CHANNEL_SHUTDOWN); - } - grpc_channel_args_destroy(args_); + } + grpc_channel_args_destroy(args_); connector_.reset(); - grpc_pollset_set_destroy(pollset_set_); + grpc_pollset_set_destroy(pollset_set_); delete key_; } Subchannel* Subchannel::Create(OrphanablePtr<SubchannelConnector> connector, - const grpc_channel_args* args) { + const grpc_channel_args* args) { SubchannelKey* key = new SubchannelKey(args); - SubchannelPoolInterface* subchannel_pool = - SubchannelPoolInterface::GetSubchannelPoolFromChannelArgs(args); - GPR_ASSERT(subchannel_pool != nullptr); - Subchannel* c = subchannel_pool->FindSubchannel(key); - if (c != nullptr) { + SubchannelPoolInterface* subchannel_pool = + SubchannelPoolInterface::GetSubchannelPoolFromChannelArgs(args); + GPR_ASSERT(subchannel_pool != nullptr); + Subchannel* c = subchannel_pool->FindSubchannel(key); + if (c != nullptr) { delete key; - return c; - } + return c; + } c = new Subchannel(key, std::move(connector), args); - // Try to register the subchannel before setting the subchannel pool. - // Otherwise, in case of a registration race, unreffing c in - // RegisterSubchannel() will cause c to be tried to be unregistered, while - // its key maps to a different subchannel. - Subchannel* registered = subchannel_pool->RegisterSubchannel(key, c); - if (registered == c) c->subchannel_pool_ = subchannel_pool->Ref(); - return registered; + // Try to register the subchannel before setting the subchannel pool. + // Otherwise, in case of a registration race, unreffing c in + // RegisterSubchannel() will cause c to be tried to be unregistered, while + // its key maps to a different subchannel. + Subchannel* registered = subchannel_pool->RegisterSubchannel(key, c); + if (registered == c) c->subchannel_pool_ = subchannel_pool->Ref(); + return registered; } void Subchannel::ThrottleKeepaliveTime(int new_keepalive_time) { @@ -762,84 +762,84 @@ void Subchannel::ThrottleKeepaliveTime(int new_keepalive_time) { } } -Subchannel* Subchannel::Ref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { - gpr_atm old_refs; - old_refs = RefMutate((1 << INTERNAL_REF_BITS), - 0 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("STRONG_REF")); - GPR_ASSERT((old_refs & STRONG_REF_MASK) != 0); - return this; +Subchannel* Subchannel::Ref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { + gpr_atm old_refs; + old_refs = RefMutate((1 << INTERNAL_REF_BITS), + 0 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("STRONG_REF")); + GPR_ASSERT((old_refs & STRONG_REF_MASK) != 0); + return this; } -void Subchannel::Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { - gpr_atm old_refs; - // add a weak ref and subtract a strong ref (atomically) - old_refs = RefMutate( - static_cast<gpr_atm>(1) - static_cast<gpr_atm>(1 << INTERNAL_REF_BITS), - 1 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("STRONG_UNREF")); - if ((old_refs & STRONG_REF_MASK) == (1 << INTERNAL_REF_BITS)) { - Disconnect(); +void Subchannel::Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { + gpr_atm old_refs; + // add a weak ref and subtract a strong ref (atomically) + old_refs = RefMutate( + static_cast<gpr_atm>(1) - static_cast<gpr_atm>(1 << INTERNAL_REF_BITS), + 1 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("STRONG_UNREF")); + if ((old_refs & STRONG_REF_MASK) == (1 << INTERNAL_REF_BITS)) { + Disconnect(); } - GRPC_SUBCHANNEL_WEAK_UNREF(this, "strong-unref"); + GRPC_SUBCHANNEL_WEAK_UNREF(this, "strong-unref"); } -Subchannel* Subchannel::WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { - gpr_atm old_refs; - old_refs = RefMutate(1, 0 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("WEAK_REF")); - GPR_ASSERT(old_refs != 0); - return this; +Subchannel* Subchannel::WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { + gpr_atm old_refs; + old_refs = RefMutate(1, 0 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("WEAK_REF")); + GPR_ASSERT(old_refs != 0); + return this; } -namespace { +namespace { void subchannel_destroy(void* arg, grpc_error* /*error*/) { - Subchannel* self = static_cast<Subchannel*>(arg); + Subchannel* self = static_cast<Subchannel*>(arg); delete self; -} +} -} // namespace +} // namespace -void Subchannel::WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { - gpr_atm old_refs; - old_refs = RefMutate(-static_cast<gpr_atm>(1), - 1 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("WEAK_UNREF")); - if (old_refs == 1) { +void Subchannel::WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS) { + gpr_atm old_refs; + old_refs = RefMutate(-static_cast<gpr_atm>(1), + 1 GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE("WEAK_UNREF")); + if (old_refs == 1) { ExecCtx::Run(DEBUG_LOCATION, GRPC_CLOSURE_CREATE(subchannel_destroy, this, grpc_schedule_on_exec_ctx), GRPC_ERROR_NONE); } -} +} Subchannel* Subchannel::RefFromWeakRef() { - for (;;) { - gpr_atm old_refs = gpr_atm_acq_load(&ref_pair_); - if (old_refs >= (1 << INTERNAL_REF_BITS)) { - gpr_atm new_refs = old_refs + (1 << INTERNAL_REF_BITS); - if (gpr_atm_rel_cas(&ref_pair_, old_refs, new_refs)) { - return this; - } + for (;;) { + gpr_atm old_refs = gpr_atm_acq_load(&ref_pair_); + if (old_refs >= (1 << INTERNAL_REF_BITS)) { + gpr_atm new_refs = old_refs + (1 << INTERNAL_REF_BITS); + if (gpr_atm_rel_cas(&ref_pair_, old_refs, new_refs)) { + return this; + } } else { - return nullptr; + return nullptr; } } } -const char* Subchannel::GetTargetAddress() { - const grpc_arg* addr_arg = - grpc_channel_args_find(args_, GRPC_ARG_SUBCHANNEL_ADDRESS); - const char* addr_str = grpc_channel_arg_get_string(addr_arg); - GPR_ASSERT(addr_str != nullptr); // Should have been set by LB policy. - return addr_str; -} - -channelz::SubchannelNode* Subchannel::channelz_node() { - return channelz_node_.get(); -} - +const char* Subchannel::GetTargetAddress() { + const grpc_arg* addr_arg = + grpc_channel_args_find(args_, GRPC_ARG_SUBCHANNEL_ADDRESS); + const char* addr_str = grpc_channel_arg_get_string(addr_arg); + GPR_ASSERT(addr_str != nullptr); // Should have been set by LB policy. + return addr_str; +} + +channelz::SubchannelNode* Subchannel::channelz_node() { + return channelz_node_.get(); +} + grpc_connectivity_state Subchannel::CheckConnectivityState( const char* health_check_service_name, RefCountedPtr<ConnectedSubchannel>* connected_subchannel) { - MutexLock lock(&mu_); + MutexLock lock(&mu_); grpc_connectivity_state state; if (health_check_service_name == nullptr) { state = state_; @@ -850,9 +850,9 @@ grpc_connectivity_state Subchannel::CheckConnectivityState( if (connected_subchannel != nullptr && state == GRPC_CHANNEL_READY) { *connected_subchannel = connected_subchannel_; } - return state; -} - + return state; +} + void Subchannel::WatchConnectivityState( grpc_connectivity_state initial_state, grpc_core::UniquePtr<char> health_check_service_name, @@ -894,173 +894,173 @@ void Subchannel::AttemptToConnect() { MaybeStartConnectingLocked(); } -void Subchannel::ResetBackoff() { - MutexLock lock(&mu_); - backoff_.Reset(); - if (have_retry_alarm_) { - retry_immediately_ = true; - grpc_timer_cancel(&retry_alarm_); - } else { - backoff_begun_ = false; - MaybeStartConnectingLocked(); - } -} - -grpc_arg Subchannel::CreateSubchannelAddressArg( - const grpc_resolved_address* addr) { - return grpc_channel_arg_string_create( - (char*)GRPC_ARG_SUBCHANNEL_ADDRESS, +void Subchannel::ResetBackoff() { + MutexLock lock(&mu_); + backoff_.Reset(); + if (have_retry_alarm_) { + retry_immediately_ = true; + grpc_timer_cancel(&retry_alarm_); + } else { + backoff_begun_ = false; + MaybeStartConnectingLocked(); + } +} + +grpc_arg Subchannel::CreateSubchannelAddressArg( + const grpc_resolved_address* addr) { + return grpc_channel_arg_string_create( + (char*)GRPC_ARG_SUBCHANNEL_ADDRESS, gpr_strdup(addr->len > 0 ? grpc_sockaddr_to_uri(addr).c_str() : "")); -} - -const char* Subchannel::GetUriFromSubchannelAddressArg( - const grpc_channel_args* args) { - const grpc_arg* addr_arg = - grpc_channel_args_find(args, GRPC_ARG_SUBCHANNEL_ADDRESS); - const char* addr_str = grpc_channel_arg_get_string(addr_arg); - GPR_ASSERT(addr_str != nullptr); // Should have been set by LB policy. - return addr_str; -} - -namespace { - -void UriToSockaddr(const char* uri_str, grpc_resolved_address* addr) { - grpc_uri* uri = grpc_uri_parse(uri_str, 0 /* suppress_errors */); - GPR_ASSERT(uri != nullptr); - if (!grpc_parse_uri(uri, addr)) memset(addr, 0, sizeof(*addr)); - grpc_uri_destroy(uri); -} - -} // namespace - -void Subchannel::GetAddressFromSubchannelAddressArg( - const grpc_channel_args* args, grpc_resolved_address* addr) { - const char* addr_uri_str = GetUriFromSubchannelAddressArg(args); - memset(addr, 0, sizeof(*addr)); - if (*addr_uri_str != '\0') { - UriToSockaddr(addr_uri_str, addr); +} + +const char* Subchannel::GetUriFromSubchannelAddressArg( + const grpc_channel_args* args) { + const grpc_arg* addr_arg = + grpc_channel_args_find(args, GRPC_ARG_SUBCHANNEL_ADDRESS); + const char* addr_str = grpc_channel_arg_get_string(addr_arg); + GPR_ASSERT(addr_str != nullptr); // Should have been set by LB policy. + return addr_str; +} + +namespace { + +void UriToSockaddr(const char* uri_str, grpc_resolved_address* addr) { + grpc_uri* uri = grpc_uri_parse(uri_str, 0 /* suppress_errors */); + GPR_ASSERT(uri != nullptr); + if (!grpc_parse_uri(uri, addr)) memset(addr, 0, sizeof(*addr)); + grpc_uri_destroy(uri); +} + +} // namespace + +void Subchannel::GetAddressFromSubchannelAddressArg( + const grpc_channel_args* args, grpc_resolved_address* addr) { + const char* addr_uri_str = GetUriFromSubchannelAddressArg(args); + memset(addr, 0, sizeof(*addr)); + if (*addr_uri_str != '\0') { + UriToSockaddr(addr_uri_str, addr); } } -namespace { - -// Returns a string indicating the subchannel's connectivity state change to -// \a state. -const char* SubchannelConnectivityStateChangeString( - grpc_connectivity_state state) { - switch (state) { - case GRPC_CHANNEL_IDLE: - return "Subchannel state change to IDLE"; - case GRPC_CHANNEL_CONNECTING: - return "Subchannel state change to CONNECTING"; - case GRPC_CHANNEL_READY: - return "Subchannel state change to READY"; - case GRPC_CHANNEL_TRANSIENT_FAILURE: - return "Subchannel state change to TRANSIENT_FAILURE"; - case GRPC_CHANNEL_SHUTDOWN: - return "Subchannel state change to SHUTDOWN"; +namespace { + +// Returns a string indicating the subchannel's connectivity state change to +// \a state. +const char* SubchannelConnectivityStateChangeString( + grpc_connectivity_state state) { + switch (state) { + case GRPC_CHANNEL_IDLE: + return "Subchannel state change to IDLE"; + case GRPC_CHANNEL_CONNECTING: + return "Subchannel state change to CONNECTING"; + case GRPC_CHANNEL_READY: + return "Subchannel state change to READY"; + case GRPC_CHANNEL_TRANSIENT_FAILURE: + return "Subchannel state change to TRANSIENT_FAILURE"; + case GRPC_CHANNEL_SHUTDOWN: + return "Subchannel state change to SHUTDOWN"; } - GPR_UNREACHABLE_CODE(return "UNKNOWN"); -} + GPR_UNREACHABLE_CODE(return "UNKNOWN"); +} -} // namespace +} // namespace // Note: Must be called with a state that is different from the current state. void Subchannel::SetConnectivityStateLocked(grpc_connectivity_state state, const y_absl::Status& status) { state_ = state; status_ = status; - if (channelz_node_ != nullptr) { + if (channelz_node_ != nullptr) { channelz_node_->UpdateConnectivityState(state); - channelz_node_->AddTraceEvent( - channelz::ChannelTrace::Severity::Info, - grpc_slice_from_static_string( - SubchannelConnectivityStateChangeString(state))); + channelz_node_->AddTraceEvent( + channelz::ChannelTrace::Severity::Info, + grpc_slice_from_static_string( + SubchannelConnectivityStateChangeString(state))); } // Notify non-health watchers. watcher_list_.NotifyLocked(this, state, status); // Notify health watchers. health_watcher_map_.NotifyLocked(state, status); -} - -void Subchannel::MaybeStartConnectingLocked() { - if (disconnected_) { - // Don't try to connect if we're already disconnected. - return; - } - if (connecting_) { - // Already connecting: don't restart. - return; - } - if (connected_subchannel_ != nullptr) { - // Already connected: don't restart. - return; - } - connecting_ = true; - GRPC_SUBCHANNEL_WEAK_REF(this, "connecting"); - if (!backoff_begun_) { - backoff_begun_ = true; - ContinueConnectingLocked(); - } else { - GPR_ASSERT(!have_retry_alarm_); - have_retry_alarm_ = true; - const grpc_millis time_til_next = - next_attempt_deadline_ - ExecCtx::Get()->Now(); - if (time_til_next <= 0) { - gpr_log(GPR_INFO, "Subchannel %p: Retry immediately", this); - } else { - gpr_log(GPR_INFO, "Subchannel %p: Retry in %" PRId64 " milliseconds", - this, time_til_next); - } - GRPC_CLOSURE_INIT(&on_retry_alarm_, OnRetryAlarm, this, - grpc_schedule_on_exec_ctx); - grpc_timer_init(&retry_alarm_, next_attempt_deadline_, &on_retry_alarm_); - } -} - -void Subchannel::OnRetryAlarm(void* arg, grpc_error* error) { - Subchannel* c = static_cast<Subchannel*>(arg); +} + +void Subchannel::MaybeStartConnectingLocked() { + if (disconnected_) { + // Don't try to connect if we're already disconnected. + return; + } + if (connecting_) { + // Already connecting: don't restart. + return; + } + if (connected_subchannel_ != nullptr) { + // Already connected: don't restart. + return; + } + connecting_ = true; + GRPC_SUBCHANNEL_WEAK_REF(this, "connecting"); + if (!backoff_begun_) { + backoff_begun_ = true; + ContinueConnectingLocked(); + } else { + GPR_ASSERT(!have_retry_alarm_); + have_retry_alarm_ = true; + const grpc_millis time_til_next = + next_attempt_deadline_ - ExecCtx::Get()->Now(); + if (time_til_next <= 0) { + gpr_log(GPR_INFO, "Subchannel %p: Retry immediately", this); + } else { + gpr_log(GPR_INFO, "Subchannel %p: Retry in %" PRId64 " milliseconds", + this, time_til_next); + } + GRPC_CLOSURE_INIT(&on_retry_alarm_, OnRetryAlarm, this, + grpc_schedule_on_exec_ctx); + grpc_timer_init(&retry_alarm_, next_attempt_deadline_, &on_retry_alarm_); + } +} + +void Subchannel::OnRetryAlarm(void* arg, grpc_error* error) { + Subchannel* c = static_cast<Subchannel*>(arg); // TODO(soheilhy): Once subchannel refcounting is simplified, we can get use // MutexLock instead of ReleasableMutexLock, here. ReleasableMutexLock lock(&c->mu_); - c->have_retry_alarm_ = false; - if (c->disconnected_) { - error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Disconnected", - &error, 1); - } else if (c->retry_immediately_) { - c->retry_immediately_ = false; - error = GRPC_ERROR_NONE; - } else { - GRPC_ERROR_REF(error); - } - if (error == GRPC_ERROR_NONE) { - gpr_log(GPR_INFO, "Failed to connect to channel, retrying"); - c->ContinueConnectingLocked(); + c->have_retry_alarm_ = false; + if (c->disconnected_) { + error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Disconnected", + &error, 1); + } else if (c->retry_immediately_) { + c->retry_immediately_ = false; + error = GRPC_ERROR_NONE; + } else { + GRPC_ERROR_REF(error); + } + if (error == GRPC_ERROR_NONE) { + gpr_log(GPR_INFO, "Failed to connect to channel, retrying"); + c->ContinueConnectingLocked(); lock.Unlock(); - } else { + } else { lock.Unlock(); - GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting"); - } - GRPC_ERROR_UNREF(error); -} + GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting"); + } + GRPC_ERROR_UNREF(error); +} -void Subchannel::ContinueConnectingLocked() { +void Subchannel::ContinueConnectingLocked() { SubchannelConnector::Args args; - args.interested_parties = pollset_set_; - const grpc_millis min_deadline = - min_connect_timeout_ms_ + ExecCtx::Get()->Now(); - next_attempt_deadline_ = backoff_.NextAttemptTime(); - args.deadline = std::max(next_attempt_deadline_, min_deadline); - args.channel_args = args_; + args.interested_parties = pollset_set_; + const grpc_millis min_deadline = + min_connect_timeout_ms_ + ExecCtx::Get()->Now(); + next_attempt_deadline_ = backoff_.NextAttemptTime(); + args.deadline = std::max(next_attempt_deadline_, min_deadline); + args.channel_args = args_; SetConnectivityStateLocked(GRPC_CHANNEL_CONNECTING, y_absl::Status()); connector_->Connect(args, &connecting_result_, &on_connecting_finished_); } -void Subchannel::OnConnectingFinished(void* arg, grpc_error* error) { - auto* c = static_cast<Subchannel*>(arg); +void Subchannel::OnConnectingFinished(void* arg, grpc_error* error) { + auto* c = static_cast<Subchannel*>(arg); const grpc_channel_args* delete_channel_args = c->connecting_result_.channel_args; - GRPC_SUBCHANNEL_WEAK_REF(c, "on_connecting_finished"); + GRPC_SUBCHANNEL_WEAK_REF(c, "on_connecting_finished"); { MutexLock lock(&c->mu_); c->connecting_ = false; @@ -1076,55 +1076,55 @@ void Subchannel::OnConnectingFinished(void* arg, grpc_error* error) { GRPC_SUBCHANNEL_WEAK_UNREF(c, "connecting"); } } - GRPC_SUBCHANNEL_WEAK_UNREF(c, "on_connecting_finished"); + GRPC_SUBCHANNEL_WEAK_UNREF(c, "on_connecting_finished"); grpc_channel_args_destroy(delete_channel_args); } -namespace { +namespace { void ConnectionDestroy(void* arg, grpc_error* /*error*/) { - grpc_channel_stack* stk = static_cast<grpc_channel_stack*>(arg); - grpc_channel_stack_destroy(stk); - gpr_free(stk); + grpc_channel_stack* stk = static_cast<grpc_channel_stack*>(arg); + grpc_channel_stack_destroy(stk); + gpr_free(stk); } -} // namespace - -bool Subchannel::PublishTransportLocked() { - // Construct channel stack. - grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create(); - grpc_channel_stack_builder_set_channel_arguments( - builder, connecting_result_.channel_args); - grpc_channel_stack_builder_set_transport(builder, - connecting_result_.transport); - if (!grpc_channel_init_create_stack(builder, GRPC_CLIENT_SUBCHANNEL)) { - grpc_channel_stack_builder_destroy(builder); - return false; - } - grpc_channel_stack* stk; - grpc_error* error = grpc_channel_stack_builder_finish( - builder, 0, 1, ConnectionDestroy, nullptr, - reinterpret_cast<void**>(&stk)); - if (error != GRPC_ERROR_NONE) { - grpc_transport_destroy(connecting_result_.transport); - gpr_log(GPR_ERROR, "error initializing subchannel stack: %s", - grpc_error_string(error)); - GRPC_ERROR_UNREF(error); - return false; - } +} // namespace + +bool Subchannel::PublishTransportLocked() { + // Construct channel stack. + grpc_channel_stack_builder* builder = grpc_channel_stack_builder_create(); + grpc_channel_stack_builder_set_channel_arguments( + builder, connecting_result_.channel_args); + grpc_channel_stack_builder_set_transport(builder, + connecting_result_.transport); + if (!grpc_channel_init_create_stack(builder, GRPC_CLIENT_SUBCHANNEL)) { + grpc_channel_stack_builder_destroy(builder); + return false; + } + grpc_channel_stack* stk; + grpc_error* error = grpc_channel_stack_builder_finish( + builder, 0, 1, ConnectionDestroy, nullptr, + reinterpret_cast<void**>(&stk)); + if (error != GRPC_ERROR_NONE) { + grpc_transport_destroy(connecting_result_.transport); + gpr_log(GPR_ERROR, "error initializing subchannel stack: %s", + grpc_error_string(error)); + GRPC_ERROR_UNREF(error); + return false; + } RefCountedPtr<channelz::SocketNode> socket = std::move(connecting_result_.socket_node); connecting_result_.Reset(); - if (disconnected_) { - grpc_channel_stack_destroy(stk); - gpr_free(stk); - return false; - } - // Publish. - connected_subchannel_.reset( + if (disconnected_) { + grpc_channel_stack_destroy(stk); + gpr_free(stk); + return false; + } + // Publish. + connected_subchannel_.reset( new ConnectedSubchannel(stk, args_, channelz_node_)); - gpr_log(GPR_INFO, "New connected subchannel at %p for subchannel %p", - connected_subchannel_.get(), this); + gpr_log(GPR_INFO, "New connected subchannel at %p for subchannel %p", + connected_subchannel_.get(), this); if (channelz_node_ != nullptr) { channelz_node_->SetChildSocket(std::move(socket)); } @@ -1133,36 +1133,36 @@ bool Subchannel::PublishTransportLocked() { pollset_set_, MakeOrphanable<ConnectedSubchannelStateWatcher>(this)); // Report initial state. SetConnectivityStateLocked(GRPC_CHANNEL_READY, y_absl::Status()); - return true; + return true; } -void Subchannel::Disconnect() { - // The subchannel_pool is only used once here in this subchannel, so the - // access can be outside of the lock. - if (subchannel_pool_ != nullptr) { - subchannel_pool_->UnregisterSubchannel(key_); - subchannel_pool_.reset(); +void Subchannel::Disconnect() { + // The subchannel_pool is only used once here in this subchannel, so the + // access can be outside of the lock. + if (subchannel_pool_ != nullptr) { + subchannel_pool_->UnregisterSubchannel(key_); + subchannel_pool_.reset(); } - MutexLock lock(&mu_); - GPR_ASSERT(!disconnected_); - disconnected_ = true; + MutexLock lock(&mu_); + GPR_ASSERT(!disconnected_); + disconnected_ = true; connector_.reset(); - connected_subchannel_.reset(); + connected_subchannel_.reset(); health_watcher_map_.ShutdownLocked(); } -gpr_atm Subchannel::RefMutate( - gpr_atm delta, int barrier GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS) { - gpr_atm old_val = barrier ? gpr_atm_full_fetch_add(&ref_pair_, delta) - : gpr_atm_no_barrier_fetch_add(&ref_pair_, delta); -#ifndef NDEBUG +gpr_atm Subchannel::RefMutate( + gpr_atm delta, int barrier GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS) { + gpr_atm old_val = barrier ? gpr_atm_full_fetch_add(&ref_pair_, delta) + : gpr_atm_no_barrier_fetch_add(&ref_pair_, delta); +#ifndef NDEBUG if (grpc_trace_subchannel_refcount.enabled()) { - gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, - "SUBCHANNEL: %p %12s 0x%" PRIxPTR " -> 0x%" PRIxPTR " [%s]", this, - purpose, old_val, old_val + delta, reason); + gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, + "SUBCHANNEL: %p %12s 0x%" PRIxPTR " -> 0x%" PRIxPTR " [%s]", this, + purpose, old_val, old_val + delta, reason); } -#endif - return old_val; +#endif + return old_val; } } // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h index 0ced846c38..3930a27451 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel.h @@ -23,10 +23,10 @@ #include <deque> -#include "src/core/ext/filters/client_channel/client_channel_channelz.h" +#include "src/core/ext/filters/client_channel/client_channel_channelz.h" #include "src/core/ext/filters/client_channel/connector.h" -#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" -#include "src/core/lib/backoff/backoff.h" +#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" +#include "src/core/lib/backoff/backoff.h" #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/gpr/time_precise.h" #include "src/core/lib/gprpp/arena.h" @@ -35,46 +35,46 @@ #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/iomgr/polling_entity.h" -#include "src/core/lib/iomgr/timer.h" +#include "src/core/lib/iomgr/timer.h" #include "src/core/lib/transport/connectivity_state.h" #include "src/core/lib/transport/metadata.h" // Channel arg containing a URI indicating the address to connect to. #define GRPC_ARG_SUBCHANNEL_ADDRESS "grpc.subchannel_address" -// For debugging refcounting. +// For debugging refcounting. #ifndef NDEBUG -#define GRPC_SUBCHANNEL_REF(p, r) (p)->Ref(__FILE__, __LINE__, (r)) +#define GRPC_SUBCHANNEL_REF(p, r) (p)->Ref(__FILE__, __LINE__, (r)) #define GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(p, r) (p)->RefFromWeakRef() -#define GRPC_SUBCHANNEL_UNREF(p, r) (p)->Unref(__FILE__, __LINE__, (r)) -#define GRPC_SUBCHANNEL_WEAK_REF(p, r) (p)->WeakRef(__FILE__, __LINE__, (r)) -#define GRPC_SUBCHANNEL_WEAK_UNREF(p, r) (p)->WeakUnref(__FILE__, __LINE__, (r)) +#define GRPC_SUBCHANNEL_UNREF(p, r) (p)->Unref(__FILE__, __LINE__, (r)) +#define GRPC_SUBCHANNEL_WEAK_REF(p, r) (p)->WeakRef(__FILE__, __LINE__, (r)) +#define GRPC_SUBCHANNEL_WEAK_UNREF(p, r) (p)->WeakUnref(__FILE__, __LINE__, (r)) #define GRPC_SUBCHANNEL_REF_EXTRA_ARGS \ - const char *file, int line, const char *reason -#define GRPC_SUBCHANNEL_REF_REASON reason -#define GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS \ - , GRPC_SUBCHANNEL_REF_EXTRA_ARGS, const char* purpose -#define GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE(x) , file, line, reason, x + const char *file, int line, const char *reason +#define GRPC_SUBCHANNEL_REF_REASON reason +#define GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS \ + , GRPC_SUBCHANNEL_REF_EXTRA_ARGS, const char* purpose +#define GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE(x) , file, line, reason, x #else -#define GRPC_SUBCHANNEL_REF(p, r) (p)->Ref() -#define GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(p, r) (p)->RefFromWeakRef() -#define GRPC_SUBCHANNEL_UNREF(p, r) (p)->Unref() -#define GRPC_SUBCHANNEL_WEAK_REF(p, r) (p)->WeakRef() -#define GRPC_SUBCHANNEL_WEAK_UNREF(p, r) (p)->WeakUnref() +#define GRPC_SUBCHANNEL_REF(p, r) (p)->Ref() +#define GRPC_SUBCHANNEL_REF_FROM_WEAK_REF(p, r) (p)->RefFromWeakRef() +#define GRPC_SUBCHANNEL_UNREF(p, r) (p)->Unref() +#define GRPC_SUBCHANNEL_WEAK_REF(p, r) (p)->WeakRef() +#define GRPC_SUBCHANNEL_WEAK_UNREF(p, r) (p)->WeakUnref() #define GRPC_SUBCHANNEL_REF_EXTRA_ARGS -#define GRPC_SUBCHANNEL_REF_REASON "" -#define GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS -#define GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE(x) +#define GRPC_SUBCHANNEL_REF_REASON "" +#define GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS +#define GRPC_SUBCHANNEL_REF_MUTATE_PURPOSE(x) #endif namespace grpc_core { -class SubchannelCall; - -class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> { +class SubchannelCall; + +class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> { public: - ConnectedSubchannel( - grpc_channel_stack* channel_stack, const grpc_channel_args* args, + ConnectedSubchannel( + grpc_channel_stack* channel_stack, const grpc_channel_args* args, RefCountedPtr<channelz::SubchannelNode> channelz_subchannel); ~ConnectedSubchannel(); @@ -83,25 +83,25 @@ class ConnectedSubchannel : public RefCounted<ConnectedSubchannel> { void Ping(grpc_closure* on_initiate, grpc_closure* on_ack); - grpc_channel_stack* channel_stack() const { return channel_stack_; } - const grpc_channel_args* args() const { return args_; } - channelz::SubchannelNode* channelz_subchannel() const { - return channelz_subchannel_.get(); - } - - size_t GetInitialCallSizeEstimate(size_t parent_data_size) const; - + grpc_channel_stack* channel_stack() const { return channel_stack_; } + const grpc_channel_args* args() const { return args_; } + channelz::SubchannelNode* channelz_subchannel() const { + return channelz_subchannel_.get(); + } + + size_t GetInitialCallSizeEstimate(size_t parent_data_size) const; + private: grpc_channel_stack* channel_stack_; - grpc_channel_args* args_; - // ref counted pointer to the channelz node in this connected subchannel's - // owning subchannel. - RefCountedPtr<channelz::SubchannelNode> channelz_subchannel_; + grpc_channel_args* args_; + // ref counted pointer to the channelz node in this connected subchannel's + // owning subchannel. + RefCountedPtr<channelz::SubchannelNode> channelz_subchannel_; }; -// Implements the interface of RefCounted<>. -class SubchannelCall { - public: +// Implements the interface of RefCounted<>. +class SubchannelCall { + public: struct Args { RefCountedPtr<ConnectedSubchannel> connected_subchannel; grpc_polling_entity* pollent; @@ -115,68 +115,68 @@ class SubchannelCall { }; static RefCountedPtr<SubchannelCall> Create(Args args, grpc_error** error); - // Continues processing a transport stream op batch. - void StartTransportStreamOpBatch(grpc_transport_stream_op_batch* batch); + // Continues processing a transport stream op batch. + void StartTransportStreamOpBatch(grpc_transport_stream_op_batch* batch); - // Returns a pointer to the parent data associated with the subchannel call. - // The data will be of the size specified in \a parent_data_size field of - // the args passed to \a ConnectedSubchannel::CreateCall(). - void* GetParentData(); + // Returns a pointer to the parent data associated with the subchannel call. + // The data will be of the size specified in \a parent_data_size field of + // the args passed to \a ConnectedSubchannel::CreateCall(). + void* GetParentData(); - // Returns the call stack of the subchannel call. - grpc_call_stack* GetCallStack(); + // Returns the call stack of the subchannel call. + grpc_call_stack* GetCallStack(); - // Sets the 'then_schedule_closure' argument for call stack destruction. - // Must be called once per call. - void SetAfterCallStackDestroy(grpc_closure* closure); + // Sets the 'then_schedule_closure' argument for call stack destruction. + // Must be called once per call. + void SetAfterCallStackDestroy(grpc_closure* closure); - // Interface of RefCounted<>. - RefCountedPtr<SubchannelCall> Ref() GRPC_MUST_USE_RESULT; - RefCountedPtr<SubchannelCall> Ref(const DebugLocation& location, - const char* reason) GRPC_MUST_USE_RESULT; - // When refcount drops to 0, destroys itself and the associated call stack, - // but does NOT free the memory because it's in the call arena. - void Unref(); - void Unref(const DebugLocation& location, const char* reason); + // Interface of RefCounted<>. + RefCountedPtr<SubchannelCall> Ref() GRPC_MUST_USE_RESULT; + RefCountedPtr<SubchannelCall> Ref(const DebugLocation& location, + const char* reason) GRPC_MUST_USE_RESULT; + // When refcount drops to 0, destroys itself and the associated call stack, + // but does NOT free the memory because it's in the call arena. + void Unref(); + void Unref(const DebugLocation& location, const char* reason); - static void Destroy(void* arg, grpc_error* error); + static void Destroy(void* arg, grpc_error* error); - private: - // Allow RefCountedPtr<> to access IncrementRefCount(). - template <typename T> - friend class RefCountedPtr; + private: + // Allow RefCountedPtr<> to access IncrementRefCount(). + template <typename T> + friend class RefCountedPtr; SubchannelCall(Args args, grpc_error** error); - // If channelz is enabled, intercepts recv_trailing so that we may check the - // status and associate it to a subchannel. - void MaybeInterceptRecvTrailingMetadata( - grpc_transport_stream_op_batch* batch); + // If channelz is enabled, intercepts recv_trailing so that we may check the + // status and associate it to a subchannel. + void MaybeInterceptRecvTrailingMetadata( + grpc_transport_stream_op_batch* batch); - static void RecvTrailingMetadataReady(void* arg, grpc_error* error); + static void RecvTrailingMetadataReady(void* arg, grpc_error* error); - // Interface of RefCounted<>. - void IncrementRefCount(); - void IncrementRefCount(const DebugLocation& location, const char* reason); + // Interface of RefCounted<>. + void IncrementRefCount(); + void IncrementRefCount(const DebugLocation& location, const char* reason); - RefCountedPtr<ConnectedSubchannel> connected_subchannel_; - grpc_closure* after_call_stack_destroy_ = nullptr; - // State needed to support channelz interception of recv trailing metadata. - grpc_closure recv_trailing_metadata_ready_; - grpc_closure* original_recv_trailing_metadata_ = nullptr; - grpc_metadata_batch* recv_trailing_metadata_ = nullptr; - grpc_millis deadline_; + RefCountedPtr<ConnectedSubchannel> connected_subchannel_; + grpc_closure* after_call_stack_destroy_ = nullptr; + // State needed to support channelz interception of recv trailing metadata. + grpc_closure recv_trailing_metadata_ready_; + grpc_closure* original_recv_trailing_metadata_ = nullptr; + grpc_metadata_batch* recv_trailing_metadata_ = nullptr; + grpc_millis deadline_; }; -// A subchannel that knows how to connect to exactly one target address. It -// provides a target for load balancing. +// A subchannel that knows how to connect to exactly one target address. It +// provides a target for load balancing. // // Note that this is the "real" subchannel implementation, whose API is // different from the SubchannelInterface that is exposed to LB policy // implementations. The client channel provides an adaptor class // (SubchannelWrapper) that "converts" between the two. -class Subchannel { - public: +class Subchannel { + public: class ConnectivityStateWatcherInterface : public RefCounted<ConnectivityStateWatcherInterface> { public: @@ -219,38 +219,38 @@ class Subchannel { Mutex mu_; // protects the queue }; - // The ctor and dtor are not intended to use directly. + // The ctor and dtor are not intended to use directly. Subchannel(SubchannelKey* key, OrphanablePtr<SubchannelConnector> connector, - const grpc_channel_args* args); - ~Subchannel(); + const grpc_channel_args* args); + ~Subchannel(); - // Creates a subchannel given \a connector and \a args. + // Creates a subchannel given \a connector and \a args. static Subchannel* Create(OrphanablePtr<SubchannelConnector> connector, - const grpc_channel_args* args); + const grpc_channel_args* args); // Throttles keepalive time to \a new_keepalive_time iff \a new_keepalive_time // is larger than the subchannel's current keepalive time. The updated value // will have an affect when the subchannel creates a new ConnectedSubchannel. void ThrottleKeepaliveTime(int new_keepalive_time); - // Strong and weak refcounting. - Subchannel* Ref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); - void Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); - Subchannel* WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); - void WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); + // Strong and weak refcounting. + Subchannel* Ref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); + void Unref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); + Subchannel* WeakRef(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); + void WeakUnref(GRPC_SUBCHANNEL_REF_EXTRA_ARGS); // Attempts to return a strong ref when only the weak refcount is guaranteed // non-zero. If the strong refcount is zero, does not alter the refcount and // returns null. Subchannel* RefFromWeakRef(); - // Gets the string representing the subchannel address. - // Caller doesn't take ownership. - const char* GetTargetAddress(); - + // Gets the string representing the subchannel address. + // Caller doesn't take ownership. + const char* GetTargetAddress(); + const grpc_channel_args* channel_args() const { return args_; } - - channelz::SubchannelNode* channelz_node(); - + + channelz::SubchannelNode* channelz_node(); + // Returns the current connectivity state of the subchannel. // If health_check_service_name is non-null, the returned connectivity // state will be based on the state reported by the backend for that @@ -259,7 +259,7 @@ class Subchannel { grpc_connectivity_state CheckConnectivityState( const char* health_check_service_name, RefCountedPtr<ConnectedSubchannel>* connected_subchannel); - + // Starts watching the subchannel's connectivity state. // The first callback to the watcher will be delivered when the // subchannel's connectivity state becomes a value other than @@ -272,7 +272,7 @@ class Subchannel { grpc_connectivity_state initial_state, grpc_core::UniquePtr<char> health_check_service_name, RefCountedPtr<ConnectivityStateWatcherInterface> watcher); - + // Cancels a connectivity state watch. // If the watcher has already been destroyed, this is a no-op. void CancelConnectivityStateWatch(const char* health_check_service_name, @@ -281,26 +281,26 @@ class Subchannel { // Attempt to connect to the backend. Has no effect if already connected. void AttemptToConnect(); - // Resets the connection backoff of the subchannel. - // TODO(roth): Move connection backoff out of subchannels and up into LB - // policy code (probably by adding a SubchannelGroup between - // SubchannelList and SubchannelData), at which point this method can - // go away. - void ResetBackoff(); - - // Returns a new channel arg encoding the subchannel address as a URI - // string. Caller is responsible for freeing the string. - static grpc_arg CreateSubchannelAddressArg(const grpc_resolved_address* addr); - - // Returns the URI string from the subchannel address arg in \a args. - static const char* GetUriFromSubchannelAddressArg( - const grpc_channel_args* args); - - // Sets \a addr from the subchannel address arg in \a args. - static void GetAddressFromSubchannelAddressArg(const grpc_channel_args* args, - grpc_resolved_address* addr); - - private: + // Resets the connection backoff of the subchannel. + // TODO(roth): Move connection backoff out of subchannels and up into LB + // policy code (probably by adding a SubchannelGroup between + // SubchannelList and SubchannelData), at which point this method can + // go away. + void ResetBackoff(); + + // Returns a new channel arg encoding the subchannel address as a URI + // string. Caller is responsible for freeing the string. + static grpc_arg CreateSubchannelAddressArg(const grpc_resolved_address* addr); + + // Returns the URI string from the subchannel address arg in \a args. + static const char* GetUriFromSubchannelAddressArg( + const grpc_channel_args* args); + + // Sets \a addr from the subchannel address arg in \a args. + static void GetAddressFromSubchannelAddressArg(const grpc_channel_args* args, + grpc_resolved_address* addr); + + private: // A linked list of ConnectivityStateWatcherInterfaces that are monitoring // the subchannel's state. class ConnectivityStateWatcherList { @@ -360,80 +360,80 @@ class Subchannel { std::map<const char*, OrphanablePtr<HealthWatcher>, StringLess> map_; }; - class ConnectedSubchannelStateWatcher; - + class ConnectedSubchannelStateWatcher; + class AsyncWatcherNotifierLocked; - // Sets the subchannel's connectivity state to \a state. + // Sets the subchannel's connectivity state to \a state. void SetConnectivityStateLocked(grpc_connectivity_state state, const y_absl::Status& status); - - // Methods for connection. - void MaybeStartConnectingLocked(); - static void OnRetryAlarm(void* arg, grpc_error* error); - void ContinueConnectingLocked(); - static void OnConnectingFinished(void* arg, grpc_error* error); - bool PublishTransportLocked(); - void Disconnect(); - - gpr_atm RefMutate(gpr_atm delta, - int barrier GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS); - - // The subchannel pool this subchannel is in. - RefCountedPtr<SubchannelPoolInterface> subchannel_pool_; - // TODO(juanlishen): Consider using args_ as key_ directly. - // Subchannel key that identifies this subchannel in the subchannel pool. - SubchannelKey* key_; - // Channel args. - grpc_channel_args* args_; - // pollset_set tracking who's interested in a connection being setup. - grpc_pollset_set* pollset_set_; - // Protects the other members. + + // Methods for connection. + void MaybeStartConnectingLocked(); + static void OnRetryAlarm(void* arg, grpc_error* error); + void ContinueConnectingLocked(); + static void OnConnectingFinished(void* arg, grpc_error* error); + bool PublishTransportLocked(); + void Disconnect(); + + gpr_atm RefMutate(gpr_atm delta, + int barrier GRPC_SUBCHANNEL_REF_MUTATE_EXTRA_ARGS); + + // The subchannel pool this subchannel is in. + RefCountedPtr<SubchannelPoolInterface> subchannel_pool_; + // TODO(juanlishen): Consider using args_ as key_ directly. + // Subchannel key that identifies this subchannel in the subchannel pool. + SubchannelKey* key_; + // Channel args. + grpc_channel_args* args_; + // pollset_set tracking who's interested in a connection being setup. + grpc_pollset_set* pollset_set_; + // Protects the other members. Mutex mu_; - // Refcount - // - lower INTERNAL_REF_BITS bits are for internal references: - // these do not keep the subchannel open. - // - upper remaining bits are for public references: these do - // keep the subchannel open - gpr_atm ref_pair_; - - // Connection states. + // Refcount + // - lower INTERNAL_REF_BITS bits are for internal references: + // these do not keep the subchannel open. + // - upper remaining bits are for public references: these do + // keep the subchannel open + gpr_atm ref_pair_; + + // Connection states. OrphanablePtr<SubchannelConnector> connector_; - // Set during connection. + // Set during connection. SubchannelConnector::Result connecting_result_; - grpc_closure on_connecting_finished_; - // Active connection, or null. - RefCountedPtr<ConnectedSubchannel> connected_subchannel_; - bool connecting_ = false; - bool disconnected_ = false; - - // Connectivity state tracking. + grpc_closure on_connecting_finished_; + // Active connection, or null. + RefCountedPtr<ConnectedSubchannel> connected_subchannel_; + bool connecting_ = false; + bool disconnected_ = false; + + // Connectivity state tracking. grpc_connectivity_state state_ = GRPC_CHANNEL_IDLE; y_absl::Status status_; // The list of watchers without a health check service name. ConnectivityStateWatcherList watcher_list_; // The map of watchers with health check service names. HealthWatcherMap health_watcher_map_; - - // Backoff state. - BackOff backoff_; - grpc_millis next_attempt_deadline_; - grpc_millis min_connect_timeout_ms_; - bool backoff_begun_ = false; - - // Retry alarm. - grpc_timer retry_alarm_; - grpc_closure on_retry_alarm_; - bool have_retry_alarm_ = false; - // reset_backoff() was called while alarm was pending. - bool retry_immediately_ = false; + + // Backoff state. + BackOff backoff_; + grpc_millis next_attempt_deadline_; + grpc_millis min_connect_timeout_ms_; + bool backoff_begun_ = false; + + // Retry alarm. + grpc_timer retry_alarm_; + grpc_closure on_retry_alarm_; + bool have_retry_alarm_ = false; + // reset_backoff() was called while alarm was pending. + bool retry_immediately_ = false; // Keepalive time period (-1 for unset) int keepalive_time_ = -1; - - // Channelz tracking. - RefCountedPtr<channelz::SubchannelNode> channelz_node_; -}; - -} // namespace grpc_core - + + // Channelz tracking. + RefCountedPtr<channelz::SubchannelNode> channelz_node_; +}; + +} // namespace grpc_core + #endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.cc b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.cc index bb35f228b7..15d0f6e3be 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.cc +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.cc @@ -1,97 +1,97 @@ -// -// -// Copyright 2018 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" - -#include "src/core/lib/gpr/useful.h" - -// The subchannel pool to reuse subchannels. -#define GRPC_ARG_SUBCHANNEL_POOL "grpc.subchannel_pool" -// The subchannel key ID that is only used in test to make each key unique. -#define GRPC_ARG_SUBCHANNEL_KEY_TEST_ONLY_ID "grpc.subchannel_key_test_only_id" - -namespace grpc_core { - -TraceFlag grpc_subchannel_pool_trace(false, "subchannel_pool"); - -SubchannelKey::SubchannelKey(const grpc_channel_args* args) { - Init(args, grpc_channel_args_normalize); -} - -SubchannelKey::~SubchannelKey() { - grpc_channel_args_destroy(const_cast<grpc_channel_args*>(args_)); -} - -SubchannelKey::SubchannelKey(const SubchannelKey& other) { - Init(other.args_, grpc_channel_args_copy); -} - -SubchannelKey& SubchannelKey::operator=(const SubchannelKey& other) { - grpc_channel_args_destroy(const_cast<grpc_channel_args*>(args_)); - Init(other.args_, grpc_channel_args_copy); - return *this; -} - -int SubchannelKey::Cmp(const SubchannelKey& other) const { - return grpc_channel_args_compare(args_, other.args_); -} - -void SubchannelKey::Init( - const grpc_channel_args* args, - grpc_channel_args* (*copy_channel_args)(const grpc_channel_args* args)) { - args_ = copy_channel_args(args); -} - -namespace { - -void* arg_copy(void* p) { - auto* subchannel_pool = static_cast<SubchannelPoolInterface*>(p); - subchannel_pool->Ref().release(); - return p; -} - -void arg_destroy(void* p) { - auto* subchannel_pool = static_cast<SubchannelPoolInterface*>(p); - subchannel_pool->Unref(); -} - -int arg_cmp(void* a, void* b) { return GPR_ICMP(a, b); } - -const grpc_arg_pointer_vtable subchannel_pool_arg_vtable = { - arg_copy, arg_destroy, arg_cmp}; - -} // namespace - -grpc_arg SubchannelPoolInterface::CreateChannelArg( - SubchannelPoolInterface* subchannel_pool) { - return grpc_channel_arg_pointer_create( - const_cast<char*>(GRPC_ARG_SUBCHANNEL_POOL), subchannel_pool, - &subchannel_pool_arg_vtable); -} - -SubchannelPoolInterface* -SubchannelPoolInterface::GetSubchannelPoolFromChannelArgs( - const grpc_channel_args* args) { - const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_SUBCHANNEL_POOL); - if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr; - return static_cast<SubchannelPoolInterface*>(arg->value.pointer.p); -} - -} // namespace grpc_core +// +// +// Copyright 2018 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/filters/client_channel/subchannel_pool_interface.h" + +#include "src/core/lib/gpr/useful.h" + +// The subchannel pool to reuse subchannels. +#define GRPC_ARG_SUBCHANNEL_POOL "grpc.subchannel_pool" +// The subchannel key ID that is only used in test to make each key unique. +#define GRPC_ARG_SUBCHANNEL_KEY_TEST_ONLY_ID "grpc.subchannel_key_test_only_id" + +namespace grpc_core { + +TraceFlag grpc_subchannel_pool_trace(false, "subchannel_pool"); + +SubchannelKey::SubchannelKey(const grpc_channel_args* args) { + Init(args, grpc_channel_args_normalize); +} + +SubchannelKey::~SubchannelKey() { + grpc_channel_args_destroy(const_cast<grpc_channel_args*>(args_)); +} + +SubchannelKey::SubchannelKey(const SubchannelKey& other) { + Init(other.args_, grpc_channel_args_copy); +} + +SubchannelKey& SubchannelKey::operator=(const SubchannelKey& other) { + grpc_channel_args_destroy(const_cast<grpc_channel_args*>(args_)); + Init(other.args_, grpc_channel_args_copy); + return *this; +} + +int SubchannelKey::Cmp(const SubchannelKey& other) const { + return grpc_channel_args_compare(args_, other.args_); +} + +void SubchannelKey::Init( + const grpc_channel_args* args, + grpc_channel_args* (*copy_channel_args)(const grpc_channel_args* args)) { + args_ = copy_channel_args(args); +} + +namespace { + +void* arg_copy(void* p) { + auto* subchannel_pool = static_cast<SubchannelPoolInterface*>(p); + subchannel_pool->Ref().release(); + return p; +} + +void arg_destroy(void* p) { + auto* subchannel_pool = static_cast<SubchannelPoolInterface*>(p); + subchannel_pool->Unref(); +} + +int arg_cmp(void* a, void* b) { return GPR_ICMP(a, b); } + +const grpc_arg_pointer_vtable subchannel_pool_arg_vtable = { + arg_copy, arg_destroy, arg_cmp}; + +} // namespace + +grpc_arg SubchannelPoolInterface::CreateChannelArg( + SubchannelPoolInterface* subchannel_pool) { + return grpc_channel_arg_pointer_create( + const_cast<char*>(GRPC_ARG_SUBCHANNEL_POOL), subchannel_pool, + &subchannel_pool_arg_vtable); +} + +SubchannelPoolInterface* +SubchannelPoolInterface::GetSubchannelPoolFromChannelArgs( + const grpc_channel_args* args) { + const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_SUBCHANNEL_POOL); + if (arg == nullptr || arg->type != GRPC_ARG_POINTER) return nullptr; + return static_cast<SubchannelPoolInterface*>(arg->value.pointer.p); +} + +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h index 2fe5fa3fd0..3ae98ffae2 100644 --- a/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h +++ b/contrib/libs/grpc/src/core/ext/filters/client_channel/subchannel_pool_interface.h @@ -1,91 +1,91 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_POOL_INTERFACE_H -#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_POOL_INTERFACE_H - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/avl/avl.h" -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/gprpp/ref_counted.h" - -namespace grpc_core { - -class Subchannel; - -extern TraceFlag grpc_subchannel_pool_trace; - -// A key that can uniquely identify a subchannel. -class SubchannelKey { - public: - explicit SubchannelKey(const grpc_channel_args* args); - ~SubchannelKey(); - - // Copyable. - SubchannelKey(const SubchannelKey& other); - SubchannelKey& operator=(const SubchannelKey& other); - // Not movable. - SubchannelKey(SubchannelKey&&) = delete; - SubchannelKey& operator=(SubchannelKey&&) = delete; - - int Cmp(const SubchannelKey& other) const; - - private: - // Initializes the subchannel key with the given \a args and the function to - // copy channel args. - void Init( - const grpc_channel_args* args, - grpc_channel_args* (*copy_channel_args)(const grpc_channel_args* args)); - - const grpc_channel_args* args_; -}; - -// Interface for subchannel pool. -// TODO(juanlishen): This refcounting mechanism may lead to memory leak. -// To solve that, we should force polling to flush any pending callbacks, then -// shut down safely. See https://github.com/grpc/grpc/issues/12560. -class SubchannelPoolInterface : public RefCounted<SubchannelPoolInterface> { - public: - SubchannelPoolInterface() : RefCounted(&grpc_subchannel_pool_trace) {} - virtual ~SubchannelPoolInterface() {} - - // Registers a subchannel against a key. Returns the subchannel registered - // with \a key, which may be different from \a constructed because we reuse - // (instead of update) any existing subchannel already registered with \a key. - virtual Subchannel* RegisterSubchannel(SubchannelKey* key, +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_POOL_INTERFACE_H +#define GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_POOL_INTERFACE_H + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/avl/avl.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/gprpp/ref_counted.h" + +namespace grpc_core { + +class Subchannel; + +extern TraceFlag grpc_subchannel_pool_trace; + +// A key that can uniquely identify a subchannel. +class SubchannelKey { + public: + explicit SubchannelKey(const grpc_channel_args* args); + ~SubchannelKey(); + + // Copyable. + SubchannelKey(const SubchannelKey& other); + SubchannelKey& operator=(const SubchannelKey& other); + // Not movable. + SubchannelKey(SubchannelKey&&) = delete; + SubchannelKey& operator=(SubchannelKey&&) = delete; + + int Cmp(const SubchannelKey& other) const; + + private: + // Initializes the subchannel key with the given \a args and the function to + // copy channel args. + void Init( + const grpc_channel_args* args, + grpc_channel_args* (*copy_channel_args)(const grpc_channel_args* args)); + + const grpc_channel_args* args_; +}; + +// Interface for subchannel pool. +// TODO(juanlishen): This refcounting mechanism may lead to memory leak. +// To solve that, we should force polling to flush any pending callbacks, then +// shut down safely. See https://github.com/grpc/grpc/issues/12560. +class SubchannelPoolInterface : public RefCounted<SubchannelPoolInterface> { + public: + SubchannelPoolInterface() : RefCounted(&grpc_subchannel_pool_trace) {} + virtual ~SubchannelPoolInterface() {} + + // Registers a subchannel against a key. Returns the subchannel registered + // with \a key, which may be different from \a constructed because we reuse + // (instead of update) any existing subchannel already registered with \a key. + virtual Subchannel* RegisterSubchannel(SubchannelKey* key, Subchannel* constructed) = 0; - - // Removes the registered subchannel found by \a key. + + // Removes the registered subchannel found by \a key. virtual void UnregisterSubchannel(SubchannelKey* key) = 0; - - // Finds the subchannel registered for the given subchannel key. Returns NULL - // if no such channel exists. Thread-safe. + + // Finds the subchannel registered for the given subchannel key. Returns NULL + // if no such channel exists. Thread-safe. virtual Subchannel* FindSubchannel(SubchannelKey* key) = 0; - - // Creates a channel arg from \a subchannel pool. - static grpc_arg CreateChannelArg(SubchannelPoolInterface* subchannel_pool); - - // Gets the subchannel pool from the channel args. - static SubchannelPoolInterface* GetSubchannelPoolFromChannelArgs( - const grpc_channel_args* args); -}; - -} // namespace grpc_core - -#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_POOL_INTERFACE_H */ + + // Creates a channel arg from \a subchannel pool. + static grpc_arg CreateChannelArg(SubchannelPoolInterface* subchannel_pool); + + // Gets the subchannel pool from the channel args. + static SubchannelPoolInterface* GetSubchannelPoolFromChannelArgs( + const grpc_channel_args* args); +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_EXT_FILTERS_CLIENT_CHANNEL_SUBCHANNEL_POOL_INTERFACE_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc index e4027b0719..26451cee11 100644 --- a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.cc @@ -27,7 +27,7 @@ #include <grpc/support/time.h> #include "src/core/lib/channel/channel_stack_builder.h" -#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/channel_init.h" @@ -128,36 +128,36 @@ static void cancel_timer_if_needed(grpc_deadline_state* deadline_state) { } } -// Callback run when we receive trailing metadata. -static void recv_trailing_metadata_ready(void* arg, grpc_error* error) { +// Callback run when we receive trailing metadata. +static void recv_trailing_metadata_ready(void* arg, grpc_error* error) { grpc_deadline_state* deadline_state = static_cast<grpc_deadline_state*>(arg); cancel_timer_if_needed(deadline_state); - // Invoke the original callback. + // Invoke the original callback. grpc_core::Closure::Run(DEBUG_LOCATION, deadline_state->original_recv_trailing_metadata_ready, GRPC_ERROR_REF(error)); } -// Inject our own recv_trailing_metadata_ready callback into op. -static void inject_recv_trailing_metadata_ready( - grpc_deadline_state* deadline_state, grpc_transport_stream_op_batch* op) { - deadline_state->original_recv_trailing_metadata_ready = - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; - GRPC_CLOSURE_INIT(&deadline_state->recv_trailing_metadata_ready, - recv_trailing_metadata_ready, deadline_state, +// Inject our own recv_trailing_metadata_ready callback into op. +static void inject_recv_trailing_metadata_ready( + grpc_deadline_state* deadline_state, grpc_transport_stream_op_batch* op) { + deadline_state->original_recv_trailing_metadata_ready = + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + GRPC_CLOSURE_INIT(&deadline_state->recv_trailing_metadata_ready, + recv_trailing_metadata_ready, deadline_state, grpc_schedule_on_exec_ctx); - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &deadline_state->recv_trailing_metadata_ready; + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &deadline_state->recv_trailing_metadata_ready; } // Callback and associated state for starting the timer after call stack // initialization has been completed. struct start_timer_after_init_state { - start_timer_after_init_state(grpc_call_element* elem, grpc_millis deadline) - : elem(elem), deadline(deadline) {} - ~start_timer_after_init_state() { start_timer_if_needed(elem, deadline); } - - bool in_call_combiner = false; + start_timer_after_init_state(grpc_call_element* elem, grpc_millis deadline) + : elem(elem), deadline(deadline) {} + ~start_timer_after_init_state() { start_timer_if_needed(elem, deadline); } + + bool in_call_combiner = false; grpc_call_element* elem; grpc_millis deadline; grpc_closure closure; @@ -181,11 +181,11 @@ static void start_timer_after_init(void* arg, grpc_error* error) { "done scheduling deadline timer"); } -grpc_deadline_state::grpc_deadline_state(grpc_call_element* elem, - grpc_call_stack* call_stack, +grpc_deadline_state::grpc_deadline_state(grpc_call_element* elem, + grpc_call_stack* call_stack, grpc_core::CallCombiner* call_combiner, - grpc_millis deadline) - : call_stack(call_stack), call_combiner(call_combiner) { + grpc_millis deadline) + : call_stack(call_stack), call_combiner(call_combiner) { // Deadline will always be infinite on servers, so the timer will only be // set on clients with a finite deadline. if (deadline != GRPC_MILLIS_INF_FUTURE) { @@ -204,7 +204,7 @@ grpc_deadline_state::grpc_deadline_state(grpc_call_element* elem, } } -grpc_deadline_state::~grpc_deadline_state() { cancel_timer_if_needed(this); } +grpc_deadline_state::~grpc_deadline_state() { cancel_timer_if_needed(this); } void grpc_deadline_state_reset(grpc_call_element* elem, grpc_millis new_deadline) { @@ -224,7 +224,7 @@ void grpc_deadline_state_client_start_transport_stream_op_batch( // Make sure we know when the call is complete, so that we can cancel // the timer. if (op->recv_trailing_metadata) { - inject_recv_trailing_metadata_ready(deadline_state, op); + inject_recv_trailing_metadata_ready(deadline_state, op); } } } @@ -263,8 +263,8 @@ typedef struct server_call_data { // Constructor for call_data. Used for both client and server filters. static grpc_error* deadline_init_call_elem(grpc_call_element* elem, const grpc_call_element_args* args) { - new (elem->call_data) grpc_deadline_state( - elem, args->call_stack, args->call_combiner, args->deadline); + new (elem->call_data) grpc_deadline_state( + elem, args->call_stack, args->call_combiner, args->deadline); return GRPC_ERROR_NONE; } @@ -272,9 +272,9 @@ static grpc_error* deadline_init_call_elem(grpc_call_element* elem, static void deadline_destroy_call_elem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { - grpc_deadline_state* deadline_state = - static_cast<grpc_deadline_state*>(elem->call_data); - deadline_state->~grpc_deadline_state(); + grpc_deadline_state* deadline_state = + static_cast<grpc_deadline_state*>(elem->call_data); + deadline_state->~grpc_deadline_state(); } // Method for starting a call op for client filter. @@ -323,7 +323,7 @@ static void deadline_server_start_transport_stream_op_batch( // the client never sends trailing metadata, because this is the // hook that tells us when the call is complete on the server side. if (op->recv_trailing_metadata) { - inject_recv_trailing_metadata_ready(&calld->base.deadline_state, op); + inject_recv_trailing_metadata_ready(&calld->base.deadline_state, op); } } // Chain to next filter. diff --git a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h index 7c4e9aaed0..2908e7b5a1 100644 --- a/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h +++ b/contrib/libs/grpc/src/core/ext/filters/deadline/deadline_filter.h @@ -22,33 +22,33 @@ #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/iomgr/timer.h" -enum grpc_deadline_timer_state { +enum grpc_deadline_timer_state { GRPC_DEADLINE_STATE_INITIAL, GRPC_DEADLINE_STATE_PENDING, GRPC_DEADLINE_STATE_FINISHED -}; +}; // State used for filters that enforce call deadlines. // Must be the first field in the filter's call_data. -struct grpc_deadline_state { - grpc_deadline_state(grpc_call_element* elem, grpc_call_stack* call_stack, +struct grpc_deadline_state { + grpc_deadline_state(grpc_call_element* elem, grpc_call_stack* call_stack, grpc_core::CallCombiner* call_combiner, grpc_millis deadline); - ~grpc_deadline_state(); - + ~grpc_deadline_state(); + // We take a reference to the call stack for the timer callback. grpc_call_stack* call_stack; grpc_core::CallCombiner* call_combiner; - grpc_deadline_timer_state timer_state = GRPC_DEADLINE_STATE_INITIAL; + grpc_deadline_timer_state timer_state = GRPC_DEADLINE_STATE_INITIAL; grpc_timer timer; grpc_closure timer_callback; - // Closure to invoke when we receive trailing metadata. + // Closure to invoke when we receive trailing metadata. // We use this to cancel the timer. - grpc_closure recv_trailing_metadata_ready; - // The original recv_trailing_metadata_ready closure, which we chain to - // after our own closure is invoked. - grpc_closure* original_recv_trailing_metadata_ready; -}; + grpc_closure recv_trailing_metadata_ready; + // The original recv_trailing_metadata_ready closure, which we chain to + // after our own closure is invoked. + grpc_closure* original_recv_trailing_metadata_ready; +}; // // NOTE: All of these functions require that the first field in diff --git a/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc index f5f18474da..1e96703f75 100644 --- a/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/http/client/http_client_filter.cc @@ -46,31 +46,31 @@ #define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1 /* default maximum size of payload eligible for GET request */ -static constexpr size_t kMaxPayloadSizeForGet = 2048; - -static void recv_initial_metadata_ready(void* user_data, grpc_error* error); -static void recv_trailing_metadata_ready(void* user_data, grpc_error* error); -static void on_send_message_next_done(void* arg, grpc_error* error); -static void send_message_on_complete(void* arg, grpc_error* error); +static constexpr size_t kMaxPayloadSizeForGet = 2048; +static void recv_initial_metadata_ready(void* user_data, grpc_error* error); +static void recv_trailing_metadata_ready(void* user_data, grpc_error* error); +static void on_send_message_next_done(void* arg, grpc_error* error); +static void send_message_on_complete(void* arg, grpc_error* error); + namespace { struct call_data { - call_data(grpc_call_element* elem, const grpc_call_element_args& args) - : call_combiner(args.call_combiner) { - GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, - ::recv_initial_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, - ::recv_trailing_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&on_send_message_next_done, ::on_send_message_next_done, - elem, grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&send_message_on_complete, ::send_message_on_complete, - elem, grpc_schedule_on_exec_ctx); - } - - ~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); } - + call_data(grpc_call_element* elem, const grpc_call_element_args& args) + : call_combiner(args.call_combiner) { + GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, + ::recv_initial_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, + ::recv_trailing_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&on_send_message_next_done, ::on_send_message_next_done, + elem, grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&send_message_on_complete, ::send_message_on_complete, + elem, grpc_schedule_on_exec_ctx); + } + + ~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); } + grpc_core::CallCombiner* call_combiner; // State for handling send_initial_metadata ops. grpc_linked_mdelem method; @@ -81,18 +81,18 @@ struct call_data { grpc_linked_mdelem user_agent; // State for handling recv_initial_metadata ops. grpc_metadata_batch* recv_initial_metadata; - grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE; - grpc_closure* original_recv_initial_metadata_ready = nullptr; + grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE; + grpc_closure* original_recv_initial_metadata_ready = nullptr; grpc_closure recv_initial_metadata_ready; // State for handling recv_trailing_metadata ops. grpc_metadata_batch* recv_trailing_metadata; - grpc_closure* original_recv_trailing_metadata_ready; - grpc_closure recv_trailing_metadata_ready; - grpc_error* recv_trailing_metadata_error = GRPC_ERROR_NONE; - bool seen_recv_trailing_metadata_ready = false; + grpc_closure* original_recv_trailing_metadata_ready; + grpc_closure recv_trailing_metadata_ready; + grpc_error* recv_trailing_metadata_error = GRPC_ERROR_NONE; + bool seen_recv_trailing_metadata_ready = false; // State for handling send_message ops. grpc_transport_stream_op_batch* send_message_batch; - size_t send_message_bytes_read = 0; + size_t send_message_bytes_read = 0; grpc_core::ManualConstructor<grpc_core::ByteStreamCache> send_message_cache; grpc_core::ManualConstructor<grpc_core::ByteStreamCache::CachingByteStream> send_message_caching_stream; @@ -110,11 +110,11 @@ struct channel_data { static grpc_error* client_filter_incoming_metadata(grpc_metadata_batch* b) { if (b->idx.named.status != nullptr) { - /* If both gRPC status and HTTP status are provided in the response, we - * should prefer the gRPC status code, as mentioned in - * https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md. - */ - if (b->idx.named.grpc_status != nullptr || + /* If both gRPC status and HTTP status are provided in the response, we + * should prefer the gRPC status code, as mentioned in + * https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md. + */ + if (b->idx.named.grpc_status != nullptr || grpc_mdelem_static_value_eq(b->idx.named.status->md, GRPC_MDELEM_STATUS_200)) { grpc_metadata_batch_remove(b, GRPC_BATCH_STATUS); @@ -187,38 +187,38 @@ static void recv_initial_metadata_ready(void* user_data, grpc_error* error) { call_data* calld = static_cast<call_data*>(elem->call_data); if (error == GRPC_ERROR_NONE) { error = client_filter_incoming_metadata(calld->recv_initial_metadata); - calld->recv_initial_metadata_error = GRPC_ERROR_REF(error); + calld->recv_initial_metadata_error = GRPC_ERROR_REF(error); } else { GRPC_ERROR_REF(error); } - grpc_closure* closure = calld->original_recv_initial_metadata_ready; - calld->original_recv_initial_metadata_ready = nullptr; - if (calld->seen_recv_trailing_metadata_ready) { - GRPC_CALL_COMBINER_START( - calld->call_combiner, &calld->recv_trailing_metadata_ready, - calld->recv_trailing_metadata_error, "continue recv_trailing_metadata"); - } + grpc_closure* closure = calld->original_recv_initial_metadata_ready; + calld->original_recv_initial_metadata_ready = nullptr; + if (calld->seen_recv_trailing_metadata_ready) { + GRPC_CALL_COMBINER_START( + calld->call_combiner, &calld->recv_trailing_metadata_ready, + calld->recv_trailing_metadata_error, "continue recv_trailing_metadata"); + } grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } -static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) { +static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); - if (calld->original_recv_initial_metadata_ready != nullptr) { - calld->recv_trailing_metadata_error = GRPC_ERROR_REF(error); - calld->seen_recv_trailing_metadata_ready = true; - GRPC_CALL_COMBINER_STOP(calld->call_combiner, - "deferring recv_trailing_metadata_ready until " - "after recv_initial_metadata_ready"); - return; - } + if (calld->original_recv_initial_metadata_ready != nullptr) { + calld->recv_trailing_metadata_error = GRPC_ERROR_REF(error); + calld->seen_recv_trailing_metadata_ready = true; + GRPC_CALL_COMBINER_STOP(calld->call_combiner, + "deferring recv_trailing_metadata_ready until " + "after recv_initial_metadata_ready"); + return; + } if (error == GRPC_ERROR_NONE) { error = client_filter_incoming_metadata(calld->recv_trailing_metadata); } else { GRPC_ERROR_REF(error); } - error = grpc_error_add_child( - error, GRPC_ERROR_REF(calld->recv_initial_metadata_error)); + error = grpc_error_add_child( + error, GRPC_ERROR_REF(calld->recv_initial_metadata_error)); grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready, error); } @@ -370,10 +370,10 @@ static void http_client_start_transport_stream_op_batch( /* substitute our callback for the higher callback */ calld->recv_trailing_metadata = batch->payload->recv_trailing_metadata.recv_trailing_metadata; - calld->original_recv_trailing_metadata_ready = - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &calld->recv_trailing_metadata_ready; + calld->original_recv_trailing_metadata_ready = + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &calld->recv_trailing_metadata_ready; } grpc_error* error = GRPC_ERROR_NONE; @@ -477,7 +477,7 @@ done: /* Constructor for call_data */ static grpc_error* http_client_init_call_elem( grpc_call_element* elem, const grpc_call_element_args* args) { - new (elem->call_data) call_data(elem, *args); + new (elem->call_data) call_data(elem, *args); return GRPC_ERROR_NONE; } @@ -485,9 +485,9 @@ static grpc_error* http_client_init_call_elem( static void http_client_destroy_call_elem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { - call_data* calld = static_cast<call_data*>(elem->call_data); - calld->~call_data(); -} + call_data* calld = static_cast<call_data*>(elem->call_data); + calld->~call_data(); +} static grpc_mdelem scheme_from_args(const grpc_channel_args* args) { unsigned i; diff --git a/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc index 2c3cae6adb..2c880c16b1 100644 --- a/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/http/client_authority_filter.cc @@ -45,7 +45,7 @@ struct call_data { struct channel_data { grpc_core::ManagedMemorySlice default_authority; - grpc_mdelem default_authority_mdelem; + grpc_mdelem default_authority_mdelem; }; void client_authority_start_transport_stream_op_batch( @@ -93,7 +93,7 @@ grpc_error* client_authority_init_channel_elem( if (default_authority_arg == nullptr) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "GRPC_ARG_DEFAULT_AUTHORITY channel arg. not found. Note that direct " - "channels must explicitly specify a value for this argument."); + "channels must explicitly specify a value for this argument."); } const char* default_authority_str = grpc_channel_arg_get_string(default_authority_arg); @@ -103,8 +103,8 @@ grpc_error* client_authority_init_channel_elem( } chand->default_authority = grpc_core::ManagedMemorySlice(default_authority_str); - chand->default_authority_mdelem = grpc_mdelem_create( - GRPC_MDSTR_AUTHORITY, chand->default_authority, nullptr); + chand->default_authority_mdelem = grpc_mdelem_create( + GRPC_MDSTR_AUTHORITY, chand->default_authority, nullptr); GPR_ASSERT(!args->is_last); return GRPC_ERROR_NONE; } @@ -112,8 +112,8 @@ grpc_error* client_authority_init_channel_elem( /* Destructor for channel data */ void client_authority_destroy_channel_elem(grpc_channel_element* elem) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); - grpc_slice_unref_internal(chand->default_authority); - GRPC_MDELEM_UNREF(chand->default_authority_mdelem); + grpc_slice_unref_internal(chand->default_authority); + GRPC_MDELEM_UNREF(chand->default_authority_mdelem); } } // namespace diff --git a/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc index 53f6e2b80d..aaebedc650 100644 --- a/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/http/message_compress/message_compress_filter.cc @@ -115,15 +115,15 @@ class CallData { } GRPC_CLOSURE_INIT(&start_send_message_batch_in_call_combiner_, StartSendMessageBatch, elem, grpc_schedule_on_exec_ctx); - } - + } + ~CallData() { if (state_initialized_) { grpc_slice_buffer_destroy_internal(&slices_); } GRPC_ERROR_UNREF(cancel_error_); - } - + } + void CompressStartTransportStreamOpBatch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch); @@ -148,7 +148,7 @@ class CallData { grpc_core::CallCombiner* call_combiner_; grpc_message_compression_algorithm message_compression_algorithm_ = - GRPC_MESSAGE_COMPRESS_NONE; + GRPC_MESSAGE_COMPRESS_NONE; grpc_error* cancel_error_ = GRPC_ERROR_NONE; grpc_transport_stream_op_batch* send_message_batch_ = nullptr; bool seen_initial_metadata_ = false; diff --git a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc index 62dc76fb6c..2c0a9c126f 100644 --- a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.cc @@ -23,7 +23,7 @@ #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <string.h> -#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/slice/b64.h" @@ -35,68 +35,68 @@ #define EXPECTED_CONTENT_TYPE "application/grpc" #define EXPECTED_CONTENT_TYPE_LENGTH sizeof(EXPECTED_CONTENT_TYPE) - 1 -static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err); -static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err); -static void hs_recv_message_ready(void* user_data, grpc_error* err); - +static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err); +static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err); +static void hs_recv_message_ready(void* user_data, grpc_error* err); + namespace { - + struct call_data { - call_data(grpc_call_element* elem, const grpc_call_element_args& args) - : call_combiner(args.call_combiner) { - GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, - hs_recv_initial_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&recv_message_ready, hs_recv_message_ready, elem, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, - hs_recv_trailing_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - } - - ~call_data() { - GRPC_ERROR_UNREF(recv_initial_metadata_ready_error); - if (have_read_stream) { - read_stream->Orphan(); - } - } - + call_data(grpc_call_element* elem, const grpc_call_element_args& args) + : call_combiner(args.call_combiner) { + GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, + hs_recv_initial_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&recv_message_ready, hs_recv_message_ready, elem, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, + hs_recv_trailing_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + } + + ~call_data() { + GRPC_ERROR_UNREF(recv_initial_metadata_ready_error); + if (have_read_stream) { + read_stream->Orphan(); + } + } + grpc_core::CallCombiner* call_combiner; - // Outgoing headers to add to send_initial_metadata. + // Outgoing headers to add to send_initial_metadata. grpc_linked_mdelem status; grpc_linked_mdelem content_type; - // If we see the recv_message contents in the GET query string, we - // store it here. - grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> read_stream; - bool have_read_stream = false; + // If we see the recv_message contents in the GET query string, we + // store it here. + grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> read_stream; + bool have_read_stream = false; - // State for intercepting recv_initial_metadata. - grpc_closure recv_initial_metadata_ready; - grpc_error* recv_initial_metadata_ready_error = GRPC_ERROR_NONE; - grpc_closure* original_recv_initial_metadata_ready; - grpc_metadata_batch* recv_initial_metadata = nullptr; + // State for intercepting recv_initial_metadata. + grpc_closure recv_initial_metadata_ready; + grpc_error* recv_initial_metadata_ready_error = GRPC_ERROR_NONE; + grpc_closure* original_recv_initial_metadata_ready; + grpc_metadata_batch* recv_initial_metadata = nullptr; uint32_t* recv_initial_metadata_flags; - bool seen_recv_initial_metadata_ready = false; - - // State for intercepting recv_message. - grpc_closure* original_recv_message_ready; - grpc_closure recv_message_ready; - grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message; - bool seen_recv_message_ready = false; - - // State for intercepting recv_trailing_metadata - grpc_closure recv_trailing_metadata_ready; - grpc_closure* original_recv_trailing_metadata_ready; - grpc_error* recv_trailing_metadata_ready_error; - bool seen_recv_trailing_metadata_ready = false; + bool seen_recv_initial_metadata_ready = false; + + // State for intercepting recv_message. + grpc_closure* original_recv_message_ready; + grpc_closure recv_message_ready; + grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message; + bool seen_recv_message_ready = false; + + // State for intercepting recv_trailing_metadata + grpc_closure recv_trailing_metadata_ready; + grpc_closure* original_recv_trailing_metadata_ready; + grpc_error* recv_trailing_metadata_ready_error; + bool seen_recv_trailing_metadata_ready = false; }; struct channel_data { - bool surface_user_agent; + bool surface_user_agent; }; - + } // namespace static grpc_error* hs_filter_outgoing_metadata(grpc_metadata_batch* b) { @@ -114,8 +114,8 @@ static grpc_error* hs_filter_outgoing_metadata(grpc_metadata_batch* b) { return GRPC_ERROR_NONE; } -static void hs_add_error(const char* error_name, grpc_error** cumulative, - grpc_error* new_err) { +static void hs_add_error(const char* error_name, grpc_error** cumulative, + grpc_error* new_err) { if (new_err == GRPC_ERROR_NONE) return; if (*cumulative == GRPC_ERROR_NONE) { *cumulative = GRPC_ERROR_CREATE_FROM_COPIED_STRING(error_name); @@ -149,8 +149,8 @@ static bool md_strict_equal(grpc_mdelem a, grpc_mdelem b_static) { } } -static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, - grpc_metadata_batch* b) { +static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, + grpc_metadata_batch* b) { call_data* calld = static_cast<call_data*>(elem->call_data); grpc_error* error = GRPC_ERROR_NONE; static const char* error_name = "Failed processing incoming headers"; @@ -173,14 +173,14 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, *calld->recv_initial_metadata_flags &= ~GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST; } else { - hs_add_error(error_name, &error, - grpc_attach_md_to_error( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"), - b->idx.named.method->md)); + hs_add_error(error_name, &error, + grpc_attach_md_to_error( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"), + b->idx.named.method->md)); } grpc_metadata_batch_remove(b, GRPC_BATCH_METHOD); } else { - hs_add_error( + hs_add_error( error_name, &error, grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), @@ -190,17 +190,17 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, if (b->idx.named.te != nullptr) { if (!grpc_mdelem_static_value_eq(b->idx.named.te->md, GRPC_MDELEM_TE_TRAILERS)) { - hs_add_error(error_name, &error, - grpc_attach_md_to_error( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"), - b->idx.named.te->md)); + hs_add_error(error_name, &error, + grpc_attach_md_to_error( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"), + b->idx.named.te->md)); } grpc_metadata_batch_remove(b, GRPC_BATCH_TE); } else { - hs_add_error(error_name, &error, - grpc_error_set_str( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), - GRPC_ERROR_STR_KEY, grpc_slice_from_static_string("te"))); + hs_add_error(error_name, &error, + grpc_error_set_str( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), + GRPC_ERROR_STR_KEY, grpc_slice_from_static_string("te"))); } if (b->idx.named.scheme != nullptr) { @@ -208,14 +208,14 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, !md_strict_equal(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_HTTPS) && !grpc_mdelem_static_value_eq(b->idx.named.scheme->md, GRPC_MDELEM_SCHEME_GRPC)) { - hs_add_error(error_name, &error, - grpc_attach_md_to_error( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"), - b->idx.named.scheme->md)); + hs_add_error(error_name, &error, + grpc_attach_md_to_error( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Bad header"), + b->idx.named.scheme->md)); } grpc_metadata_batch_remove(b, GRPC_BATCH_SCHEME); } else { - hs_add_error( + hs_add_error( error_name, &error, grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), @@ -253,11 +253,11 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, } if (b->idx.named.path == nullptr) { - hs_add_error( - error_name, &error, - grpc_error_set_str( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), - GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":path"))); + hs_add_error( + error_name, &error, + grpc_error_set_str( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), + GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":path"))); } else if (*calld->recv_initial_metadata_flags & GRPC_INITIAL_METADATA_CACHEABLE_REQUEST) { /* We have a cacheable request made with GET verb. The path contains the @@ -293,7 +293,7 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, GRPC_SLICE_LENGTH(query_slice), k_url_safe)); calld->read_stream.Init(&read_slice_buffer, 0); grpc_slice_buffer_destroy_internal(&read_slice_buffer); - calld->have_read_stream = true; + calld->have_read_stream = true; grpc_slice_unref_internal(query_slice); } else { gpr_log(GPR_ERROR, "GET request without QUERY"); @@ -315,97 +315,97 @@ static grpc_error* hs_filter_incoming_metadata(grpc_call_element* elem, } if (b->idx.named.authority == nullptr) { - hs_add_error( + hs_add_error( error_name, &error, grpc_error_set_str( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Missing header"), GRPC_ERROR_STR_KEY, grpc_slice_from_static_string(":authority"))); } - channel_data* chand = static_cast<channel_data*>(elem->channel_data); - if (!chand->surface_user_agent && b->idx.named.user_agent != nullptr) { + channel_data* chand = static_cast<channel_data*>(elem->channel_data); + if (!chand->surface_user_agent && b->idx.named.user_agent != nullptr) { grpc_metadata_batch_remove(b, GRPC_BATCH_USER_AGENT); - } - + } + return error; } -static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err) { +static void hs_recv_initial_metadata_ready(void* user_data, grpc_error* err) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); - calld->seen_recv_initial_metadata_ready = true; + calld->seen_recv_initial_metadata_ready = true; if (err == GRPC_ERROR_NONE) { - err = hs_filter_incoming_metadata(elem, calld->recv_initial_metadata); - calld->recv_initial_metadata_ready_error = GRPC_ERROR_REF(err); - if (calld->seen_recv_message_ready) { - // We've already seen the recv_message callback, but we previously - // deferred it, so we need to return it here. - // Replace the recv_message byte stream if needed. - if (calld->have_read_stream) { - calld->recv_message->reset(calld->read_stream.get()); - calld->have_read_stream = false; - } - // Re-enter call combiner for original_recv_message_ready, since the - // surface code will release the call combiner for each callback it - // receives. - GRPC_CALL_COMBINER_START( - calld->call_combiner, calld->original_recv_message_ready, - GRPC_ERROR_REF(err), - "resuming recv_message_ready from recv_initial_metadata_ready"); - } + err = hs_filter_incoming_metadata(elem, calld->recv_initial_metadata); + calld->recv_initial_metadata_ready_error = GRPC_ERROR_REF(err); + if (calld->seen_recv_message_ready) { + // We've already seen the recv_message callback, but we previously + // deferred it, so we need to return it here. + // Replace the recv_message byte stream if needed. + if (calld->have_read_stream) { + calld->recv_message->reset(calld->read_stream.get()); + calld->have_read_stream = false; + } + // Re-enter call combiner for original_recv_message_ready, since the + // surface code will release the call combiner for each callback it + // receives. + GRPC_CALL_COMBINER_START( + calld->call_combiner, calld->original_recv_message_ready, + GRPC_ERROR_REF(err), + "resuming recv_message_ready from recv_initial_metadata_ready"); + } } else { GRPC_ERROR_REF(err); } - if (calld->seen_recv_trailing_metadata_ready) { - GRPC_CALL_COMBINER_START(calld->call_combiner, - &calld->recv_trailing_metadata_ready, - calld->recv_trailing_metadata_ready_error, - "resuming hs_recv_trailing_metadata_ready from " - "hs_recv_initial_metadata_ready"); - } + if (calld->seen_recv_trailing_metadata_ready) { + GRPC_CALL_COMBINER_START(calld->call_combiner, + &calld->recv_trailing_metadata_ready, + calld->recv_trailing_metadata_ready_error, + "resuming hs_recv_trailing_metadata_ready from " + "hs_recv_initial_metadata_ready"); + } grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_initial_metadata_ready, err); } -static void hs_recv_message_ready(void* user_data, grpc_error* err) { +static void hs_recv_message_ready(void* user_data, grpc_error* err) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); - calld->seen_recv_message_ready = true; - if (calld->seen_recv_initial_metadata_ready) { - // We've already seen the recv_initial_metadata callback, so - // replace the recv_message byte stream if needed and invoke the - // original recv_message callback immediately. - if (calld->have_read_stream) { - calld->recv_message->reset(calld->read_stream.get()); - calld->have_read_stream = false; - } + calld->seen_recv_message_ready = true; + if (calld->seen_recv_initial_metadata_ready) { + // We've already seen the recv_initial_metadata callback, so + // replace the recv_message byte stream if needed and invoke the + // original recv_message callback immediately. + if (calld->have_read_stream) { + calld->recv_message->reset(calld->read_stream.get()); + calld->have_read_stream = false; + } grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_message_ready, GRPC_ERROR_REF(err)); - } else { - // We have not yet seen the recv_initial_metadata callback, so we - // need to wait to see if this is a GET request. - // Note that we release the call combiner here, so that other - // callbacks can run. - GRPC_CALL_COMBINER_STOP( - calld->call_combiner, - "pausing recv_message_ready until recv_initial_metadata_ready"); + } else { + // We have not yet seen the recv_initial_metadata callback, so we + // need to wait to see if this is a GET request. + // Note that we release the call combiner here, so that other + // callbacks can run. + GRPC_CALL_COMBINER_STOP( + calld->call_combiner, + "pausing recv_message_ready until recv_initial_metadata_ready"); } } -static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err) { +static void hs_recv_trailing_metadata_ready(void* user_data, grpc_error* err) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); - if (!calld->seen_recv_initial_metadata_ready) { - calld->recv_trailing_metadata_ready_error = GRPC_ERROR_REF(err); - calld->seen_recv_trailing_metadata_ready = true; + if (!calld->seen_recv_initial_metadata_ready) { + calld->recv_trailing_metadata_ready_error = GRPC_ERROR_REF(err); + calld->seen_recv_trailing_metadata_ready = true; GRPC_CALL_COMBINER_STOP(calld->call_combiner, - "deferring hs_recv_trailing_metadata_ready until " - "ater hs_recv_initial_metadata_ready"); - return; + "deferring hs_recv_trailing_metadata_ready until " + "ater hs_recv_initial_metadata_ready"); + return; } - err = grpc_error_add_child( - GRPC_ERROR_REF(err), - GRPC_ERROR_REF(calld->recv_initial_metadata_ready_error)); + err = grpc_error_add_child( + GRPC_ERROR_REF(err), + GRPC_ERROR_REF(calld->recv_initial_metadata_ready_error)); grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready, err); } @@ -423,10 +423,10 @@ static grpc_error* hs_mutate_op(grpc_call_element* elem, grpc_metadata_batch_add_head( op->payload->send_initial_metadata.send_initial_metadata, &calld->status, GRPC_MDELEM_STATUS_200, GRPC_BATCH_STATUS)); - hs_add_error(error_name, &error, - grpc_metadata_batch_add_tail( - op->payload->send_initial_metadata.send_initial_metadata, - &calld->content_type, + hs_add_error(error_name, &error, + grpc_metadata_batch_add_tail( + op->payload->send_initial_metadata.send_initial_metadata, + &calld->content_type, GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC, GRPC_BATCH_CONTENT_TYPE)); hs_add_error(error_name, &error, @@ -442,28 +442,28 @@ static grpc_error* hs_mutate_op(grpc_call_element* elem, op->payload->recv_initial_metadata.recv_initial_metadata; calld->recv_initial_metadata_flags = op->payload->recv_initial_metadata.recv_flags; - calld->original_recv_initial_metadata_ready = + calld->original_recv_initial_metadata_ready = op->payload->recv_initial_metadata.recv_initial_metadata_ready; op->payload->recv_initial_metadata.recv_initial_metadata_ready = - &calld->recv_initial_metadata_ready; + &calld->recv_initial_metadata_ready; } if (op->recv_message) { - calld->recv_message = op->payload->recv_message.recv_message; - calld->original_recv_message_ready = - op->payload->recv_message.recv_message_ready; - op->payload->recv_message.recv_message_ready = &calld->recv_message_ready; - } - - if (op->recv_trailing_metadata) { - calld->original_recv_trailing_metadata_ready = - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &calld->recv_trailing_metadata_ready; + calld->recv_message = op->payload->recv_message.recv_message; + calld->original_recv_message_ready = + op->payload->recv_message.recv_message_ready; + op->payload->recv_message.recv_message_ready = &calld->recv_message_ready; } + if (op->recv_trailing_metadata) { + calld->original_recv_trailing_metadata_ready = + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &calld->recv_trailing_metadata_ready; + } + if (op->send_trailing_metadata) { - grpc_error* error = hs_filter_outgoing_metadata( + grpc_error* error = hs_filter_outgoing_metadata( op->payload->send_trailing_metadata.send_trailing_metadata); if (error != GRPC_ERROR_NONE) return error; } @@ -485,29 +485,29 @@ static void hs_start_transport_stream_op_batch( } /* Constructor for call_data */ -static grpc_error* hs_init_call_elem(grpc_call_element* elem, - const grpc_call_element_args* args) { - new (elem->call_data) call_data(elem, *args); +static grpc_error* hs_init_call_elem(grpc_call_element* elem, + const grpc_call_element_args* args) { + new (elem->call_data) call_data(elem, *args); return GRPC_ERROR_NONE; } /* Destructor for call_data */ -static void hs_destroy_call_elem(grpc_call_element* elem, +static void hs_destroy_call_elem(grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { call_data* calld = static_cast<call_data*>(elem->call_data); - calld->~call_data(); + calld->~call_data(); } /* Constructor for channel_data */ -static grpc_error* hs_init_channel_elem(grpc_channel_element* elem, - grpc_channel_element_args* args) { - channel_data* chand = static_cast<channel_data*>(elem->channel_data); +static grpc_error* hs_init_channel_elem(grpc_channel_element* elem, + grpc_channel_element_args* args) { + channel_data* chand = static_cast<channel_data*>(elem->channel_data); GPR_ASSERT(!args->is_last); - chand->surface_user_agent = grpc_channel_arg_get_bool( - grpc_channel_args_find(args->channel_args, - const_cast<char*>(GRPC_ARG_SURFACE_USER_AGENT)), - true); + chand->surface_user_agent = grpc_channel_arg_get_bool( + grpc_channel_args_find(args->channel_args, + const_cast<char*>(GRPC_ARG_SURFACE_USER_AGENT)), + true); return GRPC_ERROR_NONE; } @@ -518,11 +518,11 @@ const grpc_channel_filter grpc_http_server_filter = { hs_start_transport_stream_op_batch, grpc_channel_next_op, sizeof(call_data), - hs_init_call_elem, + hs_init_call_elem, grpc_call_stack_ignore_set_pollset_or_pollset_set, - hs_destroy_call_elem, + hs_destroy_call_elem, sizeof(channel_data), - hs_init_channel_elem, - hs_destroy_channel_elem, + hs_init_channel_elem, + hs_destroy_channel_elem, grpc_channel_next_get_info, "http-server"}; diff --git a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h index e4e0546f6d..5791f01bd1 100644 --- a/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h +++ b/contrib/libs/grpc/src/core/ext/filters/http/server/http_server_filter.h @@ -23,7 +23,7 @@ #include "src/core/lib/channel/channel_stack.h" -/* Processes metadata on the server side for HTTP2 transports */ +/* Processes metadata on the server side for HTTP2 transports */ extern const grpc_channel_filter grpc_http_server_filter; #endif /* GRPC_CORE_EXT_FILTERS_HTTP_SERVER_HTTP_SERVER_FILTER_H */ diff --git a/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc b/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc index c57efd6d1c..9b63575fd8 100644 --- a/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/max_age/max_age_filter.cc @@ -105,7 +105,7 @@ struct channel_data { +--------------------------------+----------------+---------+ MAX_IDLE_STATE_INIT: The initial and final state of 'idle_state'. The - channel has 1 or 1+ active calls, and the timer is not set. Note that + channel has 1 or 1+ active calls, and the timer is not set. Note that we may put a virtual call to hold this state at channel initialization or shutdown, so that the channel won't enter other states. @@ -441,7 +441,7 @@ static grpc_error* max_age_init_channel_elem(grpc_channel_element* elem, ? GRPC_MILLIS_INF_FUTURE : DEFAULT_MAX_CONNECTION_IDLE_MS; chand->idle_state = MAX_IDLE_STATE_INIT; - gpr_atm_no_barrier_store(&chand->last_enter_idle_time_millis, GPR_ATM_MIN); + gpr_atm_no_barrier_store(&chand->last_enter_idle_time_millis, GPR_ATM_MIN); for (size_t i = 0; i < args->channel_args->num_args; ++i) { if (0 == strcmp(args->channel_args->args[i].key, GRPC_ARG_MAX_CONNECTION_AGE_MS)) { diff --git a/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc b/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc index 944479ac3b..7a217e65aa 100644 --- a/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc +++ b/contrib/libs/grpc/src/core/ext/filters/message_size/message_size_filter.cc @@ -136,23 +136,23 @@ int GetMaxSendSizeFromChannelArgs(const grpc_channel_args* args) { } // namespace grpc_core namespace { -struct channel_data { +struct channel_data { grpc_core::MessageSizeParsedConfig::message_size_limits limits; -}; - +}; + struct call_data { - call_data(grpc_call_element* elem, const channel_data& chand, - const grpc_call_element_args& args) - : call_combiner(args.call_combiner), limits(chand.limits) { - GRPC_CLOSURE_INIT(&recv_message_ready, ::recv_message_ready, elem, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, - ::recv_trailing_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - // Get max sizes from channel data, then merge in per-method config values. - // Note: Per-method config is only available on the client, so we - // apply the max request size to the send limit and the max response - // size to the receive limit. + call_data(grpc_call_element* elem, const channel_data& chand, + const grpc_call_element_args& args) + : call_combiner(args.call_combiner), limits(chand.limits) { + GRPC_CLOSURE_INIT(&recv_message_ready, ::recv_message_ready, elem, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, + ::recv_trailing_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + // Get max sizes from channel data, then merge in per-method config values. + // Note: Per-method config is only available on the client, so we + // apply the max request size to the send limit and the max response + // size to the receive limit. const grpc_core::MessageSizeParsedConfig* limits = grpc_core::MessageSizeParsedConfig::GetFromCallContext(args.context); if (limits != nullptr) { @@ -167,27 +167,27 @@ struct call_data { this->limits.max_recv_size = limits->limits().max_recv_size; } } - } - - ~call_data() { GRPC_ERROR_UNREF(error); } - + } + + ~call_data() { GRPC_ERROR_UNREF(error); } + grpc_core::CallCombiner* call_combiner; grpc_core::MessageSizeParsedConfig::message_size_limits limits; // Receive closures are chained: we inject this closure as the // recv_message_ready up-call on transport_stream_op, and remember to // call our next_recv_message_ready member after handling it. grpc_closure recv_message_ready; - grpc_closure recv_trailing_metadata_ready; - // The error caused by a message that is too large, or GRPC_ERROR_NONE - grpc_error* error = GRPC_ERROR_NONE; + grpc_closure recv_trailing_metadata_ready; + // The error caused by a message that is too large, or GRPC_ERROR_NONE + grpc_error* error = GRPC_ERROR_NONE; // Used by recv_message_ready. - grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message = nullptr; + grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message = nullptr; // Original recv_message_ready callback, invoked after our own. - grpc_closure* next_recv_message_ready = nullptr; - // Original recv_trailing_metadata callback, invoked after our own. - grpc_closure* original_recv_trailing_metadata_ready; - bool seen_recv_trailing_metadata = false; - grpc_error* recv_trailing_metadata_error; + grpc_closure* next_recv_message_ready = nullptr; + // Original recv_trailing_metadata callback, invoked after our own. + grpc_closure* original_recv_trailing_metadata_ready; + bool seen_recv_trailing_metadata = false; + grpc_error* recv_trailing_metadata_error; }; } // namespace @@ -208,49 +208,49 @@ static void recv_message_ready(void* user_data, grpc_error* error) { .c_str()), GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_RESOURCE_EXHAUSTED); error = grpc_error_add_child(GRPC_ERROR_REF(error), new_error); - GRPC_ERROR_UNREF(calld->error); - calld->error = GRPC_ERROR_REF(error); + GRPC_ERROR_UNREF(calld->error); + calld->error = GRPC_ERROR_REF(error); } else { GRPC_ERROR_REF(error); } // Invoke the next callback. - grpc_closure* closure = calld->next_recv_message_ready; - calld->next_recv_message_ready = nullptr; - if (calld->seen_recv_trailing_metadata) { - /* We might potentially see another RECV_MESSAGE op. In that case, we do not - * want to run the recv_trailing_metadata_ready closure again. The newer - * RECV_MESSAGE op cannot cause any errors since the transport has already - * invoked the recv_trailing_metadata_ready closure and all further - * RECV_MESSAGE ops will get null payloads. */ - calld->seen_recv_trailing_metadata = false; - GRPC_CALL_COMBINER_START(calld->call_combiner, - &calld->recv_trailing_metadata_ready, - calld->recv_trailing_metadata_error, - "continue recv_trailing_metadata_ready"); - } + grpc_closure* closure = calld->next_recv_message_ready; + calld->next_recv_message_ready = nullptr; + if (calld->seen_recv_trailing_metadata) { + /* We might potentially see another RECV_MESSAGE op. In that case, we do not + * want to run the recv_trailing_metadata_ready closure again. The newer + * RECV_MESSAGE op cannot cause any errors since the transport has already + * invoked the recv_trailing_metadata_ready closure and all further + * RECV_MESSAGE ops will get null payloads. */ + calld->seen_recv_trailing_metadata = false; + GRPC_CALL_COMBINER_START(calld->call_combiner, + &calld->recv_trailing_metadata_ready, + calld->recv_trailing_metadata_error, + "continue recv_trailing_metadata_ready"); + } grpc_core::Closure::Run(DEBUG_LOCATION, closure, error); } -// Callback invoked on completion of recv_trailing_metadata -// Notifies the recv_trailing_metadata batch of any message size failures -static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) { - grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); - call_data* calld = static_cast<call_data*>(elem->call_data); - if (calld->next_recv_message_ready != nullptr) { - calld->seen_recv_trailing_metadata = true; - calld->recv_trailing_metadata_error = GRPC_ERROR_REF(error); - GRPC_CALL_COMBINER_STOP(calld->call_combiner, - "deferring recv_trailing_metadata_ready until " - "after recv_message_ready"); - return; - } - error = - grpc_error_add_child(GRPC_ERROR_REF(error), GRPC_ERROR_REF(calld->error)); - // Invoke the next callback. +// Callback invoked on completion of recv_trailing_metadata +// Notifies the recv_trailing_metadata batch of any message size failures +static void recv_trailing_metadata_ready(void* user_data, grpc_error* error) { + grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); + call_data* calld = static_cast<call_data*>(elem->call_data); + if (calld->next_recv_message_ready != nullptr) { + calld->seen_recv_trailing_metadata = true; + calld->recv_trailing_metadata_error = GRPC_ERROR_REF(error); + GRPC_CALL_COMBINER_STOP(calld->call_combiner, + "deferring recv_trailing_metadata_ready until " + "after recv_message_ready"); + return; + } + error = + grpc_error_add_child(GRPC_ERROR_REF(error), GRPC_ERROR_REF(calld->error)); + // Invoke the next callback. grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready, error); -} - +} + // Start transport stream op. static void message_size_start_transport_stream_op_batch( grpc_call_element* elem, grpc_transport_stream_op_batch* op) { @@ -279,13 +279,13 @@ static void message_size_start_transport_stream_op_batch( calld->recv_message = op->payload->recv_message.recv_message; op->payload->recv_message.recv_message_ready = &calld->recv_message_ready; } - // Inject callback for receiving trailing metadata. - if (op->recv_trailing_metadata) { - calld->original_recv_trailing_metadata_ready = - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &calld->recv_trailing_metadata_ready; - } + // Inject callback for receiving trailing metadata. + if (op->recv_trailing_metadata) { + calld->original_recv_trailing_metadata_ready = + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &calld->recv_trailing_metadata_ready; + } // Chain to the next filter. grpc_call_next_op(elem, op); } @@ -294,7 +294,7 @@ static void message_size_start_transport_stream_op_batch( static grpc_error* message_size_init_call_elem( grpc_call_element* elem, const grpc_call_element_args* args) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); - new (elem->call_data) call_data(elem, *chand, *args); + new (elem->call_data) call_data(elem, *chand, *args); return GRPC_ERROR_NONE; } @@ -302,9 +302,9 @@ static grpc_error* message_size_init_call_elem( static void message_size_destroy_call_elem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { - call_data* calld = (call_data*)elem->call_data; - calld->~call_data(); -} + call_data* calld = (call_data*)elem->call_data; + calld->~call_data(); +} grpc_core::MessageSizeParsedConfig::message_size_limits get_message_size_limits( const grpc_channel_args* channel_args) { diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc index 5bdcb387c9..01d2a2b86b 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc @@ -50,7 +50,7 @@ grpc_channel* grpc_insecure_channel_create_from_fd( GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0); grpc_endpoint* client = grpc_tcp_client_create_from_fd( - grpc_fd_create(fd, "client", true), args, "fd-client"); + grpc_fd_create(fd, "client", true), args, "fd-client"); grpc_transport* transport = grpc_create_chttp2_transport(final_args, client, true); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc index 93dadf3645..e094bcfa39 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc @@ -37,7 +37,7 @@ #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/transport/authority_override.h" -#include "src/core/lib/uri/uri_parser.h" +#include "src/core/lib/uri/uri_parser.h" namespace grpc_core { @@ -187,7 +187,7 @@ grpc_channel* grpc_secure_channel_create(grpc_channel_credentials* creds, const char* arg_to_remove = channel_factory_arg.key; grpc_channel_args* new_args = grpc_channel_args_copy_and_add_and_remove( args, &arg_to_remove, 1, args_to_add, GPR_ARRAY_SIZE(args_to_add)); - new_args = creds->update_arguments(new_args); + new_args = creds->update_arguments(new_args); // Create channel. channel = grpc_core::CreateChannel(target, new_args); // Clean up. diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc index 94cf61310b..a704b827a2 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/chttp2_server.cc @@ -44,7 +44,7 @@ #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/resolve_address.h" -#include "src/core/lib/iomgr/resource_quota.h" +#include "src/core/lib/iomgr/resource_quota.h" #include "src/core/lib/iomgr/tcp_server.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/api_trace.h" @@ -198,10 +198,10 @@ void Chttp2ServerListener::ConnectionState::OnHandshakeDone(void* arg, if (error != GRPC_ERROR_NONE || self->listener_->shutdown_) { const char* error_str = grpc_error_string(error); gpr_log(GPR_DEBUG, "Handshaking failed: %s", error_str); - if (resource_user != nullptr) { - grpc_resource_user_free(resource_user, - GRPC_RESOURCE_QUOTA_CHANNEL_SIZE); - } + if (resource_user != nullptr) { + grpc_resource_user_free(resource_user, + GRPC_RESOURCE_QUOTA_CHANNEL_SIZE); + } if (error == GRPC_ERROR_NONE && args->endpoint != nullptr) { // We were shut down after handshaking completed successfully, so // destroy the endpoint here. @@ -396,9 +396,9 @@ RefCountedPtr<HandshakeManager> Chttp2ServerListener::CreateHandshakeManager() { MutexLock lock(&mu_); if (shutdown_) return nullptr; grpc_resource_user* resource_user = server_->default_resource_user(); - if (resource_user != nullptr && - !grpc_resource_user_safe_alloc(resource_user, - GRPC_RESOURCE_QUOTA_CHANNEL_SIZE)) { + if (resource_user != nullptr && + !grpc_resource_user_safe_alloc(resource_user, + GRPC_RESOURCE_QUOTA_CHANNEL_SIZE)) { gpr_log(GPR_ERROR, "Memory quota exhausted, rejecting connection, no handshaking."); return nullptr; @@ -416,11 +416,11 @@ void Chttp2ServerListener::OnAccept(void* arg, grpc_endpoint* tcp, RefCountedPtr<HandshakeManager> handshake_mgr = self->CreateHandshakeManager(); if (handshake_mgr == nullptr) { - grpc_endpoint_shutdown(tcp, GRPC_ERROR_NONE); - grpc_endpoint_destroy(tcp); - gpr_free(acceptor); - return; - } + grpc_endpoint_shutdown(tcp, GRPC_ERROR_NONE); + grpc_endpoint_destroy(tcp); + gpr_free(acceptor); + return; + } // Deletes itself when done. new ConnectionState(self, accepting_pollset, acceptor, std::move(handshake_mgr), self->args_, tcp); @@ -439,7 +439,7 @@ void Chttp2ServerListener::TcpServerShutdownComplete(void* arg, self->pending_handshake_mgrs_->ShutdownAllPending(GRPC_ERROR_REF(error)); } self->channelz_listen_socket_.reset(); - } + } // Flush queued work before destroying handshaker factory, since that // may do a synchronous unref. ExecCtx::Get()->Flush(); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc index c49e1511a5..5b8390a87e 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc @@ -32,7 +32,7 @@ #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/handshaker.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/surface/api_trace.h" @@ -42,7 +42,7 @@ int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr, grpc_server_credentials* creds) { grpc_core::ExecCtx exec_ctx; grpc_error* err = GRPC_ERROR_NONE; - grpc_core::RefCountedPtr<grpc_server_security_connector> sc; + grpc_core::RefCountedPtr<grpc_server_security_connector> sc; int port_num = 0; grpc_channel_args* args = nullptr; GRPC_API_TRACE( @@ -55,8 +55,8 @@ int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr, "No credentials specified for secure server port (creds==NULL)"); goto done; } - sc = creds->create_security_connector(); - if (sc == nullptr) { + sc = creds->create_security_connector(); + if (sc == nullptr) { err = GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("Unable to create secure server with credentials of type ", creds->type()) @@ -66,7 +66,7 @@ int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr, // Create channel args. grpc_arg args_to_add[2]; args_to_add[0] = grpc_server_credentials_to_arg(creds); - args_to_add[1] = grpc_security_connector_to_arg(sc.get()); + args_to_add[1] = grpc_security_connector_to_arg(sc.get()); args = grpc_channel_args_copy_and_add(server->core_server->channel_args(), args_to_add, GPR_ARRAY_SIZE(args_to_add)); @@ -74,7 +74,7 @@ int grpc_server_add_secure_http2_port(grpc_server* server, const char* addr, err = grpc_core::Chttp2ServerAddPort(server->core_server.get(), addr, args, &port_num); done: - sc.reset(DEBUG_LOCATION, "server"); + sc.reset(DEBUG_LOCATION, "server"); if (err != GRPC_ERROR_NONE) { const char* msg = grpc_error_string(err); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc index 249035d7e8..856a5bafed 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/bin_decoder.cc @@ -55,7 +55,7 @@ static bool input_is_valid(const uint8_t* input_ptr, size_t length) { size_t i; for (i = 0; i < length; ++i) { - if (GPR_UNLIKELY((decode_table[input_ptr[i]] & 0xC0) != 0)) { + if (GPR_UNLIKELY((decode_table[input_ptr[i]] & 0xC0) != 0)) { gpr_log(GPR_ERROR, "Base64 decoding failed, invalid character '%c' in base64 " "input.\n", @@ -86,14 +86,14 @@ size_t grpc_chttp2_base64_infer_length_after_decode(const grpc_slice& slice) { while (len > 0 && bytes[len - 1] == '=') { len--; } - if (GPR_UNLIKELY(GRPC_SLICE_LENGTH(slice) - len > 2)) { + if (GPR_UNLIKELY(GRPC_SLICE_LENGTH(slice) - len > 2)) { gpr_log(GPR_ERROR, "Base64 decoding failed. Input has more than 2 paddings."); return 0; } size_t tuples = len / 4; size_t tail_case = len % 4; - if (GPR_UNLIKELY(tail_case == 1)) { + if (GPR_UNLIKELY(tail_case == 1)) { gpr_log(GPR_ERROR, "Base64 decoding failed. Input has a length of %zu (without" " padding), which is invalid.\n", @@ -164,7 +164,7 @@ grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input) { struct grpc_base64_decode_context ctx; grpc_slice output; - if (GPR_UNLIKELY(input_length % 4 != 0)) { + if (GPR_UNLIKELY(input_length % 4 != 0)) { gpr_log(GPR_ERROR, "Base64 decoding failed, input of " "grpc_chttp2_base64_decode has a length of %d, which is not a " @@ -190,7 +190,7 @@ grpc_slice grpc_chttp2_base64_decode(const grpc_slice& input) { ctx.output_end = GRPC_SLICE_END_PTR(output); ctx.contains_tail = false; - if (GPR_UNLIKELY(!grpc_base64_decode_partial(&ctx))) { + if (GPR_UNLIKELY(!grpc_base64_decode_partial(&ctx))) { char* s = grpc_slice_to_c_string(input); gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s); gpr_free(s); @@ -209,7 +209,7 @@ grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input, struct grpc_base64_decode_context ctx; // The length of a base64 string cannot be 4 * n + 1 - if (GPR_UNLIKELY(input_length % 4 == 1)) { + if (GPR_UNLIKELY(input_length % 4 == 1)) { gpr_log(GPR_ERROR, "Base64 decoding failed, input of " "grpc_chttp2_base64_decode_with_length has a length of %d, which " @@ -219,8 +219,8 @@ grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input, return grpc_empty_slice(); } - if (GPR_UNLIKELY(output_length > - input_length / 4 * 3 + tail_xtra[input_length % 4])) { + if (GPR_UNLIKELY(output_length > + input_length / 4 * 3 + tail_xtra[input_length % 4])) { gpr_log( GPR_ERROR, "Base64 decoding failed, output_length %d is longer " @@ -237,7 +237,7 @@ grpc_slice grpc_chttp2_base64_decode_with_length(const grpc_slice& input, ctx.output_end = GRPC_SLICE_END_PTR(output); ctx.contains_tail = true; - if (GPR_UNLIKELY(!grpc_base64_decode_partial(&ctx))) { + if (GPR_UNLIKELY(!grpc_base64_decode_partial(&ctx))) { char* s = grpc_slice_to_c_string(input); gpr_log(GPR_ERROR, "Base64 decoding failed, input string:\n%s\n", s); gpr_free(s); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc index 180ca62543..669c7133b6 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.cc @@ -31,7 +31,7 @@ #include <stdio.h> #include <string.h> -#include "src/core/ext/transport/chttp2/transport/context_list.h" +#include "src/core/ext/transport/chttp2/transport/context_list.h" #include "src/core/ext/transport/chttp2/transport/frame_data.h" #include "src/core/ext/transport/chttp2/transport/internal.h" #include "src/core/ext/transport/chttp2/transport/varint.h" @@ -43,7 +43,7 @@ #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/iomgr/executor.h" -#include "src/core/lib/iomgr/iomgr.h" +#include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/slice/slice_internal.h" @@ -55,7 +55,7 @@ #include "src/core/lib/transport/timeout_encoding.h" #include "src/core/lib/transport/transport.h" #include "src/core/lib/transport/transport_impl.h" -#include "src/core/lib/uri/uri_parser.h" +#include "src/core/lib/uri/uri_parser.h" #define DEFAULT_CONNECTION_WINDOW_TARGET (1024 * 1024) #define MAX_WINDOW 0x7fffffffu @@ -173,218 +173,218 @@ bool g_flow_control_enabled = true; // CONSTRUCTION/DESTRUCTION/REFCOUNTING // -grpc_chttp2_transport::~grpc_chttp2_transport() { +grpc_chttp2_transport::~grpc_chttp2_transport() { size_t i; - if (channelz_socket != nullptr) { - channelz_socket.reset(); - } - - grpc_endpoint_destroy(ep); - - grpc_slice_buffer_destroy_internal(&qbuf); - - grpc_slice_buffer_destroy_internal(&outbuf); - grpc_chttp2_hpack_compressor_destroy(&hpack_compressor); - - grpc_error* error = - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed"); - // ContextList::Execute follows semantics of a callback function and does not - // take a ref on error - grpc_core::ContextList::Execute(cl, nullptr, error); - GRPC_ERROR_UNREF(error); - cl = nullptr; - - grpc_slice_buffer_destroy_internal(&read_buffer); - grpc_chttp2_hpack_parser_destroy(&hpack_parser); - grpc_chttp2_goaway_parser_destroy(&goaway_parser); - + if (channelz_socket != nullptr) { + channelz_socket.reset(); + } + + grpc_endpoint_destroy(ep); + + grpc_slice_buffer_destroy_internal(&qbuf); + + grpc_slice_buffer_destroy_internal(&outbuf); + grpc_chttp2_hpack_compressor_destroy(&hpack_compressor); + + grpc_error* error = + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed"); + // ContextList::Execute follows semantics of a callback function and does not + // take a ref on error + grpc_core::ContextList::Execute(cl, nullptr, error); + GRPC_ERROR_UNREF(error); + cl = nullptr; + + grpc_slice_buffer_destroy_internal(&read_buffer); + grpc_chttp2_hpack_parser_destroy(&hpack_parser); + grpc_chttp2_goaway_parser_destroy(&goaway_parser); + for (i = 0; i < STREAM_LIST_COUNT; i++) { - GPR_ASSERT(lists[i].head == nullptr); - GPR_ASSERT(lists[i].tail == nullptr); + GPR_ASSERT(lists[i].head == nullptr); + GPR_ASSERT(lists[i].tail == nullptr); } - GRPC_ERROR_UNREF(goaway_error); + GRPC_ERROR_UNREF(goaway_error); - GPR_ASSERT(grpc_chttp2_stream_map_size(&stream_map) == 0); + GPR_ASSERT(grpc_chttp2_stream_map_size(&stream_map) == 0); - grpc_chttp2_stream_map_destroy(&stream_map); + grpc_chttp2_stream_map_destroy(&stream_map); - GRPC_COMBINER_UNREF(combiner, "chttp2_transport"); + GRPC_COMBINER_UNREF(combiner, "chttp2_transport"); - cancel_pings(this, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed")); + cancel_pings(this, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed")); - while (write_cb_pool) { - grpc_chttp2_write_cb* next = write_cb_pool->next; - gpr_free(write_cb_pool); - write_cb_pool = next; + while (write_cb_pool) { + grpc_chttp2_write_cb* next = write_cb_pool->next; + gpr_free(write_cb_pool); + write_cb_pool = next; } - flow_control.Destroy(); + flow_control.Destroy(); - GRPC_ERROR_UNREF(closed_with_error); - gpr_free(ping_acks); + GRPC_ERROR_UNREF(closed_with_error); + gpr_free(ping_acks); } static const grpc_transport_vtable* get_vtable(void); // Returns whether bdp is enabled -static bool read_channel_args(grpc_chttp2_transport* t, - const grpc_channel_args* channel_args, - bool is_client) { - bool enable_bdp = true; - bool channelz_enabled = GRPC_ENABLE_CHANNELZ_DEFAULT; +static bool read_channel_args(grpc_chttp2_transport* t, + const grpc_channel_args* channel_args, + bool is_client) { + bool enable_bdp = true; + bool channelz_enabled = GRPC_ENABLE_CHANNELZ_DEFAULT; size_t i; int j; - for (i = 0; i < channel_args->num_args; i++) { - if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_INITIAL_SEQUENCE_NUMBER)) { - const grpc_integer_options options = {-1, 0, INT_MAX}; - const int value = - grpc_channel_arg_get_integer(&channel_args->args[i], options); - if (value >= 0) { - if ((t->next_stream_id & 1) != (value & 1)) { - gpr_log(GPR_ERROR, "%s: low bit must be %d on %s", - GRPC_ARG_HTTP2_INITIAL_SEQUENCE_NUMBER, t->next_stream_id & 1, - is_client ? "client" : "server"); - } else { - t->next_stream_id = static_cast<uint32_t>(value); - } - } - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_HPACK_TABLE_SIZE_ENCODER)) { - const grpc_integer_options options = {-1, 0, INT_MAX}; - const int value = - grpc_channel_arg_get_integer(&channel_args->args[i], options); - if (value >= 0) { - grpc_chttp2_hpack_compressor_set_max_usable_size( - &t->hpack_compressor, static_cast<uint32_t>(value)); - } - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA)) { - t->ping_policy.max_pings_without_data = grpc_channel_arg_get_integer( - &channel_args->args[i], - {g_default_max_pings_without_data, 0, INT_MAX}); - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_MAX_PING_STRIKES)) { - t->ping_policy.max_ping_strikes = grpc_channel_arg_get_integer( - &channel_args->args[i], {g_default_max_ping_strikes, 0, INT_MAX}); - } else if (0 == - strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS)) { - t->ping_policy.min_sent_ping_interval_without_data = - grpc_channel_arg_get_integer( - &channel_args->args[i], - grpc_integer_options{ - g_default_min_sent_ping_interval_without_data_ms, 0, - INT_MAX}); - } else if (0 == - strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS)) { - t->ping_policy.min_recv_ping_interval_without_data = - grpc_channel_arg_get_integer( - &channel_args->args[i], - grpc_integer_options{ - g_default_min_recv_ping_interval_without_data_ms, 0, - INT_MAX}); - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_HTTP2_WRITE_BUFFER_SIZE)) { - t->write_buffer_size = static_cast<uint32_t>(grpc_channel_arg_get_integer( - &channel_args->args[i], {0, 0, MAX_WRITE_BUFFER_SIZE})); - } else if (0 == - strcmp(channel_args->args[i].key, GRPC_ARG_HTTP2_BDP_PROBE)) { - enable_bdp = grpc_channel_arg_get_bool(&channel_args->args[i], true); - } else if (0 == - strcmp(channel_args->args[i].key, GRPC_ARG_KEEPALIVE_TIME_MS)) { - const int value = grpc_channel_arg_get_integer( - &channel_args->args[i], - grpc_integer_options{t->is_client - ? g_default_client_keepalive_time_ms - : g_default_server_keepalive_time_ms, - 1, INT_MAX}); - t->keepalive_time = value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value; - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_KEEPALIVE_TIMEOUT_MS)) { - const int value = grpc_channel_arg_get_integer( - &channel_args->args[i], - grpc_integer_options{t->is_client - ? g_default_client_keepalive_timeout_ms - : g_default_server_keepalive_timeout_ms, - 0, INT_MAX}); - t->keepalive_timeout = value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value; - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS)) { - t->keepalive_permit_without_calls = static_cast<uint32_t>( - grpc_channel_arg_get_integer(&channel_args->args[i], {0, 0, 1})); - } else if (0 == strcmp(channel_args->args[i].key, - GRPC_ARG_OPTIMIZATION_TARGET)) { + for (i = 0; i < channel_args->num_args; i++) { + if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_INITIAL_SEQUENCE_NUMBER)) { + const grpc_integer_options options = {-1, 0, INT_MAX}; + const int value = + grpc_channel_arg_get_integer(&channel_args->args[i], options); + if (value >= 0) { + if ((t->next_stream_id & 1) != (value & 1)) { + gpr_log(GPR_ERROR, "%s: low bit must be %d on %s", + GRPC_ARG_HTTP2_INITIAL_SEQUENCE_NUMBER, t->next_stream_id & 1, + is_client ? "client" : "server"); + } else { + t->next_stream_id = static_cast<uint32_t>(value); + } + } + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_HPACK_TABLE_SIZE_ENCODER)) { + const grpc_integer_options options = {-1, 0, INT_MAX}; + const int value = + grpc_channel_arg_get_integer(&channel_args->args[i], options); + if (value >= 0) { + grpc_chttp2_hpack_compressor_set_max_usable_size( + &t->hpack_compressor, static_cast<uint32_t>(value)); + } + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA)) { + t->ping_policy.max_pings_without_data = grpc_channel_arg_get_integer( + &channel_args->args[i], + {g_default_max_pings_without_data, 0, INT_MAX}); + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_MAX_PING_STRIKES)) { + t->ping_policy.max_ping_strikes = grpc_channel_arg_get_integer( + &channel_args->args[i], {g_default_max_ping_strikes, 0, INT_MAX}); + } else if (0 == + strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS)) { + t->ping_policy.min_sent_ping_interval_without_data = + grpc_channel_arg_get_integer( + &channel_args->args[i], + grpc_integer_options{ + g_default_min_sent_ping_interval_without_data_ms, 0, + INT_MAX}); + } else if (0 == + strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS)) { + t->ping_policy.min_recv_ping_interval_without_data = + grpc_channel_arg_get_integer( + &channel_args->args[i], + grpc_integer_options{ + g_default_min_recv_ping_interval_without_data_ms, 0, + INT_MAX}); + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_HTTP2_WRITE_BUFFER_SIZE)) { + t->write_buffer_size = static_cast<uint32_t>(grpc_channel_arg_get_integer( + &channel_args->args[i], {0, 0, MAX_WRITE_BUFFER_SIZE})); + } else if (0 == + strcmp(channel_args->args[i].key, GRPC_ARG_HTTP2_BDP_PROBE)) { + enable_bdp = grpc_channel_arg_get_bool(&channel_args->args[i], true); + } else if (0 == + strcmp(channel_args->args[i].key, GRPC_ARG_KEEPALIVE_TIME_MS)) { + const int value = grpc_channel_arg_get_integer( + &channel_args->args[i], + grpc_integer_options{t->is_client + ? g_default_client_keepalive_time_ms + : g_default_server_keepalive_time_ms, + 1, INT_MAX}); + t->keepalive_time = value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value; + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_KEEPALIVE_TIMEOUT_MS)) { + const int value = grpc_channel_arg_get_integer( + &channel_args->args[i], + grpc_integer_options{t->is_client + ? g_default_client_keepalive_timeout_ms + : g_default_server_keepalive_timeout_ms, + 0, INT_MAX}); + t->keepalive_timeout = value == INT_MAX ? GRPC_MILLIS_INF_FUTURE : value; + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS)) { + t->keepalive_permit_without_calls = static_cast<uint32_t>( + grpc_channel_arg_get_integer(&channel_args->args[i], {0, 0, 1})); + } else if (0 == strcmp(channel_args->args[i].key, + GRPC_ARG_OPTIMIZATION_TARGET)) { gpr_log(GPR_INFO, "GRPC_ARG_OPTIMIZATION_TARGET is deprecated"); - } else if (0 == - strcmp(channel_args->args[i].key, GRPC_ARG_ENABLE_CHANNELZ)) { - channelz_enabled = grpc_channel_arg_get_bool( - &channel_args->args[i], GRPC_ENABLE_CHANNELZ_DEFAULT); - } else { - static const struct { - const char* channel_arg_name; - grpc_chttp2_setting_id setting_id; - grpc_integer_options integer_options; - bool availability[2] /* server, client */; - } settings_map[] = {{GRPC_ARG_MAX_CONCURRENT_STREAMS, - GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, - {-1, 0, INT32_MAX}, - {true, false}}, - {GRPC_ARG_HTTP2_HPACK_TABLE_SIZE_DECODER, - GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE, - {-1, 0, INT32_MAX}, - {true, true}}, - {GRPC_ARG_MAX_METADATA_SIZE, - GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE, - {-1, 0, INT32_MAX}, - {true, true}}, - {GRPC_ARG_HTTP2_MAX_FRAME_SIZE, - GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE, - {-1, 16384, 16777215}, - {true, true}}, - {GRPC_ARG_HTTP2_ENABLE_TRUE_BINARY, - GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA, - {1, 0, 1}, - {true, true}}, - {GRPC_ARG_HTTP2_STREAM_LOOKAHEAD_BYTES, - GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE, - {-1, 5, INT32_MAX}, - {true, true}}}; - for (j = 0; j < static_cast<int> GPR_ARRAY_SIZE(settings_map); j++) { - if (0 == strcmp(channel_args->args[i].key, - settings_map[j].channel_arg_name)) { - if (!settings_map[j].availability[is_client]) { - gpr_log(GPR_DEBUG, "%s is not available on %s", - settings_map[j].channel_arg_name, - is_client ? "clients" : "servers"); - } else { - int value = grpc_channel_arg_get_integer( - &channel_args->args[i], settings_map[j].integer_options); - if (value >= 0) { - queue_setting_update(t, settings_map[j].setting_id, - static_cast<uint32_t>(value)); - } - } - break; - } - } - } - } - if (channelz_enabled) { - t->channelz_socket = - grpc_core::MakeRefCounted<grpc_core::channelz::SocketNode>( + } else if (0 == + strcmp(channel_args->args[i].key, GRPC_ARG_ENABLE_CHANNELZ)) { + channelz_enabled = grpc_channel_arg_get_bool( + &channel_args->args[i], GRPC_ENABLE_CHANNELZ_DEFAULT); + } else { + static const struct { + const char* channel_arg_name; + grpc_chttp2_setting_id setting_id; + grpc_integer_options integer_options; + bool availability[2] /* server, client */; + } settings_map[] = {{GRPC_ARG_MAX_CONCURRENT_STREAMS, + GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, + {-1, 0, INT32_MAX}, + {true, false}}, + {GRPC_ARG_HTTP2_HPACK_TABLE_SIZE_DECODER, + GRPC_CHTTP2_SETTINGS_HEADER_TABLE_SIZE, + {-1, 0, INT32_MAX}, + {true, true}}, + {GRPC_ARG_MAX_METADATA_SIZE, + GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE, + {-1, 0, INT32_MAX}, + {true, true}}, + {GRPC_ARG_HTTP2_MAX_FRAME_SIZE, + GRPC_CHTTP2_SETTINGS_MAX_FRAME_SIZE, + {-1, 16384, 16777215}, + {true, true}}, + {GRPC_ARG_HTTP2_ENABLE_TRUE_BINARY, + GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA, + {1, 0, 1}, + {true, true}}, + {GRPC_ARG_HTTP2_STREAM_LOOKAHEAD_BYTES, + GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE, + {-1, 5, INT32_MAX}, + {true, true}}}; + for (j = 0; j < static_cast<int> GPR_ARRAY_SIZE(settings_map); j++) { + if (0 == strcmp(channel_args->args[i].key, + settings_map[j].channel_arg_name)) { + if (!settings_map[j].availability[is_client]) { + gpr_log(GPR_DEBUG, "%s is not available on %s", + settings_map[j].channel_arg_name, + is_client ? "clients" : "servers"); + } else { + int value = grpc_channel_arg_get_integer( + &channel_args->args[i], settings_map[j].integer_options); + if (value >= 0) { + queue_setting_update(t, settings_map[j].setting_id, + static_cast<uint32_t>(value)); + } + } + break; + } + } + } + } + if (channelz_enabled) { + t->channelz_socket = + grpc_core::MakeRefCounted<grpc_core::channelz::SocketNode>( TString(grpc_endpoint_get_local_address(t->ep)), t->peer_string, y_absl::StrFormat("%s %s", get_vtable()->name, t->peer_string)); - } - return enable_bdp; -} + } + return enable_bdp; +} -static void init_transport_keepalive_settings(grpc_chttp2_transport* t) { +static void init_transport_keepalive_settings(grpc_chttp2_transport* t) { if (t->is_client) { t->keepalive_time = g_default_client_keepalive_time_ms == INT_MAX ? GRPC_MILLIS_INF_FUTURE @@ -404,119 +404,119 @@ static void init_transport_keepalive_settings(grpc_chttp2_transport* t) { t->keepalive_permit_without_calls = g_default_server_keepalive_permit_without_calls; } -} - -static void configure_transport_ping_policy(grpc_chttp2_transport* t) { - t->ping_policy.max_pings_without_data = g_default_max_pings_without_data; - t->ping_policy.min_sent_ping_interval_without_data = - g_default_min_sent_ping_interval_without_data_ms; - t->ping_policy.max_ping_strikes = g_default_max_ping_strikes; - t->ping_policy.min_recv_ping_interval_without_data = - g_default_min_recv_ping_interval_without_data_ms; -} - -static void init_keepalive_pings_if_enabled(grpc_chttp2_transport* t) { - if (t->keepalive_time != GRPC_MILLIS_INF_FUTURE) { - t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING; - GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping"); +} + +static void configure_transport_ping_policy(grpc_chttp2_transport* t) { + t->ping_policy.max_pings_without_data = g_default_max_pings_without_data; + t->ping_policy.min_sent_ping_interval_without_data = + g_default_min_sent_ping_interval_without_data_ms; + t->ping_policy.max_ping_strikes = g_default_max_ping_strikes; + t->ping_policy.min_recv_ping_interval_without_data = + g_default_min_recv_ping_interval_without_data_ms; +} + +static void init_keepalive_pings_if_enabled(grpc_chttp2_transport* t) { + if (t->keepalive_time != GRPC_MILLIS_INF_FUTURE) { + t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_WAITING; + GRPC_CHTTP2_REF_TRANSPORT(t, "init keepalive ping"); GRPC_CLOSURE_INIT(&t->init_keepalive_ping_locked, init_keepalive_ping, t, grpc_schedule_on_exec_ctx); - grpc_timer_init(&t->keepalive_ping_timer, - grpc_core::ExecCtx::Get()->Now() + t->keepalive_time, - &t->init_keepalive_ping_locked); - } else { + grpc_timer_init(&t->keepalive_ping_timer, + grpc_core::ExecCtx::Get()->Now() + t->keepalive_time, + &t->init_keepalive_ping_locked); + } else { // Use GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED to indicate there are no // inflight keeaplive timers - t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED; - } -} - -grpc_chttp2_transport::grpc_chttp2_transport( - const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client, - grpc_resource_user* resource_user) - : refs(1, &grpc_trace_chttp2_refcount), - ep(ep), - peer_string(grpc_endpoint_get_peer(ep)), - resource_user(resource_user), - combiner(grpc_combiner_create()), + t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DISABLED; + } +} + +grpc_chttp2_transport::grpc_chttp2_transport( + const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client, + grpc_resource_user* resource_user) + : refs(1, &grpc_trace_chttp2_refcount), + ep(ep), + peer_string(grpc_endpoint_get_peer(ep)), + resource_user(resource_user), + combiner(grpc_combiner_create()), state_tracker(is_client ? "client_transport" : "server_transport", GRPC_CHANNEL_READY), - is_client(is_client), - next_stream_id(is_client ? 1 : 2), - deframe_state(is_client ? GRPC_DTS_FH_0 : GRPC_DTS_CLIENT_PREFIX_0) { - GPR_ASSERT(strlen(GRPC_CHTTP2_CLIENT_CONNECT_STRING) == - GRPC_CHTTP2_CLIENT_CONNECT_STRLEN); - base.vtable = get_vtable(); + is_client(is_client), + next_stream_id(is_client ? 1 : 2), + deframe_state(is_client ? GRPC_DTS_FH_0 : GRPC_DTS_CLIENT_PREFIX_0) { + GPR_ASSERT(strlen(GRPC_CHTTP2_CLIENT_CONNECT_STRING) == + GRPC_CHTTP2_CLIENT_CONNECT_STRLEN); + base.vtable = get_vtable(); // 8 is a random stab in the dark as to a good initial size: it's small enough // that it shouldn't waste memory for infrequently used connections, yet // large enough that the exponential growth should happen nicely when it's // needed. // TODO(ctiller): tune this - grpc_chttp2_stream_map_init(&stream_map, 8); - - grpc_slice_buffer_init(&read_buffer); - grpc_slice_buffer_init(&outbuf); - if (is_client) { - grpc_slice_buffer_add(&outbuf, grpc_slice_from_copied_string( - GRPC_CHTTP2_CLIENT_CONNECT_STRING)); - } - grpc_chttp2_hpack_compressor_init(&hpack_compressor); - grpc_slice_buffer_init(&qbuf); + grpc_chttp2_stream_map_init(&stream_map, 8); + + grpc_slice_buffer_init(&read_buffer); + grpc_slice_buffer_init(&outbuf); + if (is_client) { + grpc_slice_buffer_add(&outbuf, grpc_slice_from_copied_string( + GRPC_CHTTP2_CLIENT_CONNECT_STRING)); + } + grpc_chttp2_hpack_compressor_init(&hpack_compressor); + grpc_slice_buffer_init(&qbuf); // copy in initial settings to all setting sets - size_t i; - int j; - for (i = 0; i < GRPC_CHTTP2_NUM_SETTINGS; i++) { - for (j = 0; j < GRPC_NUM_SETTING_SETS; j++) { - settings[j][i] = grpc_chttp2_settings_parameters[i].default_value; + size_t i; + int j; + for (i = 0; i < GRPC_CHTTP2_NUM_SETTINGS; i++) { + for (j = 0; j < GRPC_NUM_SETTING_SETS; j++) { + settings[j][i] = grpc_chttp2_settings_parameters[i].default_value; } } - grpc_chttp2_hpack_parser_init(&hpack_parser); - grpc_chttp2_goaway_parser_init(&goaway_parser); + grpc_chttp2_hpack_parser_init(&hpack_parser); + grpc_chttp2_goaway_parser_init(&goaway_parser); // configure http2 the way we like it - if (is_client) { - queue_setting_update(this, GRPC_CHTTP2_SETTINGS_ENABLE_PUSH, 0); - queue_setting_update(this, GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, 0); - } - queue_setting_update(this, GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE, - DEFAULT_MAX_HEADER_LIST_SIZE); - queue_setting_update(this, - GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA, 1); - - configure_transport_ping_policy(this); - init_transport_keepalive_settings(this); - - bool enable_bdp = true; - if (channel_args) { - enable_bdp = read_channel_args(this, channel_args, is_client); - } - + if (is_client) { + queue_setting_update(this, GRPC_CHTTP2_SETTINGS_ENABLE_PUSH, 0); + queue_setting_update(this, GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS, 0); + } + queue_setting_update(this, GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE, + DEFAULT_MAX_HEADER_LIST_SIZE); + queue_setting_update(this, + GRPC_CHTTP2_SETTINGS_GRPC_ALLOW_TRUE_BINARY_METADATA, 1); + + configure_transport_ping_policy(this); + init_transport_keepalive_settings(this); + + bool enable_bdp = true; + if (channel_args) { + enable_bdp = read_channel_args(this, channel_args, is_client); + } + if (g_flow_control_enabled) { - flow_control.Init<grpc_core::chttp2::TransportFlowControl>(this, - enable_bdp); + flow_control.Init<grpc_core::chttp2::TransportFlowControl>(this, + enable_bdp); } else { - flow_control.Init<grpc_core::chttp2::TransportFlowControlDisabled>(this); + flow_control.Init<grpc_core::chttp2::TransportFlowControlDisabled>(this); enable_bdp = false; } // No pings allowed before receiving a header or data frame. - ping_state.pings_before_data_required = 0; - ping_state.is_delayed_ping_timer_set = false; - ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST; + ping_state.pings_before_data_required = 0; + ping_state.is_delayed_ping_timer_set = false; + ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST; - ping_recv_state.last_ping_recv_time = GRPC_MILLIS_INF_PAST; - ping_recv_state.ping_strikes = 0; + ping_recv_state.last_ping_recv_time = GRPC_MILLIS_INF_PAST; + ping_recv_state.ping_strikes = 0; - init_keepalive_pings_if_enabled(this); + init_keepalive_pings_if_enabled(this); if (enable_bdp) { bdp_ping_blocked = true; - grpc_chttp2_act_on_flowctl_action(flow_control->PeriodicUpdate(), this, + grpc_chttp2_act_on_flowctl_action(flow_control->PeriodicUpdate(), this, nullptr); } - grpc_chttp2_initiate_write(this, GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE); - post_benign_reclaimer(this); + grpc_chttp2_initiate_write(this, GRPC_CHTTP2_INITIATE_WRITE_INITIAL_WRITE); + post_benign_reclaimer(this); } static void destroy_transport_locked(void* tp, grpc_error* /*error*/) { @@ -526,7 +526,7 @@ static void destroy_transport_locked(void* tp, grpc_error* /*error*/) { t, grpc_error_set_int( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Transport destroyed"), GRPC_ERROR_INT_OCCURRED_DURING_WRITE, t->write_state)); - // Must be the last line. + // Must be the last line. GRPC_CHTTP2_UNREF_TRANSPORT(t, "destroy"); } @@ -629,42 +629,42 @@ grpc_chttp2_stream::grpc_chttp2_stream(grpc_chttp2_transport* t, metadata_buffer{grpc_chttp2_incoming_metadata_buffer(arena), grpc_chttp2_incoming_metadata_buffer(arena)} { if (server_data) { - id = static_cast<uint32_t>((uintptr_t)server_data); - *t->accepting_stream = this; - grpc_chttp2_stream_map_add(&t->stream_map, id, this); + id = static_cast<uint32_t>((uintptr_t)server_data); + *t->accepting_stream = this; + grpc_chttp2_stream_map_add(&t->stream_map, id, this); post_destructive_reclaimer(t); } if (t->flow_control->flow_control_enabled()) { - flow_control.Init<grpc_core::chttp2::StreamFlowControl>( + flow_control.Init<grpc_core::chttp2::StreamFlowControl>( static_cast<grpc_core::chttp2::TransportFlowControl*>( t->flow_control.get()), - this); + this); } else { - flow_control.Init<grpc_core::chttp2::StreamFlowControlDisabled>(); + flow_control.Init<grpc_core::chttp2::StreamFlowControlDisabled>(); } - grpc_slice_buffer_init(&frame_storage); - grpc_slice_buffer_init(&unprocessed_incoming_frames_buffer); - grpc_slice_buffer_init(&flow_controlled_buffer); + grpc_slice_buffer_init(&frame_storage); + grpc_slice_buffer_init(&unprocessed_incoming_frames_buffer); + grpc_slice_buffer_init(&flow_controlled_buffer); GRPC_CLOSURE_INIT(&reset_byte_stream, ::reset_byte_stream, this, nullptr); } -grpc_chttp2_stream::~grpc_chttp2_stream() { - if (t->channelz_socket != nullptr) { - if ((t->is_client && eos_received) || (!t->is_client && eos_sent)) { - t->channelz_socket->RecordStreamSucceeded(); - } else { - t->channelz_socket->RecordStreamFailed(); - } - } +grpc_chttp2_stream::~grpc_chttp2_stream() { + if (t->channelz_socket != nullptr) { + if ((t->is_client && eos_received) || (!t->is_client && eos_sent)) { + t->channelz_socket->RecordStreamSucceeded(); + } else { + t->channelz_socket->RecordStreamFailed(); + } + } - GPR_ASSERT((write_closed && read_closed) || id == 0); - if (id != 0) { - GPR_ASSERT(grpc_chttp2_stream_map_find(&t->stream_map, id) == nullptr); + GPR_ASSERT((write_closed && read_closed) || id == 0); + if (id != 0) { + GPR_ASSERT(grpc_chttp2_stream_map_find(&t->stream_map, id) == nullptr); } - grpc_slice_buffer_destroy_internal(&unprocessed_incoming_frames_buffer); - grpc_slice_buffer_destroy_internal(&frame_storage); + grpc_slice_buffer_destroy_internal(&unprocessed_incoming_frames_buffer); + grpc_slice_buffer_destroy_internal(&frame_storage); if (stream_compression_method != GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS) { grpc_slice_buffer_destroy_internal(&compressed_data_buffer); } @@ -674,49 +674,49 @@ grpc_chttp2_stream::~grpc_chttp2_stream() { } for (int i = 0; i < STREAM_LIST_COUNT; i++) { - if (GPR_UNLIKELY(included[i])) { + if (GPR_UNLIKELY(included[i])) { gpr_log(GPR_ERROR, "%s stream %d still included in list %d", - t->is_client ? "client" : "server", id, i); + t->is_client ? "client" : "server", id, i); abort(); } } - GPR_ASSERT(send_initial_metadata_finished == nullptr); - GPR_ASSERT(fetching_send_message == nullptr); - GPR_ASSERT(send_trailing_metadata_finished == nullptr); - GPR_ASSERT(recv_initial_metadata_ready == nullptr); - GPR_ASSERT(recv_message_ready == nullptr); - GPR_ASSERT(recv_trailing_metadata_finished == nullptr); - grpc_slice_buffer_destroy_internal(&flow_controlled_buffer); - GRPC_ERROR_UNREF(read_closed_error); - GRPC_ERROR_UNREF(write_closed_error); - GRPC_ERROR_UNREF(byte_stream_error); + GPR_ASSERT(send_initial_metadata_finished == nullptr); + GPR_ASSERT(fetching_send_message == nullptr); + GPR_ASSERT(send_trailing_metadata_finished == nullptr); + GPR_ASSERT(recv_initial_metadata_ready == nullptr); + GPR_ASSERT(recv_message_ready == nullptr); + GPR_ASSERT(recv_trailing_metadata_finished == nullptr); + grpc_slice_buffer_destroy_internal(&flow_controlled_buffer); + GRPC_ERROR_UNREF(read_closed_error); + GRPC_ERROR_UNREF(write_closed_error); + GRPC_ERROR_UNREF(byte_stream_error); - flow_control.Destroy(); - - if (t->resource_user != nullptr) { - grpc_resource_user_free(t->resource_user, GRPC_RESOURCE_QUOTA_CALL_SIZE); - } + flow_control.Destroy(); + if (t->resource_user != nullptr) { + grpc_resource_user_free(t->resource_user, GRPC_RESOURCE_QUOTA_CALL_SIZE); + } + GRPC_CHTTP2_UNREF_TRANSPORT(t, "stream"); grpc_core::ExecCtx::Run(DEBUG_LOCATION, destroy_stream_arg, GRPC_ERROR_NONE); -} +} -static int init_stream(grpc_transport* gt, grpc_stream* gs, - grpc_stream_refcount* refcount, const void* server_data, +static int init_stream(grpc_transport* gt, grpc_stream* gs, + grpc_stream_refcount* refcount, const void* server_data, grpc_core::Arena* arena) { - GPR_TIMER_SCOPE("init_stream", 0); - grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt); - new (gs) grpc_chttp2_stream(t, refcount, server_data, arena); - return 0; + GPR_TIMER_SCOPE("init_stream", 0); + grpc_chttp2_transport* t = reinterpret_cast<grpc_chttp2_transport*>(gt); + new (gs) grpc_chttp2_stream(t, refcount, server_data, arena); + return 0; } static void destroy_stream_locked(void* sp, grpc_error* /*error*/) { - GPR_TIMER_SCOPE("destroy_stream", 0); - grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp); - s->~grpc_chttp2_stream(); -} - + GPR_TIMER_SCOPE("destroy_stream", 0); + grpc_chttp2_stream* s = static_cast<grpc_chttp2_stream*>(sp); + s->~grpc_chttp2_stream(); +} + static void destroy_stream(grpc_transport* gt, grpc_stream* gs, grpc_closure* then_schedule_closure) { GPR_TIMER_SCOPE("destroy_stream", 0); @@ -746,19 +746,19 @@ grpc_chttp2_stream* grpc_chttp2_parsing_accept_stream(grpc_chttp2_transport* t, if (t->accept_stream_cb == nullptr) { return nullptr; } - // Don't accept the stream if memory quota doesn't allow. Note that we should - // simply refuse the stream here instead of canceling the stream after it's - // accepted since the latter will create the call which costs much memory. - if (t->resource_user != nullptr && - !grpc_resource_user_safe_alloc(t->resource_user, - GRPC_RESOURCE_QUOTA_CALL_SIZE)) { - gpr_log(GPR_ERROR, "Memory exhausted, rejecting the stream."); + // Don't accept the stream if memory quota doesn't allow. Note that we should + // simply refuse the stream here instead of canceling the stream after it's + // accepted since the latter will create the call which costs much memory. + if (t->resource_user != nullptr && + !grpc_resource_user_safe_alloc(t->resource_user, + GRPC_RESOURCE_QUOTA_CALL_SIZE)) { + gpr_log(GPR_ERROR, "Memory exhausted, rejecting the stream."); grpc_chttp2_add_rst_stream_to_next_write(t, id, GRPC_HTTP2_REFUSED_STREAM, nullptr); - grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM); - return nullptr; - } - grpc_chttp2_stream* accepting = nullptr; + grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_RST_STREAM); + return nullptr; + } + grpc_chttp2_stream* accepting = nullptr; GPR_ASSERT(t->accepting_stream == nullptr); t->accepting_stream = &accepting; t->accept_stream_cb(t->accept_stream_cb_user_data, &t->base, @@ -928,7 +928,7 @@ static const char* begin_writing_desc(bool partial) { return "begin partial write in background"; } else { return "begin write in current thread"; - } + } } static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) { @@ -973,13 +973,13 @@ static void write_action_begin_locked(void* gt, grpc_error* /*error_ignored*/) { static void write_action(void* gt, grpc_error* /*error*/) { GPR_TIMER_SCOPE("write_action", 0); grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(gt); - void* cl = t->cl; - t->cl = nullptr; + void* cl = t->cl; + t->cl = nullptr; grpc_endpoint_write( t->ep, &t->outbuf, GRPC_CLOSURE_INIT(&t->write_action_end_locked, write_action_end, t, grpc_schedule_on_exec_ctx), - cl); + cl); } static void write_action_end(void* tp, grpc_error* error) { @@ -1087,9 +1087,9 @@ void grpc_chttp2_add_incoming_goaway(grpc_chttp2_transport* t, // data equal to "too_many_pings", it should log the occurrence at a log level // that is enabled by default and double the configured KEEPALIVE_TIME used // for new connections on that channel. - if (GPR_UNLIKELY(t->is_client && - goaway_error == GRPC_HTTP2_ENHANCE_YOUR_CALM && - grpc_slice_str_cmp(goaway_text, "too_many_pings") == 0)) { + if (GPR_UNLIKELY(t->is_client && + goaway_error == GRPC_HTTP2_ENHANCE_YOUR_CALM && + grpc_slice_str_cmp(goaway_text, "too_many_pings") == 0)) { gpr_log(GPR_ERROR, "Received a GOAWAY with error code ENHANCE_YOUR_CALM and debug " "data equal to \"too_many_pings\""); @@ -1167,7 +1167,7 @@ static void maybe_start_some_streams(grpc_chttp2_transport* t) { // Flag that this closure barrier may be covering a write in a pollset, and so // we should not complete this closure until we can prove that the write got // scheduled -#define CLOSURE_BARRIER_MAY_COVER_WRITE (1 << 0) +#define CLOSURE_BARRIER_MAY_COVER_WRITE (1 << 0) // First bit of the reference count, stored in the high order bits (with the low // bits being used for flags defined above) #define CLOSURE_BARRIER_FIRST_REF_BIT (1 << 16) @@ -1354,8 +1354,8 @@ static void perform_stream_op_locked(void* stream_op, GRPC_STATS_INC_HTTP2_OP_BATCHES(); - s->context = op->payload->context; - s->traced = op->is_traced; + s->context = op->payload->context; + s->traced = op->is_traced; if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) { gpr_log(GPR_INFO, "perform_stream_op_locked: %s; on_complete = %p", grpc_transport_stream_op_batch_string(op).c_str(), op->on_complete); @@ -1384,9 +1384,9 @@ static void perform_stream_op_locked(void* stream_op, } if (op->send_initial_metadata) { - if (t->is_client && t->channelz_socket != nullptr) { - t->channelz_socket->RecordStreamStartedFromLocal(); - } + if (t->is_client && t->channelz_socket != nullptr) { + t->channelz_socket->RecordStreamStartedFromLocal(); + } GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA(); GPR_ASSERT(s->send_initial_metadata_finished == nullptr); on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE; @@ -1450,14 +1450,14 @@ static void perform_stream_op_locked(void* stream_op, "send_initial_metadata_finished"); } if (op_payload->send_initial_metadata.peer_string != nullptr) { - gpr_atm_rel_store(op_payload->send_initial_metadata.peer_string, + gpr_atm_rel_store(op_payload->send_initial_metadata.peer_string, (gpr_atm)t->peer_string.c_str()); } } if (op->send_message) { GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE(); - t->num_messages_in_next_write++; + t->num_messages_in_next_write++; GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE( op->payload->send_message.send_message->length()); on_complete->next_data.scratch |= CLOSURE_BARRIER_MAY_COVER_WRITE; @@ -1543,7 +1543,7 @@ static void perform_stream_op_locked(void* stream_op, s->trailing_metadata_available = op_payload->recv_initial_metadata.trailing_metadata_available; if (op_payload->recv_initial_metadata.peer_string != nullptr) { - gpr_atm_rel_store(op_payload->recv_initial_metadata.peer_string, + gpr_atm_rel_store(op_payload->recv_initial_metadata.peer_string, (gpr_atm)t->peer_string.c_str()); } grpc_chttp2_maybe_complete_recv_initial_metadata(t, s); @@ -1576,11 +1576,11 @@ static void perform_stream_op_locked(void* stream_op, if (op->recv_trailing_metadata) { GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA(); - GPR_ASSERT(s->collecting_stats == nullptr); - s->collecting_stats = op_payload->recv_trailing_metadata.collect_stats; + GPR_ASSERT(s->collecting_stats == nullptr); + s->collecting_stats = op_payload->recv_trailing_metadata.collect_stats; GPR_ASSERT(s->recv_trailing_metadata_finished == nullptr); - s->recv_trailing_metadata_finished = - op_payload->recv_trailing_metadata.recv_trailing_metadata_ready; + s->recv_trailing_metadata_finished = + op_payload->recv_trailing_metadata.recv_trailing_metadata_ready; s->recv_trailing_metadata = op_payload->recv_trailing_metadata.recv_trailing_metadata; s->final_metadata_requested = true; @@ -1619,7 +1619,7 @@ static void perform_stream_op(grpc_transport* gt, grpc_stream* gs, grpc_transport_stream_op_batch_string(op).c_str()); } - GRPC_CHTTP2_STREAM_REF(s, "perform_stream_op"); + GRPC_CHTTP2_STREAM_REF(s, "perform_stream_op"); op->handler_private.extra_arg = gs; t->combiner->Run(GRPC_CLOSURE_INIT(&op->handler_private.closure, perform_stream_op_locked, op, nullptr), @@ -1661,7 +1661,7 @@ static void send_keepalive_ping_locked(grpc_chttp2_transport* t) { if (t->closed_with_error != GRPC_ERROR_NONE) { t->combiner->Run(GRPC_CLOSURE_INIT(&t->start_keepalive_ping_locked, start_keepalive_ping_locked, t, nullptr), - GRPC_ERROR_REF(t->closed_with_error)); + GRPC_ERROR_REF(t->closed_with_error)); t->combiner->Run( GRPC_CLOSURE_INIT(&t->finish_keepalive_ping_locked, finish_keepalive_ping_locked, t, nullptr), @@ -1726,7 +1726,7 @@ void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id) { static void send_goaway(grpc_chttp2_transport* t, grpc_error* error) { // We want to log this irrespective of whether http tracing is enabled gpr_log(GPR_INFO, "%s: Sending goaway err=%s", t->peer_string.c_str(), - grpc_error_string(error)); + grpc_error_string(error)); t->sent_goaway_state = GRPC_CHTTP2_GOAWAY_SEND_SCHEDULED; grpc_http2_error_code http_error; grpc_slice slice; @@ -1813,7 +1813,7 @@ static void perform_transport_op(grpc_transport* gt, grpc_transport_op* op) { if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) { gpr_log(GPR_INFO, "perform_transport_op[t=%p]: %s", t, grpc_transport_op_string(op).c_str()); - } + } op->handler_private.extra_arg = gt; GRPC_CHTTP2_REF_TRANSPORT(t, "transport_op"); t->combiner->Run(GRPC_CLOSURE_INIT(&op->handler_private.closure, @@ -1984,8 +1984,8 @@ void grpc_chttp2_maybe_complete_recv_trailing_metadata(grpc_chttp2_transport* t, } if (s->read_closed && s->frame_storage.length == 0 && !pending_data && s->recv_trailing_metadata_finished != nullptr) { - grpc_transport_move_stats(&s->stats, s->collecting_stats); - s->collecting_stats = nullptr; + grpc_transport_move_stats(&s->stats, s->collecting_stats); + s->collecting_stats = nullptr; grpc_chttp2_incoming_metadata_buffer_publish(&s->metadata_buffer[1], s->recv_trailing_metadata); null_then_sched_closure(&s->recv_trailing_metadata_finished); @@ -2089,7 +2089,7 @@ void grpc_chttp2_fake_status(grpc_chttp2_transport* t, grpc_chttp2_stream* s, "add_status_message", grpc_chttp2_incoming_metadata_buffer_replace_or_add( &s->metadata_buffer[1], - grpc_mdelem_create(GRPC_MDSTR_GRPC_MESSAGE, slice, nullptr))); + grpc_mdelem_create(GRPC_MDSTR_GRPC_MESSAGE, slice, nullptr))); } s->published_metadata[1] = GRPC_METADATA_SYNTHESIZED_FROM_FAKE; grpc_chttp2_maybe_complete_recv_trailing_metadata(t, s); @@ -2540,9 +2540,9 @@ static void read_action_locked(void* tp, grpc_error* error) { } else if (t->closed_with_error == GRPC_ERROR_NONE) { keep_reading = true; // Since we have read a byte, reset the keepalive timer - if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING) { - grpc_timer_cancel(&t->keepalive_ping_timer); - } + if (t->keepalive_state == GRPC_CHTTP2_KEEPALIVE_STATE_WAITING) { + grpc_timer_cancel(&t->keepalive_ping_timer); + } } grpc_slice_buffer_reset_and_unref_internal(&t->read_buffer); @@ -2757,7 +2757,7 @@ static void init_keepalive_ping_locked(void* arg, grpc_error* error) { grpc_chttp2_stream_map_size(&t->stream_map) > 0) { t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_PINGING; GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive ping end"); - grpc_timer_init_unset(&t->keepalive_watchdog_timer); + grpc_timer_init_unset(&t->keepalive_watchdog_timer); send_keepalive_ping_locked(t); grpc_chttp2_initiate_write(t, GRPC_CHTTP2_INITIATE_WRITE_KEEPALIVE_PING); } else { @@ -2789,16 +2789,16 @@ static void start_keepalive_ping(void* arg, grpc_error* error) { static void start_keepalive_ping_locked(void* arg, grpc_error* error) { grpc_chttp2_transport* t = static_cast<grpc_chttp2_transport*>(arg); - if (error != GRPC_ERROR_NONE) { - return; - } - if (t->channelz_socket != nullptr) { - t->channelz_socket->RecordKeepaliveSent(); - } + if (error != GRPC_ERROR_NONE) { + return; + } + if (t->channelz_socket != nullptr) { + t->channelz_socket->RecordKeepaliveSent(); + } if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) || GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) { gpr_log(GPR_INFO, "%s: Start keepalive ping", t->peer_string.c_str()); - } + } GRPC_CHTTP2_REF_TRANSPORT(t, "keepalive watchdog"); GRPC_CLOSURE_INIT(&t->keepalive_watchdog_fired_locked, keepalive_watchdog_fired, t, grpc_schedule_on_exec_ctx); @@ -2822,7 +2822,7 @@ static void finish_keepalive_ping_locked(void* arg, grpc_error* error) { if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace) || GRPC_TRACE_FLAG_ENABLED(grpc_keepalive_trace)) { gpr_log(GPR_INFO, "%s: Finish keepalive ping", t->peer_string.c_str()); - } + } if (!t->keepalive_ping_started) { // start_keepalive_ping_locked has not run yet. Reschedule // finish_keepalive_ping_locked for it to be run later. @@ -2862,15 +2862,15 @@ static void keepalive_watchdog_fired_locked(void* arg, grpc_error* error) { t->peer_string.c_str()); t->keepalive_state = GRPC_CHTTP2_KEEPALIVE_STATE_DYING; close_transport_locked( - t, grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "keepalive watchdog timeout"), - GRPC_ERROR_INT_GRPC_STATUS, - GRPC_STATUS_UNAVAILABLE)); + t, grpc_error_set_int(GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "keepalive watchdog timeout"), + GRPC_ERROR_INT_GRPC_STATUS, + GRPC_STATUS_UNAVAILABLE)); } } else { // The watchdog timer should have been cancelled by // finish_keepalive_ping_locked. - if (GPR_UNLIKELY(error != GRPC_ERROR_CANCELLED)) { + if (GPR_UNLIKELY(error != GRPC_ERROR_CANCELLED)) { gpr_log(GPR_ERROR, "keepalive_ping_end state error: %d (expect: %d)", t->keepalive_state, GRPC_CHTTP2_KEEPALIVE_STATE_PINGING); } @@ -2936,7 +2936,7 @@ Chttp2IncomingByteStream::Chttp2IncomingByteStream( : ByteStream(frame_size, flags), transport_(transport), stream_(stream), - refs_(2), + refs_(2), remaining_bytes_(frame_size) { GRPC_ERROR_UNREF(stream->byte_stream_error); stream->byte_stream_error = GRPC_ERROR_NONE; @@ -3023,15 +3023,15 @@ bool Chttp2IncomingByteStream::Next(size_t max_size_hint, } } -void Chttp2IncomingByteStream::MaybeCreateStreamDecompressionCtx() { +void Chttp2IncomingByteStream::MaybeCreateStreamDecompressionCtx() { GPR_DEBUG_ASSERT(stream_->stream_decompression_method != GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS); - if (!stream_->stream_decompression_ctx) { - stream_->stream_decompression_ctx = grpc_stream_compression_context_create( - stream_->stream_decompression_method); - } -} - + if (!stream_->stream_decompression_ctx) { + stream_->stream_decompression_ctx = grpc_stream_compression_context_create( + stream_->stream_decompression_method); + } +} + grpc_error* Chttp2IncomingByteStream::Pull(grpc_slice* slice) { GPR_TIMER_SCOPE("incoming_byte_stream_pull", 0); grpc_error* error; @@ -3040,7 +3040,7 @@ grpc_error* Chttp2IncomingByteStream::Pull(grpc_slice* slice) { stream_->stream_decompression_method != GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS) { bool end_of_context; - MaybeCreateStreamDecompressionCtx(); + MaybeCreateStreamDecompressionCtx(); if (!grpc_stream_decompress(stream_->stream_decompression_ctx, &stream_->unprocessed_incoming_frames_buffer, &stream_->decompressed_data_buffer, nullptr, @@ -3297,16 +3297,16 @@ static const grpc_transport_vtable vtable = {sizeof(grpc_chttp2_stream), static const grpc_transport_vtable* get_vtable(void) { return &vtable; } -grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> -grpc_chttp2_transport_get_socket_node(grpc_transport* transport) { - grpc_chttp2_transport* t = - reinterpret_cast<grpc_chttp2_transport*>(transport); - return t->channelz_socket; -} - +grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> +grpc_chttp2_transport_get_socket_node(grpc_transport* transport) { + grpc_chttp2_transport* t = + reinterpret_cast<grpc_chttp2_transport*>(transport); + return t->channelz_socket; +} + grpc_transport* grpc_create_chttp2_transport( - const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client, - grpc_resource_user* resource_user) { + const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client, + grpc_resource_user* resource_user) { auto t = new grpc_chttp2_transport(channel_args, ep, is_client, resource_user); return &t->base; diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h index b04630bbe2..4ac185597f 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/chttp2_transport.h @@ -21,7 +21,7 @@ #include <grpc/support/port_platform.h> -#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channelz.h" #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/transport/transport.h" @@ -35,12 +35,12 @@ extern grpc_core::DebugOnlyTraceFlag grpc_trace_chttp2_hpack_parser; extern bool g_flow_control_enabled; grpc_transport* grpc_create_chttp2_transport( - const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client, - grpc_resource_user* resource_user = nullptr); - -grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> -grpc_chttp2_transport_get_socket_node(grpc_transport* transport); + const grpc_channel_args* channel_args, grpc_endpoint* ep, bool is_client, + grpc_resource_user* resource_user = nullptr); +grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> +grpc_chttp2_transport_get_socket_node(grpc_transport* transport); + /// Takes ownership of \a read_buffer, which (if non-NULL) contains /// leftover bytes previously read from the endpoint (e.g., by handshakers). /// If non-null, \a notify_on_receive_settings will be scheduled when diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc index a0473ea822..f723e476a5 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.cc @@ -1,69 +1,69 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/ext/transport/chttp2/transport/context_list.h" - -namespace { -void (*write_timestamps_callback_g)(void*, grpc_core::Timestamps*, - grpc_error* error) = nullptr; -void* (*get_copied_context_fn_g)(void*) = nullptr; -} // namespace - -namespace grpc_core { -void ContextList::Append(ContextList** head, grpc_chttp2_stream* s) { - if (get_copied_context_fn_g == nullptr || - write_timestamps_callback_g == nullptr) { - return; - } - /* Create a new element in the list and add it at the front */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/ext/transport/chttp2/transport/context_list.h" + +namespace { +void (*write_timestamps_callback_g)(void*, grpc_core::Timestamps*, + grpc_error* error) = nullptr; +void* (*get_copied_context_fn_g)(void*) = nullptr; +} // namespace + +namespace grpc_core { +void ContextList::Append(ContextList** head, grpc_chttp2_stream* s) { + if (get_copied_context_fn_g == nullptr || + write_timestamps_callback_g == nullptr) { + return; + } + /* Create a new element in the list and add it at the front */ ContextList* elem = new ContextList(); - elem->trace_context_ = get_copied_context_fn_g(s->context); - elem->byte_offset_ = s->byte_counter; - elem->next_ = *head; - *head = elem; -} - -void ContextList::Execute(void* arg, grpc_core::Timestamps* ts, - grpc_error* error) { - ContextList* head = static_cast<ContextList*>(arg); - ContextList* to_be_freed; - while (head != nullptr) { - if (write_timestamps_callback_g) { + elem->trace_context_ = get_copied_context_fn_g(s->context); + elem->byte_offset_ = s->byte_counter; + elem->next_ = *head; + *head = elem; +} + +void ContextList::Execute(void* arg, grpc_core::Timestamps* ts, + grpc_error* error) { + ContextList* head = static_cast<ContextList*>(arg); + ContextList* to_be_freed; + while (head != nullptr) { + if (write_timestamps_callback_g) { if (ts) { ts->byte_offset = static_cast<uint32_t>(head->byte_offset_); } - write_timestamps_callback_g(head->trace_context_, ts, error); - } - to_be_freed = head; - head = head->next_; + write_timestamps_callback_g(head->trace_context_, ts, error); + } + to_be_freed = head; + head = head->next_; delete to_be_freed; - } -} - -void grpc_http2_set_write_timestamps_callback(void (*fn)(void*, - grpc_core::Timestamps*, - grpc_error* error)) { - write_timestamps_callback_g = fn; -} - -void grpc_http2_set_fn_get_copied_context(void* (*fn)(void*)) { - get_copied_context_fn_g = fn; -} -} /* namespace grpc_core */ + } +} + +void grpc_http2_set_write_timestamps_callback(void (*fn)(void*, + grpc_core::Timestamps*, + grpc_error* error)) { + write_timestamps_callback_g = fn; +} + +void grpc_http2_set_fn_get_copied_context(void* (*fn)(void*)) { + get_copied_context_fn_g = fn; +} +} /* namespace grpc_core */ diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.h index 5b9d2ab378..773495f7a8 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/context_list.h @@ -1,53 +1,53 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CONTEXT_LIST_H -#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CONTEXT_LIST_H - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/buffer_list.h" - -#include "src/core/ext/transport/chttp2/transport/internal.h" - -namespace grpc_core { -/** A list of RPC Contexts */ -class ContextList { - public: - /* Creates a new element with \a context as the value and appends it to the - * list. */ - static void Append(ContextList** head, grpc_chttp2_stream* s); - - /* Executes a function \a fn with each context in the list and \a ts. It also - * frees up the entire list after this operation. It is intended as a callback - * and hence does not take a ref on \a error */ - static void Execute(void* arg, grpc_core::Timestamps* ts, grpc_error* error); - - private: - void* trace_context_ = nullptr; - ContextList* next_ = nullptr; - size_t byte_offset_ = 0; -}; - -void grpc_http2_set_write_timestamps_callback(void (*fn)(void*, - grpc_core::Timestamps*, - grpc_error* error)); -void grpc_http2_set_fn_get_copied_context(void* (*fn)(void*)); -} /* namespace grpc_core */ - -#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CONTEXT_LIST_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CONTEXT_LIST_H +#define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CONTEXT_LIST_H + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/buffer_list.h" + +#include "src/core/ext/transport/chttp2/transport/internal.h" + +namespace grpc_core { +/** A list of RPC Contexts */ +class ContextList { + public: + /* Creates a new element with \a context as the value and appends it to the + * list. */ + static void Append(ContextList** head, grpc_chttp2_stream* s); + + /* Executes a function \a fn with each context in the list and \a ts. It also + * frees up the entire list after this operation. It is intended as a callback + * and hence does not take a ref on \a error */ + static void Execute(void* arg, grpc_core::Timestamps* ts, grpc_error* error); + + private: + void* trace_context_ = nullptr; + ContextList* next_ = nullptr; + size_t byte_offset_ = 0; +}; + +void grpc_http2_set_write_timestamps_callback(void (*fn)(void*, + grpc_core::Timestamps*, + grpc_error* error)); +void grpc_http2_set_fn_get_copied_context(void* (*fn)(void*)); +} /* namespace grpc_core */ + +#endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_CONTEXT_LIST_H */ diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc index fd76c4b3d9..cdb9f53159 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/flow_control.cc @@ -46,7 +46,7 @@ TestOnlyTransportTargetWindowEstimatesMocker* namespace { static constexpr const int kTracePadding = 30; -static constexpr const uint32_t kMaxWindowUpdateSize = (1u << 31) - 1; +static constexpr const uint32_t kMaxWindowUpdateSize = (1u << 31) - 1; static char* fmt_int64_diff_str(int64_t old_val, int64_t new_val) { TString str; @@ -60,7 +60,7 @@ static char* fmt_int64_diff_str(int64_t old_val, int64_t new_val) { static char* fmt_uint32_diff_str(uint32_t old_val, uint32_t new_val) { TString str; - if (old_val != new_val) { + if (old_val != new_val) { str = y_absl::StrFormat("%" PRIu32 " -> %" PRIu32 "", old_val, new_val); } else { str = y_absl::StrFormat("%" PRIu32 "", old_val); @@ -101,19 +101,19 @@ void FlowControlTrace::Finish() { if (sfc_ != nullptr) { srw_str = fmt_int64_diff_str(remote_window_delta_ + remote_window, sfc_->remote_window_delta() + remote_window); - slw_str = - fmt_int64_diff_str(local_window_delta_ + acked_local_window, - sfc_->local_window_delta() + acked_local_window); - saw_str = - fmt_int64_diff_str(announced_window_delta_ + acked_local_window, - sfc_->announced_window_delta() + acked_local_window); + slw_str = + fmt_int64_diff_str(local_window_delta_ + acked_local_window, + sfc_->local_window_delta() + acked_local_window); + saw_str = + fmt_int64_diff_str(announced_window_delta_ + acked_local_window, + sfc_->announced_window_delta() + acked_local_window); } else { srw_str = gpr_leftpad("", ' ', kTracePadding); slw_str = gpr_leftpad("", ' ', kTracePadding); saw_str = gpr_leftpad("", ' ', kTracePadding); } gpr_log(GPR_DEBUG, - "%p[%u][%s] | %s | trw:%s, tlw:%s, taw:%s, srw:%s, slw:%s, saw:%s", + "%p[%u][%s] | %s | trw:%s, tlw:%s, taw:%s, srw:%s, slw:%s, saw:%s", tfc_, sfc_ != nullptr ? sfc_->stream()->id : 0, tfc_->transport()->is_client ? "cli" : "svr", reason_, trw_str, tlw_str, taw_str, srw_str, slw_str, saw_str); @@ -196,7 +196,7 @@ uint32_t TransportFlowControl::MaybeSendUpdate(bool writing_anyway) { if ((writing_anyway || announced_window_ <= target_announced_window / 2) && announced_window_ != target_announced_window) { const uint32_t announce = static_cast<uint32_t> GPR_CLAMP( - target_announced_window - announced_window_, 0, kMaxWindowUpdateSize); + target_announced_window - announced_window_, 0, kMaxWindowUpdateSize); announced_window_ += announce; return announce; } @@ -259,7 +259,7 @@ uint32_t StreamFlowControl::MaybeSendUpdate() { FlowControlTrace trace("s updt sent", tfc_, this); if (local_window_delta_ > announced_window_delta_) { uint32_t announce = static_cast<uint32_t> GPR_CLAMP( - local_window_delta_ - announced_window_delta_, 0, kMaxWindowUpdateSize); + local_window_delta_ - announced_window_delta_, 0, kMaxWindowUpdateSize); UpdateAnnouncedWindowDelta(tfc_, announce); return announce; } diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc index 6869bdb006..1b72cf3bf8 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.cc @@ -33,12 +33,12 @@ #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/transport/transport.h" -grpc_chttp2_data_parser::~grpc_chttp2_data_parser() { - if (parsing_frame != nullptr) { - GRPC_ERROR_UNREF(parsing_frame->Finished( +grpc_chttp2_data_parser::~grpc_chttp2_data_parser() { + if (parsing_frame != nullptr) { + GRPC_ERROR_UNREF(parsing_frame->Finished( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Parser destroyed"), false)); } - GRPC_ERROR_UNREF(error); + GRPC_ERROR_UNREF(error); } grpc_error* grpc_chttp2_data_parser_begin_frame( @@ -53,7 +53,7 @@ grpc_error* grpc_chttp2_data_parser_begin_frame( if (flags & GRPC_CHTTP2_DATA_FLAG_END_STREAM) { s->received_last_frame = true; - s->eos_received = true; + s->eos_received = true; } else { s->received_last_frame = false; } @@ -181,9 +181,9 @@ grpc_error* grpc_deframe_unprocessed_incoming_frames( GPR_ASSERT(stream_out != nullptr); GPR_ASSERT(p->parsing_frame == nullptr); p->frame_size |= (static_cast<uint32_t>(*cur)); - if (t->channelz_socket != nullptr) { - t->channelz_socket->RecordMessageReceived(); - } + if (t->channelz_socket != nullptr) { + t->channelz_socket->RecordMessageReceived(); + } p->state = GRPC_CHTTP2_DATA_FRAME; ++cur; message_flags = 0; diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h index ec3890098e..b56e77401b 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_data.h @@ -43,18 +43,18 @@ namespace grpc_core { class Chttp2IncomingByteStream; } // namespace grpc_core -struct grpc_chttp2_data_parser { - grpc_chttp2_data_parser() = default; - ~grpc_chttp2_data_parser(); +struct grpc_chttp2_data_parser { + grpc_chttp2_data_parser() = default; + ~grpc_chttp2_data_parser(); - grpc_chttp2_stream_state state = GRPC_CHTTP2_DATA_FH_0; - uint8_t frame_type = 0; - uint32_t frame_size = 0; - grpc_error* error = GRPC_ERROR_NONE; + grpc_chttp2_stream_state state = GRPC_CHTTP2_DATA_FH_0; + uint8_t frame_type = 0; + uint32_t frame_size = 0; + grpc_error* error = GRPC_ERROR_NONE; - bool is_frame_compressed = false; - grpc_core::Chttp2IncomingByteStream* parsing_frame = nullptr; -}; + bool is_frame_compressed = false; + grpc_core::Chttp2IncomingByteStream* parsing_frame = nullptr; +}; /* start processing a new data frame */ grpc_error* grpc_chttp2_data_parser_begin_frame(grpc_chttp2_data_parser* parser, diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc index 5113329991..6339d57f04 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_rst_stream.cc @@ -35,7 +35,7 @@ grpc_slice grpc_chttp2_rst_stream_create(uint32_t id, uint32_t code, grpc_transport_one_way_stats* stats) { static const size_t frame_size = 13; grpc_slice slice = GRPC_SLICE_MALLOC(frame_size); - if (stats != nullptr) stats->framing_bytes += frame_size; + if (stats != nullptr) stats->framing_bytes += frame_size; uint8_t* p = GRPC_SLICE_START_PTR(slice); // Frame size. diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc index 20efb09b0d..df9bf4e2e0 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/frame_window_update.cc @@ -88,9 +88,9 @@ grpc_error* grpc_chttp2_window_update_parser_parse(void* parser, } if (p->byte == 4) { - // top bit is reserved and must be ignored. - uint32_t received_update = p->amount & 0x7fffffffu; - if (received_update == 0) { + // top bit is reserved and must be ignored. + uint32_t received_update = p->amount & 0x7fffffffu; + if (received_update == 0) { return GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("invalid window update bytes: ", p->amount).c_str()); } diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc index 4ceaec24b3..2c7641e800 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.cc @@ -56,14 +56,14 @@ namespace { existing entry rather than try to use a backup. Hence, "maybe-cuckoo." TODO(arjunroy): Add unit tests for hashtable implementation. */ #define GRPC_HPACK_ENCODER_USE_CUCKOO_HASH 1 -#define HASH_FRAGMENT_MASK (GRPC_CHTTP2_HPACKC_NUM_VALUES - 1) -#define HASH_FRAGMENT_1(x) ((x)&HASH_FRAGMENT_MASK) -#define HASH_FRAGMENT_2(x) \ - (((x) >> GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS) & HASH_FRAGMENT_MASK) -#define HASH_FRAGMENT_3(x) \ - (((x) >> (GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS * 2)) & HASH_FRAGMENT_MASK) -#define HASH_FRAGMENT_4(x) \ - (((x) >> (GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS * 3)) & HASH_FRAGMENT_MASK) +#define HASH_FRAGMENT_MASK (GRPC_CHTTP2_HPACKC_NUM_VALUES - 1) +#define HASH_FRAGMENT_1(x) ((x)&HASH_FRAGMENT_MASK) +#define HASH_FRAGMENT_2(x) \ + (((x) >> GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS) & HASH_FRAGMENT_MASK) +#define HASH_FRAGMENT_3(x) \ + (((x) >> (GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS * 2)) & HASH_FRAGMENT_MASK) +#define HASH_FRAGMENT_4(x) \ + (((x) >> (GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS * 3)) & HASH_FRAGMENT_MASK) /* don't consider adding anything bigger than this to the hpack table */ constexpr size_t kMaxDecoderSpaceUsage = 512; @@ -72,7 +72,7 @@ constexpr uint8_t kMaxFilterValue = 255; /* if the probability of this item being seen again is < 1/x then don't add it to the table */ -#define ONE_ON_ADD_PROBABILITY (GRPC_CHTTP2_HPACKC_NUM_VALUES >> 1) +#define ONE_ON_ADD_PROBABILITY (GRPC_CHTTP2_HPACKC_NUM_VALUES >> 1) /* The hpack index we encode over the wire. Meaningful to the hpack encoder and parser on the remote end as well as HTTP2. *Not* the same as HpackEncoderSlotHash, which is only meaningful to the hpack encoder @@ -710,8 +710,8 @@ static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, return; } /* should this elem be in the table? */ - const size_t decoder_space_usage = - grpc_chttp2_get_size_in_hpack_table(elem, st->use_true_binary_metadata); + const size_t decoder_space_usage = + grpc_chttp2_get_size_in_hpack_table(elem, st->use_true_binary_metadata); const bool decoder_space_available = decoder_space_usage < kMaxDecoderSpaceUsage; const bool should_add_elem = @@ -729,16 +729,16 @@ static void hpack_enc(grpc_chttp2_hpack_compressor* c, grpc_mdelem elem, } /* no elem, key in the table... fall back to literal emission */ const bool should_add_key = !elem_interned && decoder_space_available; - if (should_add_elem || should_add_key) { + if (should_add_elem || should_add_key) { emit_lithdr_v<EmitLitHdrVType::INC_IDX_V>(c, elem, st); - } else { + } else { emit_lithdr_v<EmitLitHdrVType::NO_IDX_V>(c, elem, st); - } - if (should_add_elem) { + } + if (should_add_elem) { add_elem(c, elem, decoder_space_usage, elem_hash, key_hash); - } else if (should_add_key) { + } else if (should_add_key) { add_key(c, elem, decoder_space_usage, key_hash); - } + } } #define STRLEN_LIT(x) (sizeof(x) - 1) @@ -864,7 +864,7 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c, emit_advertise_table_size_change(c, &st); } for (size_t i = 0; i < extra_headers_size; ++i) { - grpc_mdelem md = *extra_headers[i]; + grpc_mdelem md = *extra_headers[i]; const bool is_static = GRPC_MDELEM_STORAGE(md) == GRPC_MDELEM_STORAGE_STATIC; uintptr_t static_index; @@ -873,9 +873,9 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c, reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(md)) ->StaticIndex()) < GRPC_CHTTP2_LAST_STATIC_ENTRY) { emit_indexed(c, static_cast<uint32_t>(static_index + 1), &st); - } else { - hpack_enc(c, md, &st); - } + } else { + hpack_enc(c, md, &st); + } } grpc_metadata_batch_assert_ok(metadata); for (grpc_linked_mdelem* l = metadata->list.head; l; l = l->next) { @@ -887,9 +887,9 @@ void grpc_chttp2_encode_header(grpc_chttp2_hpack_compressor* c, GRPC_MDELEM_DATA(l->md)) ->StaticIndex()) < GRPC_CHTTP2_LAST_STATIC_ENTRY) { emit_indexed(c, static_cast<uint32_t>(static_index + 1), &st); - } else { - hpack_enc(c, l->md, &st); - } + } else { + hpack_enc(c, l->md, &st); + } } grpc_millis deadline = metadata->deadline; if (deadline != GRPC_MILLIS_INF_FUTURE) { diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h index 5093f80ae2..9b8b937a35 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_encoder.h @@ -28,9 +28,9 @@ #include "src/core/lib/transport/metadata_batch.h" #include "src/core/lib/transport/transport.h" -// This should be <= 8. We use 6 to save space. -#define GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS 6 -#define GRPC_CHTTP2_HPACKC_NUM_VALUES (1 << GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS) +// This should be <= 8. We use 6 to save space. +#define GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS 6 +#define GRPC_CHTTP2_HPACKC_NUM_VALUES (1 << GRPC_CHTTP2_HPACKC_NUM_VALUES_BITS) /* initial table size, per spec */ #define GRPC_CHTTP2_HPACKC_INITIAL_TABLE_SIZE 4096 /* maximum table size we'll actually use */ @@ -60,7 +60,7 @@ struct grpc_chttp2_hpack_compressor { They track a single integer that counts how often a particular value has been seen. When that count reaches max (255), all values are halved. */ uint32_t filter_elems_sum; - uint8_t filter_elems[GRPC_CHTTP2_HPACKC_NUM_VALUES]; + uint8_t filter_elems[GRPC_CHTTP2_HPACKC_NUM_VALUES]; /* entry tables for keys & elems: these tables track values that have been seen and *may* be in the decompressor table */ diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc index a325439ad5..f8a3072d2f 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_parser.cc @@ -1700,7 +1700,7 @@ grpc_error* grpc_chttp2_header_parser_parse(void* hpack_parser, grpc_chttp2_stream* s, const grpc_slice& slice, int is_last) { - GPR_TIMER_SCOPE("grpc_chttp2_header_parser_parse", 0); + GPR_TIMER_SCOPE("grpc_chttp2_header_parser_parse", 0); grpc_chttp2_hpack_parser* parser = static_cast<grpc_chttp2_hpack_parser*>(hpack_parser); if (s != nullptr) { diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc index 812d17cb45..11ef626185 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.cc @@ -32,7 +32,7 @@ #include "src/core/lib/gpr/murmur_hash.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/validate_metadata.h" -#include "src/core/lib/transport/static_metadata.h" +#include "src/core/lib/transport/static_metadata.h" extern grpc_core::TraceFlag grpc_http_trace; @@ -220,23 +220,23 @@ grpc_chttp2_hptbl_find_result grpc_chttp2_hptbl_find( return r; } - -static size_t get_base64_encoded_size(size_t raw_length) { - static const uint8_t tail_xtra[3] = {0, 2, 3}; - return raw_length / 3 * 4 + tail_xtra[raw_length % 3]; -} - -size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem, - bool use_true_binary_metadata) { + +static size_t get_base64_encoded_size(size_t raw_length) { + static const uint8_t tail_xtra[3] = {0, 2, 3}; + return raw_length / 3 * 4 + tail_xtra[raw_length % 3]; +} + +size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem, + bool use_true_binary_metadata) { const uint8_t* key_buf = GRPC_SLICE_START_PTR(GRPC_MDKEY(elem)); size_t key_len = GRPC_SLICE_LENGTH(GRPC_MDKEY(elem)); size_t overhead_and_key = 32 + key_len; - size_t value_len = GRPC_SLICE_LENGTH(GRPC_MDVALUE(elem)); + size_t value_len = GRPC_SLICE_LENGTH(GRPC_MDVALUE(elem)); if (grpc_key_is_binary_header(key_buf, key_len)) { - return overhead_and_key + (use_true_binary_metadata - ? value_len + 1 - : get_base64_encoded_size(value_len)); - } else { - return overhead_and_key + value_len; - } -} + return overhead_and_key + (use_true_binary_metadata + ? value_len + 1 + : get_base64_encoded_size(value_len)); + } else { + return overhead_and_key + value_len; + } +} diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h index 34c3dceda7..3fd52e720e 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/hpack_table.h @@ -119,13 +119,13 @@ inline grpc_mdelem grpc_chttp2_hptbl_lookup(const grpc_chttp2_hptbl* tbl, /* add a table entry to the index */ grpc_error* grpc_chttp2_hptbl_add(grpc_chttp2_hptbl* tbl, grpc_mdelem md) GRPC_MUST_USE_RESULT; - -size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem, - bool use_true_binary_metadata); - -/* Returns the static hpack table index that corresponds to /a elem. Returns 0 - if /a elem is not statically stored or if it is not in the static hpack - table */ + +size_t grpc_chttp2_get_size_in_hpack_table(grpc_mdelem elem, + bool use_true_binary_metadata); + +/* Returns the static hpack table index that corresponds to /a elem. Returns 0 + if /a elem is not statically stored or if it is not in the static hpack + table */ inline uintptr_t grpc_chttp2_get_static_hpack_table_index(grpc_mdelem md) { uintptr_t index = reinterpret_cast<grpc_core::StaticMetadata*>(GRPC_MDELEM_DATA(md)) - @@ -135,7 +135,7 @@ inline uintptr_t grpc_chttp2_get_static_hpack_table_index(grpc_mdelem md) { } return 0; } - + /* Find a key/value pair in the table... returns the index in the table of the most similar entry, or 0 if the value was not found */ struct grpc_chttp2_hptbl_find_result { diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h index b63caa1ae2..6ff7598dc1 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/incoming_metadata.h @@ -23,16 +23,16 @@ #include "src/core/lib/transport/transport.h" -struct grpc_chttp2_incoming_metadata_buffer { +struct grpc_chttp2_incoming_metadata_buffer { explicit grpc_chttp2_incoming_metadata_buffer(grpc_core::Arena* arena) : arena(arena) { - grpc_metadata_batch_init(&batch); - batch.deadline = GRPC_MILLIS_INF_FUTURE; - } - ~grpc_chttp2_incoming_metadata_buffer() { - grpc_metadata_batch_destroy(&batch); - } - + grpc_metadata_batch_init(&batch); + batch.deadline = GRPC_MILLIS_INF_FUTURE; + } + ~grpc_chttp2_incoming_metadata_buffer() { + grpc_metadata_batch_destroy(&batch); + } + static constexpr size_t kPreallocatedMDElem = 10; grpc_core::Arena* arena; @@ -41,7 +41,7 @@ struct grpc_chttp2_incoming_metadata_buffer { // These preallocated mdelems are used while count < kPreallocatedMDElem. grpc_linked_mdelem preallocated_mdelems[kPreallocatedMDElem]; grpc_metadata_batch batch; -}; +}; void grpc_chttp2_incoming_metadata_buffer_publish( grpc_chttp2_incoming_metadata_buffer* buffer, grpc_metadata_batch* batch); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h index 2f028c08f3..ea799a24e4 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/internal.h @@ -36,7 +36,7 @@ #include "src/core/ext/transport/chttp2/transport/hpack_parser.h" #include "src/core/ext/transport/chttp2/transport/incoming_metadata.h" #include "src/core/ext/transport/chttp2/transport/stream_map.h" -#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channelz.h" #include "src/core/lib/compression/stream_compression.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/iomgr/combiner.h" @@ -45,10 +45,10 @@ #include "src/core/lib/transport/connectivity_state.h" #include "src/core/lib/transport/transport_impl.h" -namespace grpc_core { -class ContextList; -} - +namespace grpc_core { +class ContextList; +} + /* streams are kept in various linked lists depending on what things need to happen to them... this enum labels each list */ typedef enum { @@ -112,8 +112,8 @@ const char* grpc_chttp2_initiate_write_reason_string( grpc_chttp2_initiate_write_reason reason); struct grpc_chttp2_ping_queue { - grpc_closure_list lists[GRPC_CHTTP2_PCL_COUNT] = {}; - uint64_t inflight_id = 0; + grpc_closure_list lists[GRPC_CHTTP2_PCL_COUNT] = {}; + uint64_t inflight_id = 0; }; struct grpc_chttp2_repeated_ping_policy { int max_pings_without_data; @@ -235,12 +235,12 @@ class Chttp2IncomingByteStream : public ByteStream { // alone for now. We can revisit this once we're able to link against // libc++, at which point we can eliminate New<> and Delete<> and // switch to std::shared_ptr<>. - void Ref() { refs_.Ref(); } - void Unref() { + void Ref() { refs_.Ref(); } + void Unref() { if (GPR_UNLIKELY(refs_.Unref())) { delete this; - } - } + } + } void PublishError(grpc_error* error); @@ -254,12 +254,12 @@ class Chttp2IncomingByteStream : public ByteStream { static void NextLocked(void* arg, grpc_error* error_ignored); static void OrphanLocked(void* arg, grpc_error* error_ignored); - void MaybeCreateStreamDecompressionCtx(); - + void MaybeCreateStreamDecompressionCtx(); + grpc_chttp2_transport* transport_; // Immutable. grpc_chttp2_stream* stream_; // Immutable. - grpc_core::RefCount refs_; + grpc_core::RefCount refs_; /* Accessed only by transport thread when stream->pending_byte_stream == false * Accessed only by application thread when stream->pending_byte_stream == @@ -287,35 +287,35 @@ typedef enum { } grpc_chttp2_keepalive_state; struct grpc_chttp2_transport { - grpc_chttp2_transport(const grpc_channel_args* channel_args, - grpc_endpoint* ep, bool is_client, - grpc_resource_user* resource_user); - ~grpc_chttp2_transport(); - + grpc_chttp2_transport(const grpc_channel_args* channel_args, + grpc_endpoint* ep, bool is_client, + grpc_resource_user* resource_user); + ~grpc_chttp2_transport(); + grpc_transport base; /* must be first */ - grpc_core::RefCount refs; + grpc_core::RefCount refs; grpc_endpoint* ep; TString peer_string; - grpc_resource_user* resource_user; - + grpc_resource_user* resource_user; + grpc_core::Combiner* combiner; - grpc_closure* notify_on_receive_settings = nullptr; + grpc_closure* notify_on_receive_settings = nullptr; /** write execution state of the transport */ - grpc_chttp2_write_state write_state = GRPC_CHTTP2_WRITE_STATE_IDLE; + grpc_chttp2_write_state write_state = GRPC_CHTTP2_WRITE_STATE_IDLE; /** is the transport destroying itself? */ - uint8_t destroying = false; + uint8_t destroying = false; /** has the upper layer closed the transport? */ - grpc_error* closed_with_error = GRPC_ERROR_NONE; + grpc_error* closed_with_error = GRPC_ERROR_NONE; /** is there a read request to the endpoint outstanding? */ - uint8_t endpoint_reading = 1; + uint8_t endpoint_reading = 1; /** various lists of streams */ - grpc_chttp2_stream_list lists[STREAM_LIST_COUNT] = {}; + grpc_chttp2_stream_list lists[STREAM_LIST_COUNT] = {}; /** maps stream id to grpc_chttp2_stream objects */ grpc_chttp2_stream_map stream_map; @@ -332,7 +332,7 @@ struct grpc_chttp2_transport { /** address to place a newly accepted stream - set and unset by grpc_chttp2_parsing_accept_stream; used by init_stream to publish the accepted server stream */ - grpc_chttp2_stream** accepting_stream = nullptr; + grpc_chttp2_stream** accepting_stream = nullptr; /* accept stream callback */ void (*accept_stream_cb)(void* user_data, grpc_transport* transport, @@ -354,43 +354,43 @@ struct grpc_chttp2_transport { /** how much data are we willing to buffer when the WRITE_BUFFER_HINT is set? */ - uint32_t write_buffer_size = grpc_core::chttp2::kDefaultWindow; + uint32_t write_buffer_size = grpc_core::chttp2::kDefaultWindow; /** Set to a grpc_error object if a goaway frame is received. By default, set * to GRPC_ERROR_NONE */ - grpc_error* goaway_error = GRPC_ERROR_NONE; + grpc_error* goaway_error = GRPC_ERROR_NONE; - grpc_chttp2_sent_goaway_state sent_goaway_state = GRPC_CHTTP2_NO_GOAWAY_SEND; + grpc_chttp2_sent_goaway_state sent_goaway_state = GRPC_CHTTP2_NO_GOAWAY_SEND; /** are the local settings dirty and need to be sent? */ - bool dirtied_local_settings = true; + bool dirtied_local_settings = true; /** have local settings been sent? */ - bool sent_local_settings = false; - /** bitmask of setting indexes to send out - Hack: it's common for implementations to assume 65536 bytes initial send - window -- this should by rights be 0 */ - uint32_t force_send_settings = 1 << GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + bool sent_local_settings = false; + /** bitmask of setting indexes to send out + Hack: it's common for implementations to assume 65536 bytes initial send + window -- this should by rights be 0 */ + uint32_t force_send_settings = 1 << GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; /** settings values */ uint32_t settings[GRPC_NUM_SETTING_SETS][GRPC_CHTTP2_NUM_SETTINGS]; /** what is the next stream id to be allocated by this peer? copied to next_stream_id in parsing when parsing commences */ - uint32_t next_stream_id = 0; + uint32_t next_stream_id = 0; /** last new stream id */ - uint32_t last_new_stream_id = 0; + uint32_t last_new_stream_id = 0; /** ping queues for various ping insertion points */ - grpc_chttp2_ping_queue ping_queue = grpc_chttp2_ping_queue(); + grpc_chttp2_ping_queue ping_queue = grpc_chttp2_ping_queue(); grpc_chttp2_repeated_ping_policy ping_policy; grpc_chttp2_repeated_ping_state ping_state; - uint64_t ping_ctr = 0; /* unique id for pings */ + uint64_t ping_ctr = 0; /* unique id for pings */ grpc_closure retry_initiate_ping_locked; /** ping acks */ - size_t ping_ack_count = 0; - size_t ping_ack_capacity = 0; - uint64_t* ping_acks = nullptr; + size_t ping_ack_count = 0; + size_t ping_ack_capacity = 0; + uint64_t* ping_acks = nullptr; grpc_chttp2_server_ping_recv_state ping_recv_state; /** parser for headers */ @@ -416,23 +416,23 @@ struct grpc_chttp2_transport { int64_t initial_window_update = 0; /* deframing */ - grpc_chttp2_deframe_transport_state deframe_state = GRPC_DTS_CLIENT_PREFIX_0; - uint8_t incoming_frame_type = 0; - uint8_t incoming_frame_flags = 0; - uint8_t header_eof = 0; - bool is_first_frame = true; - uint32_t expect_continuation_stream_id = 0; - uint32_t incoming_frame_size = 0; - uint32_t incoming_stream_id = 0; + grpc_chttp2_deframe_transport_state deframe_state = GRPC_DTS_CLIENT_PREFIX_0; + uint8_t incoming_frame_type = 0; + uint8_t incoming_frame_flags = 0; + uint8_t header_eof = 0; + bool is_first_frame = true; + uint32_t expect_continuation_stream_id = 0; + uint32_t incoming_frame_size = 0; + uint32_t incoming_stream_id = 0; /* active parser */ - void* parser_data = nullptr; - grpc_chttp2_stream* incoming_stream = nullptr; + void* parser_data = nullptr; + grpc_chttp2_stream* incoming_stream = nullptr; grpc_error* (*parser)(void* parser_user_data, grpc_chttp2_transport* t, grpc_chttp2_stream* s, const grpc_slice& slice, int is_last); - grpc_chttp2_write_cb* write_cb_pool = nullptr; + grpc_chttp2_write_cb* write_cb_pool = nullptr; /* bdp estimator */ bool bdp_ping_blocked = @@ -443,23 +443,23 @@ struct grpc_chttp2_transport { /* if non-NULL, close the transport with this error when writes are finished */ - grpc_error* close_transport_on_writes_finished = GRPC_ERROR_NONE; + grpc_error* close_transport_on_writes_finished = GRPC_ERROR_NONE; /* a list of closures to run after writes are finished */ - grpc_closure_list run_after_write = GRPC_CLOSURE_LIST_INIT; + grpc_closure_list run_after_write = GRPC_CLOSURE_LIST_INIT; /* buffer pool state */ /** have we scheduled a benign cleanup? */ - bool benign_reclaimer_registered = false; + bool benign_reclaimer_registered = false; /** have we scheduled a destructive cleanup? */ - bool destructive_reclaimer_registered = false; + bool destructive_reclaimer_registered = false; /** benign cleanup closure */ grpc_closure benign_reclaimer_locked; /** destructive cleanup closure */ grpc_closure destructive_reclaimer_locked; /* next bdp ping timer */ - bool have_next_bdp_ping_timer = false; + bool have_next_bdp_ping_timer = false; /** If start_bdp_ping_locked has been called */ bool bdp_ping_started = false; grpc_timer next_bdp_ping_timer; @@ -482,14 +482,14 @@ struct grpc_chttp2_transport { /** grace period for a ping to complete before watchdog kicks in */ grpc_millis keepalive_timeout; /** if keepalive pings are allowed when there's no outstanding streams */ - bool keepalive_permit_without_calls = false; + bool keepalive_permit_without_calls = false; /** If start_keepalive_ping_locked has been called */ bool keepalive_ping_started = false; /** keep-alive state machine state */ grpc_chttp2_keepalive_state keepalive_state; - grpc_core::ContextList* cl = nullptr; - grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> channelz_socket; - uint32_t num_messages_in_next_write = 0; + grpc_core::ContextList* cl = nullptr; + grpc_core::RefCountedPtr<grpc_core::channelz::SocketNode> channelz_socket; + uint32_t num_messages_in_next_write = 0; /** The number of pending induced frames (SETTINGS_ACK, PINGS_ACK and * RST_STREAM) in the outgoing buffer (t->qbuf). If this number goes beyond * DEFAULT_MAX_PENDING_INDUCED_FRAMES, we pause reading new frames. We would @@ -507,11 +507,11 @@ typedef enum { } grpc_published_metadata_method; struct grpc_chttp2_stream { - grpc_chttp2_stream(grpc_chttp2_transport* t, grpc_stream_refcount* refcount, + grpc_chttp2_stream(grpc_chttp2_transport* t, grpc_stream_refcount* refcount, const void* server_data, grpc_core::Arena* arena); - ~grpc_chttp2_stream(); - - void* context; + ~grpc_chttp2_stream(); + + void* context; grpc_chttp2_transport* t; grpc_stream_refcount* refcount; // Reffer is a 0-len structure, simply reffing `t` and `refcount` in its ctor @@ -525,15 +525,15 @@ struct grpc_chttp2_stream { grpc_closure* destroy_stream_arg; grpc_chttp2_stream_link links[STREAM_LIST_COUNT]; - uint8_t included[STREAM_LIST_COUNT] = {}; + uint8_t included[STREAM_LIST_COUNT] = {}; /** HTTP2 stream id for this stream, or zero if one has not been assigned */ - uint32_t id = 0; + uint32_t id = 0; /** things the upper layers would like to send */ - grpc_metadata_batch* send_initial_metadata = nullptr; - grpc_closure* send_initial_metadata_finished = nullptr; - grpc_metadata_batch* send_trailing_metadata = nullptr; + grpc_metadata_batch* send_initial_metadata = nullptr; + grpc_closure* send_initial_metadata_finished = nullptr; + grpc_metadata_batch* send_trailing_metadata = nullptr; // TODO(yashykt): Find a better name for the below field and others in this // struct to betteer distinguish inputs, return values, and // internal state. @@ -541,88 +541,88 @@ struct grpc_chttp2_stream { // layer whether this stream was able to send its trailing metadata (used for // detecting cancellation on the server-side).. bool* sent_trailing_metadata_op = nullptr; - grpc_closure* send_trailing_metadata_finished = nullptr; + grpc_closure* send_trailing_metadata_finished = nullptr; grpc_core::OrphanablePtr<grpc_core::ByteStream> fetching_send_message; - uint32_t fetched_send_message_length = 0; - grpc_slice fetching_slice = grpc_empty_slice(); + uint32_t fetched_send_message_length = 0; + grpc_slice fetching_slice = grpc_empty_slice(); int64_t next_message_end_offset; - int64_t flow_controlled_bytes_written = 0; - int64_t flow_controlled_bytes_flowed = 0; + int64_t flow_controlled_bytes_written = 0; + int64_t flow_controlled_bytes_flowed = 0; grpc_closure complete_fetch_locked; - grpc_closure* fetching_send_message_finished = nullptr; + grpc_closure* fetching_send_message_finished = nullptr; grpc_metadata_batch* recv_initial_metadata; - grpc_closure* recv_initial_metadata_ready = nullptr; - bool* trailing_metadata_available = nullptr; + grpc_closure* recv_initial_metadata_ready = nullptr; + bool* trailing_metadata_available = nullptr; grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message; - grpc_closure* recv_message_ready = nullptr; + grpc_closure* recv_message_ready = nullptr; grpc_metadata_batch* recv_trailing_metadata; - grpc_closure* recv_trailing_metadata_finished = nullptr; + grpc_closure* recv_trailing_metadata_finished = nullptr; - grpc_transport_stream_stats* collecting_stats = nullptr; - grpc_transport_stream_stats stats = grpc_transport_stream_stats(); + grpc_transport_stream_stats* collecting_stats = nullptr; + grpc_transport_stream_stats stats = grpc_transport_stream_stats(); /** Is this stream closed for writing. */ - bool write_closed = false; + bool write_closed = false; /** Is this stream reading half-closed. */ - bool read_closed = false; + bool read_closed = false; /** Are all published incoming byte streams closed. */ - bool all_incoming_byte_streams_finished = false; + bool all_incoming_byte_streams_finished = false; /** Has this stream seen an error. If true, then pending incoming frames can be thrown away. */ - bool seen_error = false; + bool seen_error = false; /** Are we buffering writes on this stream? If yes, we won't become writable until there's enough queued up in the flow_controlled_buffer */ - bool write_buffering = false; - - /* have we sent or received the EOS bit? */ - bool eos_received = false; - bool eos_sent = false; + bool write_buffering = false; + /* have we sent or received the EOS bit? */ + bool eos_received = false; + bool eos_sent = false; + /** the error that resulted in this stream being read-closed */ - grpc_error* read_closed_error = GRPC_ERROR_NONE; + grpc_error* read_closed_error = GRPC_ERROR_NONE; /** the error that resulted in this stream being write-closed */ - grpc_error* write_closed_error = GRPC_ERROR_NONE; + grpc_error* write_closed_error = GRPC_ERROR_NONE; - grpc_published_metadata_method published_metadata[2] = {}; - bool final_metadata_requested = false; + grpc_published_metadata_method published_metadata[2] = {}; + bool final_metadata_requested = false; grpc_chttp2_incoming_metadata_buffer metadata_buffer[2]; grpc_slice_buffer frame_storage; /* protected by t combiner */ - grpc_closure* on_next = nullptr; /* protected by t combiner */ - bool pending_byte_stream = false; /* protected by t combiner */ + grpc_closure* on_next = nullptr; /* protected by t combiner */ + bool pending_byte_stream = false; /* protected by t combiner */ // cached length of buffer to be used by the transport thread in cases where // stream->pending_byte_stream == true. The value is saved before // application threads are allowed to modify // unprocessed_incoming_frames_buffer - size_t unprocessed_incoming_frames_buffer_cached_length = 0; + size_t unprocessed_incoming_frames_buffer_cached_length = 0; /* Accessed only by transport thread when stream->pending_byte_stream == false * Accessed only by application thread when stream->pending_byte_stream == * true */ grpc_slice_buffer unprocessed_incoming_frames_buffer; grpc_closure reset_byte_stream; - grpc_error* byte_stream_error = GRPC_ERROR_NONE; /* protected by t combiner */ - bool received_last_frame = false; /* protected by t combiner */ + grpc_error* byte_stream_error = GRPC_ERROR_NONE; /* protected by t combiner */ + bool received_last_frame = false; /* protected by t combiner */ - grpc_millis deadline = GRPC_MILLIS_INF_FUTURE; + grpc_millis deadline = GRPC_MILLIS_INF_FUTURE; /** saw some stream level error */ - grpc_error* forced_close_error = GRPC_ERROR_NONE; + grpc_error* forced_close_error = GRPC_ERROR_NONE; /** how many header frames have we received? */ - uint8_t header_frames_received = 0; + uint8_t header_frames_received = 0; /** parsing state for data frames */ /* Accessed only by transport thread when stream->pending_byte_stream == false * Accessed only by application thread when stream->pending_byte_stream == * true */ grpc_chttp2_data_parser data_parser; /** number of bytes received - reset at end of parse thread execution */ - int64_t received_bytes = 0; + int64_t received_bytes = 0; - bool sent_initial_metadata = false; - bool sent_trailing_metadata = false; + bool sent_initial_metadata = false; + bool sent_trailing_metadata = false; grpc_core::PolymorphicManualConstructor< grpc_core::chttp2::StreamFlowControlBase, @@ -632,27 +632,27 @@ struct grpc_chttp2_stream { grpc_slice_buffer flow_controlled_buffer; - grpc_chttp2_write_cb* on_flow_controlled_cbs = nullptr; - grpc_chttp2_write_cb* on_write_finished_cbs = nullptr; - grpc_chttp2_write_cb* finish_after_write = nullptr; - size_t sending_bytes = 0; + grpc_chttp2_write_cb* on_flow_controlled_cbs = nullptr; + grpc_chttp2_write_cb* on_write_finished_cbs = nullptr; + grpc_chttp2_write_cb* finish_after_write = nullptr; + size_t sending_bytes = 0; /* Stream compression method to be used. */ - grpc_stream_compression_method stream_compression_method = - GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS; + grpc_stream_compression_method stream_compression_method = + GRPC_STREAM_COMPRESSION_IDENTITY_COMPRESS; /* Stream decompression method to be used. */ - grpc_stream_compression_method stream_decompression_method = + grpc_stream_compression_method stream_decompression_method = GRPC_STREAM_COMPRESSION_IDENTITY_DECOMPRESS; /** Whether bytes stored in unprocessed_incoming_byte_stream is decompressed */ - bool unprocessed_incoming_frames_decompressed = false; - /** Whether the bytes needs to be traced using Fathom */ - bool traced = false; + bool unprocessed_incoming_frames_decompressed = false; + /** Whether the bytes needs to be traced using Fathom */ + bool traced = false; /** gRPC header bytes that are already decompressed */ - size_t decompressed_header_bytes = 0; - /** Byte counter for number of bytes written */ - size_t byte_counter = 0; + size_t decompressed_header_bytes = 0; + /** Byte counter for number of bytes written */ + size_t byte_counter = 0; /** Amount of uncompressed bytes sent out when compressed_data_buffer is * emptied */ @@ -817,29 +817,29 @@ void grpc_chttp2_stream_unref(grpc_chttp2_stream* s); grpc_chttp2_ref_transport(t, r, __FILE__, __LINE__) #define GRPC_CHTTP2_UNREF_TRANSPORT(t, r) \ grpc_chttp2_unref_transport(t, r, __FILE__, __LINE__) -inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t, - const char* reason, const char* file, - int line) { - if (t->refs.Unref(grpc_core::DebugLocation(file, line), reason)) { +inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t, + const char* reason, const char* file, + int line) { + if (t->refs.Unref(grpc_core::DebugLocation(file, line), reason)) { delete t; - } -} -inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t, - const char* reason, const char* file, - int line) { - t->refs.Ref(grpc_core::DebugLocation(file, line), reason); -} + } +} +inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t, + const char* reason, const char* file, + int line) { + t->refs.Ref(grpc_core::DebugLocation(file, line), reason); +} #else #define GRPC_CHTTP2_REF_TRANSPORT(t, r) grpc_chttp2_ref_transport(t) #define GRPC_CHTTP2_UNREF_TRANSPORT(t, r) grpc_chttp2_unref_transport(t) -inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t) { - if (t->refs.Unref()) { +inline void grpc_chttp2_unref_transport(grpc_chttp2_transport* t) { + if (t->refs.Unref()) { delete t; - } -} -inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t) { - t->refs.Ref(); -} + } +} +inline void grpc_chttp2_ref_transport(grpc_chttp2_transport* t) { + t->refs.Ref(); +} #endif void grpc_chttp2_ack_ping(grpc_chttp2_transport* t, uint64_t id); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc index 741d72041b..1ac373f47a 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/parsing.cc @@ -372,7 +372,7 @@ static grpc_error* init_data_frame_parser(grpc_chttp2_transport* t) { &s->data_parser, t->incoming_frame_flags, s->id, s); } error_handler: - intptr_t unused; + intptr_t unused; if (err == GRPC_ERROR_NONE) { t->incoming_stream = s; /* t->parser = grpc_chttp2_data_parser_parse;*/ @@ -380,7 +380,7 @@ error_handler: t->parser_data = &s->data_parser; t->ping_state.last_ping_sent_time = GRPC_MILLIS_INF_PAST; return GRPC_ERROR_NONE; - } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) { + } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) { /* handle stream errors by closing the stream */ if (s != nullptr) { grpc_chttp2_mark_stream_closed(t, s, true, false, err); @@ -485,18 +485,18 @@ static grpc_error* on_initial_header(void* tp, grpc_mdelem md) { if (md_key_cmp(md, GRPC_MDSTR_GRPC_TIMEOUT)) { return handle_timeout(s, md); - } - - const size_t new_size = s->metadata_buffer[0].size + GRPC_MDELEM_LENGTH(md); - const size_t metadata_size_limit = - t->settings[GRPC_ACKED_SETTINGS] - [GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE]; + } + + const size_t new_size = s->metadata_buffer[0].size + GRPC_MDELEM_LENGTH(md); + const size_t metadata_size_limit = + t->settings[GRPC_ACKED_SETTINGS] + [GRPC_CHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE]; if (GPR_UNLIKELY(new_size > metadata_size_limit)) { return handle_metadata_size_limit_exceeded(t, s, md, new_size, metadata_size_limit); } else { - grpc_error* error = - grpc_chttp2_incoming_metadata_buffer_add(&s->metadata_buffer[0], md); + grpc_error* error = + grpc_chttp2_incoming_metadata_buffer_add(&s->metadata_buffer[0], md); if (GPR_UNLIKELY(error != GRPC_ERROR_NONE)) { return handle_metadata_add_failure(t, s, md, error); } @@ -580,15 +580,15 @@ static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t, /* could be a new grpc_chttp2_stream or an existing grpc_chttp2_stream */ s = grpc_chttp2_parsing_lookup_stream(t, t->incoming_stream_id); if (s == nullptr) { - if (GPR_UNLIKELY(is_continuation)) { + if (GPR_UNLIKELY(is_continuation)) { GRPC_CHTTP2_IF_TRACING( gpr_log(GPR_ERROR, "grpc_chttp2_stream disbanded before CONTINUATION received")); return init_skip_frame_parser(t, 1); } if (t->is_client) { - if (GPR_LIKELY((t->incoming_stream_id & 1) && - t->incoming_stream_id < t->next_stream_id)) { + if (GPR_LIKELY((t->incoming_stream_id & 1) && + t->incoming_stream_id < t->next_stream_id)) { /* this is an old (probably cancelled) grpc_chttp2_stream */ } else { GRPC_CHTTP2_IF_TRACING(gpr_log( @@ -599,7 +599,7 @@ static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t, grpc_chttp2_hpack_parser_set_has_priority(&t->hpack_parser); } return err; - } else if (GPR_UNLIKELY(t->last_new_stream_id >= t->incoming_stream_id)) { + } else if (GPR_UNLIKELY(t->last_new_stream_id >= t->incoming_stream_id)) { GRPC_CHTTP2_IF_TRACING(gpr_log( GPR_ERROR, "ignoring out of order new grpc_chttp2_stream request on server; " @@ -607,35 +607,35 @@ static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t, "id=%d, new grpc_chttp2_stream id=%d", t->last_new_stream_id, t->incoming_stream_id)); return init_skip_frame_parser(t, 1); - } else if (GPR_UNLIKELY((t->incoming_stream_id & 1) == 0)) { + } else if (GPR_UNLIKELY((t->incoming_stream_id & 1) == 0)) { GRPC_CHTTP2_IF_TRACING(gpr_log( GPR_ERROR, "ignoring grpc_chttp2_stream with non-client generated index %d", t->incoming_stream_id)); return init_skip_frame_parser(t, 1); - } else if (GPR_UNLIKELY( - grpc_chttp2_stream_map_size(&t->stream_map) >= - t->settings[GRPC_ACKED_SETTINGS] - [GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS])) { + } else if (GPR_UNLIKELY( + grpc_chttp2_stream_map_size(&t->stream_map) >= + t->settings[GRPC_ACKED_SETTINGS] + [GRPC_CHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS])) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Max stream count exceeded"); } t->last_new_stream_id = t->incoming_stream_id; s = t->incoming_stream = grpc_chttp2_parsing_accept_stream(t, t->incoming_stream_id); - if (GPR_UNLIKELY(s == nullptr)) { + if (GPR_UNLIKELY(s == nullptr)) { GRPC_CHTTP2_IF_TRACING( gpr_log(GPR_ERROR, "grpc_chttp2_stream not accepted")); return init_skip_frame_parser(t, 1); } - if (t->channelz_socket != nullptr) { - t->channelz_socket->RecordStreamStartedFromRemote(); - } + if (t->channelz_socket != nullptr) { + t->channelz_socket->RecordStreamStartedFromRemote(); + } } else { t->incoming_stream = s; } GPR_DEBUG_ASSERT(s != nullptr); s->stats.incoming.framing_bytes += 9; - if (GPR_UNLIKELY(s->read_closed)) { + if (GPR_UNLIKELY(s->read_closed)) { GRPC_CHTTP2_IF_TRACING(gpr_log( GPR_ERROR, "skipping already closed grpc_chttp2_stream header")); t->incoming_stream = nullptr; @@ -643,9 +643,9 @@ static grpc_error* init_header_frame_parser(grpc_chttp2_transport* t, } t->parser = grpc_chttp2_header_parser_parse; t->parser_data = &t->hpack_parser; - if (t->header_eof) { - s->eos_received = true; - } + if (t->header_eof) { + s->eos_received = true; + } switch (s->header_frames_received) { case 0: if (t->is_client && t->header_eof) { @@ -758,10 +758,10 @@ static grpc_error* parse_frame_slice(grpc_chttp2_transport* t, const grpc_slice& slice, int is_last) { grpc_chttp2_stream* s = t->incoming_stream; grpc_error* err = t->parser(t->parser_data, t, s, slice, is_last); - intptr_t unused; - if (GPR_LIKELY(err == GRPC_ERROR_NONE)) { + intptr_t unused; + if (GPR_LIKELY(err == GRPC_ERROR_NONE)) { return err; - } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) { + } else if (grpc_error_get_int(err, GRPC_ERROR_INT_STREAM_ID, &unused)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_http_trace)) { const char* msg = grpc_error_string(err); gpr_log(GPR_ERROR, "%s", msg); diff --git a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc index f8e21e8e15..9b904cd98e 100644 --- a/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc +++ b/contrib/libs/grpc/src/core/ext/transport/chttp2/transport/writing.cc @@ -19,7 +19,7 @@ #include <grpc/support/port_platform.h> #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" -#include "src/core/ext/transport/chttp2/transport/context_list.h" +#include "src/core/ext/transport/chttp2/transport/context_list.h" #include "src/core/ext/transport/chttp2/transport/internal.h" #include <limits.h> @@ -157,14 +157,14 @@ static bool update_list(grpc_chttp2_transport* t, grpc_chttp2_stream* s, static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s, const char* staller) { if (GRPC_TRACE_FLAG_ENABLED(grpc_flowctl_trace)) { - gpr_log( - GPR_DEBUG, - "%s:%p stream %d moved to stalled list by %s. This is FULLY expected " - "to happen in a healthy program that is not seeing flow control stalls." - " However, if you know that there are unwanted stalls, here is some " - "helpful data: [fc:pending=%" PRIdPTR ":pending-compressed=%" PRIdPTR - ":flowed=%" PRId64 ":peer_initwin=%d:t_win=%" PRId64 - ":s_win=%d:s_delta=%" PRId64 "]", + gpr_log( + GPR_DEBUG, + "%s:%p stream %d moved to stalled list by %s. This is FULLY expected " + "to happen in a healthy program that is not seeing flow control stalls." + " However, if you know that there are unwanted stalls, here is some " + "helpful data: [fc:pending=%" PRIdPTR ":pending-compressed=%" PRIdPTR + ":flowed=%" PRId64 ":peer_initwin=%d:t_win=%" PRId64 + ":s_win=%d:s_delta=%" PRId64 "]", t->peer_string.c_str(), t, s->id, staller, s->flow_controlled_buffer.length, s->stream_compression_method == @@ -172,16 +172,16 @@ static void report_stall(grpc_chttp2_transport* t, grpc_chttp2_stream* s, ? 0 : s->compressed_data_buffer.length, s->flow_controlled_bytes_flowed, - t->settings[GRPC_ACKED_SETTINGS] - [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE], - t->flow_control->remote_window(), - static_cast<uint32_t> GPR_MAX( - 0, - s->flow_control->remote_window_delta() + - (int64_t)t->settings[GRPC_PEER_SETTINGS] - [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]), - s->flow_control->remote_window_delta()); - } + t->settings[GRPC_ACKED_SETTINGS] + [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE], + t->flow_control->remote_window(), + static_cast<uint32_t> GPR_MAX( + 0, + s->flow_control->remote_window_delta() + + (int64_t)t->settings[GRPC_PEER_SETTINGS] + [GRPC_CHTTP2_SETTINGS_INITIAL_WINDOW_SIZE]), + s->flow_control->remote_window_delta()); + } } /* How many bytes would we like to put on the wire during a single syscall */ @@ -363,10 +363,10 @@ class DataSendContext { s_->fetching_send_message == nullptr); if (is_last_data_frame && s_->send_trailing_metadata != nullptr && s_->stream_compression_ctx != nullptr) { - if (GPR_UNLIKELY(!grpc_stream_compress( + if (GPR_UNLIKELY(!grpc_stream_compress( s_->stream_compression_ctx, &s_->flow_controlled_buffer, &s_->compressed_data_buffer, nullptr, MAX_SIZE_T, - GRPC_STREAM_COMPRESSION_FLUSH_FINISH))) { + GRPC_STREAM_COMPRESSION_FLUSH_FINISH))) { gpr_log(GPR_ERROR, "Stream compression failed."); } grpc_stream_compression_context_destroy(s_->stream_compression_ctx); @@ -397,10 +397,10 @@ class DataSendContext { grpc_stream_compression_context_create(s_->stream_compression_method); } s_->uncompressed_data_size = s_->flow_controlled_buffer.length; - if (GPR_UNLIKELY(!grpc_stream_compress( - s_->stream_compression_ctx, &s_->flow_controlled_buffer, - &s_->compressed_data_buffer, nullptr, MAX_SIZE_T, - GRPC_STREAM_COMPRESSION_FLUSH_SYNC))) { + if (GPR_UNLIKELY(!grpc_stream_compress( + s_->stream_compression_ctx, &s_->flow_controlled_buffer, + &s_->compressed_data_buffer, nullptr, MAX_SIZE_T, + GRPC_STREAM_COMPRESSION_FLUSH_SYNC))) { gpr_log(GPR_ERROR, "Stream compression failed."); } } @@ -612,7 +612,7 @@ class StreamWriteContext { s_->sent_trailing_metadata_op = nullptr; } s_->sent_trailing_metadata = true; - s_->eos_sent = true; + s_->eos_sent = true; if (!t_->is_client && !s_->read_closed) { grpc_slice_buffer_add( @@ -648,18 +648,18 @@ grpc_chttp2_begin_write_result grpc_chttp2_begin_write( (according to available window sizes) and add to the output buffer */ while (grpc_chttp2_stream* s = ctx.NextStream()) { StreamWriteContext stream_ctx(&ctx, s); - size_t orig_len = t->outbuf.length; + size_t orig_len = t->outbuf.length; stream_ctx.FlushInitialMetadata(); stream_ctx.FlushWindowUpdates(); stream_ctx.FlushData(); stream_ctx.FlushTrailingMetadata(); - if (t->outbuf.length > orig_len) { - /* Add this stream to the list of the contexts to be traced at TCP */ - s->byte_counter += t->outbuf.length - orig_len; - if (s->traced && grpc_endpoint_can_track_err(t->ep)) { - grpc_core::ContextList::Append(&t->cl, s); - } - } + if (t->outbuf.length > orig_len) { + /* Add this stream to the list of the contexts to be traced at TCP */ + s->byte_counter += t->outbuf.length - orig_len; + if (s->traced && grpc_endpoint_can_track_err(t->ep)) { + grpc_core::ContextList::Append(&t->cl, s); + } + } if (stream_ctx.stream_became_writable()) { if (!grpc_chttp2_list_add_writing_stream(t, s)) { /* already in writing list: drop ref */ @@ -683,11 +683,11 @@ void grpc_chttp2_end_write(grpc_chttp2_transport* t, grpc_error* error) { GPR_TIMER_SCOPE("grpc_chttp2_end_write", 0); grpc_chttp2_stream* s; - if (t->channelz_socket != nullptr) { - t->channelz_socket->RecordMessagesSent(t->num_messages_in_next_write); - } - t->num_messages_in_next_write = 0; - + if (t->channelz_socket != nullptr) { + t->channelz_socket->RecordMessagesSent(t->num_messages_in_next_write); + } + t->num_messages_in_next_write = 0; + while (grpc_chttp2_list_pop_writing_stream(t, &s)) { if (s->sending_bytes != 0) { update_list(t, s, static_cast<int64_t>(s->sending_bytes), diff --git a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc index 728831f364..bcb95b69f5 100644 --- a/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc +++ b/contrib/libs/grpc/src/core/ext/transport/inproc/inproc_transport.cc @@ -42,72 +42,72 @@ } \ } while (0) -namespace { -grpc_slice g_empty_slice; -grpc_slice g_fake_path_key; -grpc_slice g_fake_path_value; -grpc_slice g_fake_auth_key; -grpc_slice g_fake_auth_value; - -struct inproc_stream; -bool cancel_stream_locked(inproc_stream* s, grpc_error* error); +namespace { +grpc_slice g_empty_slice; +grpc_slice g_fake_path_key; +grpc_slice g_fake_path_value; +grpc_slice g_fake_auth_key; +grpc_slice g_fake_auth_value; + +struct inproc_stream; +bool cancel_stream_locked(inproc_stream* s, grpc_error* error); void maybe_process_ops_locked(inproc_stream* s, grpc_error* error); void op_state_machine_locked(inproc_stream* s, grpc_error* error); -void log_metadata(const grpc_metadata_batch* md_batch, bool is_client, - bool is_initial); -grpc_error* fill_in_metadata(inproc_stream* s, - const grpc_metadata_batch* metadata, - uint32_t flags, grpc_metadata_batch* out_md, - uint32_t* outflags, bool* markfilled); - -struct shared_mu { - shared_mu() { - // Share one lock between both sides since both sides get affected - gpr_mu_init(&mu); - gpr_ref_init(&refs, 2); - } - +void log_metadata(const grpc_metadata_batch* md_batch, bool is_client, + bool is_initial); +grpc_error* fill_in_metadata(inproc_stream* s, + const grpc_metadata_batch* metadata, + uint32_t flags, grpc_metadata_batch* out_md, + uint32_t* outflags, bool* markfilled); + +struct shared_mu { + shared_mu() { + // Share one lock between both sides since both sides get affected + gpr_mu_init(&mu); + gpr_ref_init(&refs, 2); + } + ~shared_mu() { gpr_mu_destroy(&mu); } gpr_mu mu; gpr_refcount refs; -}; +}; -struct inproc_transport { - inproc_transport(const grpc_transport_vtable* vtable, shared_mu* mu, - bool is_client) +struct inproc_transport { + inproc_transport(const grpc_transport_vtable* vtable, shared_mu* mu, + bool is_client) : mu(mu), is_client(is_client), state_tracker(is_client ? "inproc_client" : "inproc_server", GRPC_CHANNEL_READY) { - base.vtable = vtable; - // Start each side of transport with 2 refs since they each have a ref - // to the other - gpr_ref_init(&refs, 2); - } - - ~inproc_transport() { - if (gpr_unref(&mu->refs)) { + base.vtable = vtable; + // Start each side of transport with 2 refs since they each have a ref + // to the other + gpr_ref_init(&refs, 2); + } + + ~inproc_transport() { + if (gpr_unref(&mu->refs)) { mu->~shared_mu(); - gpr_free(mu); - } - } - - void ref() { - INPROC_LOG(GPR_INFO, "ref_transport %p", this); - gpr_ref(&refs); - } - - void unref() { - INPROC_LOG(GPR_INFO, "unref_transport %p", this); - if (!gpr_unref(&refs)) { - return; - } - INPROC_LOG(GPR_INFO, "really_destroy_transport %p", this); - this->~inproc_transport(); - gpr_free(this); - } - + gpr_free(mu); + } + } + + void ref() { + INPROC_LOG(GPR_INFO, "ref_transport %p", this); + gpr_ref(&refs); + } + + void unref() { + INPROC_LOG(GPR_INFO, "unref_transport %p", this); + if (!gpr_unref(&refs)) { + return; + } + INPROC_LOG(GPR_INFO, "really_destroy_transport %p", this); + this->~inproc_transport(); + gpr_free(this); + } + grpc_transport base; shared_mu* mu; gpr_refcount refs; @@ -116,92 +116,92 @@ struct inproc_transport { void (*accept_stream_cb)(void* user_data, grpc_transport* transport, const void* server_data); void* accept_stream_data; - bool is_closed = false; + bool is_closed = false; struct inproc_transport* other_side; - struct inproc_stream* stream_list = nullptr; -}; + struct inproc_stream* stream_list = nullptr; +}; -struct inproc_stream { - inproc_stream(inproc_transport* t, grpc_stream_refcount* refcount, +struct inproc_stream { + inproc_stream(inproc_transport* t, grpc_stream_refcount* refcount, const void* server_data, grpc_core::Arena* arena) - : t(t), refs(refcount), arena(arena) { - // Ref this stream right now for ctor and list. - ref("inproc_init_stream:init"); - ref("inproc_init_stream:list"); - - grpc_metadata_batch_init(&to_read_initial_md); - grpc_metadata_batch_init(&to_read_trailing_md); - grpc_metadata_batch_init(&write_buffer_initial_md); - grpc_metadata_batch_init(&write_buffer_trailing_md); - - stream_list_prev = nullptr; - gpr_mu_lock(&t->mu->mu); - stream_list_next = t->stream_list; - if (t->stream_list) { - t->stream_list->stream_list_prev = this; - } - t->stream_list = this; - gpr_mu_unlock(&t->mu->mu); - - if (!server_data) { - t->ref(); - inproc_transport* st = t->other_side; - st->ref(); - other_side = nullptr; // will get filled in soon - // Pass the client-side stream address to the server-side for a ref - ref("inproc_init_stream:clt"); // ref it now on behalf of server - // side to avoid destruction - INPROC_LOG(GPR_INFO, "calling accept stream cb %p %p", - st->accept_stream_cb, st->accept_stream_data); - (*st->accept_stream_cb)(st->accept_stream_data, &st->base, (void*)this); - } else { - // This is the server-side and is being called through accept_stream_cb - inproc_stream* cs = (inproc_stream*)server_data; - other_side = cs; - // Ref the server-side stream on behalf of the client now - ref("inproc_init_stream:srv"); - - // Now we are about to affect the other side, so lock the transport - // to make sure that it doesn't get destroyed - gpr_mu_lock(&t->mu->mu); - cs->other_side = this; - // Now transfer from the other side's write_buffer if any to the to_read - // buffer - if (cs->write_buffer_initial_md_filled) { - fill_in_metadata(this, &cs->write_buffer_initial_md, - cs->write_buffer_initial_md_flags, &to_read_initial_md, - &to_read_initial_md_flags, &to_read_initial_md_filled); - deadline = GPR_MIN(deadline, cs->write_buffer_deadline); - grpc_metadata_batch_clear(&cs->write_buffer_initial_md); - cs->write_buffer_initial_md_filled = false; - } - if (cs->write_buffer_trailing_md_filled) { - fill_in_metadata(this, &cs->write_buffer_trailing_md, 0, - &to_read_trailing_md, nullptr, - &to_read_trailing_md_filled); - grpc_metadata_batch_clear(&cs->write_buffer_trailing_md); - cs->write_buffer_trailing_md_filled = false; - } - if (cs->write_buffer_cancel_error != GRPC_ERROR_NONE) { - cancel_other_error = cs->write_buffer_cancel_error; - cs->write_buffer_cancel_error = GRPC_ERROR_NONE; + : t(t), refs(refcount), arena(arena) { + // Ref this stream right now for ctor and list. + ref("inproc_init_stream:init"); + ref("inproc_init_stream:list"); + + grpc_metadata_batch_init(&to_read_initial_md); + grpc_metadata_batch_init(&to_read_trailing_md); + grpc_metadata_batch_init(&write_buffer_initial_md); + grpc_metadata_batch_init(&write_buffer_trailing_md); + + stream_list_prev = nullptr; + gpr_mu_lock(&t->mu->mu); + stream_list_next = t->stream_list; + if (t->stream_list) { + t->stream_list->stream_list_prev = this; + } + t->stream_list = this; + gpr_mu_unlock(&t->mu->mu); + + if (!server_data) { + t->ref(); + inproc_transport* st = t->other_side; + st->ref(); + other_side = nullptr; // will get filled in soon + // Pass the client-side stream address to the server-side for a ref + ref("inproc_init_stream:clt"); // ref it now on behalf of server + // side to avoid destruction + INPROC_LOG(GPR_INFO, "calling accept stream cb %p %p", + st->accept_stream_cb, st->accept_stream_data); + (*st->accept_stream_cb)(st->accept_stream_data, &st->base, (void*)this); + } else { + // This is the server-side and is being called through accept_stream_cb + inproc_stream* cs = (inproc_stream*)server_data; + other_side = cs; + // Ref the server-side stream on behalf of the client now + ref("inproc_init_stream:srv"); + + // Now we are about to affect the other side, so lock the transport + // to make sure that it doesn't get destroyed + gpr_mu_lock(&t->mu->mu); + cs->other_side = this; + // Now transfer from the other side's write_buffer if any to the to_read + // buffer + if (cs->write_buffer_initial_md_filled) { + fill_in_metadata(this, &cs->write_buffer_initial_md, + cs->write_buffer_initial_md_flags, &to_read_initial_md, + &to_read_initial_md_flags, &to_read_initial_md_filled); + deadline = GPR_MIN(deadline, cs->write_buffer_deadline); + grpc_metadata_batch_clear(&cs->write_buffer_initial_md); + cs->write_buffer_initial_md_filled = false; + } + if (cs->write_buffer_trailing_md_filled) { + fill_in_metadata(this, &cs->write_buffer_trailing_md, 0, + &to_read_trailing_md, nullptr, + &to_read_trailing_md_filled); + grpc_metadata_batch_clear(&cs->write_buffer_trailing_md); + cs->write_buffer_trailing_md_filled = false; + } + if (cs->write_buffer_cancel_error != GRPC_ERROR_NONE) { + cancel_other_error = cs->write_buffer_cancel_error; + cs->write_buffer_cancel_error = GRPC_ERROR_NONE; maybe_process_ops_locked(this, cancel_other_error); - } + } - gpr_mu_unlock(&t->mu->mu); - } - } + gpr_mu_unlock(&t->mu->mu); + } + } - ~inproc_stream() { - GRPC_ERROR_UNREF(write_buffer_cancel_error); - GRPC_ERROR_UNREF(cancel_self_error); - GRPC_ERROR_UNREF(cancel_other_error); + ~inproc_stream() { + GRPC_ERROR_UNREF(write_buffer_cancel_error); + GRPC_ERROR_UNREF(cancel_self_error); + GRPC_ERROR_UNREF(cancel_other_error); - if (recv_inited) { - grpc_slice_buffer_destroy_internal(&recv_message); - } + if (recv_inited) { + grpc_slice_buffer_destroy_internal(&recv_message); + } - t->unref(); + t->unref(); } #ifndef NDEBUG @@ -211,76 +211,76 @@ struct inproc_stream { #define STREAM_REF(refs, reason) grpc_stream_ref(refs) #define STREAM_UNREF(refs, reason) grpc_stream_unref(refs) #endif - void ref(const char* reason) { - INPROC_LOG(GPR_INFO, "ref_stream %p %s", this, reason); - STREAM_REF(refs, reason); - } - - void unref(const char* reason) { - INPROC_LOG(GPR_INFO, "unref_stream %p %s", this, reason); - STREAM_UNREF(refs, reason); - } -#undef STREAM_REF -#undef STREAM_UNREF - - inproc_transport* t; - grpc_metadata_batch to_read_initial_md; - uint32_t to_read_initial_md_flags = 0; - bool to_read_initial_md_filled = false; - grpc_metadata_batch to_read_trailing_md; - bool to_read_trailing_md_filled = false; - bool ops_needed = false; - // Write buffer used only during gap at init time when client-side - // stream is set up but server side stream is not yet set up - grpc_metadata_batch write_buffer_initial_md; - bool write_buffer_initial_md_filled = false; - uint32_t write_buffer_initial_md_flags = 0; - grpc_millis write_buffer_deadline = GRPC_MILLIS_INF_FUTURE; - grpc_metadata_batch write_buffer_trailing_md; - bool write_buffer_trailing_md_filled = false; - grpc_error* write_buffer_cancel_error = GRPC_ERROR_NONE; - - struct inproc_stream* other_side; - bool other_side_closed = false; // won't talk anymore - bool write_buffer_other_side_closed = false; // on hold - grpc_stream_refcount* refs; + void ref(const char* reason) { + INPROC_LOG(GPR_INFO, "ref_stream %p %s", this, reason); + STREAM_REF(refs, reason); + } + + void unref(const char* reason) { + INPROC_LOG(GPR_INFO, "unref_stream %p %s", this, reason); + STREAM_UNREF(refs, reason); + } +#undef STREAM_REF +#undef STREAM_UNREF + + inproc_transport* t; + grpc_metadata_batch to_read_initial_md; + uint32_t to_read_initial_md_flags = 0; + bool to_read_initial_md_filled = false; + grpc_metadata_batch to_read_trailing_md; + bool to_read_trailing_md_filled = false; + bool ops_needed = false; + // Write buffer used only during gap at init time when client-side + // stream is set up but server side stream is not yet set up + grpc_metadata_batch write_buffer_initial_md; + bool write_buffer_initial_md_filled = false; + uint32_t write_buffer_initial_md_flags = 0; + grpc_millis write_buffer_deadline = GRPC_MILLIS_INF_FUTURE; + grpc_metadata_batch write_buffer_trailing_md; + bool write_buffer_trailing_md_filled = false; + grpc_error* write_buffer_cancel_error = GRPC_ERROR_NONE; + + struct inproc_stream* other_side; + bool other_side_closed = false; // won't talk anymore + bool write_buffer_other_side_closed = false; // on hold + grpc_stream_refcount* refs; grpc_core::Arena* arena; - grpc_transport_stream_op_batch* send_message_op = nullptr; - grpc_transport_stream_op_batch* send_trailing_md_op = nullptr; - grpc_transport_stream_op_batch* recv_initial_md_op = nullptr; - grpc_transport_stream_op_batch* recv_message_op = nullptr; - grpc_transport_stream_op_batch* recv_trailing_md_op = nullptr; + grpc_transport_stream_op_batch* send_message_op = nullptr; + grpc_transport_stream_op_batch* send_trailing_md_op = nullptr; + grpc_transport_stream_op_batch* recv_initial_md_op = nullptr; + grpc_transport_stream_op_batch* recv_message_op = nullptr; + grpc_transport_stream_op_batch* recv_trailing_md_op = nullptr; - grpc_slice_buffer recv_message; - grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> recv_stream; - bool recv_inited = false; + grpc_slice_buffer recv_message; + grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> recv_stream; + bool recv_inited = false; - bool initial_md_sent = false; - bool trailing_md_sent = false; - bool initial_md_recvd = false; - bool trailing_md_recvd = false; + bool initial_md_sent = false; + bool trailing_md_sent = false; + bool initial_md_recvd = false; + bool trailing_md_recvd = false; // The following tracks if the server-side only pretends to have received // trailing metadata since it no longer cares about the RPC. If that is the // case, it is still ok for the client to send trailing metadata (in which // case it will be ignored). bool trailing_md_recvd_implicit_only = false; - bool closed = false; - - grpc_error* cancel_self_error = GRPC_ERROR_NONE; - grpc_error* cancel_other_error = GRPC_ERROR_NONE; - - grpc_millis deadline = GRPC_MILLIS_INF_FUTURE; - - bool listed = true; - struct inproc_stream* stream_list_prev; - struct inproc_stream* stream_list_next; -}; - -void log_metadata(const grpc_metadata_batch* md_batch, bool is_client, - bool is_initial) { + bool closed = false; + + grpc_error* cancel_self_error = GRPC_ERROR_NONE; + grpc_error* cancel_other_error = GRPC_ERROR_NONE; + + grpc_millis deadline = GRPC_MILLIS_INF_FUTURE; + + bool listed = true; + struct inproc_stream* stream_list_prev; + struct inproc_stream* stream_list_next; +}; + +void log_metadata(const grpc_metadata_batch* md_batch, bool is_client, + bool is_initial) { for (grpc_linked_mdelem* md = md_batch->list.head; md != nullptr; md = md->next) { char* key = grpc_slice_to_c_string(GRPC_MDKEY(md->md)); @@ -292,10 +292,10 @@ void log_metadata(const grpc_metadata_batch* md_batch, bool is_client, } } -grpc_error* fill_in_metadata(inproc_stream* s, - const grpc_metadata_batch* metadata, - uint32_t flags, grpc_metadata_batch* out_md, - uint32_t* outflags, bool* markfilled) { +grpc_error* fill_in_metadata(inproc_stream* s, + const grpc_metadata_batch* metadata, + uint32_t flags, grpc_metadata_batch* out_md, + uint32_t* outflags, bool* markfilled) { if (GRPC_TRACE_FLAG_ENABLED(grpc_inproc_trace)) { log_metadata(metadata, s->t->is_client, outflags != nullptr); } @@ -320,16 +320,16 @@ grpc_error* fill_in_metadata(inproc_stream* s, return error; } -int init_stream(grpc_transport* gt, grpc_stream* gs, - grpc_stream_refcount* refcount, const void* server_data, +int init_stream(grpc_transport* gt, grpc_stream* gs, + grpc_stream_refcount* refcount, const void* server_data, grpc_core::Arena* arena) { INPROC_LOG(GPR_INFO, "init_stream %p %p %p", gt, gs, server_data); inproc_transport* t = reinterpret_cast<inproc_transport*>(gt); - new (gs) inproc_stream(t, refcount, server_data, arena); + new (gs) inproc_stream(t, refcount, server_data, arena); return 0; // return value is not important } -void close_stream_locked(inproc_stream* s) { +void close_stream_locked(inproc_stream* s) { if (!s->closed) { // Release the metadata that we would have written out grpc_metadata_batch_destroy(&s->write_buffer_initial_md); @@ -347,21 +347,21 @@ void close_stream_locked(inproc_stream* s) { n->stream_list_prev = p; } s->listed = false; - s->unref("close_stream:list"); + s->unref("close_stream:list"); } s->closed = true; - s->unref("close_stream:closing"); + s->unref("close_stream:closing"); } } // This function means that we are done talking/listening to the other side -void close_other_side_locked(inproc_stream* s, const char* reason) { +void close_other_side_locked(inproc_stream* s, const char* reason) { if (s->other_side != nullptr) { // First release the metadata that came from the other side's arena grpc_metadata_batch_destroy(&s->to_read_initial_md); grpc_metadata_batch_destroy(&s->to_read_trailing_md); - s->other_side->unref(reason); + s->other_side->unref(reason); s->other_side_closed = true; s->other_side = nullptr; } else if (!s->other_side_closed) { @@ -373,15 +373,15 @@ void close_other_side_locked(inproc_stream* s, const char* reason) { // this stream_op_batch is only one of the pending operations for this // stream. This is called when one of the pending operations for the stream // is done and about to be NULLed out -void complete_if_batch_end_locked(inproc_stream* s, grpc_error* error, - grpc_transport_stream_op_batch* op, - const char* msg) { +void complete_if_batch_end_locked(inproc_stream* s, grpc_error* error, + grpc_transport_stream_op_batch* op, + const char* msg) { int is_sm = static_cast<int>(op == s->send_message_op); int is_stm = static_cast<int>(op == s->send_trailing_md_op); - // TODO(vjpai): We should not consider the recv ops here, since they - // have their own callbacks. We should invoke a batch's on_complete - // as soon as all of the batch's send ops are complete, even if there - // are still recv ops pending. + // TODO(vjpai): We should not consider the recv ops here, since they + // have their own callbacks. We should invoke a batch's on_complete + // as soon as all of the batch's send ops are complete, even if there + // are still recv ops pending. int is_rim = static_cast<int>(op == s->recv_initial_md_op); int is_rm = static_cast<int>(op == s->recv_message_op); int is_rtm = static_cast<int>(op == s->recv_trailing_md_op); @@ -400,7 +400,7 @@ void maybe_process_ops_locked(inproc_stream* s, grpc_error* error) { } } -void fail_helper_locked(inproc_stream* s, grpc_error* error) { +void fail_helper_locked(inproc_stream* s, grpc_error* error) { INPROC_LOG(GPR_INFO, "op_state_machine %p fail_helper", s); // If we're failing this side, we need to make sure that // we also send or have already sent trailing metadata @@ -507,8 +507,8 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) { s->send_trailing_md_op = nullptr; } if (s->recv_trailing_md_op) { - INPROC_LOG(GPR_INFO, "fail_helper %p scheduling trailing-metadata-ready %p", - s, error); + INPROC_LOG(GPR_INFO, "fail_helper %p scheduling trailing-metadata-ready %p", + s, error); grpc_core::ExecCtx::Run( DEBUG_LOCATION, s->recv_trailing_md_op->payload->recv_trailing_metadata @@ -535,7 +535,7 @@ void fail_helper_locked(inproc_stream* s, grpc_error* error) { // that the incoming byte stream's next() call will always return // synchronously. That assumption is true today but may not always be // true in the future. -void message_transfer_locked(inproc_stream* sender, inproc_stream* receiver) { +void message_transfer_locked(inproc_stream* sender, inproc_stream* receiver) { size_t remaining = sender->send_message_op->payload->send_message.send_message->length(); if (receiver->recv_inited) { @@ -611,8 +611,8 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) { if (other->recv_message_op) { message_transfer_locked(s, other); maybe_process_ops_locked(other, GRPC_ERROR_NONE); - } else if (!s->t->is_client && s->trailing_md_sent) { - // A server send will never be matched if the server already sent status + } else if (!s->t->is_client && s->trailing_md_sent) { + // A server send will never be matched if the server already sent status s->send_message_op->payload->send_message.send_message.reset(); complete_if_batch_end_locked( s, GRPC_ERROR_NONE, s->send_message_op, @@ -623,15 +623,15 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) { // Pause a send trailing metadata if there is still an outstanding // send message unless we know that the send message will never get // matched to a receive. This happens on the client if the server has - // already sent status or on the server if the client has requested - // status + // already sent status or on the server if the client has requested + // status if (s->send_trailing_md_op && (!s->send_message_op || (s->t->is_client && - (s->trailing_md_recvd || s->to_read_trailing_md_filled)) || - (!s->t->is_client && other && - (other->trailing_md_recvd || other->to_read_trailing_md_filled || - other->recv_trailing_md_op)))) { + (s->trailing_md_recvd || s->to_read_trailing_md_filled)) || + (!s->t->is_client && other && + (other->trailing_md_recvd || other->to_read_trailing_md_filled || + other->recv_trailing_md_op)))) { grpc_metadata_batch* dest = (other == nullptr) ? &s->write_buffer_trailing_md : &other->to_read_trailing_md; @@ -656,13 +656,13 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) { } if (!s->t->is_client && s->trailing_md_recvd && s->recv_trailing_md_op) { INPROC_LOG(GPR_INFO, - "op_state_machine %p scheduling trailing-metadata-ready", s); + "op_state_machine %p scheduling trailing-metadata-ready", s); grpc_core::ExecCtx::Run( DEBUG_LOCATION, - s->recv_trailing_md_op->payload->recv_trailing_metadata - .recv_trailing_metadata_ready, - GRPC_ERROR_NONE); - INPROC_LOG(GPR_INFO, + s->recv_trailing_md_op->payload->recv_trailing_metadata + .recv_trailing_metadata_ready, + GRPC_ERROR_NONE); + INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling trailing-md-on-complete", s); grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->recv_trailing_md_op->on_complete, @@ -761,7 +761,7 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) { if (s->recv_message_op != nullptr) { // This message needs to be wrapped up because it will never be // satisfied - *s->recv_message_op->payload->recv_message.recv_message = nullptr; + *s->recv_message_op->payload->recv_message.recv_message = nullptr; INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s); grpc_core::ExecCtx::Run( DEBUG_LOCATION, @@ -804,9 +804,9 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) { s, new_err); grpc_core::ExecCtx::Run( DEBUG_LOCATION, - s->recv_trailing_md_op->payload->recv_trailing_metadata - .recv_trailing_metadata_ready, - GRPC_ERROR_REF(new_err)); + s->recv_trailing_md_op->payload->recv_trailing_metadata + .recv_trailing_metadata_ready, + GRPC_ERROR_REF(new_err)); grpc_core::ExecCtx::Run(DEBUG_LOCATION, s->recv_trailing_md_op->on_complete, GRPC_ERROR_REF(new_err)); @@ -849,7 +849,7 @@ void op_state_machine_locked(inproc_stream* s, grpc_error* error) { // No further message will come on this stream, so finish off the // recv_message_op INPROC_LOG(GPR_INFO, "op_state_machine %p scheduling message-ready", s); - *s->recv_message_op->payload->recv_message.recv_message = nullptr; + *s->recv_message_op->payload->recv_message.recv_message = nullptr; grpc_core::ExecCtx::Run( DEBUG_LOCATION, s->recv_message_op->payload->recv_message.recv_message_ready, @@ -886,7 +886,7 @@ done: GRPC_ERROR_UNREF(new_err); } -bool cancel_stream_locked(inproc_stream* s, grpc_error* error) { +bool cancel_stream_locked(inproc_stream* s, grpc_error* error) { bool ret = false; // was the cancel accepted INPROC_LOG(GPR_INFO, "cancel_stream %p with %s", s, grpc_error_string(error)); if (s->cancel_self_error == GRPC_ERROR_NONE) { @@ -943,9 +943,9 @@ bool cancel_stream_locked(inproc_stream* s, grpc_error* error) { } void do_nothing(void* /*arg*/, grpc_error* /*error*/) {} - -void perform_stream_op(grpc_transport* gt, grpc_stream* gs, - grpc_transport_stream_op_batch* op) { + +void perform_stream_op(grpc_transport* gt, grpc_stream* gs, + grpc_transport_stream_op_batch* op) { INPROC_LOG(GPR_INFO, "perform_stream_op %p %p %p", gt, gs, op); inproc_stream* s = reinterpret_cast<inproc_stream*>(gs); gpr_mu* mu = &s->t->mu->mu; // save aside in case s gets closed @@ -963,14 +963,14 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs, } grpc_error* error = GRPC_ERROR_NONE; grpc_closure* on_complete = op->on_complete; - // TODO(roth): This is a hack needed because we use data inside of the - // closure itself to do the barrier calculation (i.e., to ensure that - // we don't schedule the closure until all ops in the batch have been - // completed). This can go away once we move to a new C++ closure API - // that provides the ability to create a barrier closure. + // TODO(roth): This is a hack needed because we use data inside of the + // closure itself to do the barrier calculation (i.e., to ensure that + // we don't schedule the closure until all ops in the batch have been + // completed). This can go away once we move to a new C++ closure API + // that provides the ability to create a barrier closure. if (on_complete == nullptr) { - on_complete = GRPC_CLOSURE_INIT(&op->handler_private.closure, do_nothing, - nullptr, grpc_schedule_on_exec_ctx); + on_complete = GRPC_CLOSURE_INIT(&op->handler_private.closure, do_nothing, + nullptr, grpc_schedule_on_exec_ctx); } if (op->cancel_stream) { @@ -1052,18 +1052,18 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs, } // We want to initiate the state machine if: - // 1. We want to send a message and the other side wants to receive + // 1. We want to send a message and the other side wants to receive // 2. We want to send trailing metadata and there isn't an unmatched send - // or the other side wants trailing metadata + // or the other side wants trailing metadata // 3. We want initial metadata and the other side has sent it // 4. We want to receive a message and there is a message ready // 5. There is trailing metadata, even if nothing specifically wants // that because that can shut down the receive message as well - if ((op->send_message && other && other->recv_message_op != nullptr) || - (op->send_trailing_metadata && - (!s->send_message_op || (other && other->recv_trailing_md_op))) || + if ((op->send_message && other && other->recv_message_op != nullptr) || + (op->send_trailing_metadata && + (!s->send_message_op || (other && other->recv_trailing_md_op))) || (op->recv_initial_metadata && s->to_read_initial_md_filled) || - (op->recv_message && other && other->send_message_op != nullptr) || + (op->recv_message && other && other->send_message_op != nullptr) || (s->to_read_trailing_md_filled || s->trailing_md_recvd)) { op_state_machine_locked(s, error); } else { @@ -1105,16 +1105,16 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs, op->payload->recv_message.recv_message_ready, GRPC_ERROR_REF(error)); } - if (op->recv_trailing_metadata) { - INPROC_LOG( - GPR_INFO, - "perform_stream_op error %p scheduling trailing-metadata-ready %p", - s, error); + if (op->recv_trailing_metadata) { + INPROC_LOG( + GPR_INFO, + "perform_stream_op error %p scheduling trailing-metadata-ready %p", + s, error); grpc_core::ExecCtx::Run( DEBUG_LOCATION, - op->payload->recv_trailing_metadata.recv_trailing_metadata_ready, - GRPC_ERROR_REF(error)); - } + op->payload->recv_trailing_metadata.recv_trailing_metadata_ready, + GRPC_ERROR_REF(error)); + } } INPROC_LOG(GPR_INFO, "perform_stream_op %p scheduling on_complete %p", s, error); @@ -1124,7 +1124,7 @@ void perform_stream_op(grpc_transport* gt, grpc_stream* gs, GRPC_ERROR_UNREF(error); } -void close_transport_locked(inproc_transport* t) { +void close_transport_locked(inproc_transport* t) { INPROC_LOG(GPR_INFO, "close_transport %p %d", t, t->is_closed); t->state_tracker.SetState(GRPC_CHANNEL_SHUTDOWN, y_absl::Status(), "close transport"); @@ -1142,7 +1142,7 @@ void close_transport_locked(inproc_transport* t) { } } -void perform_transport_op(grpc_transport* gt, grpc_transport_op* op) { +void perform_transport_op(grpc_transport* gt, grpc_transport_op* op) { inproc_transport* t = reinterpret_cast<inproc_transport*>(gt); INPROC_LOG(GPR_INFO, "perform_transport_op %p %p", t, op); gpr_mu_lock(&t->mu->mu); @@ -1178,26 +1178,26 @@ void perform_transport_op(grpc_transport* gt, grpc_transport_op* op) { } void destroy_stream(grpc_transport* gt, grpc_stream* gs, - grpc_closure* then_schedule_closure) { + grpc_closure* then_schedule_closure) { INPROC_LOG(GPR_INFO, "destroy_stream %p %p", gs, then_schedule_closure); inproc_transport* t = reinterpret_cast<inproc_transport*>(gt); inproc_stream* s = reinterpret_cast<inproc_stream*>(gs); gpr_mu_lock(&t->mu->mu); close_stream_locked(s); gpr_mu_unlock(&t->mu->mu); - s->~inproc_stream(); + s->~inproc_stream(); grpc_core::ExecCtx::Run(DEBUG_LOCATION, then_schedule_closure, GRPC_ERROR_NONE); } -void destroy_transport(grpc_transport* gt) { +void destroy_transport(grpc_transport* gt) { inproc_transport* t = reinterpret_cast<inproc_transport*>(gt); INPROC_LOG(GPR_INFO, "destroy_transport %p", t); gpr_mu_lock(&t->mu->mu); close_transport_locked(t); gpr_mu_unlock(&t->mu->mu); - t->other_side->unref(); - t->unref(); + t->other_side->unref(); + t->unref(); } /******************************************************************************* @@ -1216,33 +1216,33 @@ void set_pollset_set(grpc_transport* /*gt*/, grpc_stream* /*gs*/, grpc_endpoint* get_endpoint(grpc_transport* /*t*/) { return nullptr; } -const grpc_transport_vtable inproc_vtable = { - sizeof(inproc_stream), "inproc", init_stream, - set_pollset, set_pollset_set, perform_stream_op, - perform_transport_op, destroy_stream, destroy_transport, - get_endpoint}; - +const grpc_transport_vtable inproc_vtable = { + sizeof(inproc_stream), "inproc", init_stream, + set_pollset, set_pollset_set, perform_stream_op, + perform_transport_op, destroy_stream, destroy_transport, + get_endpoint}; + /******************************************************************************* - * Main inproc transport functions - */ -void inproc_transports_create(grpc_transport** server_transport, + * Main inproc transport functions + */ +void inproc_transports_create(grpc_transport** server_transport, const grpc_channel_args* /*server_args*/, - grpc_transport** client_transport, + grpc_transport** client_transport, const grpc_channel_args* /*client_args*/) { - INPROC_LOG(GPR_INFO, "inproc_transports_create"); - shared_mu* mu = new (gpr_malloc(sizeof(*mu))) shared_mu(); - inproc_transport* st = new (gpr_malloc(sizeof(*st))) - inproc_transport(&inproc_vtable, mu, /*is_client=*/false); - inproc_transport* ct = new (gpr_malloc(sizeof(*ct))) - inproc_transport(&inproc_vtable, mu, /*is_client=*/true); - st->other_side = ct; - ct->other_side = st; - *server_transport = reinterpret_cast<grpc_transport*>(st); - *client_transport = reinterpret_cast<grpc_transport*>(ct); -} -} // namespace - -/******************************************************************************* + INPROC_LOG(GPR_INFO, "inproc_transports_create"); + shared_mu* mu = new (gpr_malloc(sizeof(*mu))) shared_mu(); + inproc_transport* st = new (gpr_malloc(sizeof(*st))) + inproc_transport(&inproc_vtable, mu, /*is_client=*/false); + inproc_transport* ct = new (gpr_malloc(sizeof(*ct))) + inproc_transport(&inproc_vtable, mu, /*is_client=*/true); + st->other_side = ct; + ct->other_side = st; + *server_transport = reinterpret_cast<grpc_transport*>(st); + *client_transport = reinterpret_cast<grpc_transport*>(ct); +} +} // namespace + +/******************************************************************************* * GLOBAL INIT AND DESTROY */ void grpc_inproc_transport_init(void) { @@ -1291,7 +1291,7 @@ grpc_channel* grpc_inproc_channel_create(grpc_server* server, inproc_transports_create(&server_transport, server_args, &client_transport, client_args); - // TODO(ncteisen): design and support channelz GetSocket for inproc. + // TODO(ncteisen): design and support channelz GetSocket for inproc. server->core_server->SetupTransport(server_transport, nullptr, server_args, nullptr); grpc_channel* channel = grpc_channel_create( diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc b/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc index e9b348972f..2832456ddf 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc +++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack.cc @@ -21,7 +21,7 @@ #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include "src/core/lib/channel/channel_stack.h" -#include "src/core/lib/gpr/alloc.h" +#include "src/core/lib/gpr/alloc.h" #include <stdlib.h> #include <string.h> @@ -47,9 +47,9 @@ grpc_core::TraceFlag grpc_trace_channel(false, "channel"); size_t grpc_channel_stack_size(const grpc_channel_filter** filters, size_t filter_count) { /* always need the header, and size for the channel elements */ - size_t size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)) + - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * - sizeof(grpc_channel_element)); + size_t size = GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack)) + + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * + sizeof(grpc_channel_element)); size_t i; GPR_ASSERT((GPR_MAX_ALIGNMENT & (GPR_MAX_ALIGNMENT - 1)) == 0 && @@ -57,19 +57,19 @@ size_t grpc_channel_stack_size(const grpc_channel_filter** filters, /* add the size for each filter */ for (i = 0; i < filter_count; i++) { - size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data); + size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data); } return size; } -#define CHANNEL_ELEMS_FROM_STACK(stk) \ - ((grpc_channel_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \ +#define CHANNEL_ELEMS_FROM_STACK(stk) \ + ((grpc_channel_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \ sizeof(grpc_channel_stack)))) -#define CALL_ELEMS_FROM_STACK(stk) \ - ((grpc_call_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \ - sizeof(grpc_call_stack)))) +#define CALL_ELEMS_FROM_STACK(stk) \ + ((grpc_call_element*)((char*)(stk) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE( \ + sizeof(grpc_call_stack)))) grpc_channel_element* grpc_channel_stack_element( grpc_channel_stack* channel_stack, size_t index) { @@ -92,8 +92,8 @@ grpc_error* grpc_channel_stack_init( const grpc_channel_args* channel_args, grpc_transport* optional_transport, const char* name, grpc_channel_stack* stack) { size_t call_size = - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)) + - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * sizeof(grpc_call_element)); + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack)) + + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * sizeof(grpc_call_element)); grpc_channel_element* elems; grpc_channel_element_args args; char* user_data; @@ -103,9 +103,9 @@ grpc_error* grpc_channel_stack_init( GRPC_STREAM_REF_INIT(&stack->refcount, initial_refs, destroy, destroy_arg, name); elems = CHANNEL_ELEMS_FROM_STACK(stack); - user_data = (reinterpret_cast<char*>(elems)) + - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * - sizeof(grpc_channel_element)); + user_data = (reinterpret_cast<char*>(elems)) + + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filter_count * + sizeof(grpc_channel_element)); /* init per-filter data */ grpc_error* first_error = GRPC_ERROR_NONE; @@ -125,9 +125,9 @@ grpc_error* grpc_channel_stack_init( GRPC_ERROR_UNREF(error); } } - user_data += - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data); - call_size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_call_data); + user_data += + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_channel_data); + call_size += GPR_ROUND_UP_TO_ALIGNMENT_SIZE(filters[i]->sizeof_call_data); } GPR_ASSERT(user_data > (char*)stack); @@ -163,18 +163,18 @@ grpc_error* grpc_call_stack_init(grpc_channel_stack* channel_stack, destroy_arg, "CALL_STACK"); call_elems = CALL_ELEMS_FROM_STACK(elem_args->call_stack); user_data = (reinterpret_cast<char*>(call_elems)) + - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(count * sizeof(grpc_call_element)); + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(count * sizeof(grpc_call_element)); /* init per-filter data */ grpc_error* first_error = GRPC_ERROR_NONE; - for (size_t i = 0; i < count; i++) { + for (size_t i = 0; i < count; i++) { call_elems[i].filter = channel_elems[i].filter; call_elems[i].channel_data = channel_elems[i].channel_data; call_elems[i].call_data = user_data; - user_data += - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(call_elems[i].filter->sizeof_call_data); - } - for (size_t i = 0; i < count; i++) { + user_data += + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(call_elems[i].filter->sizeof_call_data); + } + for (size_t i = 0; i < count; i++) { grpc_error* error = call_elems[i].filter->init_call_elem(&call_elems[i], elem_args); if (error != GRPC_ERROR_NONE) { @@ -242,11 +242,11 @@ grpc_channel_stack* grpc_channel_stack_from_top_element( grpc_channel_element* elem) { return reinterpret_cast<grpc_channel_stack*>( reinterpret_cast<char*>(elem) - - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack))); + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_channel_stack))); } grpc_call_stack* grpc_call_stack_from_top_element(grpc_call_element* elem) { return reinterpret_cast<grpc_call_stack*>( reinterpret_cast<char*>(elem) - - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack))); + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call_stack))); } diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack.h b/contrib/libs/grpc/src/core/lib/channel/channel_stack.h index e297df9488..da62eccf34 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channel_stack.h +++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack.h @@ -88,11 +88,11 @@ struct grpc_call_stats { gpr_timespec latency; /* From call creating to enqueing of received status */ }; /** Information about the call upon completion. */ -struct grpc_call_final_info { +struct grpc_call_final_info { grpc_call_stats stats; - grpc_status_code final_status = GRPC_STATUS_OK; - const char* error_string = nullptr; -}; + grpc_status_code final_status = GRPC_STATUS_OK; + const char* error_string = nullptr; +}; /* Channel filters specify: 1. the amount of memory needed in the channel & call (via the sizeof_XXX @@ -147,7 +147,7 @@ struct grpc_channel_filter { is_first, is_last designate this elements position in the stack, and are useful for asserting correct configuration by upper layer code. The filter does not need to do any chaining. - Implementations may assume that elem->channel_data is all zeros. */ + Implementations may assume that elem->channel_data is all zeros. */ grpc_error* (*init_channel_elem)(grpc_channel_element* elem, grpc_channel_element_args* args); /* Destroy per channel data. diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc index 8b3008f221..d4526d3f10 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc +++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.cc @@ -40,7 +40,7 @@ struct grpc_channel_stack_builder { // various set/get-able parameters grpc_channel_args* args; grpc_transport* transport; - grpc_resource_user* resource_user; + grpc_resource_user* resource_user; char* target; const char* name; }; @@ -158,11 +158,11 @@ void grpc_channel_stack_builder_set_channel_arguments( builder->args = grpc_channel_args_copy(args); } -const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments( - grpc_channel_stack_builder* builder) { - return builder->args; -} - +const grpc_channel_args* grpc_channel_stack_builder_get_channel_arguments( + grpc_channel_stack_builder* builder) { + return builder->args; +} + void grpc_channel_stack_builder_set_transport( grpc_channel_stack_builder* builder, grpc_transport* transport) { GPR_ASSERT(builder->transport == nullptr); @@ -174,15 +174,15 @@ grpc_transport* grpc_channel_stack_builder_get_transport( return builder->transport; } -void grpc_channel_stack_builder_set_resource_user( - grpc_channel_stack_builder* builder, grpc_resource_user* resource_user) { - GPR_ASSERT(builder->resource_user == nullptr); - builder->resource_user = resource_user; -} - -grpc_resource_user* grpc_channel_stack_builder_get_resource_user( +void grpc_channel_stack_builder_set_resource_user( + grpc_channel_stack_builder* builder, grpc_resource_user* resource_user) { + GPR_ASSERT(builder->resource_user == nullptr); + builder->resource_user = resource_user; +} + +grpc_resource_user* grpc_channel_stack_builder_get_resource_user( grpc_channel_stack_builder* builder) { - return builder->resource_user; + return builder->resource_user; } bool grpc_channel_stack_builder_append_filter( diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h index 89c30e0c5e..355dffe903 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h +++ b/contrib/libs/grpc/src/core/lib/channel/channel_stack_builder.h @@ -54,14 +54,14 @@ void grpc_channel_stack_builder_set_transport( grpc_transport* grpc_channel_stack_builder_get_transport( grpc_channel_stack_builder* builder); -/// Attach \a resource_user to the builder (does not take ownership) -void grpc_channel_stack_builder_set_resource_user( - grpc_channel_stack_builder* builder, grpc_resource_user* resource_user); - -/// Fetch attached resource user -grpc_resource_user* grpc_channel_stack_builder_get_resource_user( - grpc_channel_stack_builder* builder); - +/// Attach \a resource_user to the builder (does not take ownership) +void grpc_channel_stack_builder_set_resource_user( + grpc_channel_stack_builder* builder, grpc_resource_user* resource_user); + +/// Fetch attached resource user +grpc_resource_user* grpc_channel_stack_builder_get_resource_user( + grpc_channel_stack_builder* builder); + /// Set channel arguments: copies args void grpc_channel_stack_builder_set_channel_arguments( grpc_channel_stack_builder* builder, const grpc_channel_args* args); diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc b/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc index dbc33af2d4..5ef2390033 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc +++ b/contrib/libs/grpc/src/core/lib/channel/channel_trace.cc @@ -39,44 +39,44 @@ #include "src/core/lib/transport/error_utils.h" namespace grpc_core { -namespace channelz { +namespace channelz { ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_entity) + RefCountedPtr<BaseNode> referenced_entity) : severity_(severity), data_(data), timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(), GPR_CLOCK_REALTIME)), next_(nullptr), - referenced_entity_(std::move(referenced_entity)), - memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {} + referenced_entity_(std::move(referenced_entity)), + memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {} ChannelTrace::TraceEvent::TraceEvent(Severity severity, const grpc_slice& data) : severity_(severity), data_(data), timestamp_(grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(), GPR_CLOCK_REALTIME)), - next_(nullptr), - memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {} + next_(nullptr), + memory_usage_(sizeof(TraceEvent) + grpc_slice_memory_usage(data)) {} ChannelTrace::TraceEvent::~TraceEvent() { grpc_slice_unref_internal(data_); } -ChannelTrace::ChannelTrace(size_t max_event_memory) - : num_events_logged_(0), - event_list_memory_usage_(0), - max_event_memory_(max_event_memory), +ChannelTrace::ChannelTrace(size_t max_event_memory) + : num_events_logged_(0), + event_list_memory_usage_(0), + max_event_memory_(max_event_memory), head_trace_(nullptr), tail_trace_(nullptr) { - if (max_event_memory_ == 0) - return; // tracing is disabled if max_event_memory_ == 0 + if (max_event_memory_ == 0) + return; // tracing is disabled if max_event_memory_ == 0 gpr_mu_init(&tracer_mu_); time_created_ = grpc_millis_to_timespec(grpc_core::ExecCtx::Get()->Now(), GPR_CLOCK_REALTIME); } ChannelTrace::~ChannelTrace() { - if (max_event_memory_ == 0) - return; // tracing is disabled if max_event_memory_ == 0 + if (max_event_memory_ == 0) + return; // tracing is disabled if max_event_memory_ == 0 TraceEvent* it = head_trace_; while (it != nullptr) { TraceEvent* to_free = it; @@ -97,31 +97,31 @@ void ChannelTrace::AddTraceEventHelper(TraceEvent* new_trace_event) { tail_trace_->set_next(new_trace_event); tail_trace_ = tail_trace_->next(); } - event_list_memory_usage_ += new_trace_event->memory_usage(); - // maybe garbage collect the tail until we are under the memory limit. - while (event_list_memory_usage_ > max_event_memory_) { + event_list_memory_usage_ += new_trace_event->memory_usage(); + // maybe garbage collect the tail until we are under the memory limit. + while (event_list_memory_usage_ > max_event_memory_) { TraceEvent* to_free = head_trace_; - event_list_memory_usage_ -= to_free->memory_usage(); + event_list_memory_usage_ -= to_free->memory_usage(); head_trace_ = head_trace_->next(); delete to_free; } } void ChannelTrace::AddTraceEvent(Severity severity, const grpc_slice& data) { - if (max_event_memory_ == 0) { - grpc_slice_unref_internal(data); - return; // tracing is disabled if max_event_memory_ == 0 - } + if (max_event_memory_ == 0) { + grpc_slice_unref_internal(data); + return; // tracing is disabled if max_event_memory_ == 0 + } AddTraceEventHelper(new TraceEvent(severity, data)); } -void ChannelTrace::AddTraceEventWithReference( +void ChannelTrace::AddTraceEventWithReference( Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_entity) { - if (max_event_memory_ == 0) { - grpc_slice_unref_internal(data); - return; // tracing is disabled if max_event_memory_ == 0 - } + RefCountedPtr<BaseNode> referenced_entity) { + if (max_event_memory_ == 0) { + grpc_slice_unref_internal(data); + return; // tracing is disabled if max_event_memory_ == 0 + } // create and fill up the new event AddTraceEventHelper( new TraceEvent(severity, data, std::move(referenced_entity))); @@ -152,10 +152,10 @@ Json ChannelTrace::TraceEvent::RenderTraceEvent() const { {"timestamp", gpr_format_timespec(timestamp_)}, }; gpr_free(description); - if (referenced_entity_ != nullptr) { - const bool is_channel = - (referenced_entity_->type() == BaseNode::EntityType::kTopLevelChannel || - referenced_entity_->type() == BaseNode::EntityType::kInternalChannel); + if (referenced_entity_ != nullptr) { + const bool is_channel = + (referenced_entity_->type() == BaseNode::EntityType::kTopLevelChannel || + referenced_entity_->type() == BaseNode::EntityType::kInternalChannel); object[is_channel ? "channelRef" : "subchannelRef"] = Json::Object{ {(is_channel ? "channelId" : "subchannelId"), ToString(referenced_entity_->uuid())}, @@ -172,19 +172,19 @@ Json ChannelTrace::RenderJson() const { Json::Object object = { {"creationTimestamp", gpr_format_timespec(time_created_)}, }; - if (num_events_logged_ > 0) { + if (num_events_logged_ > 0) { object["numEventsLogged"] = ToString(num_events_logged_); } // Only add in the event list if it is non-empty. - if (head_trace_ != nullptr) { + if (head_trace_ != nullptr) { Json::Array array; for (TraceEvent* it = head_trace_; it != nullptr; it = it->next()) { array.emplace_back(it->RenderTraceEvent()); - } + } object["events"] = std::move(array); - } + } return object; } -} // namespace channelz +} // namespace channelz } // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/channel/channel_trace.h b/contrib/libs/grpc/src/core/lib/channel/channel_trace.h index c26e3016da..a4052096c8 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channel_trace.h +++ b/contrib/libs/grpc/src/core/lib/channel/channel_trace.h @@ -28,20 +28,20 @@ #include "src/core/lib/json/json.h" namespace grpc_core { -namespace channelz { - -namespace testing { -size_t GetSizeofTraceEvent(void); -} - -class BaseNode; - +namespace channelz { + +namespace testing { +size_t GetSizeofTraceEvent(void); +} + +class BaseNode; + // Object used to hold live data for a channel. This data is exposed via the // channelz service: // https://github.com/grpc/proposal/blob/master/A14-channelz.md -class ChannelTrace { +class ChannelTrace { public: - ChannelTrace(size_t max_event_memory); + ChannelTrace(size_t max_event_memory); ~ChannelTrace(); enum Severity { @@ -53,42 +53,42 @@ class ChannelTrace { // Adds a new trace event to the tracing object // - // NOTE: each ChannelTrace tracks the memory used by its list of trace - // events, so adding an event with a large amount of data could cause other - // trace event to be evicted. If a single trace is larger than the limit, it - // will cause all events to be evicted. The limit is set with the arg: - // GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE. - // + // NOTE: each ChannelTrace tracks the memory used by its list of trace + // events, so adding an event with a large amount of data could cause other + // trace event to be evicted. If a single trace is larger than the limit, it + // will cause all events to be evicted. The limit is set with the arg: + // GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE. + // // TODO(ncteisen): as this call is used more and more throughout the gRPC // stack, determine if it makes more sense to accept a char* instead of a // slice. void AddTraceEvent(Severity severity, const grpc_slice& data); // Adds a new trace event to the tracing object. This trace event refers to a - // an event that concerns a different channelz entity. For example, if this - // channel has created a new subchannel, then it would record that with - // a TraceEvent referencing the new subchannel. + // an event that concerns a different channelz entity. For example, if this + // channel has created a new subchannel, then it would record that with + // a TraceEvent referencing the new subchannel. // - // NOTE: see the note in the method above. - // - // TODO(ncteisen): see the todo in the method above. + // NOTE: see the note in the method above. + // + // TODO(ncteisen): see the todo in the method above. void AddTraceEventWithReference(Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_entity); + RefCountedPtr<BaseNode> referenced_entity); // Creates and returns the raw Json object, so a parent channelz - // object may incorporate the json before rendering. + // object may incorporate the json before rendering. Json RenderJson() const; private: - friend size_t testing::GetSizeofTraceEvent(void); - + friend size_t testing::GetSizeofTraceEvent(void); + // Private class to encapsulate all the data and bookkeeping needed for a // a trace event. class TraceEvent { public: - // Constructor for a TraceEvent that references a channel. + // Constructor for a TraceEvent that references a channel. TraceEvent(Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_entity_); + RefCountedPtr<BaseNode> referenced_entity_); // Constructor for a TraceEvent that does not reverence a different // channel. @@ -104,16 +104,16 @@ class ChannelTrace { TraceEvent* next() const { return next_; } void set_next(TraceEvent* next) { next_ = next; } - size_t memory_usage() const { return memory_usage_; } - + size_t memory_usage() const { return memory_usage_; } + private: Severity severity_; grpc_slice data_; gpr_timespec timestamp_; TraceEvent* next_; // the tracer object for the (sub)channel that this trace event refers to. - RefCountedPtr<BaseNode> referenced_entity_; - size_t memory_usage_; + RefCountedPtr<BaseNode> referenced_entity_; + size_t memory_usage_; }; // TraceEvent // Internal helper to add and link in a trace event @@ -121,14 +121,14 @@ class ChannelTrace { gpr_mu tracer_mu_; uint64_t num_events_logged_; - size_t event_list_memory_usage_; - size_t max_event_memory_; + size_t event_list_memory_usage_; + size_t max_event_memory_; TraceEvent* head_trace_; TraceEvent* tail_trace_; gpr_timespec time_created_; }; -} // namespace channelz +} // namespace channelz } // namespace grpc_core #endif /* GRPC_CORE_LIB_CHANNEL_CHANNEL_TRACE_H */ diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz.cc b/contrib/libs/grpc/src/core/lib/channel/channelz.cc index 16f505c053..672c6b0018 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channelz.cc +++ b/contrib/libs/grpc/src/core/lib/channel/channelz.cc @@ -1,104 +1,104 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/impl/codegen/port_platform.h> - -#include "src/core/lib/channel/channelz.h" - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include "src/core/lib/channel/channelz_registry.h" -#include "src/core/lib/channel/status_util.h" -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/gpr/useful.h" +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/impl/codegen/port_platform.h> + +#include "src/core/lib/channel/channelz.h" + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "src/core/lib/channel/channelz_registry.h" +#include "src/core/lib/channel/status_util.h" +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/gpr/useful.h" #include "src/core/lib/gprpp/atomic.h" #include "src/core/lib/gprpp/host_port.h" -#include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/iomgr/error.h" -#include "src/core/lib/iomgr/exec_ctx.h" -#include "src/core/lib/slice/b64.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/surface/channel.h" -#include "src/core/lib/surface/server.h" +#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/slice/b64.h" +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/surface/channel.h" +#include "src/core/lib/surface/server.h" #include "src/core/lib/transport/connectivity_state.h" -#include "src/core/lib/transport/error_utils.h" -#include "src/core/lib/uri/uri_parser.h" - +#include "src/core/lib/transport/error_utils.h" +#include "src/core/lib/uri/uri_parser.h" + #include <util/string/cast.h> -namespace grpc_core { -namespace channelz { - +namespace grpc_core { +namespace channelz { + // // BaseNode // BaseNode::BaseNode(EntityType type, TString name) : type_(type), uuid_(-1), name_(std::move(name)) { - // The registry will set uuid_ under its lock. - ChannelzRegistry::Register(this); -} - -BaseNode::~BaseNode() { ChannelzRegistry::Unregister(uuid_); } - + // The registry will set uuid_ under its lock. + ChannelzRegistry::Register(this); +} + +BaseNode::~BaseNode() { ChannelzRegistry::Unregister(uuid_); } + TString BaseNode::RenderJsonString() { Json json = RenderJson(); return json.Dump(); -} - +} + // // CallCountingHelper // -CallCountingHelper::CallCountingHelper() { - num_cores_ = GPR_MAX(1, gpr_cpu_num_cores()); +CallCountingHelper::CallCountingHelper() { + num_cores_ = GPR_MAX(1, gpr_cpu_num_cores()); per_cpu_counter_data_storage_.reserve(num_cores_); for (size_t i = 0; i < num_cores_; ++i) { per_cpu_counter_data_storage_.emplace_back(); } -} - -void CallCountingHelper::RecordCallStarted() { +} + +void CallCountingHelper::RecordCallStarted() { AtomicCounterData& data = per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()]; data.calls_started.FetchAdd(1, MemoryOrder::RELAXED); data.last_call_started_cycle.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED); -} - -void CallCountingHelper::RecordCallFailed() { +} + +void CallCountingHelper::RecordCallFailed() { per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()] .calls_failed.FetchAdd(1, MemoryOrder::RELAXED); -} - -void CallCountingHelper::RecordCallSucceeded() { +} + +void CallCountingHelper::RecordCallSucceeded() { per_cpu_counter_data_storage_[ExecCtx::Get()->starting_cpu()] .calls_succeeded.FetchAdd(1, MemoryOrder::RELAXED); -} - -void CallCountingHelper::CollectData(CounterData* out) { - for (size_t core = 0; core < num_cores_; ++core) { +} + +void CallCountingHelper::CollectData(CounterData* out) { + for (size_t core = 0; core < num_cores_; ++core) { AtomicCounterData& data = per_cpu_counter_data_storage_[core]; out->calls_started += data.calls_started.Load(MemoryOrder::RELAXED); @@ -112,32 +112,32 @@ void CallCountingHelper::CollectData(CounterData* out) { MemoryOrder::RELAXED); if (last_call > out->last_call_started_cycle) { out->last_call_started_cycle = last_call; - } - } -} - + } + } +} + void CallCountingHelper::PopulateCallCounts(Json::Object* object) { - CounterData data; - CollectData(&data); - if (data.calls_started != 0) { + CounterData data; + CollectData(&data); + if (data.calls_started != 0) { (*object)["callsStarted"] = ToString(data.calls_started); gpr_timespec ts = gpr_convert_clock_type( gpr_cycle_counter_to_time(data.last_call_started_cycle), GPR_CLOCK_REALTIME); (*object)["lastCallStartedTimestamp"] = gpr_format_timespec(ts); - } - if (data.calls_succeeded != 0) { + } + if (data.calls_succeeded != 0) { (*object)["callsSucceeded"] = ToString(data.calls_succeeded); - } - if (data.calls_failed) { + } + if (data.calls_failed) { (*object)["callsFailed"] = ToString(data.calls_failed); - } -} - + } +} + // // ChannelNode // - + ChannelNode::ChannelNode(TString target, size_t channel_tracer_max_nodes, bool is_internal_channel) : BaseNode(is_internal_channel ? EntityType::kInternalChannel @@ -145,7 +145,7 @@ ChannelNode::ChannelNode(TString target, size_t channel_tracer_max_nodes, target), target_(std::move(target)), trace_(channel_tracer_max_nodes) {} - + const char* ChannelNode::GetChannelConnectivityStateChangeString( grpc_connectivity_state state) { switch (state) { @@ -181,7 +181,7 @@ Json ChannelNode::RenderJson() { Json trace_json = trace_.RenderJson(); if (trace_json.type() != Json::Type::JSON_NULL) { data["trace"] = std::move(trace_json); - } + } // Ask CallCountingHelper to populate call count data. call_counter_.PopulateCallCounts(&data); // Construct outer object. @@ -193,11 +193,11 @@ Json ChannelNode::RenderJson() { {"data", std::move(data)}, }; // Template method. Child classes may override this to add their specific - // functionality. + // functionality. PopulateChildRefs(&json); return json; -} - +} + void ChannelNode::PopulateChildRefs(Json::Object* json) { MutexLock lock(&child_mu_); if (!child_subchannels_.empty()) { @@ -218,14 +218,14 @@ void ChannelNode::PopulateChildRefs(Json::Object* json) { } (*json)["channelRef"] = std::move(array); } -} - +} + void ChannelNode::SetConnectivityState(grpc_connectivity_state state) { // Store with low-order bit set to indicate that the field is set. int state_field = (state << 1) + 1; connectivity_state_.Store(state_field, MemoryOrder::RELAXED); } - + void ChannelNode::AddChildChannel(intptr_t child_uuid) { MutexLock lock(&child_mu_); child_channels_.insert(child_uuid); @@ -253,8 +253,8 @@ void ChannelNode::RemoveChildSubchannel(intptr_t child_uuid) { ServerNode::ServerNode(size_t channel_tracer_max_nodes) : BaseNode(EntityType::kServer, ""), trace_(channel_tracer_max_nodes) {} -ServerNode::~ServerNode() {} - +ServerNode::~ServerNode() {} + void ServerNode::AddChildSocket(RefCountedPtr<SocketNode> node) { MutexLock lock(&child_mu_); child_sockets_.insert(std::make_pair(node->uuid(), std::move(node))); @@ -280,7 +280,7 @@ TString ServerNode::RenderServerSockets(intptr_t start_socket_id, GPR_ASSERT(start_socket_id >= 0); GPR_ASSERT(max_results >= 0); // If user does not set max_results, we choose 500. - size_t pagination_limit = max_results == 0 ? 500 : max_results; + size_t pagination_limit = max_results == 0 ? 500 : max_results; Json::Object object; { MutexLock lock(&child_mu_); @@ -294,21 +294,21 @@ TString ServerNode::RenderServerSockets(intptr_t start_socket_id, {"socketId", ToString(it->first)}, {"name", it->second->name()}, }); - } + } object["socketRef"] = std::move(array); if (it == child_sockets_.end()) object["end"] = true; - } + } Json json = std::move(object); return json.Dump(); -} - +} + Json ServerNode::RenderJson() { Json::Object data; // Fill in the channel trace if applicable. Json trace_json = trace_.RenderJson(); if (trace_json.type() != Json::Type::JSON_NULL) { data["trace"] = std::move(trace_json); - } + } // Ask CallCountingHelper to populate call count data. call_counter_.PopulateCallCounts(&data); // Construct top-level object. @@ -331,11 +331,11 @@ Json ServerNode::RenderJson() { }); } object["listenSocket"] = std::move(array); - } - } + } + } return object; -} - +} + // // SocketNode // @@ -344,73 +344,73 @@ namespace { void PopulateSocketAddressJson(Json::Object* json, const char* name, const char* addr_str) { - if (addr_str == nullptr) return; + if (addr_str == nullptr) return; Json::Object data; - grpc_uri* uri = grpc_uri_parse(addr_str, true); - if ((uri != nullptr) && ((strcmp(uri->scheme, "ipv4") == 0) || - (strcmp(uri->scheme, "ipv6") == 0))) { - const char* host_port = uri->path; - if (*host_port == '/') ++host_port; + grpc_uri* uri = grpc_uri_parse(addr_str, true); + if ((uri != nullptr) && ((strcmp(uri->scheme, "ipv4") == 0) || + (strcmp(uri->scheme, "ipv6") == 0))) { + const char* host_port = uri->path; + if (*host_port == '/') ++host_port; TString host; TString port; GPR_ASSERT(SplitHostPort(host_port, &host, &port)); - int port_num = -1; + int port_num = -1; if (!port.empty()) { port_num = atoi(port.data()); - } + } char* b64_host = grpc_base64_encode(host.data(), host.size(), false, false); data["tcpip_address"] = Json::Object{ {"port", port_num}, {"ip_address", b64_host}, }; gpr_free(b64_host); - } else if (uri != nullptr && strcmp(uri->scheme, "unix") == 0) { + } else if (uri != nullptr && strcmp(uri->scheme, "unix") == 0) { data["uds_address"] = Json::Object{ {"filename", uri->path}, }; - } else { + } else { data["other_address"] = Json::Object{ {"name", addr_str}, }; - } - grpc_uri_destroy(uri); + } + grpc_uri_destroy(uri); (*json)[name] = std::move(data); -} - +} + } // namespace SocketNode::SocketNode(TString local, TString remote, TString name) : BaseNode(EntityType::kSocket, std::move(name)), - local_(std::move(local)), - remote_(std::move(remote)) {} - -void SocketNode::RecordStreamStartedFromLocal() { + local_(std::move(local)), + remote_(std::move(remote)) {} + +void SocketNode::RecordStreamStartedFromLocal() { streams_started_.FetchAdd(1, MemoryOrder::RELAXED); last_local_stream_created_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED); -} - -void SocketNode::RecordStreamStartedFromRemote() { +} + +void SocketNode::RecordStreamStartedFromRemote() { streams_started_.FetchAdd(1, MemoryOrder::RELAXED); last_remote_stream_created_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED); -} - -void SocketNode::RecordMessagesSent(uint32_t num_sent) { +} + +void SocketNode::RecordMessagesSent(uint32_t num_sent) { messages_sent_.FetchAdd(num_sent, MemoryOrder::RELAXED); last_message_sent_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED); -} - -void SocketNode::RecordMessageReceived() { +} + +void SocketNode::RecordMessageReceived() { messages_received_.FetchAdd(1, MemoryOrder::RELAXED); last_message_received_cycle_.Store(gpr_get_cycle_counter(), MemoryOrder::RELAXED); -} - +} + Json SocketNode::RenderJson() { // Create and fill the data child. Json::Object data; - gpr_timespec ts; + gpr_timespec ts; int64_t streams_started = streams_started_.Load(MemoryOrder::RELAXED); if (streams_started != 0) { data["streamsStarted"] = ToString(streams_started); @@ -421,7 +421,7 @@ Json SocketNode::RenderJson() { gpr_cycle_counter_to_time(last_local_stream_created_cycle), GPR_CLOCK_REALTIME); data["lastLocalStreamCreatedTimestamp"] = gpr_format_timespec(ts); - } + } gpr_cycle_counter last_remote_stream_created_cycle = last_remote_stream_created_cycle_.Load(MemoryOrder::RELAXED); if (last_remote_stream_created_cycle != 0) { @@ -429,16 +429,16 @@ Json SocketNode::RenderJson() { gpr_cycle_counter_to_time(last_remote_stream_created_cycle), GPR_CLOCK_REALTIME); data["lastRemoteStreamCreatedTimestamp"] = gpr_format_timespec(ts); - } - } + } + } int64_t streams_succeeded = streams_succeeded_.Load(MemoryOrder::RELAXED); if (streams_succeeded != 0) { data["streamsSucceeded"] = ToString(streams_succeeded); - } + } int64_t streams_failed = streams_failed_.Load(MemoryOrder::RELAXED); if (streams_failed != 0) { data["streamsFailed"] = ToString(streams_failed); - } + } int64_t messages_sent = messages_sent_.Load(MemoryOrder::RELAXED); if (messages_sent != 0) { data["messagesSent"] = ToString(messages_sent); @@ -447,7 +447,7 @@ Json SocketNode::RenderJson() { last_message_sent_cycle_.Load(MemoryOrder::RELAXED)), GPR_CLOCK_REALTIME); data["lastMessageSentTimestamp"] = gpr_format_timespec(ts); - } + } int64_t messages_received = messages_received_.Load(MemoryOrder::RELAXED); if (messages_received != 0) { data["messagesReceived"] = ToString(messages_received); @@ -456,11 +456,11 @@ Json SocketNode::RenderJson() { last_message_received_cycle_.Load(MemoryOrder::RELAXED)), GPR_CLOCK_REALTIME); data["lastMessageReceivedTimestamp"] = gpr_format_timespec(ts); - } + } int64_t keepalives_sent = keepalives_sent_.Load(MemoryOrder::RELAXED); if (keepalives_sent != 0) { data["keepAlivesSent"] = ToString(keepalives_sent); - } + } // Create and fill the parent object. Json::Object object = { {"ref", @@ -473,12 +473,12 @@ Json SocketNode::RenderJson() { PopulateSocketAddressJson(&object, "remote", remote_.c_str()); PopulateSocketAddressJson(&object, "local", local_.c_str()); return object; -} - +} + // // ListenSocketNode // - + ListenSocketNode::ListenSocketNode(TString local_addr, TString name) : BaseNode(EntityType::kSocket, std::move(name)), local_addr_(std::move(local_addr)) {} @@ -493,7 +493,7 @@ Json ListenSocketNode::RenderJson() { }; PopulateSocketAddressJson(&object, "local", local_addr_.c_str()); return object; -} - -} // namespace channelz -} // namespace grpc_core +} + +} // namespace channelz +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz.h b/contrib/libs/grpc/src/core/lib/channel/channelz.h index 596770ccdc..38efee7d43 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channelz.h +++ b/contrib/libs/grpc/src/core/lib/channel/channelz.h @@ -1,136 +1,136 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_CHANNEL_CHANNELZ_H -#define GRPC_CORE_LIB_CHANNEL_CHANNELZ_H - -#include <grpc/impl/codegen/port_platform.h> - -#include <grpc/grpc.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_CHANNEL_CHANNELZ_H +#define GRPC_CORE_LIB_CHANNEL_CHANNELZ_H + +#include <grpc/impl/codegen/port_platform.h> + +#include <grpc/grpc.h> + #include <set> #include <util/generic/string.h> #include "y_absl/container/inlined_vector.h" -#include "src/core/lib/channel/channel_trace.h" +#include "src/core/lib/channel/channel_trace.h" #include "src/core/lib/gpr/time_precise.h" #include "src/core/lib/gprpp/atomic.h" -#include "src/core/lib/gprpp/manual_constructor.h" +#include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/gprpp/map.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/iomgr/error.h" -#include "src/core/lib/iomgr/exec_ctx.h" -#include "src/core/lib/json/json.h" - +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/json/json.h" + // Channel arg key for channelz node. #define GRPC_ARG_CHANNELZ_CHANNEL_NODE "grpc.channelz_channel_node" - + // Channel arg key for indicating an internal channel. #define GRPC_ARG_CHANNELZ_IS_INTERNAL_CHANNEL \ "grpc.channelz_is_internal_channel" - -/** This is the default value for whether or not to enable channelz. If - * GRPC_ARG_ENABLE_CHANNELZ is set, it will override this default value. */ -#define GRPC_ENABLE_CHANNELZ_DEFAULT true - -/** This is the default value for the maximum amount of memory used by trace - * events per channel trace node. If - * GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE is set, it will override - * this default value. */ -#define GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT 1024 * 4 - -namespace grpc_core { - -namespace channelz { - -class SocketNode; + +/** This is the default value for whether or not to enable channelz. If + * GRPC_ARG_ENABLE_CHANNELZ is set, it will override this default value. */ +#define GRPC_ENABLE_CHANNELZ_DEFAULT true + +/** This is the default value for the maximum amount of memory used by trace + * events per channel trace node. If + * GRPC_ARG_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE is set, it will override + * this default value. */ +#define GRPC_MAX_CHANNEL_TRACE_EVENT_MEMORY_PER_NODE_DEFAULT 1024 * 4 + +namespace grpc_core { + +namespace channelz { + +class SocketNode; class ListenSocketNode; - -namespace testing { -class CallCountingHelperPeer; -class ChannelNodePeer; -} // namespace testing - -// base class for all channelz entities -class BaseNode : public RefCounted<BaseNode> { - public: - // There are only four high level channelz entities. However, to support - // GetTopChannelsRequest, we split the Channel entity into two different - // types. All children of BaseNode must be one of these types. - enum class EntityType { - kTopLevelChannel, - kInternalChannel, - kSubchannel, - kServer, - kSocket, - }; - + +namespace testing { +class CallCountingHelperPeer; +class ChannelNodePeer; +} // namespace testing + +// base class for all channelz entities +class BaseNode : public RefCounted<BaseNode> { + public: + // There are only four high level channelz entities. However, to support + // GetTopChannelsRequest, we split the Channel entity into two different + // types. All children of BaseNode must be one of these types. + enum class EntityType { + kTopLevelChannel, + kInternalChannel, + kSubchannel, + kServer, + kSocket, + }; + protected: BaseNode(EntityType type, TString name); public: - virtual ~BaseNode(); - - // All children must implement this function. + virtual ~BaseNode(); + + // All children must implement this function. virtual Json RenderJson() = 0; - - // Renders the json and returns allocated string that must be freed by the - // caller. + + // Renders the json and returns allocated string that must be freed by the + // caller. TString RenderJsonString(); - - EntityType type() const { return type_; } - intptr_t uuid() const { return uuid_; } + + EntityType type() const { return type_; } + intptr_t uuid() const { return uuid_; } const TString& name() const { return name_; } - - private: - // to allow the ChannelzRegistry to set uuid_ under its lock. - friend class ChannelzRegistry; - const EntityType type_; - intptr_t uuid_; + + private: + // to allow the ChannelzRegistry to set uuid_ under its lock. + friend class ChannelzRegistry; + const EntityType type_; + intptr_t uuid_; TString name_; -}; - -// This class is a helper class for channelz entities that deal with Channels, -// Subchannels, and Servers, since those have similar proto definitions. -// This class has the ability to: -// - track calls_{started,succeeded,failed} -// - track last_call_started_timestamp -// - perform rendering of the above items -class CallCountingHelper { - public: - CallCountingHelper(); - - void RecordCallStarted(); - void RecordCallFailed(); - void RecordCallSucceeded(); - - // Common rendering of the call count data and last_call_started_timestamp. +}; + +// This class is a helper class for channelz entities that deal with Channels, +// Subchannels, and Servers, since those have similar proto definitions. +// This class has the ability to: +// - track calls_{started,succeeded,failed} +// - track last_call_started_timestamp +// - perform rendering of the above items +class CallCountingHelper { + public: + CallCountingHelper(); + + void RecordCallStarted(); + void RecordCallFailed(); + void RecordCallSucceeded(); + + // Common rendering of the call count data and last_call_started_timestamp. void PopulateCallCounts(Json::Object* json); - - private: - // testing peer friend. - friend class testing::CallCountingHelperPeer; - + + private: + // testing peer friend. + friend class testing::CallCountingHelperPeer; + // TODO(soheil): add a proper PerCPU helper and use it here. - struct AtomicCounterData { + struct AtomicCounterData { // Define the ctors so that we can use this structure in InlinedVector. AtomicCounterData() = default; AtomicCounterData(const AtomicCounterData& that) @@ -139,7 +139,7 @@ class CallCountingHelper { calls_failed(that.calls_failed.Load(MemoryOrder::RELAXED)), last_call_started_cycle( that.last_call_started_cycle.Load(MemoryOrder::RELAXED)) {} - + Atomic<int64_t> calls_started{0}; Atomic<int64_t> calls_succeeded{0}; Atomic<int64_t> calls_failed{0}; @@ -155,47 +155,47 @@ class CallCountingHelper { // abseil inlined_vector. // GPR_ALIGN_STRUCT(GPR_CACHELINE_SIZE); - struct CounterData { + struct CounterData { int64_t calls_started = 0; int64_t calls_succeeded = 0; int64_t calls_failed = 0; gpr_cycle_counter last_call_started_cycle = 0; - }; - - // collects the sharded data into one CounterData struct. - void CollectData(CounterData* out); - + }; + + // collects the sharded data into one CounterData struct. + void CollectData(CounterData* out); + // Really zero-sized, but 0-sized arrays are illegal on MSVC. y_absl::InlinedVector<AtomicCounterData, 1> per_cpu_counter_data_storage_; - size_t num_cores_ = 0; -}; - -// Handles channelz bookkeeping for channels -class ChannelNode : public BaseNode { - public: + size_t num_cores_ = 0; +}; + +// Handles channelz bookkeeping for channels +class ChannelNode : public BaseNode { + public: ChannelNode(TString target, size_t channel_tracer_max_nodes, bool is_internal_channel); - + // Returns the string description of the given connectivity state. static const char* GetChannelConnectivityStateChangeString( grpc_connectivity_state state); - + Json RenderJson() override; - - // proxy methods to composed classes. + + // proxy methods to composed classes. void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) { - trace_.AddTraceEvent(severity, data); - } - void AddTraceEventWithReference(ChannelTrace::Severity severity, + trace_.AddTraceEvent(severity, data); + } + void AddTraceEventWithReference(ChannelTrace::Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_channel) { - trace_.AddTraceEventWithReference(severity, data, - std::move(referenced_channel)); - } - void RecordCallStarted() { call_counter_.RecordCallStarted(); } - void RecordCallFailed() { call_counter_.RecordCallFailed(); } - void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); } - + RefCountedPtr<BaseNode> referenced_channel) { + trace_.AddTraceEventWithReference(severity, data, + std::move(referenced_channel)); + } + void RecordCallStarted() { call_counter_.RecordCallStarted(); } + void RecordCallFailed() { call_counter_.RecordCallFailed(); } + void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); } + void SetConnectivityState(grpc_connectivity_state state); // TODO(roth): take in a RefCountedPtr to the child channel so we can retrieve @@ -208,15 +208,15 @@ class ChannelNode : public BaseNode { void AddChildSubchannel(intptr_t child_uuid); void RemoveChildSubchannel(intptr_t child_uuid); - private: + private: // Allows the channel trace test to access trace_. friend class testing::ChannelNodePeer; void PopulateChildRefs(Json::Object* json); TString target_; - CallCountingHelper call_counter_; - ChannelTrace trace_; + CallCountingHelper call_counter_; + ChannelTrace trace_; // Least significant bit indicates whether the value is set. Remaining // bits are a grpc_connectivity_state value. @@ -225,20 +225,20 @@ class ChannelNode : public BaseNode { Mutex child_mu_; // Guards sets below. std::set<intptr_t> child_channels_; std::set<intptr_t> child_subchannels_; -}; - -// Handles channelz bookkeeping for servers -class ServerNode : public BaseNode { - public: +}; + +// Handles channelz bookkeeping for servers +class ServerNode : public BaseNode { + public: explicit ServerNode(size_t channel_tracer_max_nodes); - ~ServerNode() override; - + ~ServerNode() override; + Json RenderJson() override; - + TString RenderServerSockets(intptr_t start_socket_id, intptr_t max_results); - + void AddChildSocket(RefCountedPtr<SocketNode> node); void RemoveChildSocket(intptr_t child_uuid); @@ -247,53 +247,53 @@ class ServerNode : public BaseNode { void RemoveChildListenSocket(intptr_t child_uuid); - // proxy methods to composed classes. + // proxy methods to composed classes. void AddTraceEvent(ChannelTrace::Severity severity, const grpc_slice& data) { - trace_.AddTraceEvent(severity, data); - } - void AddTraceEventWithReference(ChannelTrace::Severity severity, + trace_.AddTraceEvent(severity, data); + } + void AddTraceEventWithReference(ChannelTrace::Severity severity, const grpc_slice& data, - RefCountedPtr<BaseNode> referenced_channel) { - trace_.AddTraceEventWithReference(severity, data, - std::move(referenced_channel)); - } - void RecordCallStarted() { call_counter_.RecordCallStarted(); } - void RecordCallFailed() { call_counter_.RecordCallFailed(); } - void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); } - - private: - CallCountingHelper call_counter_; - ChannelTrace trace_; + RefCountedPtr<BaseNode> referenced_channel) { + trace_.AddTraceEventWithReference(severity, data, + std::move(referenced_channel)); + } + void RecordCallStarted() { call_counter_.RecordCallStarted(); } + void RecordCallFailed() { call_counter_.RecordCallFailed(); } + void RecordCallSucceeded() { call_counter_.RecordCallSucceeded(); } + + private: + CallCountingHelper call_counter_; + ChannelTrace trace_; Mutex child_mu_; // Guards child maps below. std::map<intptr_t, RefCountedPtr<SocketNode>> child_sockets_; std::map<intptr_t, RefCountedPtr<ListenSocketNode>> child_listen_sockets_; -}; - -// Handles channelz bookkeeping for sockets -class SocketNode : public BaseNode { - public: +}; + +// Handles channelz bookkeeping for sockets +class SocketNode : public BaseNode { + public: SocketNode(TString local, TString remote, TString name); - ~SocketNode() override {} - + ~SocketNode() override {} + Json RenderJson() override; - - void RecordStreamStartedFromLocal(); - void RecordStreamStartedFromRemote(); - void RecordStreamSucceeded() { + + void RecordStreamStartedFromLocal(); + void RecordStreamStartedFromRemote(); + void RecordStreamSucceeded() { streams_succeeded_.FetchAdd(1, MemoryOrder::RELAXED); - } - void RecordStreamFailed() { + } + void RecordStreamFailed() { streams_failed_.FetchAdd(1, MemoryOrder::RELAXED); - } - void RecordMessagesSent(uint32_t num_sent); - void RecordMessageReceived(); - void RecordKeepaliveSent() { + } + void RecordMessagesSent(uint32_t num_sent); + void RecordMessageReceived(); + void RecordKeepaliveSent() { keepalives_sent_.FetchAdd(1, MemoryOrder::RELAXED); - } - + } + const TString& remote() { return remote_; } - - private: + + private: Atomic<int64_t> streams_started_{0}; Atomic<int64_t> streams_succeeded_{0}; Atomic<int64_t> streams_failed_{0}; @@ -306,21 +306,21 @@ class SocketNode : public BaseNode { Atomic<gpr_cycle_counter> last_message_received_cycle_{0}; TString local_; TString remote_; -}; - -// Handles channelz bookkeeping for listen sockets -class ListenSocketNode : public BaseNode { - public: +}; + +// Handles channelz bookkeeping for listen sockets +class ListenSocketNode : public BaseNode { + public: ListenSocketNode(TString local_addr, TString name); - ~ListenSocketNode() override {} - + ~ListenSocketNode() override {} + Json RenderJson() override; - - private: + + private: TString local_addr_; -}; - -} // namespace channelz -} // namespace grpc_core - -#endif /* GRPC_CORE_LIB_CHANNEL_CHANNELZ_H */ +}; + +} // namespace channelz +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_CHANNEL_CHANNELZ_H */ diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc index 5a6e28ad78..78f2b01287 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc +++ b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.cc @@ -1,86 +1,86 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/impl/codegen/port_platform.h> - +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/impl/codegen/port_platform.h> + #include <algorithm> #include <cstring> #include "y_absl/container/inlined_vector.h" -#include "src/core/lib/channel/channel_trace.h" -#include "src/core/lib/channel/channelz.h" -#include "src/core/lib/channel/channelz_registry.h" -#include "src/core/lib/gpr/useful.h" -#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/channel/channel_trace.h" +#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channelz_registry.h" +#include "src/core/lib/gpr/useful.h" +#include "src/core/lib/gprpp/memory.h" #include "src/core/lib/gprpp/sync.h" - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> #include <grpc/support/string_util.h> -#include <grpc/support/sync.h> - -namespace grpc_core { -namespace channelz { -namespace { - -// singleton instance of the registry. -ChannelzRegistry* g_channelz_registry = nullptr; - -const int kPaginationLimit = 100; - -} // anonymous namespace - +#include <grpc/support/sync.h> + +namespace grpc_core { +namespace channelz { +namespace { + +// singleton instance of the registry. +ChannelzRegistry* g_channelz_registry = nullptr; + +const int kPaginationLimit = 100; + +} // anonymous namespace + void ChannelzRegistry::Init() { g_channelz_registry = new ChannelzRegistry(); } - + void ChannelzRegistry::Shutdown() { delete g_channelz_registry; } - -ChannelzRegistry* ChannelzRegistry::Default() { - GPR_DEBUG_ASSERT(g_channelz_registry != nullptr); - return g_channelz_registry; -} - -void ChannelzRegistry::InternalRegister(BaseNode* node) { - MutexLock lock(&mu_); - node->uuid_ = ++uuid_generator_; + +ChannelzRegistry* ChannelzRegistry::Default() { + GPR_DEBUG_ASSERT(g_channelz_registry != nullptr); + return g_channelz_registry; +} + +void ChannelzRegistry::InternalRegister(BaseNode* node) { + MutexLock lock(&mu_); + node->uuid_ = ++uuid_generator_; node_map_[node->uuid_] = node; -} - -void ChannelzRegistry::InternalUnregister(intptr_t uuid) { - GPR_ASSERT(uuid >= 1); - MutexLock lock(&mu_); - GPR_ASSERT(uuid <= uuid_generator_); +} + +void ChannelzRegistry::InternalUnregister(intptr_t uuid) { + GPR_ASSERT(uuid >= 1); + MutexLock lock(&mu_); + GPR_ASSERT(uuid <= uuid_generator_); node_map_.erase(uuid); -} - +} + RefCountedPtr<BaseNode> ChannelzRegistry::InternalGet(intptr_t uuid) { - MutexLock lock(&mu_); - if (uuid < 1 || uuid > uuid_generator_) { - return nullptr; - } + MutexLock lock(&mu_); + if (uuid < 1 || uuid > uuid_generator_) { + return nullptr; + } auto it = node_map_.find(uuid); if (it == node_map_.end()) return nullptr; // Found node. Return only if its refcount is not zero (i.e., when we // know that there is no other thread about to destroy it). BaseNode* node = it->second; return node->RefIfNonZero(); -} - +} + TString ChannelzRegistry::InternalGetTopChannels( intptr_t start_channel_id) { y_absl::InlinedVector<RefCountedPtr<BaseNode>, 10> top_level_channels; @@ -104,23 +104,23 @@ TString ChannelzRegistry::InternalGetTopChannels( break; } top_level_channels.emplace_back(std::move(node_ref)); - } - } - } + } + } + } Json::Object object; - if (!top_level_channels.empty()) { + if (!top_level_channels.empty()) { // Create list of channels. Json::Array array; - for (size_t i = 0; i < top_level_channels.size(); ++i) { + for (size_t i = 0; i < top_level_channels.size(); ++i) { array.emplace_back(top_level_channels[i]->RenderJson()); - } + } object["channel"] = std::move(array); - } + } if (node_after_pagination_limit == nullptr) object["end"] = true; Json json(std::move(object)); return json.Dump(); -} - +} + TString ChannelzRegistry::InternalGetServers(intptr_t start_server_id) { y_absl::InlinedVector<RefCountedPtr<BaseNode>, 10> servers; RefCountedPtr<BaseNode> node_after_pagination_limit; @@ -143,24 +143,24 @@ TString ChannelzRegistry::InternalGetServers(intptr_t start_server_id) { break; } servers.emplace_back(std::move(node_ref)); - } - } - } + } + } + } Json::Object object; - if (!servers.empty()) { + if (!servers.empty()) { // Create list of servers. Json::Array array; - for (size_t i = 0; i < servers.size(); ++i) { + for (size_t i = 0; i < servers.size(); ++i) { array.emplace_back(servers[i]->RenderJson()); - } + } object["server"] = std::move(array); - } + } if (node_after_pagination_limit == nullptr) object["end"] = true; Json json(std::move(object)); return json.Dump(); -} - -void ChannelzRegistry::InternalLogAllEntities() { +} + +void ChannelzRegistry::InternalLogAllEntities() { y_absl::InlinedVector<RefCountedPtr<BaseNode>, 10> nodes; { MutexLock lock(&mu_); @@ -169,102 +169,102 @@ void ChannelzRegistry::InternalLogAllEntities() { if (node != nullptr) { nodes.emplace_back(std::move(node)); } - } - } + } + } for (size_t i = 0; i < nodes.size(); ++i) { TString json = nodes[i]->RenderJsonString(); gpr_log(GPR_INFO, "%s", json.c_str()); } -} - -} // namespace channelz -} // namespace grpc_core - -char* grpc_channelz_get_top_channels(intptr_t start_channel_id) { +} + +} // namespace channelz +} // namespace grpc_core + +char* grpc_channelz_get_top_channels(intptr_t start_channel_id) { return gpr_strdup( grpc_core::channelz::ChannelzRegistry::GetTopChannels(start_channel_id) .c_str()); -} - -char* grpc_channelz_get_servers(intptr_t start_server_id) { +} + +char* grpc_channelz_get_servers(intptr_t start_server_id) { return gpr_strdup( grpc_core::channelz::ChannelzRegistry::GetServers(start_server_id) .c_str()); -} - -char* grpc_channelz_get_server(intptr_t server_id) { +} + +char* grpc_channelz_get_server(intptr_t server_id) { grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> server_node = - grpc_core::channelz::ChannelzRegistry::Get(server_id); - if (server_node == nullptr || - server_node->type() != - grpc_core::channelz::BaseNode::EntityType::kServer) { - return nullptr; - } + grpc_core::channelz::ChannelzRegistry::Get(server_id); + if (server_node == nullptr || + server_node->type() != + grpc_core::channelz::BaseNode::EntityType::kServer) { + return nullptr; + } grpc_core::Json json = grpc_core::Json::Object{ {"server", server_node->RenderJson()}, }; return gpr_strdup(json.Dump().c_str()); -} - -char* grpc_channelz_get_server_sockets(intptr_t server_id, - intptr_t start_socket_id, - intptr_t max_results) { +} + +char* grpc_channelz_get_server_sockets(intptr_t server_id, + intptr_t start_socket_id, + intptr_t max_results) { // Validate inputs before handing them of to the renderer. grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> base_node = - grpc_core::channelz::ChannelzRegistry::Get(server_id); - if (base_node == nullptr || + grpc_core::channelz::ChannelzRegistry::Get(server_id); + if (base_node == nullptr || base_node->type() != grpc_core::channelz::BaseNode::EntityType::kServer || start_socket_id < 0 || max_results < 0) { - return nullptr; - } - // This cast is ok since we have just checked to make sure base_node is + return nullptr; + } + // This cast is ok since we have just checked to make sure base_node is // actually a server node. - grpc_core::channelz::ServerNode* server_node = + grpc_core::channelz::ServerNode* server_node = static_cast<grpc_core::channelz::ServerNode*>(base_node.get()); return gpr_strdup( server_node->RenderServerSockets(start_socket_id, max_results).c_str()); -} - -char* grpc_channelz_get_channel(intptr_t channel_id) { +} + +char* grpc_channelz_get_channel(intptr_t channel_id) { grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> channel_node = - grpc_core::channelz::ChannelzRegistry::Get(channel_id); - if (channel_node == nullptr || - (channel_node->type() != - grpc_core::channelz::BaseNode::EntityType::kTopLevelChannel && - channel_node->type() != - grpc_core::channelz::BaseNode::EntityType::kInternalChannel)) { - return nullptr; - } + grpc_core::channelz::ChannelzRegistry::Get(channel_id); + if (channel_node == nullptr || + (channel_node->type() != + grpc_core::channelz::BaseNode::EntityType::kTopLevelChannel && + channel_node->type() != + grpc_core::channelz::BaseNode::EntityType::kInternalChannel)) { + return nullptr; + } grpc_core::Json json = grpc_core::Json::Object{ {"channel", channel_node->RenderJson()}, }; return gpr_strdup(json.Dump().c_str()); -} - -char* grpc_channelz_get_subchannel(intptr_t subchannel_id) { +} + +char* grpc_channelz_get_subchannel(intptr_t subchannel_id) { grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> subchannel_node = - grpc_core::channelz::ChannelzRegistry::Get(subchannel_id); - if (subchannel_node == nullptr || - subchannel_node->type() != - grpc_core::channelz::BaseNode::EntityType::kSubchannel) { - return nullptr; - } + grpc_core::channelz::ChannelzRegistry::Get(subchannel_id); + if (subchannel_node == nullptr || + subchannel_node->type() != + grpc_core::channelz::BaseNode::EntityType::kSubchannel) { + return nullptr; + } grpc_core::Json json = grpc_core::Json::Object{ {"subchannel", subchannel_node->RenderJson()}, }; return gpr_strdup(json.Dump().c_str()); -} - -char* grpc_channelz_get_socket(intptr_t socket_id) { +} + +char* grpc_channelz_get_socket(intptr_t socket_id) { grpc_core::RefCountedPtr<grpc_core::channelz::BaseNode> socket_node = - grpc_core::channelz::ChannelzRegistry::Get(socket_id); - if (socket_node == nullptr || - socket_node->type() != - grpc_core::channelz::BaseNode::EntityType::kSocket) { - return nullptr; - } + grpc_core::channelz::ChannelzRegistry::Get(socket_id); + if (socket_node == nullptr || + socket_node->type() != + grpc_core::channelz::BaseNode::EntityType::kSocket) { + return nullptr; + } grpc_core::Json json = grpc_core::Json::Object{ {"socket", socket_node->RenderJson()}, }; return gpr_strdup(json.Dump().c_str()); -} +} diff --git a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h index 73a5e20fbd..603ce86c4f 100644 --- a/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h +++ b/contrib/libs/grpc/src/core/lib/channel/channelz_registry.h @@ -1,100 +1,100 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_CHANNEL_CHANNELZ_REGISTRY_H -#define GRPC_CORE_LIB_CHANNEL_CHANNELZ_REGISTRY_H - -#include <grpc/impl/codegen/port_platform.h> - +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_CHANNEL_CHANNELZ_REGISTRY_H +#define GRPC_CORE_LIB_CHANNEL_CHANNELZ_REGISTRY_H + +#include <grpc/impl/codegen/port_platform.h> + #include <stdint.h> #include <map> #include <util/generic/string.h> -#include "src/core/lib/channel/channel_trace.h" -#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channel_trace.h" +#include "src/core/lib/channel/channelz.h" #include "src/core/lib/gprpp/map.h" #include "src/core/lib/gprpp/sync.h" - -namespace grpc_core { -namespace channelz { - -// singleton registry object to track all objects that are needed to support -// channelz bookkeeping. All objects share globally distributed uuids. -class ChannelzRegistry { - public: - // To be called in grpc_init() - static void Init(); - - // To be called in grpc_shutdown(); - static void Shutdown(); - - static void Register(BaseNode* node) { - return Default()->InternalRegister(node); - } - static void Unregister(intptr_t uuid) { Default()->InternalUnregister(uuid); } + +namespace grpc_core { +namespace channelz { + +// singleton registry object to track all objects that are needed to support +// channelz bookkeeping. All objects share globally distributed uuids. +class ChannelzRegistry { + public: + // To be called in grpc_init() + static void Init(); + + // To be called in grpc_shutdown(); + static void Shutdown(); + + static void Register(BaseNode* node) { + return Default()->InternalRegister(node); + } + static void Unregister(intptr_t uuid) { Default()->InternalUnregister(uuid); } static RefCountedPtr<BaseNode> Get(intptr_t uuid) { return Default()->InternalGet(uuid); } - - // Returns the allocated JSON string that represents the proto - // GetTopChannelsResponse as per channelz.proto. + + // Returns the allocated JSON string that represents the proto + // GetTopChannelsResponse as per channelz.proto. static TString GetTopChannels(intptr_t start_channel_id) { - return Default()->InternalGetTopChannels(start_channel_id); - } - - // Returns the allocated JSON string that represents the proto - // GetServersResponse as per channelz.proto. + return Default()->InternalGetTopChannels(start_channel_id); + } + + // Returns the allocated JSON string that represents the proto + // GetServersResponse as per channelz.proto. static TString GetServers(intptr_t start_server_id) { - return Default()->InternalGetServers(start_server_id); - } - - // Test only helper function to dump the JSON representation to std out. - // This can aid in debugging channelz code. - static void LogAllEntities() { Default()->InternalLogAllEntities(); } - - private: - // Returned the singleton instance of ChannelzRegistry; - static ChannelzRegistry* Default(); - - // globally registers an Entry. Returns its unique uuid - void InternalRegister(BaseNode* node); - - // globally unregisters the object that is associated to uuid. Also does - // sanity check that an object doesn't try to unregister the wrong type. - void InternalUnregister(intptr_t uuid); - - // if object with uuid has previously been registered as the correct type, - // returns the void* associated with that uuid. Else returns nullptr. + return Default()->InternalGetServers(start_server_id); + } + + // Test only helper function to dump the JSON representation to std out. + // This can aid in debugging channelz code. + static void LogAllEntities() { Default()->InternalLogAllEntities(); } + + private: + // Returned the singleton instance of ChannelzRegistry; + static ChannelzRegistry* Default(); + + // globally registers an Entry. Returns its unique uuid + void InternalRegister(BaseNode* node); + + // globally unregisters the object that is associated to uuid. Also does + // sanity check that an object doesn't try to unregister the wrong type. + void InternalUnregister(intptr_t uuid); + + // if object with uuid has previously been registered as the correct type, + // returns the void* associated with that uuid. Else returns nullptr. RefCountedPtr<BaseNode> InternalGet(intptr_t uuid); - + TString InternalGetTopChannels(intptr_t start_channel_id); TString InternalGetServers(intptr_t start_server_id); - - void InternalLogAllEntities(); - - // protects members + + void InternalLogAllEntities(); + + // protects members Mutex mu_; std::map<intptr_t, BaseNode*> node_map_; - intptr_t uuid_generator_ = 0; -}; - -} // namespace channelz -} // namespace grpc_core - -#endif /* GRPC_CORE_LIB_CHANNEL_CHANNELZ_REGISTRY_H */ + intptr_t uuid_generator_ = 0; +}; + +} // namespace channelz +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_CHANNEL_CHANNELZ_REGISTRY_H */ diff --git a/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc b/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc index be74d9e88b..8c7dc8953d 100644 --- a/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc +++ b/contrib/libs/grpc/src/core/lib/channel/connected_channel.cc @@ -50,7 +50,7 @@ typedef struct connected_channel_call_data { callback_state on_complete[6]; // Max number of pending batches. callback_state recv_initial_metadata_ready; callback_state recv_message_ready; - callback_state recv_trailing_metadata_ready; + callback_state recv_trailing_metadata_ready; } call_data; static void run_in_call_combiner(void* arg, grpc_error* error) { @@ -114,12 +114,12 @@ static void connected_channel_start_transport_stream_op_batch( intercept_callback(calld, state, false, "recv_message_ready", &batch->payload->recv_message.recv_message_ready); } - if (batch->recv_trailing_metadata) { - callback_state* state = &calld->recv_trailing_metadata_ready; - intercept_callback( - calld, state, false, "recv_trailing_metadata_ready", - &batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready); - } + if (batch->recv_trailing_metadata) { + callback_state* state = &calld->recv_trailing_metadata_ready; + intercept_callback( + calld, state, false, "recv_trailing_metadata_ready", + &batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready); + } if (batch->cancel_stream) { // There can be more than one cancellation batch in flight at any // given time, so we can't just pick out a fixed index into @@ -130,7 +130,7 @@ static void connected_channel_start_transport_stream_op_batch( static_cast<callback_state*>(gpr_malloc(sizeof(*state))); intercept_callback(calld, state, true, "on_complete (cancel_stream)", &batch->on_complete); - } else if (batch->on_complete != nullptr) { + } else if (batch->on_complete != nullptr) { callback_state* state = get_state_for_batch(calld, batch); intercept_callback(calld, state, false, "on_complete", &batch->on_complete); } diff --git a/contrib/libs/grpc/src/core/lib/channel/context.h b/contrib/libs/grpc/src/core/lib/channel/context.h index bd7fd495e4..3fd0eaadf8 100644 --- a/contrib/libs/grpc/src/core/lib/channel/context.h +++ b/contrib/libs/grpc/src/core/lib/channel/context.h @@ -41,9 +41,9 @@ typedef enum { GRPC_CONTEXT_COUNT } grpc_context_index; -struct grpc_call_context_element { - void* value = nullptr; - void (*destroy)(void*) = nullptr; -}; +struct grpc_call_context_element { + void* value = nullptr; + void (*destroy)(void*) = nullptr; +}; #endif /* GRPC_CORE_LIB_CHANNEL_CONTEXT_H */ diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker.cc b/contrib/libs/grpc/src/core/lib/channel/handshaker.cc index 826be41cbb..55d025d95a 100644 --- a/contrib/libs/grpc/src/core/lib/channel/handshaker.cc +++ b/contrib/libs/grpc/src/core/lib/channel/handshaker.cc @@ -31,18 +31,18 @@ #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/timer.h" -#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/slice/slice_internal.h" -namespace grpc_core { +namespace grpc_core { -TraceFlag grpc_handshaker_trace(false, "handshaker"); +TraceFlag grpc_handshaker_trace(false, "handshaker"); -namespace { +namespace { TString HandshakerArgsString(HandshakerArgs* args) { - size_t num_args = args->args != nullptr ? args->args->num_args : 0; - size_t read_buffer_length = - args->read_buffer != nullptr ? args->read_buffer->length : 0; + size_t num_args = args->args != nullptr ? args->args->num_args : 0; + size_t read_buffer_length = + args->read_buffer != nullptr ? args->read_buffer->length : 0; return y_absl::StrFormat( "{endpoint=%p, args=%p {size=%" PRIuPTR ": %s}, read_buffer=%p (length=%" PRIuPTR "), exit_early=%d}", @@ -51,72 +51,72 @@ TString HandshakerArgsString(HandshakerArgs* args) { read_buffer_length, args->exit_early); } -} // namespace +} // namespace -HandshakeManager::HandshakeManager() { gpr_mu_init(&mu_); } +HandshakeManager::HandshakeManager() { gpr_mu_init(&mu_); } -/// Add \a mgr to the server side list of all pending handshake managers, the -/// list starts with \a *head. -// Not thread-safe. Caller needs to synchronize. -void HandshakeManager::AddToPendingMgrList(HandshakeManager** head) { - GPR_ASSERT(prev_ == nullptr); - GPR_ASSERT(next_ == nullptr); - next_ = *head; +/// Add \a mgr to the server side list of all pending handshake managers, the +/// list starts with \a *head. +// Not thread-safe. Caller needs to synchronize. +void HandshakeManager::AddToPendingMgrList(HandshakeManager** head) { + GPR_ASSERT(prev_ == nullptr); + GPR_ASSERT(next_ == nullptr); + next_ = *head; if (*head) { - (*head)->prev_ = this; + (*head)->prev_ = this; } - *head = this; + *head = this; } -/// Remove \a mgr from the server side list of all pending handshake managers. -// Not thread-safe. Caller needs to synchronize. -void HandshakeManager::RemoveFromPendingMgrList(HandshakeManager** head) { - if (next_ != nullptr) { - next_->prev_ = prev_; +/// Remove \a mgr from the server side list of all pending handshake managers. +// Not thread-safe. Caller needs to synchronize. +void HandshakeManager::RemoveFromPendingMgrList(HandshakeManager** head) { + if (next_ != nullptr) { + next_->prev_ = prev_; } - if (prev_ != nullptr) { - prev_->next_ = next_; + if (prev_ != nullptr) { + prev_->next_ = next_; } else { - GPR_ASSERT(*head == this); - *head = next_; + GPR_ASSERT(*head == this); + *head = next_; } } -/// Shutdown all pending handshake managers starting at head on the server -/// side. Not thread-safe. Caller needs to synchronize. -void HandshakeManager::ShutdownAllPending(grpc_error* why) { - auto* head = this; +/// Shutdown all pending handshake managers starting at head on the server +/// side. Not thread-safe. Caller needs to synchronize. +void HandshakeManager::ShutdownAllPending(grpc_error* why) { + auto* head = this; while (head != nullptr) { - head->Shutdown(GRPC_ERROR_REF(why)); - head = head->next_; + head->Shutdown(GRPC_ERROR_REF(why)); + head = head->next_; } GRPC_ERROR_UNREF(why); } -void HandshakeManager::Add(RefCountedPtr<Handshaker> handshaker) { +void HandshakeManager::Add(RefCountedPtr<Handshaker> handshaker) { if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) { gpr_log( GPR_INFO, "handshake_manager %p: adding handshaker %s [%p] at index %" PRIuPTR, - this, handshaker->name(), handshaker.get(), handshakers_.size()); + this, handshaker->name(), handshaker.get(), handshakers_.size()); } - MutexLock lock(&mu_); - handshakers_.push_back(std::move(handshaker)); + MutexLock lock(&mu_); + handshakers_.push_back(std::move(handshaker)); } -HandshakeManager::~HandshakeManager() { - handshakers_.clear(); - gpr_mu_destroy(&mu_); +HandshakeManager::~HandshakeManager() { + handshakers_.clear(); + gpr_mu_destroy(&mu_); } -void HandshakeManager::Shutdown(grpc_error* why) { - { - MutexLock lock(&mu_); - // Shutdown the handshaker that's currently in progress, if any. - if (!is_shutdown_ && index_ > 0) { - is_shutdown_ = true; - handshakers_[index_ - 1]->Shutdown(GRPC_ERROR_REF(why)); - } +void HandshakeManager::Shutdown(grpc_error* why) { + { + MutexLock lock(&mu_); + // Shutdown the handshaker that's currently in progress, if any. + if (!is_shutdown_ && index_ > 0) { + is_shutdown_ = true; + handshakers_[index_ - 1]->Shutdown(GRPC_ERROR_REF(why)); + } } GRPC_ERROR_UNREF(why); } @@ -124,7 +124,7 @@ void HandshakeManager::Shutdown(grpc_error* why) { // Helper function to call either the next handshaker or the // on_handshake_done callback. // Returns true if we've scheduled the on_handshake_done callback. -bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) { +bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) { if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) { gpr_log(GPR_INFO, "handshake_manager %p: error=%s shutdown=%d index=%" PRIuPTR @@ -132,131 +132,131 @@ bool HandshakeManager::CallNextHandshakerLocked(grpc_error* error) { this, grpc_error_string(error), is_shutdown_, index_, HandshakerArgsString(&args_).c_str()); } - GPR_ASSERT(index_ <= handshakers_.size()); + GPR_ASSERT(index_ <= handshakers_.size()); // If we got an error or we've been shut down or we're exiting early or // we've finished the last handshaker, invoke the on_handshake_done // callback. Otherwise, call the next handshaker. - if (error != GRPC_ERROR_NONE || is_shutdown_ || args_.exit_early || - index_ == handshakers_.size()) { - if (error == GRPC_ERROR_NONE && is_shutdown_) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("handshaker shutdown"); - // It is possible that the endpoint has already been destroyed by - // a shutdown call while this callback was sitting on the ExecCtx - // with no error. - if (args_.endpoint != nullptr) { - // TODO(roth): It is currently necessary to shutdown endpoints - // before destroying then, even when we know that there are no - // pending read/write callbacks. This should be fixed, at which - // point this can be removed. - grpc_endpoint_shutdown(args_.endpoint, GRPC_ERROR_REF(error)); - grpc_endpoint_destroy(args_.endpoint); - args_.endpoint = nullptr; - grpc_channel_args_destroy(args_.args); - args_.args = nullptr; - grpc_slice_buffer_destroy_internal(args_.read_buffer); - gpr_free(args_.read_buffer); - args_.read_buffer = nullptr; - } - } + if (error != GRPC_ERROR_NONE || is_shutdown_ || args_.exit_early || + index_ == handshakers_.size()) { + if (error == GRPC_ERROR_NONE && is_shutdown_) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("handshaker shutdown"); + // It is possible that the endpoint has already been destroyed by + // a shutdown call while this callback was sitting on the ExecCtx + // with no error. + if (args_.endpoint != nullptr) { + // TODO(roth): It is currently necessary to shutdown endpoints + // before destroying then, even when we know that there are no + // pending read/write callbacks. This should be fixed, at which + // point this can be removed. + grpc_endpoint_shutdown(args_.endpoint, GRPC_ERROR_REF(error)); + grpc_endpoint_destroy(args_.endpoint); + args_.endpoint = nullptr; + grpc_channel_args_destroy(args_.args); + args_.args = nullptr; + grpc_slice_buffer_destroy_internal(args_.read_buffer); + gpr_free(args_.read_buffer); + args_.read_buffer = nullptr; + } + } if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) { - gpr_log(GPR_INFO, - "handshake_manager %p: handshaking complete -- scheduling " - "on_handshake_done with error=%s", - this, grpc_error_string(error)); + gpr_log(GPR_INFO, + "handshake_manager %p: handshaking complete -- scheduling " + "on_handshake_done with error=%s", + this, grpc_error_string(error)); } // Cancel deadline timer, since we're invoking the on_handshake_done // callback now. - grpc_timer_cancel(&deadline_timer_); + grpc_timer_cancel(&deadline_timer_); ExecCtx::Run(DEBUG_LOCATION, &on_handshake_done_, error); - is_shutdown_ = true; + is_shutdown_ = true; } else { - auto handshaker = handshakers_[index_]; + auto handshaker = handshakers_[index_]; if (GRPC_TRACE_FLAG_ENABLED(grpc_handshaker_trace)) { gpr_log( GPR_INFO, "handshake_manager %p: calling handshaker %s [%p] at index %" PRIuPTR, - this, handshaker->name(), handshaker.get(), index_); + this, handshaker->name(), handshaker.get(), index_); } - handshaker->DoHandshake(acceptor_, &call_next_handshaker_, &args_); + handshaker->DoHandshake(acceptor_, &call_next_handshaker_, &args_); } - ++index_; - return is_shutdown_; + ++index_; + return is_shutdown_; } -void HandshakeManager::CallNextHandshakerFn(void* arg, grpc_error* error) { - auto* mgr = static_cast<HandshakeManager*>(arg); - bool done; - { - MutexLock lock(&mgr->mu_); - done = mgr->CallNextHandshakerLocked(GRPC_ERROR_REF(error)); - } +void HandshakeManager::CallNextHandshakerFn(void* arg, grpc_error* error) { + auto* mgr = static_cast<HandshakeManager*>(arg); + bool done; + { + MutexLock lock(&mgr->mu_); + done = mgr->CallNextHandshakerLocked(GRPC_ERROR_REF(error)); + } // If we're invoked the final callback, we won't be coming back // to this function, so we can release our reference to the // handshake manager. if (done) { - mgr->Unref(); + mgr->Unref(); } } -void HandshakeManager::OnTimeoutFn(void* arg, grpc_error* error) { - auto* mgr = static_cast<HandshakeManager*>(arg); - if (error == GRPC_ERROR_NONE) { // Timer fired, rather than being cancelled - mgr->Shutdown(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshake timed out")); +void HandshakeManager::OnTimeoutFn(void* arg, grpc_error* error) { + auto* mgr = static_cast<HandshakeManager*>(arg); + if (error == GRPC_ERROR_NONE) { // Timer fired, rather than being cancelled + mgr->Shutdown(GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshake timed out")); } - mgr->Unref(); + mgr->Unref(); } -void HandshakeManager::DoHandshake(grpc_endpoint* endpoint, - const grpc_channel_args* channel_args, - grpc_millis deadline, - grpc_tcp_server_acceptor* acceptor, - grpc_iomgr_cb_func on_handshake_done, - void* user_data) { - bool done; - { - MutexLock lock(&mu_); - GPR_ASSERT(index_ == 0); - GPR_ASSERT(!is_shutdown_); - // Construct handshaker args. These will be passed through all - // handshakers and eventually be freed by the on_handshake_done callback. - args_.endpoint = endpoint; - args_.args = grpc_channel_args_copy(channel_args); - args_.user_data = user_data; - args_.read_buffer = - static_cast<grpc_slice_buffer*>(gpr_malloc(sizeof(*args_.read_buffer))); - grpc_slice_buffer_init(args_.read_buffer); +void HandshakeManager::DoHandshake(grpc_endpoint* endpoint, + const grpc_channel_args* channel_args, + grpc_millis deadline, + grpc_tcp_server_acceptor* acceptor, + grpc_iomgr_cb_func on_handshake_done, + void* user_data) { + bool done; + { + MutexLock lock(&mu_); + GPR_ASSERT(index_ == 0); + GPR_ASSERT(!is_shutdown_); + // Construct handshaker args. These will be passed through all + // handshakers and eventually be freed by the on_handshake_done callback. + args_.endpoint = endpoint; + args_.args = grpc_channel_args_copy(channel_args); + args_.user_data = user_data; + args_.read_buffer = + static_cast<grpc_slice_buffer*>(gpr_malloc(sizeof(*args_.read_buffer))); + grpc_slice_buffer_init(args_.read_buffer); if (acceptor != nullptr && acceptor->external_connection && acceptor->pending_data != nullptr) { grpc_slice_buffer_swap(args_.read_buffer, &(acceptor->pending_data->data.raw.slice_buffer)); } - // Initialize state needed for calling handshakers. - acceptor_ = acceptor; - GRPC_CLOSURE_INIT(&call_next_handshaker_, - &HandshakeManager::CallNextHandshakerFn, this, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&on_handshake_done_, on_handshake_done, &args_, - grpc_schedule_on_exec_ctx); - // Start deadline timer, which owns a ref. - Ref().release(); - GRPC_CLOSURE_INIT(&on_timeout_, &HandshakeManager::OnTimeoutFn, this, - grpc_schedule_on_exec_ctx); - grpc_timer_init(&deadline_timer_, deadline, &on_timeout_); - // Start first handshaker, which also owns a ref. - Ref().release(); - done = CallNextHandshakerLocked(GRPC_ERROR_NONE); - } + // Initialize state needed for calling handshakers. + acceptor_ = acceptor; + GRPC_CLOSURE_INIT(&call_next_handshaker_, + &HandshakeManager::CallNextHandshakerFn, this, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&on_handshake_done_, on_handshake_done, &args_, + grpc_schedule_on_exec_ctx); + // Start deadline timer, which owns a ref. + Ref().release(); + GRPC_CLOSURE_INIT(&on_timeout_, &HandshakeManager::OnTimeoutFn, this, + grpc_schedule_on_exec_ctx); + grpc_timer_init(&deadline_timer_, deadline, &on_timeout_); + // Start first handshaker, which also owns a ref. + Ref().release(); + done = CallNextHandshakerLocked(GRPC_ERROR_NONE); + } if (done) { - Unref(); + Unref(); } } - -} // namespace grpc_core - -void grpc_handshake_manager_add(grpc_handshake_manager* mgr, - grpc_handshaker* handshaker) { - // This is a transition method to aid the API change for handshakers. - using namespace grpc_core; - RefCountedPtr<Handshaker> refd_hs(static_cast<Handshaker*>(handshaker)); - mgr->Add(refd_hs); -} + +} // namespace grpc_core + +void grpc_handshake_manager_add(grpc_handshake_manager* mgr, + grpc_handshaker* handshaker) { + // This is a transition method to aid the API change for handshakers. + using namespace grpc_core; + RefCountedPtr<Handshaker> refd_hs(static_cast<Handshaker*>(handshaker)); + mgr->Add(refd_hs); +} diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker.h b/contrib/libs/grpc/src/core/lib/channel/handshaker.h index cc8e9b2578..847bd2026c 100644 --- a/contrib/libs/grpc/src/core/lib/channel/handshaker.h +++ b/contrib/libs/grpc/src/core/lib/channel/handshaker.h @@ -23,21 +23,21 @@ #include "y_absl/container/inlined_vector.h" -#include <grpc/support/string_util.h> - +#include <grpc/support/string_util.h> + #include <grpc/impl/codegen/grpc_types.h> -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/tcp_server.h" -#include "src/core/lib/iomgr/timer.h" - -namespace grpc_core { +#include "src/core/lib/iomgr/timer.h" +namespace grpc_core { + /// Handshakers are used to perform initial handshakes on a connection /// before the client sends the initial request. Some examples of what /// a handshaker can be used for includes support for HTTP CONNECT on @@ -59,121 +59,121 @@ namespace grpc_core { /// /// For the on_handshake_done callback, all members are input arguments, /// which the callback takes ownership of. -struct HandshakerArgs { - grpc_endpoint* endpoint = nullptr; - grpc_channel_args* args = nullptr; - grpc_slice_buffer* read_buffer = nullptr; +struct HandshakerArgs { + grpc_endpoint* endpoint = nullptr; + grpc_channel_args* args = nullptr; + grpc_slice_buffer* read_buffer = nullptr; // A handshaker may set this to true before invoking on_handshake_done // to indicate that subsequent handshakers should be skipped. - bool exit_early = false; + bool exit_early = false; // User data passed through the handshake manager. Not used by // individual handshakers. - void* user_data = nullptr; -}; + void* user_data = nullptr; +}; -/// -/// Handshaker -/// +/// +/// Handshaker +/// -class Handshaker : public RefCounted<Handshaker> { - public: - virtual ~Handshaker() = default; +class Handshaker : public RefCounted<Handshaker> { + public: + virtual ~Handshaker() = default; virtual void Shutdown(grpc_error* why) = 0; - virtual void DoHandshake(grpc_tcp_server_acceptor* acceptor, - grpc_closure* on_handshake_done, + virtual void DoHandshake(grpc_tcp_server_acceptor* acceptor, + grpc_closure* on_handshake_done, HandshakerArgs* args) = 0; virtual const char* name() const = 0; -}; - -// -// HandshakeManager -// - -class HandshakeManager : public RefCounted<HandshakeManager> { - public: - HandshakeManager(); - ~HandshakeManager(); - - /// Add \a mgr to the server side list of all pending handshake managers, the - /// list starts with \a *head. - // Not thread-safe. Caller needs to synchronize. - void AddToPendingMgrList(HandshakeManager** head); - - /// Remove \a mgr from the server side list of all pending handshake managers. - // Not thread-safe. Caller needs to synchronize. - void RemoveFromPendingMgrList(HandshakeManager** head); - - /// Shutdown all pending handshake managers starting at head on the server - /// side. Not thread-safe. Caller needs to synchronize. - void ShutdownAllPending(grpc_error* why); - - /// Adds a handshaker to the handshake manager. - /// Takes ownership of \a handshaker. - void Add(RefCountedPtr<Handshaker> handshaker); - - /// Shuts down the handshake manager (e.g., to clean up when the operation is - /// aborted in the middle). - void Shutdown(grpc_error* why); - - /// Invokes handshakers in the order they were added. - /// Takes ownership of \a endpoint, and then passes that ownership to - /// the \a on_handshake_done callback. - /// Does NOT take ownership of \a channel_args. Instead, makes a copy before - /// invoking the first handshaker. - /// \a acceptor will be nullptr for client-side handshakers. - /// - /// When done, invokes \a on_handshake_done with a HandshakerArgs - /// object as its argument. If the callback is invoked with error != - /// GRPC_ERROR_NONE, then handshaking failed and the handshaker has done - /// the necessary clean-up. Otherwise, the callback takes ownership of - /// the arguments. - void DoHandshake(grpc_endpoint* endpoint, - const grpc_channel_args* channel_args, grpc_millis deadline, - grpc_tcp_server_acceptor* acceptor, - grpc_iomgr_cb_func on_handshake_done, void* user_data); - - private: - bool CallNextHandshakerLocked(grpc_error* error); - - // A function used as the handshaker-done callback when chaining - // handshakers together. - static void CallNextHandshakerFn(void* arg, grpc_error* error); - - // Callback invoked when deadline is exceeded. - static void OnTimeoutFn(void* arg, grpc_error* error); - - static const size_t HANDSHAKERS_INIT_SIZE = 2; - - gpr_mu mu_; - bool is_shutdown_ = false; - // An array of handshakers added via grpc_handshake_manager_add(). +}; + +// +// HandshakeManager +// + +class HandshakeManager : public RefCounted<HandshakeManager> { + public: + HandshakeManager(); + ~HandshakeManager(); + + /// Add \a mgr to the server side list of all pending handshake managers, the + /// list starts with \a *head. + // Not thread-safe. Caller needs to synchronize. + void AddToPendingMgrList(HandshakeManager** head); + + /// Remove \a mgr from the server side list of all pending handshake managers. + // Not thread-safe. Caller needs to synchronize. + void RemoveFromPendingMgrList(HandshakeManager** head); + + /// Shutdown all pending handshake managers starting at head on the server + /// side. Not thread-safe. Caller needs to synchronize. + void ShutdownAllPending(grpc_error* why); + + /// Adds a handshaker to the handshake manager. + /// Takes ownership of \a handshaker. + void Add(RefCountedPtr<Handshaker> handshaker); + + /// Shuts down the handshake manager (e.g., to clean up when the operation is + /// aborted in the middle). + void Shutdown(grpc_error* why); + + /// Invokes handshakers in the order they were added. + /// Takes ownership of \a endpoint, and then passes that ownership to + /// the \a on_handshake_done callback. + /// Does NOT take ownership of \a channel_args. Instead, makes a copy before + /// invoking the first handshaker. + /// \a acceptor will be nullptr for client-side handshakers. + /// + /// When done, invokes \a on_handshake_done with a HandshakerArgs + /// object as its argument. If the callback is invoked with error != + /// GRPC_ERROR_NONE, then handshaking failed and the handshaker has done + /// the necessary clean-up. Otherwise, the callback takes ownership of + /// the arguments. + void DoHandshake(grpc_endpoint* endpoint, + const grpc_channel_args* channel_args, grpc_millis deadline, + grpc_tcp_server_acceptor* acceptor, + grpc_iomgr_cb_func on_handshake_done, void* user_data); + + private: + bool CallNextHandshakerLocked(grpc_error* error); + + // A function used as the handshaker-done callback when chaining + // handshakers together. + static void CallNextHandshakerFn(void* arg, grpc_error* error); + + // Callback invoked when deadline is exceeded. + static void OnTimeoutFn(void* arg, grpc_error* error); + + static const size_t HANDSHAKERS_INIT_SIZE = 2; + + gpr_mu mu_; + bool is_shutdown_ = false; + // An array of handshakers added via grpc_handshake_manager_add(). y_absl::InlinedVector<RefCountedPtr<Handshaker>, HANDSHAKERS_INIT_SIZE> handshakers_; - // The index of the handshaker to invoke next and closure to invoke it. - size_t index_ = 0; - grpc_closure call_next_handshaker_; - // The acceptor to call the handshakers with. - grpc_tcp_server_acceptor* acceptor_; - // Deadline timer across all handshakers. - grpc_timer deadline_timer_; - grpc_closure on_timeout_; - // The final callback and user_data to invoke after the last handshaker. - grpc_closure on_handshake_done_; - // Handshaker args. - HandshakerArgs args_; - // Links to the previous and next managers in a list of all pending handshakes - // Used at server side only. - HandshakeManager* prev_ = nullptr; - HandshakeManager* next_ = nullptr; -}; - -} // namespace grpc_core - -// TODO(arjunroy): These are transitional to account for the new handshaker API -// and will eventually be removed entirely. -typedef grpc_core::HandshakeManager grpc_handshake_manager; -typedef grpc_core::Handshaker grpc_handshaker; -void grpc_handshake_manager_add(grpc_handshake_manager* mgr, - grpc_handshaker* handshaker); + // The index of the handshaker to invoke next and closure to invoke it. + size_t index_ = 0; + grpc_closure call_next_handshaker_; + // The acceptor to call the handshakers with. + grpc_tcp_server_acceptor* acceptor_; + // Deadline timer across all handshakers. + grpc_timer deadline_timer_; + grpc_closure on_timeout_; + // The final callback and user_data to invoke after the last handshaker. + grpc_closure on_handshake_done_; + // Handshaker args. + HandshakerArgs args_; + // Links to the previous and next managers in a list of all pending handshakes + // Used at server side only. + HandshakeManager* prev_ = nullptr; + HandshakeManager* next_ = nullptr; +}; + +} // namespace grpc_core + +// TODO(arjunroy): These are transitional to account for the new handshaker API +// and will eventually be removed entirely. +typedef grpc_core::HandshakeManager grpc_handshake_manager; +typedef grpc_core::Handshaker grpc_handshaker; +void grpc_handshake_manager_add(grpc_handshake_manager* mgr, + grpc_handshaker* handshaker); #endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_H */ diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h b/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h index 520e5e4b25..636e8e49e1 100644 --- a/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h +++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_factory.h @@ -27,16 +27,16 @@ // A handshaker factory is used to create handshakers. -namespace grpc_core { +namespace grpc_core { -class HandshakerFactory { - public: - virtual void AddHandshakers(const grpc_channel_args* args, - grpc_pollset_set* interested_parties, +class HandshakerFactory { + public: + virtual void AddHandshakers(const grpc_channel_args* args, + grpc_pollset_set* interested_parties, HandshakeManager* handshake_mgr) = 0; - virtual ~HandshakerFactory() = default; + virtual ~HandshakerFactory() = default; }; -} // namespace grpc_core +} // namespace grpc_core #endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_FACTORY_H */ diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc index 614531832d..b7e01799e2 100644 --- a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc +++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.cc @@ -22,10 +22,10 @@ #include "src/core/lib/channel/handshaker_registry.h" #include "src/core/lib/gpr/alloc.h" -#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/gprpp/memory.h" #include <string.h> -#include <algorithm> +#include <algorithm> #include <grpc/support/alloc.h> @@ -33,40 +33,40 @@ // grpc_handshaker_factory_list // -namespace grpc_core { +namespace grpc_core { -namespace { - -class HandshakerFactoryList { - public: +namespace { + +class HandshakerFactoryList { + public: void Register(bool at_start, std::unique_ptr<HandshakerFactory> factory); - void AddHandshakers(const grpc_channel_args* args, - grpc_pollset_set* interested_parties, - HandshakeManager* handshake_mgr); - - private: + void AddHandshakers(const grpc_channel_args* args, + grpc_pollset_set* interested_parties, + HandshakeManager* handshake_mgr); + + private: y_absl::InlinedVector<std::unique_ptr<HandshakerFactory>, 2> factories_; -}; - -HandshakerFactoryList* g_handshaker_factory_lists = nullptr; - -} // namespace - +}; + +HandshakerFactoryList* g_handshaker_factory_lists = nullptr; + +} // namespace + void HandshakerFactoryList::Register( bool at_start, std::unique_ptr<HandshakerFactory> factory) { - factories_.push_back(std::move(factory)); + factories_.push_back(std::move(factory)); if (at_start) { - auto* end = &factories_[factories_.size() - 1]; - std::rotate(&factories_[0], end, end + 1); + auto* end = &factories_[factories_.size() - 1]; + std::rotate(&factories_[0], end, end + 1); } } -void HandshakerFactoryList::AddHandshakers(const grpc_channel_args* args, - grpc_pollset_set* interested_parties, - HandshakeManager* handshake_mgr) { - for (size_t idx = 0; idx < factories_.size(); ++idx) { - auto& handshaker_factory = factories_[idx]; - handshaker_factory->AddHandshakers(args, interested_parties, handshake_mgr); +void HandshakerFactoryList::AddHandshakers(const grpc_channel_args* args, + grpc_pollset_set* interested_parties, + HandshakeManager* handshake_mgr) { + for (size_t idx = 0; idx < factories_.size(); ++idx) { + auto& handshaker_factory = factories_[idx]; + handshaker_factory->AddHandshakers(args, interested_parties, handshake_mgr); } } @@ -74,32 +74,32 @@ void HandshakerFactoryList::AddHandshakers(const grpc_channel_args* args, // plugin // -void HandshakerRegistry::Init() { - GPR_ASSERT(g_handshaker_factory_lists == nullptr); +void HandshakerRegistry::Init() { + GPR_ASSERT(g_handshaker_factory_lists == nullptr); g_handshaker_factory_lists = new HandshakerFactoryList[NUM_HANDSHAKER_TYPES]; } -void HandshakerRegistry::Shutdown() { - GPR_ASSERT(g_handshaker_factory_lists != nullptr); +void HandshakerRegistry::Shutdown() { + GPR_ASSERT(g_handshaker_factory_lists != nullptr); delete[] g_handshaker_factory_lists; - g_handshaker_factory_lists = nullptr; + g_handshaker_factory_lists = nullptr; } -void HandshakerRegistry::RegisterHandshakerFactory( - bool at_start, HandshakerType handshaker_type, +void HandshakerRegistry::RegisterHandshakerFactory( + bool at_start, HandshakerType handshaker_type, std::unique_ptr<HandshakerFactory> factory) { - GPR_ASSERT(g_handshaker_factory_lists != nullptr); - auto& factory_list = g_handshaker_factory_lists[handshaker_type]; - factory_list.Register(at_start, std::move(factory)); + GPR_ASSERT(g_handshaker_factory_lists != nullptr); + auto& factory_list = g_handshaker_factory_lists[handshaker_type]; + factory_list.Register(at_start, std::move(factory)); } -void HandshakerRegistry::AddHandshakers(HandshakerType handshaker_type, - const grpc_channel_args* args, - grpc_pollset_set* interested_parties, - HandshakeManager* handshake_mgr) { - GPR_ASSERT(g_handshaker_factory_lists != nullptr); - auto& factory_list = g_handshaker_factory_lists[handshaker_type]; - factory_list.AddHandshakers(args, interested_parties, handshake_mgr); +void HandshakerRegistry::AddHandshakers(HandshakerType handshaker_type, + const grpc_channel_args* args, + grpc_pollset_set* interested_parties, + HandshakeManager* handshake_mgr) { + GPR_ASSERT(g_handshaker_factory_lists != nullptr); + auto& factory_list = g_handshaker_factory_lists[handshaker_type]; + factory_list.AddHandshakers(args, interested_parties, handshake_mgr); } - -} // namespace grpc_core + +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h index 4a02efc3f2..ce92dd1041 100644 --- a/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h +++ b/contrib/libs/grpc/src/core/lib/channel/handshaker_registry.h @@ -25,30 +25,30 @@ #include "src/core/lib/channel/handshaker_factory.h" -namespace grpc_core { - +namespace grpc_core { + typedef enum { HANDSHAKER_CLIENT = 0, HANDSHAKER_SERVER, NUM_HANDSHAKER_TYPES, // Must be last. -} HandshakerType; +} HandshakerType; -class HandshakerRegistry { - public: - /// Registers a new handshaker factory. Takes ownership. - /// If \a at_start is true, the new handshaker will be at the beginning of - /// the list. Otherwise, it will be added to the end. +class HandshakerRegistry { + public: + /// Registers a new handshaker factory. Takes ownership. + /// If \a at_start is true, the new handshaker will be at the beginning of + /// the list. Otherwise, it will be added to the end. static void RegisterHandshakerFactory( bool at_start, HandshakerType handshaker_type, std::unique_ptr<HandshakerFactory> factory); - static void AddHandshakers(HandshakerType handshaker_type, - const grpc_channel_args* args, - grpc_pollset_set* interested_parties, - HandshakeManager* handshake_mgr); - static void Init(); - static void Shutdown(); -}; - -} // namespace grpc_core + static void AddHandshakers(HandshakerType handshaker_type, + const grpc_channel_args* args, + grpc_pollset_set* interested_parties, + HandshakeManager* handshake_mgr); + static void Init(); + static void Shutdown(); +}; + +} // namespace grpc_core #endif /* GRPC_CORE_LIB_CHANNEL_HANDSHAKER_REGISTRY_H */ diff --git a/contrib/libs/grpc/src/core/lib/debug/stats.h b/contrib/libs/grpc/src/core/lib/debug/stats.h index c184fa7fc7..ba50351a23 100644 --- a/contrib/libs/grpc/src/core/lib/debug/stats.h +++ b/contrib/libs/grpc/src/core/lib/debug/stats.h @@ -37,9 +37,9 @@ extern grpc_stats_data* grpc_stats_per_cpu_storage; #define GRPC_THREAD_STATS_DATA() \ (&grpc_stats_per_cpu_storage[grpc_core::ExecCtx::Get()->starting_cpu()]) -/* Only collect stats if GRPC_COLLECT_STATS is defined or it is a debug build. - */ -#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) +/* Only collect stats if GRPC_COLLECT_STATS is defined or it is a debug build. + */ +#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) #define GRPC_STATS_INC_COUNTER(ctr) \ (gpr_atm_no_barrier_fetch_add(&GRPC_THREAD_STATS_DATA()->counters[(ctr)], 1)) @@ -47,10 +47,10 @@ extern grpc_stats_data* grpc_stats_per_cpu_storage; (gpr_atm_no_barrier_fetch_add( \ &GRPC_THREAD_STATS_DATA()->histograms[histogram##_FIRST_SLOT + (index)], \ 1)) -#else /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */ -#define GRPC_STATS_INC_COUNTER(ctr) -#define GRPC_STATS_INC_HISTOGRAM(histogram, index) -#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */ +#else /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */ +#define GRPC_STATS_INC_COUNTER(ctr) +#define GRPC_STATS_INC_HISTOGRAM(histogram, index) +#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */ void grpc_stats_init(void); void grpc_stats_shutdown(void); diff --git a/contrib/libs/grpc/src/core/lib/debug/stats_data.cc b/contrib/libs/grpc/src/core/lib/debug/stats_data.cc index f8c27db0a8..cb4d10624a 100644 --- a/contrib/libs/grpc/src/core/lib/debug/stats_data.cc +++ b/contrib/libs/grpc/src/core/lib/debug/stats_data.cc @@ -40,8 +40,8 @@ const char* grpc_stats_counter_name[GRPC_STATS_COUNTER_COUNT] = { "pollset_kick_wakeup_fd", "pollset_kick_wakeup_cv", "pollset_kick_own_thread", - "syscall_epoll_ctl", - "pollset_fd_cache_hits", + "syscall_epoll_ctl", + "pollset_fd_cache_hits", "histogram_slow_lookups", "syscall_write", "syscall_read", @@ -146,9 +146,9 @@ const char* grpc_stats_counter_doc[GRPC_STATS_COUNTER_COUNT] = { "polling wakeup (only valid for epoll1 right now)", "How many times could a polling wakeup be satisfied by keeping the waking " "thread awake? (only valid for epoll1 right now)", - "Number of epoll_ctl calls made (only valid for epollex right now)", - "Number of epoll_ctl calls skipped because the fd was cached as already " - "being added. (only valid for epollex right now)", + "Number of epoll_ctl calls made (only valid for epollex right now)", + "Number of epoll_ctl calls skipped because the fd was cached as already " + "being added. (only valid for epollex right now)", "Number of times histogram increments went through the slow (binary " "search) path", "Number of write syscalls (or equivalent - eg sendmsg) made by this " diff --git a/contrib/libs/grpc/src/core/lib/debug/stats_data.h b/contrib/libs/grpc/src/core/lib/debug/stats_data.h index 1f3861f494..e222d5d259 100644 --- a/contrib/libs/grpc/src/core/lib/debug/stats_data.h +++ b/contrib/libs/grpc/src/core/lib/debug/stats_data.h @@ -41,8 +41,8 @@ typedef enum { GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_FD, GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_CV, GRPC_STATS_COUNTER_POLLSET_KICK_OWN_THREAD, - GRPC_STATS_COUNTER_SYSCALL_EPOLL_CTL, - GRPC_STATS_COUNTER_POLLSET_FD_CACHE_HITS, + GRPC_STATS_COUNTER_SYSCALL_EPOLL_CTL, + GRPC_STATS_COUNTER_POLLSET_FD_CACHE_HITS, GRPC_STATS_COUNTER_HISTOGRAM_SLOW_LOOKUPS, GRPC_STATS_COUNTER_SYSCALL_WRITE, GRPC_STATS_COUNTER_SYSCALL_READ, @@ -176,7 +176,7 @@ typedef enum { GRPC_STATS_HISTOGRAM_SERVER_CQS_CHECKED_BUCKETS = 8, GRPC_STATS_HISTOGRAM_BUCKETS = 840 } grpc_stats_histogram_constants; -#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) +#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) #define GRPC_STATS_INC_CLIENT_CALLS_CREATED() \ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_CLIENT_CALLS_CREATED) #define GRPC_STATS_INC_SERVER_CALLS_CREATED() \ @@ -205,10 +205,10 @@ typedef enum { GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_WAKEUP_CV) #define GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD() \ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_KICK_OWN_THREAD) -#define GRPC_STATS_INC_SYSCALL_EPOLL_CTL() \ - GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_EPOLL_CTL) -#define GRPC_STATS_INC_POLLSET_FD_CACHE_HITS() \ - GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_FD_CACHE_HITS) +#define GRPC_STATS_INC_SYSCALL_EPOLL_CTL() \ + GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_SYSCALL_EPOLL_CTL) +#define GRPC_STATS_INC_POLLSET_FD_CACHE_HITS() \ + GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_POLLSET_FD_CACHE_HITS) #define GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS() \ GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_HISTOGRAM_SLOW_LOOKUPS) #define GRPC_STATS_INC_SYSCALL_WRITE() \ @@ -434,119 +434,119 @@ void grpc_stats_inc_http2_send_flowctl_per_write(int x); #define GRPC_STATS_INC_SERVER_CQS_CHECKED(value) \ grpc_stats_inc_server_cqs_checked((int)(value)) void grpc_stats_inc_server_cqs_checked(int x); -#else -#define GRPC_STATS_INC_CLIENT_CALLS_CREATED() -#define GRPC_STATS_INC_SERVER_CALLS_CREATED() -#define GRPC_STATS_INC_CQS_CREATED() -#define GRPC_STATS_INC_CLIENT_CHANNELS_CREATED() -#define GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED() -#define GRPC_STATS_INC_SERVER_CHANNELS_CREATED() -#define GRPC_STATS_INC_SYSCALL_POLL() -#define GRPC_STATS_INC_SYSCALL_WAIT() -#define GRPC_STATS_INC_POLLSET_KICK() -#define GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER() -#define GRPC_STATS_INC_POLLSET_KICKED_AGAIN() -#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD() -#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV() -#define GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD() -#define GRPC_STATS_INC_SYSCALL_EPOLL_CTL() -#define GRPC_STATS_INC_POLLSET_FD_CACHE_HITS() -#define GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS() -#define GRPC_STATS_INC_SYSCALL_WRITE() -#define GRPC_STATS_INC_SYSCALL_READ() -#define GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED() -#define GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS() -#define GRPC_STATS_INC_HTTP2_OP_BATCHES() -#define GRPC_STATS_INC_HTTP2_OP_CANCEL() -#define GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA() -#define GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE() -#define GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA() -#define GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA() -#define GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE() -#define GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA() -#define GRPC_STATS_INC_HTTP2_SETTINGS_WRITES() -#define GRPC_STATS_INC_HTTP2_PINGS_SENT() -#define GRPC_STATS_INC_HTTP2_WRITES_BEGUN() -#define GRPC_STATS_INC_HTTP2_WRITES_OFFLOADED() -#define GRPC_STATS_INC_HTTP2_WRITES_CONTINUED() -#define GRPC_STATS_INC_HTTP2_PARTIAL_WRITES() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE() -#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM() -#define GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN() -#define GRPC_STATS_INC_HPACK_RECV_INDEXED() -#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX() -#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX_V() -#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX() -#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX_V() -#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX() -#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX_V() -#define GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED() -#define GRPC_STATS_INC_HPACK_RECV_HUFFMAN() -#define GRPC_STATS_INC_HPACK_RECV_BINARY() -#define GRPC_STATS_INC_HPACK_RECV_BINARY_BASE64() -#define GRPC_STATS_INC_HPACK_SEND_INDEXED() -#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX() -#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V() -#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX() -#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V() -#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX() -#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX_V() -#define GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED() -#define GRPC_STATS_INC_HPACK_SEND_HUFFMAN() -#define GRPC_STATS_INC_HPACK_SEND_BINARY() -#define GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64() -#define GRPC_STATS_INC_COMBINER_LOCKS_INITIATED() -#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS() -#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS() -#define GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED() -#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED() -#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS() -#define GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL() -#define GRPC_STATS_INC_CALL_COMBINER_CANCELLED() -#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS() -#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS() -#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF() -#define GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED() -#define GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED() -#define GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES() -#define GRPC_STATS_INC_SERVER_REQUESTED_CALLS() -#define GRPC_STATS_INC_SERVER_SLOWPATH_REQUESTS_QUEUED() -#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_FAILURES() -#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES() -#define GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES() -#define GRPC_STATS_INC_CALL_INITIAL_SIZE(value) -#define GRPC_STATS_INC_POLL_EVENTS_RETURNED(value) -#define GRPC_STATS_INC_TCP_WRITE_SIZE(value) -#define GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(value) -#define GRPC_STATS_INC_TCP_READ_SIZE(value) -#define GRPC_STATS_INC_TCP_READ_OFFER(value) -#define GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(value) -#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(value) -#define GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(value) -#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(value) -#define GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(value) -#define GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(value) -#define GRPC_STATS_INC_SERVER_CQS_CHECKED(value) -#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */ +#else +#define GRPC_STATS_INC_CLIENT_CALLS_CREATED() +#define GRPC_STATS_INC_SERVER_CALLS_CREATED() +#define GRPC_STATS_INC_CQS_CREATED() +#define GRPC_STATS_INC_CLIENT_CHANNELS_CREATED() +#define GRPC_STATS_INC_CLIENT_SUBCHANNELS_CREATED() +#define GRPC_STATS_INC_SERVER_CHANNELS_CREATED() +#define GRPC_STATS_INC_SYSCALL_POLL() +#define GRPC_STATS_INC_SYSCALL_WAIT() +#define GRPC_STATS_INC_POLLSET_KICK() +#define GRPC_STATS_INC_POLLSET_KICKED_WITHOUT_POLLER() +#define GRPC_STATS_INC_POLLSET_KICKED_AGAIN() +#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_FD() +#define GRPC_STATS_INC_POLLSET_KICK_WAKEUP_CV() +#define GRPC_STATS_INC_POLLSET_KICK_OWN_THREAD() +#define GRPC_STATS_INC_SYSCALL_EPOLL_CTL() +#define GRPC_STATS_INC_POLLSET_FD_CACHE_HITS() +#define GRPC_STATS_INC_HISTOGRAM_SLOW_LOOKUPS() +#define GRPC_STATS_INC_SYSCALL_WRITE() +#define GRPC_STATS_INC_SYSCALL_READ() +#define GRPC_STATS_INC_TCP_BACKUP_POLLERS_CREATED() +#define GRPC_STATS_INC_TCP_BACKUP_POLLER_POLLS() +#define GRPC_STATS_INC_HTTP2_OP_BATCHES() +#define GRPC_STATS_INC_HTTP2_OP_CANCEL() +#define GRPC_STATS_INC_HTTP2_OP_SEND_INITIAL_METADATA() +#define GRPC_STATS_INC_HTTP2_OP_SEND_MESSAGE() +#define GRPC_STATS_INC_HTTP2_OP_SEND_TRAILING_METADATA() +#define GRPC_STATS_INC_HTTP2_OP_RECV_INITIAL_METADATA() +#define GRPC_STATS_INC_HTTP2_OP_RECV_MESSAGE() +#define GRPC_STATS_INC_HTTP2_OP_RECV_TRAILING_METADATA() +#define GRPC_STATS_INC_HTTP2_SETTINGS_WRITES() +#define GRPC_STATS_INC_HTTP2_PINGS_SENT() +#define GRPC_STATS_INC_HTTP2_WRITES_BEGUN() +#define GRPC_STATS_INC_HTTP2_WRITES_OFFLOADED() +#define GRPC_STATS_INC_HTTP2_WRITES_CONTINUED() +#define GRPC_STATS_INC_HTTP2_PARTIAL_WRITES() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_INITIAL_WRITE() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_START_NEW_STREAM() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_MESSAGE() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_INITIAL_METADATA() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_TRAILING_METADATA() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RETRY_SEND_PING() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CONTINUE_PINGS() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_GOAWAY_SENT() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_RST_STREAM() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_CLOSE_FROM_API() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_STREAM_FLOW_CONTROL() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_SEND_SETTINGS() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_BDP_ESTIMATOR_PING() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_SETTING() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FLOW_CONTROL_UNSTALLED_BY_UPDATE() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_APPLICATION_PING() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_KEEPALIVE_PING() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_TRANSPORT_FLOW_CONTROL_UNSTALLED() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_PING_RESPONSE() +#define GRPC_STATS_INC_HTTP2_INITIATE_WRITE_DUE_TO_FORCE_RST_STREAM() +#define GRPC_STATS_INC_HTTP2_SPURIOUS_WRITES_BEGUN() +#define GRPC_STATS_INC_HPACK_RECV_INDEXED() +#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX() +#define GRPC_STATS_INC_HPACK_RECV_LITHDR_INCIDX_V() +#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX() +#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NOTIDX_V() +#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX() +#define GRPC_STATS_INC_HPACK_RECV_LITHDR_NVRIDX_V() +#define GRPC_STATS_INC_HPACK_RECV_UNCOMPRESSED() +#define GRPC_STATS_INC_HPACK_RECV_HUFFMAN() +#define GRPC_STATS_INC_HPACK_RECV_BINARY() +#define GRPC_STATS_INC_HPACK_RECV_BINARY_BASE64() +#define GRPC_STATS_INC_HPACK_SEND_INDEXED() +#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX() +#define GRPC_STATS_INC_HPACK_SEND_LITHDR_INCIDX_V() +#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX() +#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NOTIDX_V() +#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX() +#define GRPC_STATS_INC_HPACK_SEND_LITHDR_NVRIDX_V() +#define GRPC_STATS_INC_HPACK_SEND_UNCOMPRESSED() +#define GRPC_STATS_INC_HPACK_SEND_HUFFMAN() +#define GRPC_STATS_INC_HPACK_SEND_BINARY() +#define GRPC_STATS_INC_HPACK_SEND_BINARY_BASE64() +#define GRPC_STATS_INC_COMBINER_LOCKS_INITIATED() +#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_ITEMS() +#define GRPC_STATS_INC_COMBINER_LOCKS_SCHEDULED_FINAL_ITEMS() +#define GRPC_STATS_INC_COMBINER_LOCKS_OFFLOADED() +#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_INITIATED() +#define GRPC_STATS_INC_CALL_COMBINER_LOCKS_SCHEDULED_ITEMS() +#define GRPC_STATS_INC_CALL_COMBINER_SET_NOTIFY_ON_CANCEL() +#define GRPC_STATS_INC_CALL_COMBINER_CANCELLED() +#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS() +#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS() +#define GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF() +#define GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED() +#define GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED() +#define GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES() +#define GRPC_STATS_INC_SERVER_REQUESTED_CALLS() +#define GRPC_STATS_INC_SERVER_SLOWPATH_REQUESTS_QUEUED() +#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_FAILURES() +#define GRPC_STATS_INC_CQ_EV_QUEUE_TRYLOCK_SUCCESSES() +#define GRPC_STATS_INC_CQ_EV_QUEUE_TRANSIENT_POP_FAILURES() +#define GRPC_STATS_INC_CALL_INITIAL_SIZE(value) +#define GRPC_STATS_INC_POLL_EVENTS_RETURNED(value) +#define GRPC_STATS_INC_TCP_WRITE_SIZE(value) +#define GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(value) +#define GRPC_STATS_INC_TCP_READ_SIZE(value) +#define GRPC_STATS_INC_TCP_READ_OFFER(value) +#define GRPC_STATS_INC_TCP_READ_OFFER_IOV_SIZE(value) +#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_SIZE(value) +#define GRPC_STATS_INC_HTTP2_SEND_INITIAL_METADATA_PER_WRITE(value) +#define GRPC_STATS_INC_HTTP2_SEND_MESSAGE_PER_WRITE(value) +#define GRPC_STATS_INC_HTTP2_SEND_TRAILING_METADATA_PER_WRITE(value) +#define GRPC_STATS_INC_HTTP2_SEND_FLOWCTL_PER_WRITE(value) +#define GRPC_STATS_INC_SERVER_CQS_CHECKED(value) +#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */ extern const int grpc_stats_histo_buckets[13]; extern const int grpc_stats_histo_start[13]; extern const int* const grpc_stats_histo_bucket_boundaries[13]; diff --git a/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql b/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql index 7d1ab1dae9..70f4bb42b3 100644 --- a/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql +++ b/contrib/libs/grpc/src/core/lib/debug/stats_data_bq_schema.sql @@ -12,8 +12,8 @@ pollset_kicked_again_per_iteration:FLOAT, pollset_kick_wakeup_fd_per_iteration:FLOAT, pollset_kick_wakeup_cv_per_iteration:FLOAT, pollset_kick_own_thread_per_iteration:FLOAT, -syscall_epoll_ctl_per_iteration:FLOAT, -pollset_fd_cache_hits_per_iteration:FLOAT, +syscall_epoll_ctl_per_iteration:FLOAT, +pollset_fd_cache_hits_per_iteration:FLOAT, histogram_slow_lookups_per_iteration:FLOAT, syscall_write_per_iteration:FLOAT, syscall_read_per_iteration:FLOAT, diff --git a/contrib/libs/grpc/src/core/lib/debug/trace.cc b/contrib/libs/grpc/src/core/lib/debug/trace.cc index 84c0a3805d..dd7c6c056b 100644 --- a/contrib/libs/grpc/src/core/lib/debug/trace.cc +++ b/contrib/libs/grpc/src/core/lib/debug/trace.cc @@ -21,7 +21,7 @@ #include "src/core/lib/debug/trace.h" #include <string.h> -#include <type_traits> +#include <type_traits> #include <grpc/grpc.h> #include <grpc/support/alloc.h> @@ -84,8 +84,8 @@ void TraceFlagList::LogAllTracers() { // Flags register themselves on the list during construction TraceFlag::TraceFlag(bool default_enabled, const char* name) : name_(name) { - static_assert(std::is_trivially_destructible<TraceFlag>::value, - "TraceFlag needs to be trivially destructible."); + static_assert(std::is_trivially_destructible<TraceFlag>::value, + "TraceFlag needs to be trivially destructible."); set_enabled(default_enabled); TraceFlagList::Add(this); } diff --git a/contrib/libs/grpc/src/core/lib/debug/trace.h b/contrib/libs/grpc/src/core/lib/debug/trace.h index ac7b40e58a..8741b150b8 100644 --- a/contrib/libs/grpc/src/core/lib/debug/trace.h +++ b/contrib/libs/grpc/src/core/lib/debug/trace.h @@ -63,20 +63,20 @@ class TraceFlag { TraceFlag(bool default_enabled, const char* name); // TraceFlag needs to be trivially destructible since it is used as global // variable. - ~TraceFlag() = default; + ~TraceFlag() = default; const char* name() const { return name_; } -// Use the symbol GRPC_USE_TRACERS to determine if tracers will be enabled in -// opt builds (tracers are always on in dbg builds). The default in OSS is for -// tracers to be on since we support binary distributions of gRPC for the -// wrapped language (wr don't want to force recompilation to get tracing). -// Internally, however, for performance reasons, we compile them out by -// default, since internal build systems make recompiling trivial. +// Use the symbol GRPC_USE_TRACERS to determine if tracers will be enabled in +// opt builds (tracers are always on in dbg builds). The default in OSS is for +// tracers to be on since we support binary distributions of gRPC for the +// wrapped language (wr don't want to force recompilation to get tracing). +// Internally, however, for performance reasons, we compile them out by +// default, since internal build systems make recompiling trivial. // // Prefer GRPC_TRACE_FLAG_ENABLED() macro instead of using enabled() directly. -#define GRPC_USE_TRACERS // tracers on by default in OSS -#if defined(GRPC_USE_TRACERS) || !defined(NDEBUG) +#define GRPC_USE_TRACERS // tracers on by default in OSS +#if defined(GRPC_USE_TRACERS) || !defined(NDEBUG) bool enabled() { #ifdef GRPC_THREADSAFE_TRACER return gpr_atm_no_barrier_load(&value_) != 0; @@ -84,9 +84,9 @@ class TraceFlag { return value_; #endif // GRPC_THREADSAFE_TRACER } -#else - bool enabled() { return false; } -#endif /* defined(GRPC_USE_TRACERS) || !defined(NDEBUG) */ +#else + bool enabled() { return false; } +#endif /* defined(GRPC_USE_TRACERS) || !defined(NDEBUG) */ private: friend void grpc_core::testing::grpc_tracer_enable_flag(TraceFlag* flag); @@ -118,8 +118,8 @@ class DebugOnlyTraceFlag { public: constexpr DebugOnlyTraceFlag(bool /*default_enabled*/, const char* /*name*/) { } - constexpr bool enabled() const { return false; } - constexpr const char* name() const { return "DebugOnlyTraceFlag"; } + constexpr bool enabled() const { return false; } + constexpr const char* name() const { return "DebugOnlyTraceFlag"; } private: void set_enabled(bool /*enabled*/) {} diff --git a/contrib/libs/grpc/src/core/lib/gpr/alloc.h b/contrib/libs/grpc/src/core/lib/gpr/alloc.h index 762b51bf66..0bfc30ab40 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/alloc.h +++ b/contrib/libs/grpc/src/core/lib/gpr/alloc.h @@ -1,28 +1,28 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_GPR_ALLOC_H -#define GRPC_CORE_LIB_GPR_ALLOC_H - -#include <grpc/support/port_platform.h> - -/// Given a size, round up to the next multiple of sizeof(void*). -#define GPR_ROUND_UP_TO_ALIGNMENT_SIZE(x) \ - (((x) + GPR_MAX_ALIGNMENT - 1u) & ~(GPR_MAX_ALIGNMENT - 1u)) - -#endif /* GRPC_CORE_LIB_GPR_ALLOC_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_GPR_ALLOC_H +#define GRPC_CORE_LIB_GPR_ALLOC_H + +#include <grpc/support/port_platform.h> + +/// Given a size, round up to the next multiple of sizeof(void*). +#define GPR_ROUND_UP_TO_ALIGNMENT_SIZE(x) \ + (((x) + GPR_MAX_ALIGNMENT - 1u) & ~(GPR_MAX_ALIGNMENT - 1u)) + +#endif /* GRPC_CORE_LIB_GPR_ALLOC_H */ diff --git a/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc index bc02118d94..3cd3bdddcf 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc +++ b/contrib/libs/grpc/src/core/lib/gpr/log_posix.cc @@ -23,7 +23,7 @@ #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc/support/time.h> -#include <inttypes.h> +#include <inttypes.h> #include <pthread.h> #include <stdarg.h> #include <stdio.h> diff --git a/contrib/libs/grpc/src/core/lib/gpr/string.cc b/contrib/libs/grpc/src/core/lib/gpr/string.cc index 28f1ae437d..9d44b058aa 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/string.cc +++ b/contrib/libs/grpc/src/core/lib/gpr/string.cc @@ -23,10 +23,10 @@ #include <ctype.h> #include <limits.h> #include <stddef.h> -#include <stdio.h> +#include <stdio.h> #include <stdlib.h> #include <string.h> -#include <time.h> +#include <time.h> #include "y_absl/strings/str_cat.h" @@ -53,29 +53,29 @@ char* gpr_strdup(const char* src) { } TString gpr_format_timespec(gpr_timespec tm) { - char time_buffer[35]; - char ns_buffer[11]; // '.' + 9 digits of precision - struct tm* tm_info = localtime((const time_t*)&tm.tv_sec); - strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%dT%H:%M:%S", tm_info); - snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec); - // This loop trims off trailing zeros by inserting a null character that the - // right point. We iterate in chunks of three because we want 0, 3, 6, or 9 - // fractional digits. - for (int i = 7; i >= 1; i -= 3) { - if (ns_buffer[i] == '0' && ns_buffer[i + 1] == '0' && - ns_buffer[i + 2] == '0') { - ns_buffer[i] = '\0'; - // Edge case in which all fractional digits were 0. - if (i == 1) { - ns_buffer[0] = '\0'; - } - } else { - break; - } - } + char time_buffer[35]; + char ns_buffer[11]; // '.' + 9 digits of precision + struct tm* tm_info = localtime((const time_t*)&tm.tv_sec); + strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%dT%H:%M:%S", tm_info); + snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec); + // This loop trims off trailing zeros by inserting a null character that the + // right point. We iterate in chunks of three because we want 0, 3, 6, or 9 + // fractional digits. + for (int i = 7; i >= 1; i -= 3) { + if (ns_buffer[i] == '0' && ns_buffer[i + 1] == '0' && + ns_buffer[i + 2] == '0') { + ns_buffer[i] = '\0'; + // Edge case in which all fractional digits were 0. + if (i == 1) { + ns_buffer[0] = '\0'; + } + } else { + break; + } + } return y_absl::StrCat(time_buffer, ns_buffer, "Z"); -} - +} + struct dump_out { size_t capacity; size_t length; diff --git a/contrib/libs/grpc/src/core/lib/gpr/string.h b/contrib/libs/grpc/src/core/lib/gpr/string.h index 4b348198b8..6dc0d5ea5d 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/string.h +++ b/contrib/libs/grpc/src/core/lib/gpr/string.h @@ -21,8 +21,8 @@ #include <grpc/support/port_platform.h> -#include <grpc/impl/codegen/gpr_types.h> - +#include <grpc/impl/codegen/gpr_types.h> + #include <stdbool.h> #include <stddef.h> @@ -91,13 +91,13 @@ void gpr_string_split(const char* input, const char* sep, char*** strs, size_t* nstrs); /* Returns a string that represents tm according to RFC-3339, and, - more specifically, follows: - https://developers.google.com/protocol-buffers/docs/proto3#json - - Uses RFC 3339, where generated output will always be Z-normalized and uses - 0, 3, 6 or 9 fractional digits. */ + more specifically, follows: + https://developers.google.com/protocol-buffers/docs/proto3#json + + Uses RFC 3339, where generated output will always be Z-normalized and uses + 0, 3, 6 or 9 fractional digits. */ TString gpr_format_timespec(gpr_timespec); - + /** Case insensitive string comparison... return <0 if lower(a)<lower(b), ==0 if lower(a)==lower(b), >0 if lower(a)>lower(b) */ int gpr_stricmp(const char* a, const char* b); diff --git a/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc index fdd278be23..62486df63e 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc +++ b/contrib/libs/grpc/src/core/lib/gpr/sync_posix.cc @@ -114,8 +114,8 @@ void gpr_cv_destroy(gpr_cv* cv) { #else GPR_ASSERT(pthread_cond_destroy(cv) == 0); #endif -} - +} + int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) { int err = 0; if (gpr_time_cmp(abs_deadline, gpr_inf_future(abs_deadline.clock_type)) == @@ -138,7 +138,7 @@ int gpr_cv_wait(gpr_cv* cv, gpr_mu* mu, gpr_timespec abs_deadline) { err = pthread_cond_timedwait(&cv->cond_var, &mu->mutex, &abs_deadline_ts); #else err = pthread_cond_timedwait(cv, mu, &abs_deadline_ts); -#endif +#endif } GPR_ASSERT(err == 0 || err == ETIMEDOUT || err == EAGAIN); return err == ETIMEDOUT; diff --git a/contrib/libs/grpc/src/core/lib/gpr/time.cc b/contrib/libs/grpc/src/core/lib/gpr/time.cc index db5a7f64f7..ef8984026a 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/time.cc +++ b/contrib/libs/grpc/src/core/lib/gpr/time.cc @@ -135,10 +135,10 @@ gpr_timespec gpr_time_add(gpr_timespec a, gpr_timespec b) { gpr_timespec sum; int64_t inc = 0; GPR_ASSERT(b.clock_type == GPR_TIMESPAN); - // tv_nsec in a timespan is always +ve. -ve timespan is represented as (-ve - // tv_sec, +ve tv_nsec). For example, timespan = -2.5 seconds is represented - // as {-3, 5e8, GPR_TIMESPAN} - GPR_ASSERT(b.tv_nsec >= 0); + // tv_nsec in a timespan is always +ve. -ve timespan is represented as (-ve + // tv_sec, +ve tv_nsec). For example, timespan = -2.5 seconds is represented + // as {-3, 5e8, GPR_TIMESPAN} + GPR_ASSERT(b.tv_nsec >= 0); sum.clock_type = a.clock_type; sum.tv_nsec = a.tv_nsec + b.tv_nsec; if (sum.tv_nsec >= GPR_NS_PER_SEC) { @@ -169,10 +169,10 @@ gpr_timespec gpr_time_sub(gpr_timespec a, gpr_timespec b) { int64_t dec = 0; if (b.clock_type == GPR_TIMESPAN) { diff.clock_type = a.clock_type; - // tv_nsec in a timespan is always +ve. -ve timespan is represented as (-ve - // tv_sec, +ve tv_nsec). For example, timespan = -2.5 seconds is represented - // as {-3, 5e8, GPR_TIMESPAN} - GPR_ASSERT(b.tv_nsec >= 0); + // tv_nsec in a timespan is always +ve. -ve timespan is represented as (-ve + // tv_sec, +ve tv_nsec). For example, timespan = -2.5 seconds is represented + // as {-3, 5e8, GPR_TIMESPAN} + GPR_ASSERT(b.tv_nsec >= 0); } else { GPR_ASSERT(a.clock_type == b.clock_type); diff.clock_type = GPR_TIMESPAN; diff --git a/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc b/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc index 0a9e1158b3..74fb9f7735 100644 --- a/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc +++ b/contrib/libs/grpc/src/core/lib/gpr/time_posix.cc @@ -150,14 +150,14 @@ gpr_timespec gpr_now(gpr_clock_type clock_type) { #ifdef GPR_LOW_LEVEL_COUNTERS __atomic_fetch_add(&gpr_now_call_count, 1, __ATOMIC_RELAXED); #endif - // validate clock type - GPR_ASSERT(clock_type == GPR_CLOCK_MONOTONIC || - clock_type == GPR_CLOCK_REALTIME || - clock_type == GPR_CLOCK_PRECISE); - gpr_timespec ts = gpr_now_impl(clock_type); - // tv_nsecs must be in the range [0, 1e9). - GPR_ASSERT(ts.tv_nsec >= 0 && ts.tv_nsec < 1e9); - return ts; + // validate clock type + GPR_ASSERT(clock_type == GPR_CLOCK_MONOTONIC || + clock_type == GPR_CLOCK_REALTIME || + clock_type == GPR_CLOCK_PRECISE); + gpr_timespec ts = gpr_now_impl(clock_type); + // tv_nsecs must be in the range [0, 1e9). + GPR_ASSERT(ts.tv_nsec >= 0 && ts.tv_nsec < 1e9); + return ts; } void gpr_sleep_until(gpr_timespec until) { diff --git a/contrib/libs/grpc/src/core/lib/gprpp/fork.cc b/contrib/libs/grpc/src/core/lib/gprpp/fork.cc index 51d1c80e67..560939dce9 100644 --- a/contrib/libs/grpc/src/core/lib/gprpp/fork.cc +++ b/contrib/libs/grpc/src/core/lib/gprpp/fork.cc @@ -1,40 +1,40 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/gprpp/fork.h" - -#include <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/sync.h> -#include <grpc/support/time.h> - -#include "src/core/lib/gpr/useful.h" +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/gprpp/fork.h" + +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/sync.h> +#include <grpc/support/time.h> + +#include "src/core/lib/gpr/useful.h" #include "src/core/lib/gprpp/global_config.h" -#include "src/core/lib/gprpp/memory.h" - -/* - * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK - * AROUND VERY SPECIFIC USE CASES. - */ - +#include "src/core/lib/gprpp/memory.h" + +/* + * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK + * AROUND VERY SPECIFIC USE CASES. + */ + #ifdef GRPC_ENABLE_FORK_SUPPORT #define GRPC_ENABLE_FORK_SUPPORT_DEFAULT true #else @@ -45,198 +45,198 @@ GPR_GLOBAL_CONFIG_DEFINE_BOOL(grpc_enable_fork_support, GRPC_ENABLE_FORK_SUPPORT_DEFAULT, "Enable folk support"); -namespace grpc_core { -namespace internal { -// The exec_ctx_count has 2 modes, blocked and unblocked. -// When unblocked, the count is 2-indexed; exec_ctx_count=2 indicates -// 0 active ExecCtxs, exex_ctx_count=3 indicates 1 active ExecCtxs... - -// When blocked, the exec_ctx_count is 0-indexed. Note that ExecCtx -// creation can only be blocked if there is exactly 1 outstanding ExecCtx, -// meaning that BLOCKED and UNBLOCKED counts partition the integers -#define UNBLOCKED(n) (n + 2) -#define BLOCKED(n) (n) - -class ExecCtxState { - public: - ExecCtxState() : fork_complete_(true) { - gpr_mu_init(&mu_); - gpr_cv_init(&cv_); - gpr_atm_no_barrier_store(&count_, UNBLOCKED(0)); - } - - void IncExecCtxCount() { - gpr_atm count = gpr_atm_no_barrier_load(&count_); - while (true) { - if (count <= BLOCKED(1)) { - // This only occurs if we are trying to fork. Wait until the fork() - // operation completes before allowing new ExecCtxs. - gpr_mu_lock(&mu_); - if (gpr_atm_no_barrier_load(&count_) <= BLOCKED(1)) { - while (!fork_complete_) { - gpr_cv_wait(&cv_, &mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); - } - } - gpr_mu_unlock(&mu_); - } else if (gpr_atm_no_barrier_cas(&count_, count, count + 1)) { - break; - } - count = gpr_atm_no_barrier_load(&count_); - } - } - - void DecExecCtxCount() { gpr_atm_no_barrier_fetch_add(&count_, -1); } - - bool BlockExecCtx() { - // Assumes there is an active ExecCtx when this function is called - if (gpr_atm_no_barrier_cas(&count_, UNBLOCKED(1), BLOCKED(1))) { - gpr_mu_lock(&mu_); - fork_complete_ = false; - gpr_mu_unlock(&mu_); - return true; - } - return false; - } - - void AllowExecCtx() { - gpr_mu_lock(&mu_); - gpr_atm_no_barrier_store(&count_, UNBLOCKED(0)); - fork_complete_ = true; - gpr_cv_broadcast(&cv_); - gpr_mu_unlock(&mu_); - } - - ~ExecCtxState() { - gpr_mu_destroy(&mu_); - gpr_cv_destroy(&cv_); - } - - private: - bool fork_complete_; - gpr_mu mu_; - gpr_cv cv_; - gpr_atm count_; -}; - -class ThreadState { - public: - ThreadState() : awaiting_threads_(false), threads_done_(false), count_(0) { - gpr_mu_init(&mu_); - gpr_cv_init(&cv_); - } - - void IncThreadCount() { - gpr_mu_lock(&mu_); - count_++; - gpr_mu_unlock(&mu_); - } - - void DecThreadCount() { - gpr_mu_lock(&mu_); - count_--; - if (awaiting_threads_ && count_ == 0) { - threads_done_ = true; - gpr_cv_signal(&cv_); - } - gpr_mu_unlock(&mu_); - } - void AwaitThreads() { - gpr_mu_lock(&mu_); - awaiting_threads_ = true; - threads_done_ = (count_ == 0); - while (!threads_done_) { - gpr_cv_wait(&cv_, &mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); - } - awaiting_threads_ = true; - gpr_mu_unlock(&mu_); - } - - ~ThreadState() { - gpr_mu_destroy(&mu_); - gpr_cv_destroy(&cv_); - } - - private: - bool awaiting_threads_; - bool threads_done_; - gpr_mu mu_; - gpr_cv cv_; - int count_; -}; - +namespace grpc_core { +namespace internal { +// The exec_ctx_count has 2 modes, blocked and unblocked. +// When unblocked, the count is 2-indexed; exec_ctx_count=2 indicates +// 0 active ExecCtxs, exex_ctx_count=3 indicates 1 active ExecCtxs... + +// When blocked, the exec_ctx_count is 0-indexed. Note that ExecCtx +// creation can only be blocked if there is exactly 1 outstanding ExecCtx, +// meaning that BLOCKED and UNBLOCKED counts partition the integers +#define UNBLOCKED(n) (n + 2) +#define BLOCKED(n) (n) + +class ExecCtxState { + public: + ExecCtxState() : fork_complete_(true) { + gpr_mu_init(&mu_); + gpr_cv_init(&cv_); + gpr_atm_no_barrier_store(&count_, UNBLOCKED(0)); + } + + void IncExecCtxCount() { + gpr_atm count = gpr_atm_no_barrier_load(&count_); + while (true) { + if (count <= BLOCKED(1)) { + // This only occurs if we are trying to fork. Wait until the fork() + // operation completes before allowing new ExecCtxs. + gpr_mu_lock(&mu_); + if (gpr_atm_no_barrier_load(&count_) <= BLOCKED(1)) { + while (!fork_complete_) { + gpr_cv_wait(&cv_, &mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); + } + } + gpr_mu_unlock(&mu_); + } else if (gpr_atm_no_barrier_cas(&count_, count, count + 1)) { + break; + } + count = gpr_atm_no_barrier_load(&count_); + } + } + + void DecExecCtxCount() { gpr_atm_no_barrier_fetch_add(&count_, -1); } + + bool BlockExecCtx() { + // Assumes there is an active ExecCtx when this function is called + if (gpr_atm_no_barrier_cas(&count_, UNBLOCKED(1), BLOCKED(1))) { + gpr_mu_lock(&mu_); + fork_complete_ = false; + gpr_mu_unlock(&mu_); + return true; + } + return false; + } + + void AllowExecCtx() { + gpr_mu_lock(&mu_); + gpr_atm_no_barrier_store(&count_, UNBLOCKED(0)); + fork_complete_ = true; + gpr_cv_broadcast(&cv_); + gpr_mu_unlock(&mu_); + } + + ~ExecCtxState() { + gpr_mu_destroy(&mu_); + gpr_cv_destroy(&cv_); + } + + private: + bool fork_complete_; + gpr_mu mu_; + gpr_cv cv_; + gpr_atm count_; +}; + +class ThreadState { + public: + ThreadState() : awaiting_threads_(false), threads_done_(false), count_(0) { + gpr_mu_init(&mu_); + gpr_cv_init(&cv_); + } + + void IncThreadCount() { + gpr_mu_lock(&mu_); + count_++; + gpr_mu_unlock(&mu_); + } + + void DecThreadCount() { + gpr_mu_lock(&mu_); + count_--; + if (awaiting_threads_ && count_ == 0) { + threads_done_ = true; + gpr_cv_signal(&cv_); + } + gpr_mu_unlock(&mu_); + } + void AwaitThreads() { + gpr_mu_lock(&mu_); + awaiting_threads_ = true; + threads_done_ = (count_ == 0); + while (!threads_done_) { + gpr_cv_wait(&cv_, &mu_, gpr_inf_future(GPR_CLOCK_REALTIME)); + } + awaiting_threads_ = true; + gpr_mu_unlock(&mu_); + } + + ~ThreadState() { + gpr_mu_destroy(&mu_); + gpr_cv_destroy(&cv_); + } + + private: + bool awaiting_threads_; + bool threads_done_; + gpr_mu mu_; + gpr_cv cv_; + int count_; +}; + } // namespace internal - -void Fork::GlobalInit() { - if (!override_enabled_) { + +void Fork::GlobalInit() { + if (!override_enabled_) { support_enabled_.Store(GPR_GLOBAL_CONFIG_GET(grpc_enable_fork_support), MemoryOrder::RELAXED); - } + } if (support_enabled_.Load(MemoryOrder::RELAXED)) { exec_ctx_state_ = new internal::ExecCtxState(); thread_state_ = new internal::ThreadState(); - } -} - -void Fork::GlobalShutdown() { + } +} + +void Fork::GlobalShutdown() { if (support_enabled_.Load(MemoryOrder::RELAXED)) { delete exec_ctx_state_; delete thread_state_; - } -} - + } +} + bool Fork::Enabled() { return support_enabled_.Load(MemoryOrder::RELAXED); } - -// Testing Only -void Fork::Enable(bool enable) { - override_enabled_ = true; + +// Testing Only +void Fork::Enable(bool enable) { + override_enabled_ = true; support_enabled_.Store(enable, MemoryOrder::RELAXED); -} - +} + void Fork::DoIncExecCtxCount() { exec_ctx_state_->IncExecCtxCount(); } - + void Fork::DoDecExecCtxCount() { exec_ctx_state_->DecExecCtxCount(); } - -void Fork::SetResetChildPollingEngineFunc( - Fork::child_postfork_func reset_child_polling_engine) { - reset_child_polling_engine_ = reset_child_polling_engine; -} -Fork::child_postfork_func Fork::GetResetChildPollingEngineFunc() { - return reset_child_polling_engine_; -} - -bool Fork::BlockExecCtx() { + +void Fork::SetResetChildPollingEngineFunc( + Fork::child_postfork_func reset_child_polling_engine) { + reset_child_polling_engine_ = reset_child_polling_engine; +} +Fork::child_postfork_func Fork::GetResetChildPollingEngineFunc() { + return reset_child_polling_engine_; +} + +bool Fork::BlockExecCtx() { if (support_enabled_.Load(MemoryOrder::RELAXED)) { - return exec_ctx_state_->BlockExecCtx(); - } - return false; -} - -void Fork::AllowExecCtx() { + return exec_ctx_state_->BlockExecCtx(); + } + return false; +} + +void Fork::AllowExecCtx() { if (support_enabled_.Load(MemoryOrder::RELAXED)) { - exec_ctx_state_->AllowExecCtx(); - } -} - -void Fork::IncThreadCount() { + exec_ctx_state_->AllowExecCtx(); + } +} + +void Fork::IncThreadCount() { if (support_enabled_.Load(MemoryOrder::RELAXED)) { - thread_state_->IncThreadCount(); - } -} - -void Fork::DecThreadCount() { + thread_state_->IncThreadCount(); + } +} + +void Fork::DecThreadCount() { if (support_enabled_.Load(MemoryOrder::RELAXED)) { - thread_state_->DecThreadCount(); - } -} -void Fork::AwaitThreads() { + thread_state_->DecThreadCount(); + } +} +void Fork::AwaitThreads() { if (support_enabled_.Load(MemoryOrder::RELAXED)) { - thread_state_->AwaitThreads(); - } -} - -internal::ExecCtxState* Fork::exec_ctx_state_ = nullptr; -internal::ThreadState* Fork::thread_state_ = nullptr; + thread_state_->AwaitThreads(); + } +} + +internal::ExecCtxState* Fork::exec_ctx_state_ = nullptr; +internal::ThreadState* Fork::thread_state_ = nullptr; Atomic<bool> Fork::support_enabled_(false); -bool Fork::override_enabled_ = false; -Fork::child_postfork_func Fork::reset_child_polling_engine_ = nullptr; -} // namespace grpc_core +bool Fork::override_enabled_ = false; +Fork::child_postfork_func Fork::reset_child_polling_engine_ = nullptr; +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/gprpp/fork.h b/contrib/libs/grpc/src/core/lib/gprpp/fork.h index 3601d7ca92..03f5709476 100644 --- a/contrib/libs/grpc/src/core/lib/gprpp/fork.h +++ b/contrib/libs/grpc/src/core/lib/gprpp/fork.h @@ -1,103 +1,103 @@ -/* - * - * Copyright 2017 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_GPRPP_FORK_H -#define GRPC_CORE_LIB_GPRPP_FORK_H - +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_GPRPP_FORK_H +#define GRPC_CORE_LIB_GPRPP_FORK_H + #include <grpc/support/port_platform.h> #include "src/core/lib/gprpp/atomic.h" -/* - * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK - * AROUND VERY SPECIFIC USE CASES. - */ - -namespace grpc_core { - -namespace internal { -class ExecCtxState; -class ThreadState; -} // namespace internal - -class Fork { - public: - typedef void (*child_postfork_func)(void); - - static void GlobalInit(); - static void GlobalShutdown(); - - // Returns true if fork suppport is enabled, false otherwise - static bool Enabled(); - - // Increment the count of active ExecCtxs. - // Will block until a pending fork is complete if one is in progress. +/* + * NOTE: FORKING IS NOT GENERALLY SUPPORTED, THIS IS ONLY INTENDED TO WORK + * AROUND VERY SPECIFIC USE CASES. + */ + +namespace grpc_core { + +namespace internal { +class ExecCtxState; +class ThreadState; +} // namespace internal + +class Fork { + public: + typedef void (*child_postfork_func)(void); + + static void GlobalInit(); + static void GlobalShutdown(); + + // Returns true if fork suppport is enabled, false otherwise + static bool Enabled(); + + // Increment the count of active ExecCtxs. + // Will block until a pending fork is complete if one is in progress. static void IncExecCtxCount() { if (GPR_UNLIKELY(support_enabled_.Load(MemoryOrder::RELAXED))) { DoIncExecCtxCount(); } } - - // Decrement the count of active ExecCtxs + + // Decrement the count of active ExecCtxs static void DecExecCtxCount() { if (GPR_UNLIKELY(support_enabled_.Load(MemoryOrder::RELAXED))) { DoDecExecCtxCount(); } } - - // Provide a function that will be invoked in the child's postfork handler to - // reset the polling engine's internal state. - static void SetResetChildPollingEngineFunc( - child_postfork_func reset_child_polling_engine); - static child_postfork_func GetResetChildPollingEngineFunc(); - - // Check if there is a single active ExecCtx - // (the one used to invoke this function). If there are more, - // return false. Otherwise, return true and block creation of - // more ExecCtx s until AlloWExecCtx() is called - // - static bool BlockExecCtx(); - static void AllowExecCtx(); - - // Increment the count of active threads. - static void IncThreadCount(); - - // Decrement the count of active threads. - static void DecThreadCount(); - - // Await all core threads to be joined. - static void AwaitThreads(); - - // Test only: overrides environment variables/compile flags - // Must be called before grpc_init() - static void Enable(bool enable); - - private: + + // Provide a function that will be invoked in the child's postfork handler to + // reset the polling engine's internal state. + static void SetResetChildPollingEngineFunc( + child_postfork_func reset_child_polling_engine); + static child_postfork_func GetResetChildPollingEngineFunc(); + + // Check if there is a single active ExecCtx + // (the one used to invoke this function). If there are more, + // return false. Otherwise, return true and block creation of + // more ExecCtx s until AlloWExecCtx() is called + // + static bool BlockExecCtx(); + static void AllowExecCtx(); + + // Increment the count of active threads. + static void IncThreadCount(); + + // Decrement the count of active threads. + static void DecThreadCount(); + + // Await all core threads to be joined. + static void AwaitThreads(); + + // Test only: overrides environment variables/compile flags + // Must be called before grpc_init() + static void Enable(bool enable); + + private: static void DoIncExecCtxCount(); static void DoDecExecCtxCount(); - static internal::ExecCtxState* exec_ctx_state_; - static internal::ThreadState* thread_state_; + static internal::ExecCtxState* exec_ctx_state_; + static internal::ThreadState* thread_state_; static grpc_core::Atomic<bool> support_enabled_; - static bool override_enabled_; - static child_postfork_func reset_child_polling_engine_; -}; - -} // namespace grpc_core - -#endif /* GRPC_CORE_LIB_GPRPP_FORK_H */ + static bool override_enabled_; + static child_postfork_func reset_child_polling_engine_; +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_GPRPP_FORK_H */ diff --git a/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h b/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h index 79542de6dd..158ad79331 100644 --- a/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h +++ b/contrib/libs/grpc/src/core/lib/gprpp/orphanable.h @@ -30,7 +30,7 @@ #include "src/core/lib/debug/trace.h" #include "src/core/lib/gprpp/debug_location.h" #include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" namespace grpc_core { @@ -83,16 +83,16 @@ class InternallyRefCounted : public Orphanable { protected: // Allow RefCountedPtr<> to access Unref() and IncrementRefCount(). template <typename T> - friend class RefCountedPtr; + friend class RefCountedPtr; - // TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag. - // Note: RefCount tracing is only enabled on debug builds, even when a - // TraceFlag is used. - template <typename TraceFlagT = TraceFlag> + // TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag. + // Note: RefCount tracing is only enabled on debug builds, even when a + // TraceFlag is used. + template <typename TraceFlagT = TraceFlag> explicit InternallyRefCounted(TraceFlagT* trace_flag = nullptr, intptr_t initial_refcount = 1) : refs_(initial_refcount, trace_flag) {} - virtual ~InternallyRefCounted() = default; + virtual ~InternallyRefCounted() = default; RefCountedPtr<Child> Ref() GRPC_MUST_USE_RESULT { IncrementRefCount(); @@ -100,8 +100,8 @@ class InternallyRefCounted : public Orphanable { } RefCountedPtr<Child> Ref(const DebugLocation& location, const char* reason) GRPC_MUST_USE_RESULT { - IncrementRefCount(location, reason); - return RefCountedPtr<Child>(static_cast<Child*>(this)); + IncrementRefCount(location, reason); + return RefCountedPtr<Child>(static_cast<Child*>(this)); } void Unref() { @@ -116,12 +116,12 @@ class InternallyRefCounted : public Orphanable { } private: - void IncrementRefCount() { refs_.Ref(); } - void IncrementRefCount(const DebugLocation& location, const char* reason) { - refs_.Ref(location, reason); - } + void IncrementRefCount() { refs_.Ref(); } + void IncrementRefCount(const DebugLocation& location, const char* reason) { + refs_.Ref(location, reason); + } - grpc_core::RefCount refs_; + grpc_core::RefCount refs_; }; } // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h index d05ff6e44c..38780075f2 100644 --- a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h +++ b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted.h @@ -21,12 +21,12 @@ #include <grpc/support/port_platform.h> -#include <grpc/support/atm.h> +#include <grpc/support/atm.h> #include <grpc/support/log.h> #include <grpc/support/sync.h> -#include <atomic> -#include <cassert> +#include <atomic> +#include <cassert> #include <cinttypes> #include "src/core/lib/debug/trace.h" @@ -37,24 +37,24 @@ namespace grpc_core { -// RefCount is a simple atomic ref-count. -// -// This is a C++ implementation of gpr_refcount, with inline functions. Due to -// inline functions, this class is significantly more efficient than -// gpr_refcount and should be preferred over gpr_refcount whenever possible. -// -// TODO(soheil): Remove gpr_refcount after submitting the GRFC and the paragraph -// above. -class RefCount { - public: - using Value = intptr_t; +// RefCount is a simple atomic ref-count. +// +// This is a C++ implementation of gpr_refcount, with inline functions. Due to +// inline functions, this class is significantly more efficient than +// gpr_refcount and should be preferred over gpr_refcount whenever possible. +// +// TODO(soheil): Remove gpr_refcount after submitting the GRFC and the paragraph +// above. +class RefCount { + public: + using Value = intptr_t; - // `init` is the initial refcount stored in this object. - // - // TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag. - // Note: RefCount tracing is only enabled on debug builds, even when a - // TraceFlag is used. - template <typename TraceFlagT = TraceFlag> + // `init` is the initial refcount stored in this object. + // + // TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag. + // Note: RefCount tracing is only enabled on debug builds, even when a + // TraceFlag is used. + template <typename TraceFlagT = TraceFlag> constexpr explicit RefCount( Value init = 1, TraceFlagT* @@ -63,15 +63,15 @@ class RefCount { trace_flag #endif = nullptr) - : -#ifndef NDEBUG - trace_flag_(trace_flag), -#endif - value_(init) { - } - - // Increases the ref-count by `n`. - void Ref(Value n = 1) { + : +#ifndef NDEBUG + trace_flag_(trace_flag), +#endif + value_(init) { + } + + // Increases the ref-count by `n`. + void Ref(Value n = 1) { #ifndef NDEBUG const Value prior = value_.FetchAdd(n, MemoryOrder::RELAXED); if (trace_flag_ != nullptr && trace_flag_->enabled()) { @@ -81,54 +81,54 @@ class RefCount { #else value_.FetchAdd(n, MemoryOrder::RELAXED); #endif - } - void Ref(const DebugLocation& location, const char* reason, Value n = 1) { -#ifndef NDEBUG + } + void Ref(const DebugLocation& location, const char* reason, Value n = 1) { +#ifndef NDEBUG const Value prior = value_.FetchAdd(n, MemoryOrder::RELAXED); if (trace_flag_ != nullptr && trace_flag_->enabled()) { - gpr_log(GPR_INFO, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s", - trace_flag_->name(), this, location.file(), location.line(), + gpr_log(GPR_INFO, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s", + trace_flag_->name(), this, location.file(), location.line(), prior, prior + n, reason); - } + } #else // Use conditionally-important parameters (void)location; (void)reason; value_.FetchAdd(n, MemoryOrder::RELAXED); -#endif - } - - // Similar to Ref() with an assert on the ref-count being non-zero. - void RefNonZero() { -#ifndef NDEBUG +#endif + } + + // Similar to Ref() with an assert on the ref-count being non-zero. + void RefNonZero() { +#ifndef NDEBUG const Value prior = value_.FetchAdd(1, MemoryOrder::RELAXED); if (trace_flag_ != nullptr && trace_flag_->enabled()) { gpr_log(GPR_INFO, "%s:%p ref %" PRIdPTR " -> %" PRIdPTR, trace_flag_->name(), this, prior, prior + 1); } - assert(prior > 0); -#else + assert(prior > 0); +#else value_.FetchAdd(1, MemoryOrder::RELAXED); -#endif - } - void RefNonZero(const DebugLocation& location, const char* reason) { -#ifndef NDEBUG +#endif + } + void RefNonZero(const DebugLocation& location, const char* reason) { +#ifndef NDEBUG const Value prior = value_.FetchAdd(1, MemoryOrder::RELAXED); if (trace_flag_ != nullptr && trace_flag_->enabled()) { - gpr_log(GPR_INFO, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s", - trace_flag_->name(), this, location.file(), location.line(), + gpr_log(GPR_INFO, "%s:%p %s:%d ref %" PRIdPTR " -> %" PRIdPTR " %s", + trace_flag_->name(), this, location.file(), location.line(), prior, prior + 1, reason); - } + } assert(prior > 0); #else // Avoid unused-parameter warnings for debug-only parameters (void)location; (void)reason; RefNonZero(); -#endif - } - +#endif + } + bool RefIfNonZero() { #ifndef NDEBUG if (trace_flag_ != nullptr && trace_flag_->enabled()) { @@ -156,8 +156,8 @@ class RefCount { return value_.IncrementIfNonzero(); } - // Decrements the ref-count and returns true if the ref-count reaches 0. - bool Unref() { + // Decrements the ref-count and returns true if the ref-count reaches 0. + bool Unref() { #ifndef NDEBUG // Grab a copy of the trace flag before the atomic change, since we // can't safely access it afterwards if we're going to be freed. @@ -169,12 +169,12 @@ class RefCount { gpr_log(GPR_INFO, "%s:%p unref %" PRIdPTR " -> %" PRIdPTR, trace_flag->name(), this, prior, prior - 1); } - GPR_DEBUG_ASSERT(prior > 0); + GPR_DEBUG_ASSERT(prior > 0); #endif - return prior == 1; - } - bool Unref(const DebugLocation& location, const char* reason) { -#ifndef NDEBUG + return prior == 1; + } + bool Unref(const DebugLocation& location, const char* reason) { +#ifndef NDEBUG // Grab a copy of the trace flag before the atomic change, since we // can't safely access it afterwards if we're going to be freed. auto* trace_flag = trace_flag_; @@ -182,25 +182,25 @@ class RefCount { const Value prior = value_.FetchSub(1, MemoryOrder::ACQ_REL); #ifndef NDEBUG if (trace_flag != nullptr && trace_flag->enabled()) { - gpr_log(GPR_INFO, "%s:%p %s:%d unref %" PRIdPTR " -> %" PRIdPTR " %s", + gpr_log(GPR_INFO, "%s:%p %s:%d unref %" PRIdPTR " -> %" PRIdPTR " %s", trace_flag->name(), this, location.file(), location.line(), prior, prior - 1, reason); - } + } GPR_DEBUG_ASSERT(prior > 0); #else // Avoid unused-parameter warnings for debug-only parameters (void)location; (void)reason; -#endif +#endif return prior == 1; - } - + } + private: Value get() const { return value_.Load(MemoryOrder::RELAXED); } -#ifndef NDEBUG - TraceFlag* trace_flag_; -#endif +#ifndef NDEBUG + TraceFlag* trace_flag_; +#endif Atomic<Value> value_; }; @@ -233,10 +233,10 @@ class Delete<T, false> { }; } // namespace internal -// A base class for reference-counted objects. +// A base class for reference-counted objects. // New objects should be created via new and start with a refcount of 1. // When the refcount reaches 0, the object will be deleted via delete. -// +// // If DeleteUponUnref is false, deletion will not occur when the ref // count reaches 0. This is useful in cases where all existing objects // must be tracked in a registry but the object's entry in the registry @@ -244,31 +244,31 @@ class Delete<T, false> { // In this case, the registry can be cleaned up later by identifying // entries for which RefIfNonZero() returns null. // -// This will commonly be used by CRTP (curiously-recurring template pattern) -// e.g., class MyClass : public RefCounted<MyClass> -// -// Use PolymorphicRefCount and NonPolymorphicRefCount to select between -// different implementations of RefCounted. -// -// Note that NonPolymorphicRefCount does not support polymorphic destruction. -// So, use NonPolymorphicRefCount only when both of the following conditions -// are guaranteed to hold: -// (a) Child is a concrete leaf class in RefCounted<Child>, and +// This will commonly be used by CRTP (curiously-recurring template pattern) +// e.g., class MyClass : public RefCounted<MyClass> +// +// Use PolymorphicRefCount and NonPolymorphicRefCount to select between +// different implementations of RefCounted. +// +// Note that NonPolymorphicRefCount does not support polymorphic destruction. +// So, use NonPolymorphicRefCount only when both of the following conditions +// are guaranteed to hold: +// (a) Child is a concrete leaf class in RefCounted<Child>, and // (b) you are guaranteed to call Unref only on concrete leaf classes and not -// their parents. -// -// The following example is illegal, because calling Unref() will not call -// the dtor of Child. -// -// class Parent : public RefCounted<Parent, NonPolymorphicRefCount> {} -// class Child : public Parent {} -// -// Child* ch; -// ch->Unref(); -// +// their parents. +// +// The following example is illegal, because calling Unref() will not call +// the dtor of Child. +// +// class Parent : public RefCounted<Parent, NonPolymorphicRefCount> {} +// class Child : public Parent {} +// +// Child* ch; +// ch->Unref(); +// template <typename Child, typename Impl = PolymorphicRefCount, bool DeleteUponUnref = true> -class RefCounted : public Impl { +class RefCounted : public Impl { public: // Note: Depending on the Impl used, this dtor can be implicitly virtual. ~RefCounted() = default; @@ -280,13 +280,13 @@ class RefCounted : public Impl { RefCountedPtr<Child> Ref(const DebugLocation& location, const char* reason) GRPC_MUST_USE_RESULT { - IncrementRefCount(location, reason); - return RefCountedPtr<Child>(static_cast<Child*>(this)); + IncrementRefCount(location, reason); + return RefCountedPtr<Child>(static_cast<Child*>(this)); } // TODO(roth): Once all of our code is converted to C++ and can use - // RefCountedPtr<> instead of manual ref-counting, make this method - // private, since it will only be used by RefCountedPtr<>, which is a + // RefCountedPtr<> instead of manual ref-counting, make this method + // private, since it will only be used by RefCountedPtr<>, which is a // friend of this class. void Unref() { if (GPR_UNLIKELY(refs_.Unref())) { @@ -311,29 +311,29 @@ class RefCounted : public Impl { } // Not copyable nor movable. - RefCounted(const RefCounted&) = delete; - RefCounted& operator=(const RefCounted&) = delete; + RefCounted(const RefCounted&) = delete; + RefCounted& operator=(const RefCounted&) = delete; protected: - // TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag. - // Note: RefCount tracing is only enabled on debug builds, even when a - // TraceFlag is used. - template <typename TraceFlagT = TraceFlag> + // TraceFlagT is defined to accept both DebugOnlyTraceFlag and TraceFlag. + // Note: RefCount tracing is only enabled on debug builds, even when a + // TraceFlag is used. + template <typename TraceFlagT = TraceFlag> explicit RefCounted(TraceFlagT* trace_flag = nullptr, intptr_t initial_refcount = 1) : refs_(initial_refcount, trace_flag) {} private: // Allow RefCountedPtr<> to access IncrementRefCount(). - template <typename T> - friend class RefCountedPtr; + template <typename T> + friend class RefCountedPtr; - void IncrementRefCount() { refs_.Ref(); } - void IncrementRefCount(const DebugLocation& location, const char* reason) { - refs_.Ref(location, reason); - } + void IncrementRefCount() { refs_.Ref(); } + void IncrementRefCount(const DebugLocation& location, const char* reason) { + refs_.Ref(location, reason); + } - RefCount refs_; + RefCount refs_; }; } // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h index c28e762532..46f238cd1c 100644 --- a/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h +++ b/contrib/libs/grpc/src/core/lib/gprpp/ref_counted_ptr.h @@ -21,10 +21,10 @@ #include <grpc/support/port_platform.h> -#include <type_traits> +#include <type_traits> #include <utility> -#include "src/core/lib/gprpp/debug_location.h" +#include "src/core/lib/gprpp/debug_location.h" #include "src/core/lib/gprpp/memory.h" namespace grpc_core { @@ -38,66 +38,66 @@ class RefCountedPtr { RefCountedPtr(std::nullptr_t) {} // If value is non-null, we take ownership of a ref to it. - template <typename Y> - explicit RefCountedPtr(Y* value) { - value_ = value; - } + template <typename Y> + explicit RefCountedPtr(Y* value) { + value_ = value; + } - // Move ctors. + // Move ctors. RefCountedPtr(RefCountedPtr&& other) { value_ = other.value_; other.value_ = nullptr; } - template <typename Y> - RefCountedPtr(RefCountedPtr<Y>&& other) { - value_ = static_cast<T*>(other.value_); - other.value_ = nullptr; - } - - // Move assignment. + template <typename Y> + RefCountedPtr(RefCountedPtr<Y>&& other) { + value_ = static_cast<T*>(other.value_); + other.value_ = nullptr; + } + + // Move assignment. RefCountedPtr& operator=(RefCountedPtr&& other) { - reset(other.value_); - other.value_ = nullptr; - return *this; - } - template <typename Y> - RefCountedPtr& operator=(RefCountedPtr<Y>&& other) { - reset(other.value_); + reset(other.value_); other.value_ = nullptr; return *this; } + template <typename Y> + RefCountedPtr& operator=(RefCountedPtr<Y>&& other) { + reset(other.value_); + other.value_ = nullptr; + return *this; + } - // Copy ctors. + // Copy ctors. RefCountedPtr(const RefCountedPtr& other) { if (other.value_ != nullptr) other.value_->IncrementRefCount(); value_ = other.value_; } - template <typename Y> - RefCountedPtr(const RefCountedPtr<Y>& other) { - static_assert(std::has_virtual_destructor<T>::value, - "T does not have a virtual dtor"); - if (other.value_ != nullptr) other.value_->IncrementRefCount(); - value_ = static_cast<T*>(other.value_); - } - - // Copy assignment. + template <typename Y> + RefCountedPtr(const RefCountedPtr<Y>& other) { + static_assert(std::has_virtual_destructor<T>::value, + "T does not have a virtual dtor"); + if (other.value_ != nullptr) other.value_->IncrementRefCount(); + value_ = static_cast<T*>(other.value_); + } + + // Copy assignment. RefCountedPtr& operator=(const RefCountedPtr& other) { // Note: Order of reffing and unreffing is important here in case value_ // and other.value_ are the same object. if (other.value_ != nullptr) other.value_->IncrementRefCount(); - reset(other.value_); - return *this; - } - template <typename Y> - RefCountedPtr& operator=(const RefCountedPtr<Y>& other) { - static_assert(std::has_virtual_destructor<T>::value, - "T does not have a virtual dtor"); - // Note: Order of reffing and unreffing is important here in case value_ - // and other.value_ are the same object. - if (other.value_ != nullptr) other.value_->IncrementRefCount(); - reset(other.value_); + reset(other.value_); return *this; } + template <typename Y> + RefCountedPtr& operator=(const RefCountedPtr<Y>& other) { + static_assert(std::has_virtual_destructor<T>::value, + "T does not have a virtual dtor"); + // Note: Order of reffing and unreffing is important here in case value_ + // and other.value_ are the same object. + if (other.value_ != nullptr) other.value_->IncrementRefCount(); + reset(other.value_); + return *this; + } ~RefCountedPtr() { if (value_ != nullptr) value_->Unref(); @@ -110,26 +110,26 @@ class RefCountedPtr { if (value_ != nullptr) value_->Unref(); value_ = value; } - void reset(const DebugLocation& location, const char* reason, - T* value = nullptr) { - if (value_ != nullptr) value_->Unref(location, reason); - value_ = value; - } - template <typename Y> - void reset(Y* value = nullptr) { - static_assert(std::has_virtual_destructor<T>::value, - "T does not have a virtual dtor"); - if (value_ != nullptr) value_->Unref(); - value_ = static_cast<T*>(value); - } - template <typename Y> - void reset(const DebugLocation& location, const char* reason, - Y* value = nullptr) { - static_assert(std::has_virtual_destructor<T>::value, - "T does not have a virtual dtor"); - if (value_ != nullptr) value_->Unref(location, reason); - value_ = static_cast<T*>(value); - } + void reset(const DebugLocation& location, const char* reason, + T* value = nullptr) { + if (value_ != nullptr) value_->Unref(location, reason); + value_ = value; + } + template <typename Y> + void reset(Y* value = nullptr) { + static_assert(std::has_virtual_destructor<T>::value, + "T does not have a virtual dtor"); + if (value_ != nullptr) value_->Unref(); + value_ = static_cast<T*>(value); + } + template <typename Y> + void reset(const DebugLocation& location, const char* reason, + Y* value = nullptr) { + static_assert(std::has_virtual_destructor<T>::value, + "T does not have a virtual dtor"); + if (value_ != nullptr) value_->Unref(location, reason); + value_ = static_cast<T*>(value); + } // TODO(roth): This method exists solely as a transition mechanism to allow // us to pass a ref to idiomatic C code that does not use RefCountedPtr<>. @@ -146,34 +146,34 @@ class RefCountedPtr { T& operator*() const { return *value_; } T* operator->() const { return value_; } - template <typename Y> - bool operator==(const RefCountedPtr<Y>& other) const { + template <typename Y> + bool operator==(const RefCountedPtr<Y>& other) const { return value_ == other.value_; } - - template <typename Y> - bool operator==(const Y* other) const { - return value_ == other; - } - - bool operator==(std::nullptr_t) const { return value_ == nullptr; } - - template <typename Y> - bool operator!=(const RefCountedPtr<Y>& other) const { + + template <typename Y> + bool operator==(const Y* other) const { + return value_ == other; + } + + bool operator==(std::nullptr_t) const { return value_ == nullptr; } + + template <typename Y> + bool operator!=(const RefCountedPtr<Y>& other) const { return value_ != other.value_; } - template <typename Y> - bool operator!=(const Y* other) const { - return value_ != other; - } - - bool operator!=(std::nullptr_t) const { return value_ != nullptr; } - + template <typename Y> + bool operator!=(const Y* other) const { + return value_ != other; + } + + bool operator!=(std::nullptr_t) const { return value_ != nullptr; } + private: - template <typename Y> - friend class RefCountedPtr; - + template <typename Y> + friend class RefCountedPtr; + T* value_ = nullptr; }; diff --git a/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc b/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc index f6f6af9c26..eea200f5a8 100644 --- a/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc +++ b/contrib/libs/grpc/src/core/lib/gprpp/thd_posix.cc @@ -35,7 +35,7 @@ #include <unistd.h> #include "src/core/lib/gpr/useful.h" -#include "src/core/lib/gprpp/fork.h" +#include "src/core/lib/gprpp/fork.h" #include "src/core/lib/gprpp/memory.h" namespace grpc_core { @@ -136,7 +136,7 @@ class ThreadInternalsPosix : public internal::ThreadInternalsInterface { GPR_ASSERT(pthread_attr_destroy(&attr) == 0); - if (!(*success)) { + if (!(*success)) { /* don't use gpr_free, as this was allocated using malloc (see above) */ free(info); if (options.tracked()) { diff --git a/contrib/libs/grpc/src/core/lib/http/httpcli.cc b/contrib/libs/grpc/src/core/lib/http/httpcli.cc index c196a8faac..19b22977d5 100644 --- a/contrib/libs/grpc/src/core/lib/http/httpcli.cc +++ b/contrib/libs/grpc/src/core/lib/http/httpcli.cc @@ -166,7 +166,7 @@ static void done_write(void* arg, grpc_error* error) { static void start_write(internal_request* req) { grpc_slice_ref_internal(req->request_text); grpc_slice_buffer_add(&req->outgoing, req->request_text); - grpc_endpoint_write(req->ep, &req->outgoing, &req->done_write, nullptr); + grpc_endpoint_write(req->ep, &req->outgoing, &req->done_write, nullptr); } static void on_handshake_done(void* arg, grpc_endpoint* ep) { diff --git a/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc b/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc index 62643186ad..0ce3c30da3 100644 --- a/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc +++ b/contrib/libs/grpc/src/core/lib/http/httpcli_security_connector.cc @@ -32,125 +32,125 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/handshaker_registry.h" #include "src/core/lib/gpr/string.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/iomgr/pollset.h" -#include "src/core/lib/security/credentials/credentials.h" -#include "src/core/lib/security/security_connector/ssl_utils.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/iomgr/pollset.h" +#include "src/core/lib/security/credentials/credentials.h" +#include "src/core/lib/security/security_connector/ssl_utils.h" #include "src/core/lib/security/transport/security_handshaker.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/tsi/ssl_transport_security.h" -class grpc_httpcli_ssl_channel_security_connector final - : public grpc_channel_security_connector { - public: +class grpc_httpcli_ssl_channel_security_connector final + : public grpc_channel_security_connector { + public: grpc_httpcli_ssl_channel_security_connector(char* secure_peer_name) - : grpc_channel_security_connector( - /*url_scheme=*/nullptr, - /*channel_creds=*/nullptr, - /*request_metadata_creds=*/nullptr), - secure_peer_name_(secure_peer_name) {} - - ~grpc_httpcli_ssl_channel_security_connector() override { - if (handshaker_factory_ != nullptr) { - tsi_ssl_client_handshaker_factory_unref(handshaker_factory_); - } - if (secure_peer_name_ != nullptr) { - gpr_free(secure_peer_name_); - } - } - - tsi_result InitHandshakerFactory(const char* pem_root_certs, - const tsi_ssl_root_certs_store* root_store) { - tsi_ssl_client_handshaker_options options; - options.pem_root_certs = pem_root_certs; - options.root_store = root_store; - return tsi_create_ssl_client_handshaker_factory_with_options( - &options, &handshaker_factory_); + : grpc_channel_security_connector( + /*url_scheme=*/nullptr, + /*channel_creds=*/nullptr, + /*request_metadata_creds=*/nullptr), + secure_peer_name_(secure_peer_name) {} + + ~grpc_httpcli_ssl_channel_security_connector() override { + if (handshaker_factory_ != nullptr) { + tsi_ssl_client_handshaker_factory_unref(handshaker_factory_); + } + if (secure_peer_name_ != nullptr) { + gpr_free(secure_peer_name_); + } } + tsi_result InitHandshakerFactory(const char* pem_root_certs, + const tsi_ssl_root_certs_store* root_store) { + tsi_ssl_client_handshaker_options options; + options.pem_root_certs = pem_root_certs; + options.root_store = root_store; + return tsi_create_ssl_client_handshaker_factory_with_options( + &options, &handshaker_factory_); + } + void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_mgr) override { - tsi_handshaker* handshaker = nullptr; - if (handshaker_factory_ != nullptr) { - tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( - handshaker_factory_, secure_peer_name_, &handshaker); - if (result != TSI_OK) { - gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", - tsi_result_to_string(result)); - } + grpc_core::HandshakeManager* handshake_mgr) override { + tsi_handshaker* handshaker = nullptr; + if (handshaker_factory_ != nullptr) { + tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( + handshaker_factory_, secure_peer_name_, &handshaker); + if (result != TSI_OK) { + gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", + tsi_result_to_string(result)); + } } handshake_mgr->Add( grpc_core::SecurityHandshakerCreate(handshaker, this, args)); } - tsi_ssl_client_handshaker_factory* handshaker_factory() const { - return handshaker_factory_; - } + tsi_ssl_client_handshaker_factory* handshaker_factory() const { + return handshaker_factory_; + } void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* /*auth_context*/, - grpc_closure* on_peer_checked) override { - grpc_error* error = GRPC_ERROR_NONE; - - /* Check the peer name. */ - if (secure_peer_name_ != nullptr && - !tsi_ssl_peer_matches_name(&peer, secure_peer_name_)) { + grpc_core::RefCountedPtr<grpc_auth_context>* /*auth_context*/, + grpc_closure* on_peer_checked) override { + grpc_error* error = GRPC_ERROR_NONE; + + /* Check the peer name. */ + if (secure_peer_name_ != nullptr && + !tsi_ssl_peer_matches_name(&peer, secure_peer_name_)) { error = GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("Peer name ", secure_peer_name_, " is not in peer certificate") .c_str()); - } + } grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); - tsi_peer_destruct(&peer); + tsi_peer_destruct(&peer); } - int cmp(const grpc_security_connector* other_sc) const override { - auto* other = - reinterpret_cast<const grpc_httpcli_ssl_channel_security_connector*>( - other_sc); - return strcmp(secure_peer_name_, other->secure_peer_name_); - } + int cmp(const grpc_security_connector* other_sc) const override { + auto* other = + reinterpret_cast<const grpc_httpcli_ssl_channel_security_connector*>( + other_sc); + return strcmp(secure_peer_name_, other->secure_peer_name_); + } bool check_call_host(y_absl::string_view /*host*/, grpc_auth_context* /*auth_context*/, grpc_closure* /*on_call_host_checked*/, - grpc_error** error) override { - *error = GRPC_ERROR_NONE; - return true; - } + grpc_error** error) override { + *error = GRPC_ERROR_NONE; + return true; + } void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/, - grpc_error* error) override { - GRPC_ERROR_UNREF(error); - } - - const char* secure_peer_name() const { return secure_peer_name_; } - - private: - tsi_ssl_client_handshaker_factory* handshaker_factory_ = nullptr; - char* secure_peer_name_; -}; - -static grpc_core::RefCountedPtr<grpc_channel_security_connector> -httpcli_ssl_channel_security_connector_create( + grpc_error* error) override { + GRPC_ERROR_UNREF(error); + } + + const char* secure_peer_name() const { return secure_peer_name_; } + + private: + tsi_ssl_client_handshaker_factory* handshaker_factory_ = nullptr; + char* secure_peer_name_; +}; + +static grpc_core::RefCountedPtr<grpc_channel_security_connector> +httpcli_ssl_channel_security_connector_create( const char* pem_root_certs, const tsi_ssl_root_certs_store* root_store, const char* secure_peer_name, grpc_channel_args* /*channel_args*/) { if (secure_peer_name != nullptr && pem_root_certs == nullptr) { gpr_log(GPR_ERROR, "Cannot assert a secure peer name without a trust root."); - return nullptr; + return nullptr; } - grpc_core::RefCountedPtr<grpc_httpcli_ssl_channel_security_connector> c = - grpc_core::MakeRefCounted<grpc_httpcli_ssl_channel_security_connector>( - secure_peer_name == nullptr ? nullptr : gpr_strdup(secure_peer_name)); - tsi_result result = c->InitHandshakerFactory(pem_root_certs, root_store); + grpc_core::RefCountedPtr<grpc_httpcli_ssl_channel_security_connector> c = + grpc_core::MakeRefCounted<grpc_httpcli_ssl_channel_security_connector>( + secure_peer_name == nullptr ? nullptr : gpr_strdup(secure_peer_name)); + tsi_result result = c->InitHandshakerFactory(pem_root_certs, root_store); if (result != TSI_OK) { gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", tsi_result_to_string(result)); - return nullptr; + return nullptr; } - return c; + return c; } /* handshaker */ @@ -158,10 +158,10 @@ httpcli_ssl_channel_security_connector_create( struct on_done_closure { void (*func)(void* arg, grpc_endpoint* endpoint); void* arg; - grpc_core::RefCountedPtr<grpc_core::HandshakeManager> handshake_mgr; + grpc_core::RefCountedPtr<grpc_core::HandshakeManager> handshake_mgr; }; static void on_handshake_done(void* arg, grpc_error* error) { - auto* args = static_cast<grpc_core::HandshakerArgs*>(arg); + auto* args = static_cast<grpc_core::HandshakerArgs*>(arg); on_done_closure* c = static_cast<on_done_closure*>(args->user_data); if (error != GRPC_ERROR_NONE) { const char* msg = grpc_error_string(error); @@ -193,22 +193,22 @@ static void ssl_handshake(void* arg, grpc_endpoint* tcp, const char* host, } c->func = on_done; c->arg = arg; - grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = + grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = httpcli_ssl_channel_security_connector_create( pem_root_certs, root_store, host, static_cast<grpc_core::HandshakerArgs*>(arg)->args); - GPR_ASSERT(sc != nullptr); - grpc_arg channel_arg = grpc_security_connector_to_arg(sc.get()); + GPR_ASSERT(sc != nullptr); + grpc_arg channel_arg = grpc_security_connector_to_arg(sc.get()); grpc_channel_args args = {1, &channel_arg}; - c->handshake_mgr = grpc_core::MakeRefCounted<grpc_core::HandshakeManager>(); - grpc_core::HandshakerRegistry::AddHandshakers( - grpc_core::HANDSHAKER_CLIENT, &args, /*interested_parties=*/nullptr, - c->handshake_mgr.get()); - c->handshake_mgr->DoHandshake(tcp, /*channel_args=*/nullptr, deadline, - /*acceptor=*/nullptr, on_handshake_done, - /*user_data=*/c); - sc.reset(DEBUG_LOCATION, "httpcli"); + c->handshake_mgr = grpc_core::MakeRefCounted<grpc_core::HandshakeManager>(); + grpc_core::HandshakerRegistry::AddHandshakers( + grpc_core::HANDSHAKER_CLIENT, &args, /*interested_parties=*/nullptr, + c->handshake_mgr.get()); + c->handshake_mgr->DoHandshake(tcp, /*channel_args=*/nullptr, deadline, + /*acceptor=*/nullptr, on_handshake_done, + /*user_data=*/c); + sc.reset(DEBUG_LOCATION, "httpcli"); } const grpc_httpcli_handshaker grpc_httpcli_ssl = {"https", ssl_handshake}; diff --git a/contrib/libs/grpc/src/core/lib/http/parser.h b/contrib/libs/grpc/src/core/lib/http/parser.h index 2da21903e6..aefc2c7b34 100644 --- a/contrib/libs/grpc/src/core/lib/http/parser.h +++ b/contrib/libs/grpc/src/core/lib/http/parser.h @@ -70,13 +70,13 @@ typedef struct grpc_http_request { /* A response */ typedef struct grpc_http_response { /* HTTP status code */ - int status = 0; + int status = 0; /* Headers: count and key/values */ - size_t hdr_count = 0; - grpc_http_header* hdrs = nullptr; + size_t hdr_count = 0; + grpc_http_header* hdrs = nullptr; /* Body: length and contents; contents are NOT null-terminated */ - size_t body_length = 0; - char* body = nullptr; + size_t body_length = 0; + char* body = nullptr; } grpc_http_response; struct grpc_http_parser { diff --git a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc index e1b87da4d0..7e9f372b6b 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.cc @@ -1,308 +1,308 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/buffer_list.h" -#include "src/core/lib/iomgr/port.h" - -#include <grpc/support/log.h> - -#ifdef GRPC_LINUX_ERRQUEUE -#include <netinet/in.h> -#include <string.h> -#include <time.h> - -#include "src/core/lib/gprpp/memory.h" - -namespace grpc_core { -namespace { -/** Fills gpr_timespec gts based on values from timespec ts */ -void fill_gpr_from_timestamp(gpr_timespec* gts, const struct timespec* ts) { - gts->tv_sec = ts->tv_sec; - gts->tv_nsec = static_cast<int32_t>(ts->tv_nsec); - gts->clock_type = GPR_CLOCK_REALTIME; -} - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/buffer_list.h" +#include "src/core/lib/iomgr/port.h" + +#include <grpc/support/log.h> + +#ifdef GRPC_LINUX_ERRQUEUE +#include <netinet/in.h> +#include <string.h> +#include <time.h> + +#include "src/core/lib/gprpp/memory.h" + +namespace grpc_core { +namespace { +/** Fills gpr_timespec gts based on values from timespec ts */ +void fill_gpr_from_timestamp(gpr_timespec* gts, const struct timespec* ts) { + gts->tv_sec = ts->tv_sec; + gts->tv_nsec = static_cast<int32_t>(ts->tv_nsec); + gts->clock_type = GPR_CLOCK_REALTIME; +} + void default_timestamps_callback(void* /*arg*/, grpc_core::Timestamps* /*ts*/, grpc_error* /*shudown_err*/) { - gpr_log(GPR_DEBUG, "Timestamps callback has not been registered"); -} - -/** The saved callback function that will be invoked when we get all the - * timestamps that we are going to get for a TracedBuffer. */ -void (*timestamps_callback)(void*, grpc_core::Timestamps*, - grpc_error* shutdown_err) = - default_timestamps_callback; - -/* Used to extract individual opt stats from cmsg, so as to avoid troubles with - * unaligned reads */ -template <typename T> -T read_unaligned(const void* ptr) { - T val; - memcpy(&val, ptr, sizeof(val)); - return val; -} - -/* Extracts opt stats from the tcp_info struct \a info to \a metrics */ -void extract_opt_stats_from_tcp_info(ConnectionMetrics* metrics, - const grpc_core::tcp_info* info) { - if (info == nullptr) { - return; - } - if (info->length > offsetof(grpc_core::tcp_info, tcpi_sndbuf_limited)) { + gpr_log(GPR_DEBUG, "Timestamps callback has not been registered"); +} + +/** The saved callback function that will be invoked when we get all the + * timestamps that we are going to get for a TracedBuffer. */ +void (*timestamps_callback)(void*, grpc_core::Timestamps*, + grpc_error* shutdown_err) = + default_timestamps_callback; + +/* Used to extract individual opt stats from cmsg, so as to avoid troubles with + * unaligned reads */ +template <typename T> +T read_unaligned(const void* ptr) { + T val; + memcpy(&val, ptr, sizeof(val)); + return val; +} + +/* Extracts opt stats from the tcp_info struct \a info to \a metrics */ +void extract_opt_stats_from_tcp_info(ConnectionMetrics* metrics, + const grpc_core::tcp_info* info) { + if (info == nullptr) { + return; + } + if (info->length > offsetof(grpc_core::tcp_info, tcpi_sndbuf_limited)) { metrics->recurring_retrans.emplace(info->tcpi_retransmits); metrics->is_delivery_rate_app_limited.emplace( - info->tcpi_delivery_rate_app_limited); + info->tcpi_delivery_rate_app_limited); metrics->congestion_window.emplace(info->tcpi_snd_cwnd); metrics->reordering.emplace(info->tcpi_reordering); metrics->packet_retx.emplace(info->tcpi_total_retrans); metrics->pacing_rate.emplace(info->tcpi_pacing_rate); metrics->data_notsent.emplace(info->tcpi_notsent_bytes); - if (info->tcpi_min_rtt != UINT32_MAX) { + if (info->tcpi_min_rtt != UINT32_MAX) { metrics->min_rtt.emplace(info->tcpi_min_rtt); - } + } metrics->packet_sent.emplace(info->tcpi_data_segs_out); metrics->delivery_rate.emplace(info->tcpi_delivery_rate); metrics->busy_usec.emplace(info->tcpi_busy_time); metrics->rwnd_limited_usec.emplace(info->tcpi_rwnd_limited); metrics->sndbuf_limited_usec.emplace(info->tcpi_sndbuf_limited); - } - if (info->length > offsetof(grpc_core::tcp_info, tcpi_dsack_dups)) { + } + if (info->length > offsetof(grpc_core::tcp_info, tcpi_dsack_dups)) { metrics->data_sent.emplace(info->tcpi_bytes_sent); metrics->data_retx.emplace(info->tcpi_bytes_retrans); metrics->packet_spurious_retx.emplace(info->tcpi_dsack_dups); - } -} - -/** Extracts opt stats from the given control message \a opt_stats to the - * connection metrics \a metrics */ -void extract_opt_stats_from_cmsg(ConnectionMetrics* metrics, - const cmsghdr* opt_stats) { - if (opt_stats == nullptr) { - return; - } - const auto* data = CMSG_DATA(opt_stats); - constexpr int64_t cmsg_hdr_len = CMSG_ALIGN(sizeof(struct cmsghdr)); - const int64_t len = opt_stats->cmsg_len - cmsg_hdr_len; - int64_t offset = 0; - - while (offset < len) { - const auto* attr = reinterpret_cast<const nlattr*>(data + offset); - const void* val = data + offset + NLA_HDRLEN; - switch (attr->nla_type) { - case TCP_NLA_BUSY: { + } +} + +/** Extracts opt stats from the given control message \a opt_stats to the + * connection metrics \a metrics */ +void extract_opt_stats_from_cmsg(ConnectionMetrics* metrics, + const cmsghdr* opt_stats) { + if (opt_stats == nullptr) { + return; + } + const auto* data = CMSG_DATA(opt_stats); + constexpr int64_t cmsg_hdr_len = CMSG_ALIGN(sizeof(struct cmsghdr)); + const int64_t len = opt_stats->cmsg_len - cmsg_hdr_len; + int64_t offset = 0; + + while (offset < len) { + const auto* attr = reinterpret_cast<const nlattr*>(data + offset); + const void* val = data + offset + NLA_HDRLEN; + switch (attr->nla_type) { + case TCP_NLA_BUSY: { metrics->busy_usec.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_RWND_LIMITED: { + break; + } + case TCP_NLA_RWND_LIMITED: { metrics->rwnd_limited_usec.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_SNDBUF_LIMITED: { + break; + } + case TCP_NLA_SNDBUF_LIMITED: { metrics->sndbuf_limited_usec.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_PACING_RATE: { + break; + } + case TCP_NLA_PACING_RATE: { metrics->pacing_rate.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_DELIVERY_RATE: { + break; + } + case TCP_NLA_DELIVERY_RATE: { metrics->delivery_rate.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_DELIVERY_RATE_APP_LMT: { + break; + } + case TCP_NLA_DELIVERY_RATE_APP_LMT: { metrics->is_delivery_rate_app_limited.emplace( read_unaligned<uint8_t>(val)); - break; - } - case TCP_NLA_SND_CWND: { + break; + } + case TCP_NLA_SND_CWND: { metrics->congestion_window.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_MIN_RTT: { + break; + } + case TCP_NLA_MIN_RTT: { metrics->min_rtt.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_SRTT: { + break; + } + case TCP_NLA_SRTT: { metrics->srtt.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_RECUR_RETRANS: { + break; + } + case TCP_NLA_RECUR_RETRANS: { metrics->recurring_retrans.emplace(read_unaligned<uint8_t>(val)); - break; - } - case TCP_NLA_BYTES_SENT: { + break; + } + case TCP_NLA_BYTES_SENT: { metrics->data_sent.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_DATA_SEGS_OUT: { + break; + } + case TCP_NLA_DATA_SEGS_OUT: { metrics->packet_sent.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_TOTAL_RETRANS: { + break; + } + case TCP_NLA_TOTAL_RETRANS: { metrics->packet_retx.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_DELIVERED: { + break; + } + case TCP_NLA_DELIVERED: { metrics->packet_delivered.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_DELIVERED_CE: { + break; + } + case TCP_NLA_DELIVERED_CE: { metrics->packet_delivered_ce.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_BYTES_RETRANS: { + break; + } + case TCP_NLA_BYTES_RETRANS: { metrics->data_retx.emplace(read_unaligned<uint64_t>(val)); - break; - } - case TCP_NLA_DSACK_DUPS: { + break; + } + case TCP_NLA_DSACK_DUPS: { metrics->packet_spurious_retx.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_REORDERING: { + break; + } + case TCP_NLA_REORDERING: { metrics->reordering.emplace(read_unaligned<uint32_t>(val)); - break; - } - case TCP_NLA_SND_SSTHRESH: { + break; + } + case TCP_NLA_SND_SSTHRESH: { metrics->snd_ssthresh.emplace(read_unaligned<uint32_t>(val)); - break; - } - } - offset += NLA_ALIGN(attr->nla_len); - } -} - -static int get_socket_tcp_info(grpc_core::tcp_info* info, int fd) { - memset(info, 0, sizeof(*info)); - info->length = sizeof(*info) - sizeof(socklen_t); - return getsockopt(fd, IPPROTO_TCP, TCP_INFO, info, &(info->length)); -} -} /* namespace */ - -void TracedBuffer::AddNewEntry(TracedBuffer** head, uint32_t seq_no, int fd, - void* arg) { - GPR_DEBUG_ASSERT(head != nullptr); + break; + } + } + offset += NLA_ALIGN(attr->nla_len); + } +} + +static int get_socket_tcp_info(grpc_core::tcp_info* info, int fd) { + memset(info, 0, sizeof(*info)); + info->length = sizeof(*info) - sizeof(socklen_t); + return getsockopt(fd, IPPROTO_TCP, TCP_INFO, info, &(info->length)); +} +} /* namespace */ + +void TracedBuffer::AddNewEntry(TracedBuffer** head, uint32_t seq_no, int fd, + void* arg) { + GPR_DEBUG_ASSERT(head != nullptr); TracedBuffer* new_elem = new TracedBuffer(seq_no, arg); - /* Store the current time as the sendmsg time. */ - new_elem->ts_.sendmsg_time.time = gpr_now(GPR_CLOCK_REALTIME); - new_elem->ts_.scheduled_time.time = gpr_inf_past(GPR_CLOCK_REALTIME); - new_elem->ts_.sent_time.time = gpr_inf_past(GPR_CLOCK_REALTIME); - new_elem->ts_.acked_time.time = gpr_inf_past(GPR_CLOCK_REALTIME); - - if (get_socket_tcp_info(&new_elem->ts_.info, fd) == 0) { - extract_opt_stats_from_tcp_info(&new_elem->ts_.sendmsg_time.metrics, - &new_elem->ts_.info); - } - if (*head == nullptr) { - *head = new_elem; - return; - } - /* Append at the end. */ - TracedBuffer* ptr = *head; - while (ptr->next_ != nullptr) { - ptr = ptr->next_; - } - ptr->next_ = new_elem; -} - -void TracedBuffer::ProcessTimestamp(TracedBuffer** head, - struct sock_extended_err* serr, - struct cmsghdr* opt_stats, - struct scm_timestamping* tss) { - GPR_DEBUG_ASSERT(head != nullptr); - TracedBuffer* elem = *head; - TracedBuffer* next = nullptr; - while (elem != nullptr) { - /* The byte number refers to the sequence number of the last byte which this - * timestamp relates to. */ - if (serr->ee_data >= elem->seq_no_) { - switch (serr->ee_info) { - case SCM_TSTAMP_SCHED: - fill_gpr_from_timestamp(&(elem->ts_.scheduled_time.time), - &(tss->ts[0])); - extract_opt_stats_from_cmsg(&(elem->ts_.scheduled_time.metrics), - opt_stats); - elem = elem->next_; - break; - case SCM_TSTAMP_SND: - fill_gpr_from_timestamp(&(elem->ts_.sent_time.time), &(tss->ts[0])); - extract_opt_stats_from_cmsg(&(elem->ts_.sent_time.metrics), - opt_stats); - elem = elem->next_; - break; - case SCM_TSTAMP_ACK: - fill_gpr_from_timestamp(&(elem->ts_.acked_time.time), &(tss->ts[0])); - extract_opt_stats_from_cmsg(&(elem->ts_.acked_time.metrics), - opt_stats); - /* Got all timestamps. Do the callback and free this TracedBuffer. - * The thing below can be passed by value if we don't want the - * restriction on the lifetime. */ - timestamps_callback(elem->arg_, &(elem->ts_), GRPC_ERROR_NONE); - next = elem->next_; + /* Store the current time as the sendmsg time. */ + new_elem->ts_.sendmsg_time.time = gpr_now(GPR_CLOCK_REALTIME); + new_elem->ts_.scheduled_time.time = gpr_inf_past(GPR_CLOCK_REALTIME); + new_elem->ts_.sent_time.time = gpr_inf_past(GPR_CLOCK_REALTIME); + new_elem->ts_.acked_time.time = gpr_inf_past(GPR_CLOCK_REALTIME); + + if (get_socket_tcp_info(&new_elem->ts_.info, fd) == 0) { + extract_opt_stats_from_tcp_info(&new_elem->ts_.sendmsg_time.metrics, + &new_elem->ts_.info); + } + if (*head == nullptr) { + *head = new_elem; + return; + } + /* Append at the end. */ + TracedBuffer* ptr = *head; + while (ptr->next_ != nullptr) { + ptr = ptr->next_; + } + ptr->next_ = new_elem; +} + +void TracedBuffer::ProcessTimestamp(TracedBuffer** head, + struct sock_extended_err* serr, + struct cmsghdr* opt_stats, + struct scm_timestamping* tss) { + GPR_DEBUG_ASSERT(head != nullptr); + TracedBuffer* elem = *head; + TracedBuffer* next = nullptr; + while (elem != nullptr) { + /* The byte number refers to the sequence number of the last byte which this + * timestamp relates to. */ + if (serr->ee_data >= elem->seq_no_) { + switch (serr->ee_info) { + case SCM_TSTAMP_SCHED: + fill_gpr_from_timestamp(&(elem->ts_.scheduled_time.time), + &(tss->ts[0])); + extract_opt_stats_from_cmsg(&(elem->ts_.scheduled_time.metrics), + opt_stats); + elem = elem->next_; + break; + case SCM_TSTAMP_SND: + fill_gpr_from_timestamp(&(elem->ts_.sent_time.time), &(tss->ts[0])); + extract_opt_stats_from_cmsg(&(elem->ts_.sent_time.metrics), + opt_stats); + elem = elem->next_; + break; + case SCM_TSTAMP_ACK: + fill_gpr_from_timestamp(&(elem->ts_.acked_time.time), &(tss->ts[0])); + extract_opt_stats_from_cmsg(&(elem->ts_.acked_time.metrics), + opt_stats); + /* Got all timestamps. Do the callback and free this TracedBuffer. + * The thing below can be passed by value if we don't want the + * restriction on the lifetime. */ + timestamps_callback(elem->arg_, &(elem->ts_), GRPC_ERROR_NONE); + next = elem->next_; delete static_cast<TracedBuffer*>(elem); - *head = elem = next; - break; - default: - abort(); - } - } else { - break; - } - } -} - -void TracedBuffer::Shutdown(TracedBuffer** head, void* remaining, - grpc_error* shutdown_err) { - GPR_DEBUG_ASSERT(head != nullptr); - TracedBuffer* elem = *head; - while (elem != nullptr) { - timestamps_callback(elem->arg_, &(elem->ts_), shutdown_err); - auto* next = elem->next_; + *head = elem = next; + break; + default: + abort(); + } + } else { + break; + } + } +} + +void TracedBuffer::Shutdown(TracedBuffer** head, void* remaining, + grpc_error* shutdown_err) { + GPR_DEBUG_ASSERT(head != nullptr); + TracedBuffer* elem = *head; + while (elem != nullptr) { + timestamps_callback(elem->arg_, &(elem->ts_), shutdown_err); + auto* next = elem->next_; delete elem; - elem = next; - } - *head = nullptr; - if (remaining != nullptr) { - timestamps_callback(remaining, nullptr, shutdown_err); - } - GRPC_ERROR_UNREF(shutdown_err); -} - -void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*, - grpc_core::Timestamps*, - grpc_error* error)) { - timestamps_callback = fn; -} -} /* namespace grpc_core */ - -#else /* GRPC_LINUX_ERRQUEUE */ - -namespace grpc_core { -void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*, - grpc_core::Timestamps*, - grpc_error* error)) { + elem = next; + } + *head = nullptr; + if (remaining != nullptr) { + timestamps_callback(remaining, nullptr, shutdown_err); + } + GRPC_ERROR_UNREF(shutdown_err); +} + +void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*, + grpc_core::Timestamps*, + grpc_error* error)) { + timestamps_callback = fn; +} +} /* namespace grpc_core */ + +#else /* GRPC_LINUX_ERRQUEUE */ + +namespace grpc_core { +void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*, + grpc_core::Timestamps*, + grpc_error* error)) { // Cast value of fn to void to avoid unused parameter warning. // Can't comment out the name because some compilers and formatters don't // like the sequence */* , which would arise from */*fn*/. (void)fn; - gpr_log(GPR_DEBUG, "Timestamps callback is not enabled for this platform"); -} -} /* namespace grpc_core */ - -#endif /* GRPC_LINUX_ERRQUEUE */ + gpr_log(GPR_DEBUG, "Timestamps callback is not enabled for this platform"); +} +} /* namespace grpc_core */ + +#endif /* GRPC_LINUX_ERRQUEUE */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h index 54a2dc748f..29cb0ac6ac 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/buffer_list.h @@ -1,165 +1,165 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H -#define GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H - -#include <grpc/support/port_platform.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H +#define GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H + +#include <grpc/support/port_platform.h> + #include "y_absl/types/optional.h" -#include "src/core/lib/iomgr/port.h" - -#include <grpc/support/time.h> - -#include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/iomgr/error.h" -#include "src/core/lib/iomgr/internal_errqueue.h" - -namespace grpc_core { - -struct ConnectionMetrics { - /* Delivery rate in Bytes/s. */ +#include "src/core/lib/iomgr/port.h" + +#include <grpc/support/time.h> + +#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/internal_errqueue.h" + +namespace grpc_core { + +struct ConnectionMetrics { + /* Delivery rate in Bytes/s. */ y_absl::optional<uint64_t> delivery_rate; - /* If the delivery rate is limited by the application, this is set to true. */ + /* If the delivery rate is limited by the application, this is set to true. */ y_absl::optional<bool> is_delivery_rate_app_limited; - /* Total packets retransmitted. */ + /* Total packets retransmitted. */ y_absl::optional<uint32_t> packet_retx; - /* Total packets retransmitted spuriously. This metric is smaller than or - equal to packet_retx. */ + /* Total packets retransmitted spuriously. This metric is smaller than or + equal to packet_retx. */ y_absl::optional<uint32_t> packet_spurious_retx; - /* Total packets sent. */ + /* Total packets sent. */ y_absl::optional<uint32_t> packet_sent; - /* Total packets delivered. */ + /* Total packets delivered. */ y_absl::optional<uint32_t> packet_delivered; - /* Total packets delivered with ECE marked. This metric is smaller than or - equal to packet_delivered. */ + /* Total packets delivered with ECE marked. This metric is smaller than or + equal to packet_delivered. */ y_absl::optional<uint32_t> packet_delivered_ce; - /* Total bytes lost so far. */ + /* Total bytes lost so far. */ y_absl::optional<uint64_t> data_retx; - /* Total bytes sent so far. */ + /* Total bytes sent so far. */ y_absl::optional<uint64_t> data_sent; - /* Total bytes in write queue but not sent. */ + /* Total bytes in write queue but not sent. */ y_absl::optional<uint64_t> data_notsent; - /* Pacing rate of the connection in Bps */ + /* Pacing rate of the connection in Bps */ y_absl::optional<uint64_t> pacing_rate; - /* Minimum RTT observed in usec. */ + /* Minimum RTT observed in usec. */ y_absl::optional<uint32_t> min_rtt; - /* Smoothed RTT in usec */ + /* Smoothed RTT in usec */ y_absl::optional<uint32_t> srtt; - /* Send congestion window. */ + /* Send congestion window. */ y_absl::optional<uint32_t> congestion_window; - /* Slow start threshold in packets. */ + /* Slow start threshold in packets. */ y_absl::optional<uint32_t> snd_ssthresh; - /* Maximum degree of reordering (i.e., maximum number of packets reodered) - on the connection. */ + /* Maximum degree of reordering (i.e., maximum number of packets reodered) + on the connection. */ y_absl::optional<uint32_t> reordering; - /* Represents the number of recurring retransmissions of the first sequence - that is not acknowledged yet. */ + /* Represents the number of recurring retransmissions of the first sequence + that is not acknowledged yet. */ y_absl::optional<uint8_t> recurring_retrans; - /* The cumulative time (in usec) that the transport protocol was busy - sending data. */ + /* The cumulative time (in usec) that the transport protocol was busy + sending data. */ y_absl::optional<uint64_t> busy_usec; - /* The cumulative time (in usec) that the transport protocol was limited by - the receive window size. */ + /* The cumulative time (in usec) that the transport protocol was limited by + the receive window size. */ y_absl::optional<uint64_t> rwnd_limited_usec; - /* The cumulative time (in usec) that the transport protocol was limited by - the send buffer size. */ + /* The cumulative time (in usec) that the transport protocol was limited by + the send buffer size. */ y_absl::optional<uint64_t> sndbuf_limited_usec; -}; - -struct Timestamp { - gpr_timespec time; - ConnectionMetrics metrics; /* Metrics collected with this timestamp */ -}; - -struct Timestamps { - Timestamp sendmsg_time; - Timestamp scheduled_time; - Timestamp sent_time; - Timestamp acked_time; - - uint32_t byte_offset; /* byte offset relative to the start of the RPC */ - -#ifdef GRPC_LINUX_ERRQUEUE - grpc_core::tcp_info info; /* tcp_info collected on sendmsg */ -#endif /* GRPC_LINUX_ERRQUEUE */ -}; - -/** TracedBuffer is a class to keep track of timestamps for a specific buffer in - * the TCP layer. We are only tracking timestamps for Linux kernels and hence - * this class would only be used by Linux platforms. For all other platforms, - * TracedBuffer would be an empty class. - * - * The timestamps collected are according to grpc_core::Timestamps declared - * above. - * - * A TracedBuffer list is kept track of using the head element of the list. If - * the head element of the list is nullptr, then the list is empty. - */ -#ifdef GRPC_LINUX_ERRQUEUE -class TracedBuffer { - public: +}; + +struct Timestamp { + gpr_timespec time; + ConnectionMetrics metrics; /* Metrics collected with this timestamp */ +}; + +struct Timestamps { + Timestamp sendmsg_time; + Timestamp scheduled_time; + Timestamp sent_time; + Timestamp acked_time; + + uint32_t byte_offset; /* byte offset relative to the start of the RPC */ + +#ifdef GRPC_LINUX_ERRQUEUE + grpc_core::tcp_info info; /* tcp_info collected on sendmsg */ +#endif /* GRPC_LINUX_ERRQUEUE */ +}; + +/** TracedBuffer is a class to keep track of timestamps for a specific buffer in + * the TCP layer. We are only tracking timestamps for Linux kernels and hence + * this class would only be used by Linux platforms. For all other platforms, + * TracedBuffer would be an empty class. + * + * The timestamps collected are according to grpc_core::Timestamps declared + * above. + * + * A TracedBuffer list is kept track of using the head element of the list. If + * the head element of the list is nullptr, then the list is empty. + */ +#ifdef GRPC_LINUX_ERRQUEUE +class TracedBuffer { + public: /** Use AddNewEntry function instead of using this directly. */ TracedBuffer(uint32_t seq_no, void* arg) : seq_no_(seq_no), arg_(arg), next_(nullptr) {} - /** Add a new entry in the TracedBuffer list pointed to by head. Also saves - * sendmsg_time with the current timestamp. */ - static void AddNewEntry(grpc_core::TracedBuffer** head, uint32_t seq_no, - int fd, void* arg); - - /** Processes a received timestamp based on sock_extended_err and - * scm_timestamping structures. It will invoke the timestamps callback if the - * timestamp type is SCM_TSTAMP_ACK. */ - static void ProcessTimestamp(grpc_core::TracedBuffer** head, - struct sock_extended_err* serr, - struct cmsghdr* opt_stats, - struct scm_timestamping* tss); - - /** Cleans the list by calling the callback for each traced buffer in the list - * with timestamps that it has. */ - static void Shutdown(grpc_core::TracedBuffer** head, void* remaining, - grpc_error* shutdown_err); - - private: - uint32_t seq_no_; /* The sequence number for the last byte in the buffer */ - void* arg_; /* The arg to pass to timestamps_callback */ - grpc_core::Timestamps ts_; /* The timestamps corresponding to this buffer */ - grpc_core::TracedBuffer* next_; /* The next TracedBuffer in the list */ -}; -#else /* GRPC_LINUX_ERRQUEUE */ -class TracedBuffer { - public: - /* Dummy shutdown function */ + /** Add a new entry in the TracedBuffer list pointed to by head. Also saves + * sendmsg_time with the current timestamp. */ + static void AddNewEntry(grpc_core::TracedBuffer** head, uint32_t seq_no, + int fd, void* arg); + + /** Processes a received timestamp based on sock_extended_err and + * scm_timestamping structures. It will invoke the timestamps callback if the + * timestamp type is SCM_TSTAMP_ACK. */ + static void ProcessTimestamp(grpc_core::TracedBuffer** head, + struct sock_extended_err* serr, + struct cmsghdr* opt_stats, + struct scm_timestamping* tss); + + /** Cleans the list by calling the callback for each traced buffer in the list + * with timestamps that it has. */ + static void Shutdown(grpc_core::TracedBuffer** head, void* remaining, + grpc_error* shutdown_err); + + private: + uint32_t seq_no_; /* The sequence number for the last byte in the buffer */ + void* arg_; /* The arg to pass to timestamps_callback */ + grpc_core::Timestamps ts_; /* The timestamps corresponding to this buffer */ + grpc_core::TracedBuffer* next_; /* The next TracedBuffer in the list */ +}; +#else /* GRPC_LINUX_ERRQUEUE */ +class TracedBuffer { + public: + /* Dummy shutdown function */ static void Shutdown(grpc_core::TracedBuffer** /*head*/, void* /*remaining*/, - grpc_error* shutdown_err) { - GRPC_ERROR_UNREF(shutdown_err); - } -}; -#endif /* GRPC_LINUX_ERRQUEUE */ - -/** Sets the callback function to call when timestamps for a write are - * collected. The callback does not own a reference to error. */ -void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*, - grpc_core::Timestamps*, - grpc_error* error)); - + grpc_error* shutdown_err) { + GRPC_ERROR_UNREF(shutdown_err); + } +}; +#endif /* GRPC_LINUX_ERRQUEUE */ + +/** Sets the callback function to call when timestamps for a write are + * collected. The callback does not own a reference to error. */ +void grpc_tcp_set_write_timestamps_callback(void (*fn)(void*, + grpc_core::Timestamps*, + grpc_error* error)); + } /* namespace grpc_core */ - -#endif /* GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H */ + +#endif /* GRPC_CORE_LIB_IOMGR_BUFFER_LIST_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc index ed0ae17488..ed79b26ddf 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.cc @@ -48,7 +48,7 @@ gpr_atm EncodeCancelStateError(grpc_error* error) { CallCombiner::CallCombiner() { gpr_atm_no_barrier_store(&cancel_state_, 0); gpr_atm_no_barrier_store(&size_, 0); -#ifdef GRPC_TSAN_ENABLED +#ifdef GRPC_TSAN_ENABLED GRPC_CLOSURE_INIT(&tsan_closure_, TsanClosure, this, grpc_schedule_on_exec_ctx); #endif @@ -61,44 +61,44 @@ CallCombiner::~CallCombiner() { #ifdef GRPC_TSAN_ENABLED void CallCombiner::TsanClosure(void* arg, grpc_error* error) { CallCombiner* self = static_cast<CallCombiner*>(arg); - // We ref-count the lock, and check if it's already taken. - // If it was taken, we should do nothing. Otherwise, we will mark it as - // locked. Note that if two different threads try to do this, only one of - // them will be able to mark the lock as acquired, while they both run their - // callbacks. In such cases (which should never happen for call_combiner), - // TSAN will correctly produce an error. - // - // TODO(soheil): This only covers the callbacks scheduled by + // We ref-count the lock, and check if it's already taken. + // If it was taken, we should do nothing. Otherwise, we will mark it as + // locked. Note that if two different threads try to do this, only one of + // them will be able to mark the lock as acquired, while they both run their + // callbacks. In such cases (which should never happen for call_combiner), + // TSAN will correctly produce an error. + // + // TODO(soheil): This only covers the callbacks scheduled by // CallCombiner::Start() and CallCombiner::Stop(). // If in the future, a callback gets scheduled using other // mechanisms, we will need to add APIs to externally lock // call combiners. RefCountedPtr<TsanLock> lock = self->tsan_lock_; - bool prev = false; - if (lock->taken.compare_exchange_strong(prev, true)) { - TSAN_ANNOTATE_RWLOCK_ACQUIRED(&lock->taken, true); - } else { - lock.reset(); - } + bool prev = false; + if (lock->taken.compare_exchange_strong(prev, true)) { + TSAN_ANNOTATE_RWLOCK_ACQUIRED(&lock->taken, true); + } else { + lock.reset(); + } grpc_core::Closure::Run(DEBUG_LOCATION, self->original_closure_, GRPC_ERROR_REF(error)); - if (lock != nullptr) { - TSAN_ANNOTATE_RWLOCK_RELEASED(&lock->taken, true); - bool prev = true; - GPR_ASSERT(lock->taken.compare_exchange_strong(prev, false)); - } -} -#endif - + if (lock != nullptr) { + TSAN_ANNOTATE_RWLOCK_RELEASED(&lock->taken, true); + bool prev = true; + GPR_ASSERT(lock->taken.compare_exchange_strong(prev, false)); + } +} +#endif + void CallCombiner::ScheduleClosure(grpc_closure* closure, grpc_error* error) { -#ifdef GRPC_TSAN_ENABLED +#ifdef GRPC_TSAN_ENABLED original_closure_ = closure; ExecCtx::Run(DEBUG_LOCATION, &tsan_closure_, error); -#else +#else ExecCtx::Run(DEBUG_LOCATION, closure, error); -#endif -} - +#endif +} + #ifndef NDEBUG #define DEBUG_ARGS const char *file, int line, #define DEBUG_FMT_STR "%s:%d: " diff --git a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h index aed847c972..0ff8410fcd 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/call_combiner.h @@ -28,10 +28,10 @@ #include <grpc/support/atm.h> #include "src/core/lib/gprpp/mpscq.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/dynamic_annotations.h" +#include "src/core/lib/iomgr/dynamic_annotations.h" #include "src/core/lib/iomgr/exec_ctx.h" // A simple, lock-free mechanism for serializing activity related to a @@ -115,103 +115,103 @@ class CallCombiner { // a grpc_closure* (if the lowest bit is 0), // or a grpc_error* (if the lowest bit is 1). gpr_atm cancel_state_ = 0; -#ifdef GRPC_TSAN_ENABLED - // A fake ref-counted lock that is kept alive after the destruction of - // grpc_call_combiner, when we are running the original closure. - // - // Ideally we want to lock and unlock the call combiner as a pointer, when the - // callback is called. However, original_closure is free to trigger - // anything on the call combiner (including destruction of grpc_call). - // Thus, we need a ref-counted structure that can outlive the call combiner. +#ifdef GRPC_TSAN_ENABLED + // A fake ref-counted lock that is kept alive after the destruction of + // grpc_call_combiner, when we are running the original closure. + // + // Ideally we want to lock and unlock the call combiner as a pointer, when the + // callback is called. However, original_closure is free to trigger + // anything on the call combiner (including destruction of grpc_call). + // Thus, we need a ref-counted structure that can outlive the call combiner. struct TsanLock : public RefCounted<TsanLock, NonPolymorphicRefCount> { - TsanLock() { TSAN_ANNOTATE_RWLOCK_CREATE(&taken); } - ~TsanLock() { TSAN_ANNOTATE_RWLOCK_DESTROY(&taken); } - // To avoid double-locking by the same thread, we should acquire/release - // the lock only when taken is false. On each acquire taken must be set to - // true. - std::atomic<bool> taken{false}; - }; + TsanLock() { TSAN_ANNOTATE_RWLOCK_CREATE(&taken); } + ~TsanLock() { TSAN_ANNOTATE_RWLOCK_DESTROY(&taken); } + // To avoid double-locking by the same thread, we should acquire/release + // the lock only when taken is false. On each acquire taken must be set to + // true. + std::atomic<bool> taken{false}; + }; RefCountedPtr<TsanLock> tsan_lock_ = MakeRefCounted<TsanLock>(); grpc_closure tsan_closure_; grpc_closure* original_closure_; -#endif -}; - -// Helper for running a list of closures in a call combiner. -// -// Each callback running in the call combiner will eventually be -// returned to the surface, at which point the surface will yield the -// call combiner. So when we are running in the call combiner and have -// more than one callback to return to the surface, we need to re-enter -// the call combiner for all but one of those callbacks. -class CallCombinerClosureList { - public: - CallCombinerClosureList() {} - - // Adds a closure to the list. The closure must eventually result in - // the call combiner being yielded. - void Add(grpc_closure* closure, grpc_error* error, const char* reason) { - closures_.emplace_back(closure, error, reason); - } - - // Runs all closures in the call combiner and yields the call combiner. - // - // All but one of the closures in the list will be scheduled via - // GRPC_CALL_COMBINER_START(), and the remaining closure will be +#endif +}; + +// Helper for running a list of closures in a call combiner. +// +// Each callback running in the call combiner will eventually be +// returned to the surface, at which point the surface will yield the +// call combiner. So when we are running in the call combiner and have +// more than one callback to return to the surface, we need to re-enter +// the call combiner for all but one of those callbacks. +class CallCombinerClosureList { + public: + CallCombinerClosureList() {} + + // Adds a closure to the list. The closure must eventually result in + // the call combiner being yielded. + void Add(grpc_closure* closure, grpc_error* error, const char* reason) { + closures_.emplace_back(closure, error, reason); + } + + // Runs all closures in the call combiner and yields the call combiner. + // + // All but one of the closures in the list will be scheduled via + // GRPC_CALL_COMBINER_START(), and the remaining closure will be // scheduled via ExecCtx::Run(), which will eventually result // in yielding the call combiner. If the list is empty, then the call - // combiner will be yielded immediately. + // combiner will be yielded immediately. void RunClosures(CallCombiner* call_combiner) { - if (closures_.empty()) { - GRPC_CALL_COMBINER_STOP(call_combiner, "no closures to schedule"); - return; - } - for (size_t i = 1; i < closures_.size(); ++i) { - auto& closure = closures_[i]; - GRPC_CALL_COMBINER_START(call_combiner, closure.closure, closure.error, - closure.reason); - } + if (closures_.empty()) { + GRPC_CALL_COMBINER_STOP(call_combiner, "no closures to schedule"); + return; + } + for (size_t i = 1; i < closures_.size(); ++i) { + auto& closure = closures_[i]; + GRPC_CALL_COMBINER_START(call_combiner, closure.closure, closure.error, + closure.reason); + } if (GRPC_TRACE_FLAG_ENABLED(grpc_call_combiner_trace)) { - gpr_log(GPR_INFO, - "CallCombinerClosureList executing closure while already " - "holding call_combiner %p: closure=%p error=%s reason=%s", - call_combiner, closures_[0].closure, - grpc_error_string(closures_[0].error), closures_[0].reason); - } - // This will release the call combiner. + gpr_log(GPR_INFO, + "CallCombinerClosureList executing closure while already " + "holding call_combiner %p: closure=%p error=%s reason=%s", + call_combiner, closures_[0].closure, + grpc_error_string(closures_[0].error), closures_[0].reason); + } + // This will release the call combiner. ExecCtx::Run(DEBUG_LOCATION, closures_[0].closure, closures_[0].error); - closures_.clear(); - } - - // Runs all closures in the call combiner, but does NOT yield the call - // combiner. All closures will be scheduled via GRPC_CALL_COMBINER_START(). + closures_.clear(); + } + + // Runs all closures in the call combiner, but does NOT yield the call + // combiner. All closures will be scheduled via GRPC_CALL_COMBINER_START(). void RunClosuresWithoutYielding(CallCombiner* call_combiner) { - for (size_t i = 0; i < closures_.size(); ++i) { - auto& closure = closures_[i]; - GRPC_CALL_COMBINER_START(call_combiner, closure.closure, closure.error, - closure.reason); - } - closures_.clear(); - } - - size_t size() const { return closures_.size(); } - - private: - struct CallCombinerClosure { - grpc_closure* closure; - grpc_error* error; - const char* reason; - - CallCombinerClosure(grpc_closure* closure, grpc_error* error, - const char* reason) - : closure(closure), error(error), reason(reason) {} - }; - - // There are generally a maximum of 6 closures to run in the call - // combiner, one for each pending op. + for (size_t i = 0; i < closures_.size(); ++i) { + auto& closure = closures_[i]; + GRPC_CALL_COMBINER_START(call_combiner, closure.closure, closure.error, + closure.reason); + } + closures_.clear(); + } + + size_t size() const { return closures_.size(); } + + private: + struct CallCombinerClosure { + grpc_closure* closure; + grpc_error* error; + const char* reason; + + CallCombinerClosure(grpc_closure* closure, grpc_error* error, + const char* reason) + : closure(closure), error(error), reason(reason) {} + }; + + // There are generally a maximum of 6 closures to run in the call + // combiner, one for each pending op. y_absl::InlinedVector<CallCombinerClosure, 6> closures_; -}; - -} // namespace grpc_core - +}; + +} // namespace grpc_core + #endif /* GRPC_CORE_LIB_IOMGR_CALL_COMBINER_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc index 46914e5175..fcab86b676 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.cc @@ -1,83 +1,83 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + #include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/iomgr/port.h" - -#ifdef GRPC_CFSTREAM -#import <CoreFoundation/CoreFoundation.h> -#import "src/core/lib/iomgr/cfstream_handle.h" - +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_CFSTREAM +#import <CoreFoundation/CoreFoundation.h> +#import "src/core/lib/iomgr/cfstream_handle.h" + #include <grpc/grpc.h> -#include <grpc/support/atm.h> -#include <grpc/support/sync.h> - -#include "src/core/lib/debug/trace.h" -#include "src/core/lib/iomgr/closure.h" +#include <grpc/support/atm.h> +#include <grpc/support/sync.h> + +#include "src/core/lib/debug/trace.h" +#include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/error_cfstream.h" #include "src/core/lib/iomgr/ev_apple.h" -#include "src/core/lib/iomgr/exec_ctx.h" - -extern grpc_core::TraceFlag grpc_tcp_trace; - +#include "src/core/lib/iomgr/exec_ctx.h" + +extern grpc_core::TraceFlag grpc_tcp_trace; + GrpcLibraryInitHolder::GrpcLibraryInitHolder() { grpc_init(); } GrpcLibraryInitHolder::~GrpcLibraryInitHolder() { grpc_shutdown(); } -void* CFStreamHandle::Retain(void* info) { - CFStreamHandle* handle = static_cast<CFStreamHandle*>(info); - CFSTREAM_HANDLE_REF(handle, "retain"); - return info; -} - -void CFStreamHandle::Release(void* info) { - CFStreamHandle* handle = static_cast<CFStreamHandle*>(info); - CFSTREAM_HANDLE_UNREF(handle, "release"); -} - -CFStreamHandle* CFStreamHandle::CreateStreamHandle( - CFReadStreamRef read_stream, CFWriteStreamRef write_stream) { - return new CFStreamHandle(read_stream, write_stream); -} - -void CFStreamHandle::ReadCallback(CFReadStreamRef stream, - CFStreamEventType type, - void* client_callback_info) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - grpc_core::ExecCtx exec_ctx; +void* CFStreamHandle::Retain(void* info) { + CFStreamHandle* handle = static_cast<CFStreamHandle*>(info); + CFSTREAM_HANDLE_REF(handle, "retain"); + return info; +} + +void CFStreamHandle::Release(void* info) { + CFStreamHandle* handle = static_cast<CFStreamHandle*>(info); + CFSTREAM_HANDLE_UNREF(handle, "release"); +} + +CFStreamHandle* CFStreamHandle::CreateStreamHandle( + CFReadStreamRef read_stream, CFWriteStreamRef write_stream) { + return new CFStreamHandle(read_stream, write_stream); +} + +void CFStreamHandle::ReadCallback(CFReadStreamRef stream, + CFStreamEventType type, + void* client_callback_info) { + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ExecCtx exec_ctx; grpc_error* error; CFErrorRef stream_error; - CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream ReadCallback (%p, %p, %lu, %p)", handle, - stream, type, client_callback_info); - } - switch (type) { - case kCFStreamEventOpenCompleted: - handle->open_event_.SetReady(); - break; - case kCFStreamEventHasBytesAvailable: - case kCFStreamEventEndEncountered: - handle->read_event_.SetReady(); - break; - case kCFStreamEventErrorOccurred: + CFStreamHandle* handle = static_cast<CFStreamHandle*>(client_callback_info); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream ReadCallback (%p, %p, %lu, %p)", handle, + stream, type, client_callback_info); + } + switch (type) { + case kCFStreamEventOpenCompleted: + handle->open_event_.SetReady(); + break; + case kCFStreamEventHasBytesAvailable: + case kCFStreamEventEndEncountered: + handle->read_event_.SetReady(); + break; + case kCFStreamEventErrorOccurred: stream_error = CFReadStreamCopyError(stream); error = grpc_error_set_int( GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "read error"), @@ -87,32 +87,32 @@ void CFStreamHandle::ReadCallback(CFReadStreamRef stream, handle->write_event_.SetShutdown(GRPC_ERROR_REF(error)); handle->read_event_.SetShutdown(GRPC_ERROR_REF(error)); GRPC_ERROR_UNREF(error); - break; - default: - GPR_UNREACHABLE_CODE(return ); - } -} -void CFStreamHandle::WriteCallback(CFWriteStreamRef stream, - CFStreamEventType type, - void* clientCallBackInfo) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - grpc_core::ExecCtx exec_ctx; + break; + default: + GPR_UNREACHABLE_CODE(return ); + } +} +void CFStreamHandle::WriteCallback(CFWriteStreamRef stream, + CFStreamEventType type, + void* clientCallBackInfo) { + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ExecCtx exec_ctx; grpc_error* error; CFErrorRef stream_error; - CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream WriteCallback (%p, %p, %lu, %p)", handle, - stream, type, clientCallBackInfo); - } - switch (type) { - case kCFStreamEventOpenCompleted: - handle->open_event_.SetReady(); - break; - case kCFStreamEventCanAcceptBytes: - case kCFStreamEventEndEncountered: - handle->write_event_.SetReady(); - break; - case kCFStreamEventErrorOccurred: + CFStreamHandle* handle = static_cast<CFStreamHandle*>(clientCallBackInfo); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream WriteCallback (%p, %p, %lu, %p)", handle, + stream, type, clientCallBackInfo); + } + switch (type) { + case kCFStreamEventOpenCompleted: + handle->open_event_.SetReady(); + break; + case kCFStreamEventCanAcceptBytes: + case kCFStreamEventEndEncountered: + handle->write_event_.SetReady(); + break; + case kCFStreamEventErrorOccurred: stream_error = CFWriteStreamCopyError(stream); error = grpc_error_set_int( GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "write error"), @@ -122,84 +122,84 @@ void CFStreamHandle::WriteCallback(CFWriteStreamRef stream, handle->write_event_.SetShutdown(GRPC_ERROR_REF(error)); handle->read_event_.SetShutdown(GRPC_ERROR_REF(error)); GRPC_ERROR_UNREF(error); - break; - default: - GPR_UNREACHABLE_CODE(return ); - } -} - -CFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream, - CFWriteStreamRef write_stream) { - gpr_ref_init(&refcount_, 1); - open_event_.InitEvent(); - read_event_.InitEvent(); - write_event_.InitEvent(); - dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL); - CFStreamClientContext ctx = {0, static_cast<void*>(this), - CFStreamHandle::Retain, CFStreamHandle::Release, - nil}; - CFReadStreamSetClient( - read_stream, - kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | - kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, - CFStreamHandle::ReadCallback, &ctx); - CFWriteStreamSetClient( - write_stream, - kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes | - kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, - CFStreamHandle::WriteCallback, &ctx); + break; + default: + GPR_UNREACHABLE_CODE(return ); + } +} + +CFStreamHandle::CFStreamHandle(CFReadStreamRef read_stream, + CFWriteStreamRef write_stream) { + gpr_ref_init(&refcount_, 1); + open_event_.InitEvent(); + read_event_.InitEvent(); + write_event_.InitEvent(); + dispatch_queue_ = dispatch_queue_create(nullptr, DISPATCH_QUEUE_SERIAL); + CFStreamClientContext ctx = {0, static_cast<void*>(this), + CFStreamHandle::Retain, CFStreamHandle::Release, + nil}; + CFReadStreamSetClient( + read_stream, + kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable | + kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, + CFStreamHandle::ReadCallback, &ctx); + CFWriteStreamSetClient( + write_stream, + kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes | + kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered, + CFStreamHandle::WriteCallback, &ctx); grpc_apple_register_read_stream(read_stream, dispatch_queue_); grpc_apple_register_write_stream(write_stream, dispatch_queue_); -} - -CFStreamHandle::~CFStreamHandle() { - open_event_.DestroyEvent(); - read_event_.DestroyEvent(); - write_event_.DestroyEvent(); +} + +CFStreamHandle::~CFStreamHandle() { + open_event_.DestroyEvent(); + read_event_.DestroyEvent(); + write_event_.DestroyEvent(); dispatch_release(dispatch_queue_); -} - -void CFStreamHandle::NotifyOnOpen(grpc_closure* closure) { - open_event_.NotifyOn(closure); -} - -void CFStreamHandle::NotifyOnRead(grpc_closure* closure) { - read_event_.NotifyOn(closure); -} - -void CFStreamHandle::NotifyOnWrite(grpc_closure* closure) { - write_event_.NotifyOn(closure); -} - -void CFStreamHandle::Shutdown(grpc_error* error) { - open_event_.SetShutdown(GRPC_ERROR_REF(error)); - read_event_.SetShutdown(GRPC_ERROR_REF(error)); - write_event_.SetShutdown(GRPC_ERROR_REF(error)); - GRPC_ERROR_UNREF(error); -} - -void CFStreamHandle::Ref(const char* file, int line, const char* reason) { - if (grpc_tcp_trace.enabled()) { - gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count); - gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, - "CFStream Handle ref %p : %s %" PRIdPTR " -> %" PRIdPTR, this, - reason, val, val + 1); - } - gpr_ref(&refcount_); -} - -void CFStreamHandle::Unref(const char* file, int line, const char* reason) { - if (grpc_tcp_trace.enabled()) { - gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count); +} + +void CFStreamHandle::NotifyOnOpen(grpc_closure* closure) { + open_event_.NotifyOn(closure); +} + +void CFStreamHandle::NotifyOnRead(grpc_closure* closure) { + read_event_.NotifyOn(closure); +} + +void CFStreamHandle::NotifyOnWrite(grpc_closure* closure) { + write_event_.NotifyOn(closure); +} + +void CFStreamHandle::Shutdown(grpc_error* error) { + open_event_.SetShutdown(GRPC_ERROR_REF(error)); + read_event_.SetShutdown(GRPC_ERROR_REF(error)); + write_event_.SetShutdown(GRPC_ERROR_REF(error)); + GRPC_ERROR_UNREF(error); +} + +void CFStreamHandle::Ref(const char* file, int line, const char* reason) { + if (grpc_tcp_trace.enabled()) { + gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count); + gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, + "CFStream Handle ref %p : %s %" PRIdPTR " -> %" PRIdPTR, this, + reason, val, val + 1); + } + gpr_ref(&refcount_); +} + +void CFStreamHandle::Unref(const char* file, int line, const char* reason) { + if (grpc_tcp_trace.enabled()) { + gpr_atm val = gpr_atm_no_barrier_load(&refcount_.count); gpr_log(GPR_DEBUG, - "CFStream Handle unref %p : %s %" PRIdPTR " -> %" PRIdPTR, this, - reason, val, val - 1); - } - if (gpr_unref(&refcount_)) { - delete this; - } -} - + "CFStream Handle unref %p : %s %" PRIdPTR " -> %" PRIdPTR, this, + reason, val, val - 1); + } + if (gpr_unref(&refcount_)) { + delete this; + } +} + #else /* Creating a dummy function so that the grpc_cfstream library will be @@ -207,4 +207,4 @@ void CFStreamHandle::Unref(const char* file, int line, const char* reason) { */ void CFStreamDummy() {} -#endif +#endif diff --git a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h index b0f0664a04..e020479858 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/cfstream_handle.h @@ -1,90 +1,90 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* The CFStream handle acts as an event synchronization entity for - * read/write/open/error/eos events happening on CFStream streams. */ - -#ifndef GRPC_CORE_LIB_IOMGR_CFSTREAM_HANDLE_H -#define GRPC_CORE_LIB_IOMGR_CFSTREAM_HANDLE_H - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#ifdef GRPC_CFSTREAM -#import <CoreFoundation/CoreFoundation.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* The CFStream handle acts as an event synchronization entity for + * read/write/open/error/eos events happening on CFStream streams. */ + +#ifndef GRPC_CORE_LIB_IOMGR_CFSTREAM_HANDLE_H +#define GRPC_CORE_LIB_IOMGR_CFSTREAM_HANDLE_H + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_CFSTREAM +#import <CoreFoundation/CoreFoundation.h> + #include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/lockfree_event.h" - +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/lockfree_event.h" + class GrpcLibraryInitHolder { - public: + public: GrpcLibraryInitHolder(); virtual ~GrpcLibraryInitHolder(); }; class CFStreamHandle : public GrpcLibraryInitHolder { public: - static CFStreamHandle* CreateStreamHandle(CFReadStreamRef read_stream, - CFWriteStreamRef write_stream); + static CFStreamHandle* CreateStreamHandle(CFReadStreamRef read_stream, + CFWriteStreamRef write_stream); /** Use CreateStreamHandle function instead of using this directly. */ CFStreamHandle(CFReadStreamRef read_stream, CFWriteStreamRef write_stream); CFStreamHandle(const CFStreamHandle& ref) = delete; CFStreamHandle(CFStreamHandle&& ref) = delete; - CFStreamHandle& operator=(const CFStreamHandle& rhs) = delete; + CFStreamHandle& operator=(const CFStreamHandle& rhs) = delete; ~CFStreamHandle() override; - - void NotifyOnOpen(grpc_closure* closure); - void NotifyOnRead(grpc_closure* closure); - void NotifyOnWrite(grpc_closure* closure); - void Shutdown(grpc_error* error); - - void Ref(const char* file = "", int line = 0, const char* reason = nullptr); - void Unref(const char* file = "", int line = 0, const char* reason = nullptr); - - private: - static void ReadCallback(CFReadStreamRef stream, CFStreamEventType type, - void* client_callback_info); - static void WriteCallback(CFWriteStreamRef stream, CFStreamEventType type, - void* client_callback_info); - static void* Retain(void* info); - static void Release(void* info); - - grpc_core::LockfreeEvent open_event_; - grpc_core::LockfreeEvent read_event_; - grpc_core::LockfreeEvent write_event_; - - dispatch_queue_t dispatch_queue_; - - gpr_refcount refcount_; -}; - -#ifdef DEBUG -#define CFSTREAM_HANDLE_REF(handle, reason) \ - (handle)->Ref(__FILE__, __LINE__, (reason)) -#define CFSTREAM_HANDLE_UNREF(handle, reason) \ - (handle)->Unref(__FILE__, __LINE__, (reason)) -#else -#define CFSTREAM_HANDLE_REF(handle, reason) (handle)->Ref() -#define CFSTREAM_HANDLE_UNREF(handle, reason) (handle)->Unref() -#endif - -#endif - -#endif /* GRPC_CORE_LIB_IOMGR_CFSTREAM_HANDLE_H */ + + void NotifyOnOpen(grpc_closure* closure); + void NotifyOnRead(grpc_closure* closure); + void NotifyOnWrite(grpc_closure* closure); + void Shutdown(grpc_error* error); + + void Ref(const char* file = "", int line = 0, const char* reason = nullptr); + void Unref(const char* file = "", int line = 0, const char* reason = nullptr); + + private: + static void ReadCallback(CFReadStreamRef stream, CFStreamEventType type, + void* client_callback_info); + static void WriteCallback(CFWriteStreamRef stream, CFStreamEventType type, + void* client_callback_info); + static void* Retain(void* info); + static void Release(void* info); + + grpc_core::LockfreeEvent open_event_; + grpc_core::LockfreeEvent read_event_; + grpc_core::LockfreeEvent write_event_; + + dispatch_queue_t dispatch_queue_; + + gpr_refcount refcount_; +}; + +#ifdef DEBUG +#define CFSTREAM_HANDLE_REF(handle, reason) \ + (handle)->Ref(__FILE__, __LINE__, (reason)) +#define CFSTREAM_HANDLE_UNREF(handle, reason) \ + (handle)->Unref(__FILE__, __LINE__, (reason)) +#else +#define CFSTREAM_HANDLE_REF(handle, reason) (handle)->Ref() +#define CFSTREAM_HANDLE_UNREF(handle, reason) (handle)->Unref() +#endif + +#endif + +#endif /* GRPC_CORE_LIB_IOMGR_CFSTREAM_HANDLE_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/closure.h b/contrib/libs/grpc/src/core/lib/iomgr/closure.h index 6bb65340d1..d21d33c2d6 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/closure.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/closure.h @@ -98,7 +98,7 @@ inline grpc_closure* grpc_closure_init(grpc_closure* closure, #endif closure->cb = cb; closure->cb_arg = cb_arg; - closure->error_data.error = GRPC_ERROR_NONE; + closure->error_data.error = GRPC_ERROR_NONE; #ifndef NDEBUG closure->scheduled = false; closure->file_initiated = nullptr; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc b/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc index 4b85766aef..44101cefcb 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/combiner.cc @@ -30,10 +30,10 @@ #include "src/core/lib/debug/stats.h" #include "src/core/lib/gprpp/mpscq.h" #include "src/core/lib/iomgr/executor.h" -#include "src/core/lib/iomgr/iomgr.h" +#include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/profiling/timers.h" -grpc_core::DebugOnlyTraceFlag grpc_combiner_trace(false, "combiner"); +grpc_core::DebugOnlyTraceFlag grpc_combiner_trace(false, "combiner"); #define GRPC_COMBINER_TRACE(fn) \ do { \ @@ -198,9 +198,9 @@ bool grpc_combiner_continue_exec_ctx() { grpc_core::ExecCtx::Get()->IsReadyToFinish(), lock->time_to_execute_final_list)); - // offload only if all the following conditions are true: - // 1. the combiner is contended and has more than one closure to execute - // 2. the current execution context needs to finish as soon as possible + // offload only if all the following conditions are true: + // 1. the combiner is contended and has more than one closure to execute + // 2. the current execution context needs to finish as soon as possible // 3. the current thread is not a worker for any background poller // 4. the DEFAULT executor is threaded if (contended && grpc_core::ExecCtx::Get()->IsReadyToFinish() && diff --git a/contrib/libs/grpc/src/core/lib/iomgr/combiner.h b/contrib/libs/grpc/src/core/lib/iomgr/combiner.h index 32712066be..0d1d23871a 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/combiner.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/combiner.h @@ -83,6 +83,6 @@ void grpc_combiner_unref(grpc_core::Combiner* lock GRPC_COMBINER_DEBUG_ARGS); bool grpc_combiner_continue_exec_ctx(); -extern grpc_core::DebugOnlyTraceFlag grpc_combiner_trace; +extern grpc_core::DebugOnlyTraceFlag grpc_combiner_trace; #endif /* GRPC_CORE_LIB_IOMGR_COMBINER_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/dynamic_annotations.h b/contrib/libs/grpc/src/core/lib/iomgr/dynamic_annotations.h index 713928023a..c5de1f86ef 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/dynamic_annotations.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/dynamic_annotations.h @@ -1,67 +1,67 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_IOMGR_DYNAMIC_ANNOTATIONS_H -#define GRPC_CORE_LIB_IOMGR_DYNAMIC_ANNOTATIONS_H - -#include <grpc/support/port_platform.h> - -#ifdef GRPC_TSAN_ENABLED - -#define TSAN_ANNOTATE_HAPPENS_BEFORE(addr) \ - AnnotateHappensBefore(__FILE__, __LINE__, (void*)(addr)) -#define TSAN_ANNOTATE_HAPPENS_AFTER(addr) \ - AnnotateHappensAfter(__FILE__, __LINE__, (void*)(addr)) -#define TSAN_ANNOTATE_RWLOCK_CREATE(addr) \ - AnnotateRWLockCreate(__FILE__, __LINE__, (void*)(addr)) -#define TSAN_ANNOTATE_RWLOCK_DESTROY(addr) \ - AnnotateRWLockDestroy(__FILE__, __LINE__, (void*)(addr)) -#define TSAN_ANNOTATE_RWLOCK_ACQUIRED(addr, is_w) \ - AnnotateRWLockAcquired(__FILE__, __LINE__, (void*)(addr), (is_w)) -#define TSAN_ANNOTATE_RWLOCK_RELEASED(addr, is_w) \ - AnnotateRWLockReleased(__FILE__, __LINE__, (void*)(addr), (is_w)) - -#ifdef __cplusplus -extern "C" { -#endif -void AnnotateHappensBefore(const char* file, int line, const volatile void* cv); -void AnnotateHappensAfter(const char* file, int line, const volatile void* cv); -void AnnotateRWLockCreate(const char* file, int line, - const volatile void* lock); -void AnnotateRWLockDestroy(const char* file, int line, - const volatile void* lock); -void AnnotateRWLockAcquired(const char* file, int line, - const volatile void* lock, long is_w); -void AnnotateRWLockReleased(const char* file, int line, - const volatile void* lock, long is_w); -#ifdef __cplusplus -} -#endif - -#else /* GRPC_TSAN_ENABLED */ - -#define TSAN_ANNOTATE_HAPPENS_BEFORE(addr) -#define TSAN_ANNOTATE_HAPPENS_AFTER(addr) -#define TSAN_ANNOTATE_RWLOCK_CREATE(addr) -#define TSAN_ANNOTATE_RWLOCK_DESTROY(addr) -#define TSAN_ANNOTATE_RWLOCK_ACQUIRED(addr, is_w) -#define TSAN_ANNOTATE_RWLOCK_RELEASED(addr, is_w) - -#endif /* GRPC_TSAN_ENABLED */ - -#endif /* GRPC_CORE_LIB_IOMGR_DYNAMIC_ANNOTATIONS_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_IOMGR_DYNAMIC_ANNOTATIONS_H +#define GRPC_CORE_LIB_IOMGR_DYNAMIC_ANNOTATIONS_H + +#include <grpc/support/port_platform.h> + +#ifdef GRPC_TSAN_ENABLED + +#define TSAN_ANNOTATE_HAPPENS_BEFORE(addr) \ + AnnotateHappensBefore(__FILE__, __LINE__, (void*)(addr)) +#define TSAN_ANNOTATE_HAPPENS_AFTER(addr) \ + AnnotateHappensAfter(__FILE__, __LINE__, (void*)(addr)) +#define TSAN_ANNOTATE_RWLOCK_CREATE(addr) \ + AnnotateRWLockCreate(__FILE__, __LINE__, (void*)(addr)) +#define TSAN_ANNOTATE_RWLOCK_DESTROY(addr) \ + AnnotateRWLockDestroy(__FILE__, __LINE__, (void*)(addr)) +#define TSAN_ANNOTATE_RWLOCK_ACQUIRED(addr, is_w) \ + AnnotateRWLockAcquired(__FILE__, __LINE__, (void*)(addr), (is_w)) +#define TSAN_ANNOTATE_RWLOCK_RELEASED(addr, is_w) \ + AnnotateRWLockReleased(__FILE__, __LINE__, (void*)(addr), (is_w)) + +#ifdef __cplusplus +extern "C" { +#endif +void AnnotateHappensBefore(const char* file, int line, const volatile void* cv); +void AnnotateHappensAfter(const char* file, int line, const volatile void* cv); +void AnnotateRWLockCreate(const char* file, int line, + const volatile void* lock); +void AnnotateRWLockDestroy(const char* file, int line, + const volatile void* lock); +void AnnotateRWLockAcquired(const char* file, int line, + const volatile void* lock, long is_w); +void AnnotateRWLockReleased(const char* file, int line, + const volatile void* lock, long is_w); +#ifdef __cplusplus +} +#endif + +#else /* GRPC_TSAN_ENABLED */ + +#define TSAN_ANNOTATE_HAPPENS_BEFORE(addr) +#define TSAN_ANNOTATE_HAPPENS_AFTER(addr) +#define TSAN_ANNOTATE_RWLOCK_CREATE(addr) +#define TSAN_ANNOTATE_RWLOCK_DESTROY(addr) +#define TSAN_ANNOTATE_RWLOCK_ACQUIRED(addr, is_w) +#define TSAN_ANNOTATE_RWLOCK_RELEASED(addr, is_w) + +#endif /* GRPC_TSAN_ENABLED */ + +#endif /* GRPC_CORE_LIB_IOMGR_DYNAMIC_ANNOTATIONS_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc index 37e0400102..18eae0d5c0 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.cc @@ -28,8 +28,8 @@ void grpc_endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* slices, } void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* arg) { - ep->vtable->write(ep, slices, cb, arg); + grpc_closure* cb, void* arg) { + ep->vtable->write(ep, slices, cb, arg); } void grpc_endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) { @@ -65,7 +65,7 @@ int grpc_endpoint_get_fd(grpc_endpoint* ep) { return ep->vtable->get_fd(ep); } grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* ep) { return ep->vtable->get_resource_user(ep); } - -bool grpc_endpoint_can_track_err(grpc_endpoint* ep) { - return ep->vtable->can_track_err(ep); -} + +bool grpc_endpoint_can_track_err(grpc_endpoint* ep) { + return ep->vtable->can_track_err(ep); +} diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h index e704c3be49..f51bf9ba76 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint.h @@ -39,8 +39,8 @@ typedef struct grpc_endpoint_vtable grpc_endpoint_vtable; struct grpc_endpoint_vtable { void (*read)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb, bool urgent); - void (*write)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb, - void* arg); + void (*write)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb, + void* arg); void (*add_to_pollset)(grpc_endpoint* ep, grpc_pollset* pollset); void (*add_to_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset); void (*delete_from_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset); @@ -50,7 +50,7 @@ struct grpc_endpoint_vtable { y_absl::string_view (*get_peer)(grpc_endpoint* ep); y_absl::string_view (*get_local_address)(grpc_endpoint* ep); int (*get_fd)(grpc_endpoint* ep); - bool (*can_track_err)(grpc_endpoint* ep); + bool (*can_track_err)(grpc_endpoint* ep); }; /* When data is available on the connection, calls the callback with slices. @@ -78,11 +78,11 @@ int grpc_endpoint_get_fd(grpc_endpoint* ep); \a slices may be mutated at will by the endpoint until cb is called. No guarantee is made to the content of slices after a write EXCEPT that it is a valid slice buffer. - \a arg is platform specific. It is currently only used by TCP on linux - platforms as an argument that would be forwarded to the timestamps callback. + \a arg is platform specific. It is currently only used by TCP on linux + platforms as an argument that would be forwarded to the timestamps callback. */ void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* arg); + grpc_closure* cb, void* arg); /* Causes any pending and future read/write callbacks to run immediately with success==0 */ @@ -101,8 +101,8 @@ void grpc_endpoint_delete_from_pollset_set(grpc_endpoint* ep, grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* endpoint); -bool grpc_endpoint_can_track_err(grpc_endpoint* ep); - +bool grpc_endpoint_can_track_err(grpc_endpoint* ep); + struct grpc_endpoint { const grpc_endpoint_vtable* vtable; }; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc index d3a9c9b200..a9956d7451 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.cc @@ -1,369 +1,369 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#ifdef GRPC_CFSTREAM_ENDPOINT - -#import <CoreFoundation/CoreFoundation.h> -#import "src/core/lib/iomgr/endpoint_cfstream.h" - -#include <grpc/slice_buffer.h> -#include <grpc/support/alloc.h> -#include <grpc/support/string_util.h> - -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/iomgr/cfstream_handle.h" -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/endpoint.h" -#include "src/core/lib/iomgr/error_cfstream.h" +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_CFSTREAM_ENDPOINT + +#import <CoreFoundation/CoreFoundation.h> +#import "src/core/lib/iomgr/endpoint_cfstream.h" + +#include <grpc/slice_buffer.h> +#include <grpc/support/alloc.h> +#include <grpc/support/string_util.h> + +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/iomgr/cfstream_handle.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/endpoint.h" +#include "src/core/lib/iomgr/error_cfstream.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/slice/slice_string_helpers.h" - -extern grpc_core::TraceFlag grpc_tcp_trace; - +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/slice/slice_string_helpers.h" + +extern grpc_core::TraceFlag grpc_tcp_trace; + struct CFStreamEndpoint { - grpc_endpoint base; - gpr_refcount refcount; - - CFReadStreamRef read_stream; - CFWriteStreamRef write_stream; - CFStreamHandle* stream_sync; - - grpc_closure* read_cb; - grpc_closure* write_cb; - grpc_slice_buffer* read_slices; - grpc_slice_buffer* write_slices; - - grpc_closure read_action; - grpc_closure write_action; - + grpc_endpoint base; + gpr_refcount refcount; + + CFReadStreamRef read_stream; + CFWriteStreamRef write_stream; + CFStreamHandle* stream_sync; + + grpc_closure* read_cb; + grpc_closure* write_cb; + grpc_slice_buffer* read_slices; + grpc_slice_buffer* write_slices; + + grpc_closure read_action; + grpc_closure write_action; + TString peer_string; TString local_address; - grpc_resource_user* resource_user; - grpc_resource_user_slice_allocator slice_allocator; + grpc_resource_user* resource_user; + grpc_resource_user_slice_allocator slice_allocator; }; -static void CFStreamFree(CFStreamEndpoint* ep) { - grpc_resource_user_unref(ep->resource_user); - CFRelease(ep->read_stream); - CFRelease(ep->write_stream); - CFSTREAM_HANDLE_UNREF(ep->stream_sync, "free"); +static void CFStreamFree(CFStreamEndpoint* ep) { + grpc_resource_user_unref(ep->resource_user); + CFRelease(ep->read_stream); + CFRelease(ep->write_stream); + CFSTREAM_HANDLE_UNREF(ep->stream_sync, "free"); delete ep; -} - -#ifndef NDEBUG -#define EP_REF(ep, reason) CFStreamRef((ep), (reason), __FILE__, __LINE__) -#define EP_UNREF(ep, reason) CFStreamUnref((ep), (reason), __FILE__, __LINE__) -static void CFStreamUnref(CFStreamEndpoint* ep, const char* reason, - const char* file, int line) { - if (grpc_tcp_trace.enabled()) { - gpr_atm val = gpr_atm_no_barrier_load(&ep->refcount.count); - gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, - "CFStream endpoint unref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, - reason, val, val - 1); - } - if (gpr_unref(&ep->refcount)) { - CFStreamFree(ep); - } -} -static void CFStreamRef(CFStreamEndpoint* ep, const char* reason, - const char* file, int line) { - if (grpc_tcp_trace.enabled()) { - gpr_atm val = gpr_atm_no_barrier_load(&ep->refcount.count); - gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, - "CFStream endpoint ref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, - reason, val, val + 1); - } - gpr_ref(&ep->refcount); -} -#else -#define EP_REF(ep, reason) CFStreamRef((ep)) -#define EP_UNREF(ep, reason) CFStreamUnref((ep)) -static void CFStreamUnref(CFStreamEndpoint* ep) { - if (gpr_unref(&ep->refcount)) { - CFStreamFree(ep); - } -} -static void CFStreamRef(CFStreamEndpoint* ep) { gpr_ref(&ep->refcount); } -#endif - -static grpc_error* CFStreamAnnotateError(grpc_error* src_error, - CFStreamEndpoint* ep) { - return grpc_error_set_str( - grpc_error_set_int(src_error, GRPC_ERROR_INT_GRPC_STATUS, - GRPC_STATUS_UNAVAILABLE), - GRPC_ERROR_STR_TARGET_ADDRESS, +} + +#ifndef NDEBUG +#define EP_REF(ep, reason) CFStreamRef((ep), (reason), __FILE__, __LINE__) +#define EP_UNREF(ep, reason) CFStreamUnref((ep), (reason), __FILE__, __LINE__) +static void CFStreamUnref(CFStreamEndpoint* ep, const char* reason, + const char* file, int line) { + if (grpc_tcp_trace.enabled()) { + gpr_atm val = gpr_atm_no_barrier_load(&ep->refcount.count); + gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, + "CFStream endpoint unref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, + reason, val, val - 1); + } + if (gpr_unref(&ep->refcount)) { + CFStreamFree(ep); + } +} +static void CFStreamRef(CFStreamEndpoint* ep, const char* reason, + const char* file, int line) { + if (grpc_tcp_trace.enabled()) { + gpr_atm val = gpr_atm_no_barrier_load(&ep->refcount.count); + gpr_log(file, line, GPR_LOG_SEVERITY_DEBUG, + "CFStream endpoint ref %p : %s %" PRIdPTR " -> %" PRIdPTR, ep, + reason, val, val + 1); + } + gpr_ref(&ep->refcount); +} +#else +#define EP_REF(ep, reason) CFStreamRef((ep)) +#define EP_UNREF(ep, reason) CFStreamUnref((ep)) +static void CFStreamUnref(CFStreamEndpoint* ep) { + if (gpr_unref(&ep->refcount)) { + CFStreamFree(ep); + } +} +static void CFStreamRef(CFStreamEndpoint* ep) { gpr_ref(&ep->refcount); } +#endif + +static grpc_error* CFStreamAnnotateError(grpc_error* src_error, + CFStreamEndpoint* ep) { + return grpc_error_set_str( + grpc_error_set_int(src_error, GRPC_ERROR_INT_GRPC_STATUS, + GRPC_STATUS_UNAVAILABLE), + GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_copied_string(ep->peer_string.c_str())); -} - -static void CallReadCb(CFStreamEndpoint* ep, grpc_error* error) { - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p call_read_cb %p %p:%p", ep, - ep->read_cb, ep->read_cb->cb, ep->read_cb->cb_arg); - size_t i; - const char* str = grpc_error_string(error); - gpr_log(GPR_DEBUG, "read: error=%s", str); - - for (i = 0; i < ep->read_slices->count; i++) { - char* dump = grpc_dump_slice(ep->read_slices->slices[i], - GPR_DUMP_HEX | GPR_DUMP_ASCII); +} + +static void CallReadCb(CFStreamEndpoint* ep, grpc_error* error) { + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p call_read_cb %p %p:%p", ep, + ep->read_cb, ep->read_cb->cb, ep->read_cb->cb_arg); + size_t i; + const char* str = grpc_error_string(error); + gpr_log(GPR_DEBUG, "read: error=%s", str); + + for (i = 0; i < ep->read_slices->count; i++) { + char* dump = grpc_dump_slice(ep->read_slices->slices[i], + GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "READ %p (peer=%s): %s", ep, ep->peer_string.c_str(), dump); - gpr_free(dump); - } - } - grpc_closure* cb = ep->read_cb; - ep->read_cb = nullptr; - ep->read_slices = nullptr; + gpr_free(dump); + } + } + grpc_closure* cb = ep->read_cb; + ep->read_cb = nullptr; + ep->read_slices = nullptr; grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error); -} - -static void CallWriteCb(CFStreamEndpoint* ep, grpc_error* error) { - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p call_write_cb %p %p:%p", ep, - ep->write_cb, ep->write_cb->cb, ep->write_cb->cb_arg); - const char* str = grpc_error_string(error); - gpr_log(GPR_DEBUG, "write: error=%s", str); - } - grpc_closure* cb = ep->write_cb; - ep->write_cb = nullptr; - ep->write_slices = nullptr; +} + +static void CallWriteCb(CFStreamEndpoint* ep, grpc_error* error) { + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p call_write_cb %p %p:%p", ep, + ep->write_cb, ep->write_cb->cb, ep->write_cb->cb_arg); + const char* str = grpc_error_string(error); + gpr_log(GPR_DEBUG, "write: error=%s", str); + } + grpc_closure* cb = ep->write_cb; + ep->write_cb = nullptr; + ep->write_slices = nullptr; grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error); -} - -static void ReadAction(void* arg, grpc_error* error) { - CFStreamEndpoint* ep = static_cast<CFStreamEndpoint*>(arg); - GPR_ASSERT(ep->read_cb != nullptr); - if (error) { - grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); - CallReadCb(ep, GRPC_ERROR_REF(error)); - EP_UNREF(ep, "read"); - return; - } - - GPR_ASSERT(ep->read_slices->count == 1); - grpc_slice slice = ep->read_slices->slices[0]; - size_t len = GRPC_SLICE_LENGTH(slice); - CFIndex read_size = - CFReadStreamRead(ep->read_stream, GRPC_SLICE_START_PTR(slice), len); - if (read_size == -1) { - grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); - CFErrorRef stream_error = CFReadStreamCopyError(ep->read_stream); - if (stream_error != nullptr) { - error = CFStreamAnnotateError( - GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "Read error"), ep); - CFRelease(stream_error); - } else { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Read error"); - } - CallReadCb(ep, error); - EP_UNREF(ep, "read"); - } else if (read_size == 0) { - grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); - CallReadCb(ep, - CFStreamAnnotateError( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Socket closed"), ep)); - EP_UNREF(ep, "read"); - } else { +} + +static void ReadAction(void* arg, grpc_error* error) { + CFStreamEndpoint* ep = static_cast<CFStreamEndpoint*>(arg); + GPR_ASSERT(ep->read_cb != nullptr); + if (error) { + grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); + CallReadCb(ep, GRPC_ERROR_REF(error)); + EP_UNREF(ep, "read"); + return; + } + + GPR_ASSERT(ep->read_slices->count == 1); + grpc_slice slice = ep->read_slices->slices[0]; + size_t len = GRPC_SLICE_LENGTH(slice); + CFIndex read_size = + CFReadStreamRead(ep->read_stream, GRPC_SLICE_START_PTR(slice), len); + if (read_size == -1) { + grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); + CFErrorRef stream_error = CFReadStreamCopyError(ep->read_stream); + if (stream_error != nullptr) { + error = CFStreamAnnotateError( + GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "Read error"), ep); + CFRelease(stream_error); + } else { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Read error"); + } + CallReadCb(ep, error); + EP_UNREF(ep, "read"); + } else if (read_size == 0) { + grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); + CallReadCb(ep, + CFStreamAnnotateError( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Socket closed"), ep)); + EP_UNREF(ep, "read"); + } else { if (read_size < static_cast<CFIndex>(len)) { - grpc_slice_buffer_trim_end(ep->read_slices, len - read_size, nullptr); - } - CallReadCb(ep, GRPC_ERROR_NONE); - EP_UNREF(ep, "read"); - } -} - -static void WriteAction(void* arg, grpc_error* error) { - CFStreamEndpoint* ep = static_cast<CFStreamEndpoint*>(arg); - GPR_ASSERT(ep->write_cb != nullptr); - if (error) { - grpc_slice_buffer_reset_and_unref_internal(ep->write_slices); - CallWriteCb(ep, GRPC_ERROR_REF(error)); - EP_UNREF(ep, "write"); - return; - } - - grpc_slice slice = grpc_slice_buffer_take_first(ep->write_slices); - size_t slice_len = GRPC_SLICE_LENGTH(slice); - CFIndex write_size = CFWriteStreamWrite( - ep->write_stream, GRPC_SLICE_START_PTR(slice), slice_len); - if (write_size == -1) { - grpc_slice_buffer_reset_and_unref_internal(ep->write_slices); - CFErrorRef stream_error = CFWriteStreamCopyError(ep->write_stream); - if (stream_error != nullptr) { - error = CFStreamAnnotateError( - GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "write failed."), ep); - CFRelease(stream_error); - } else { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("write failed."); - } - CallWriteCb(ep, error); - EP_UNREF(ep, "write"); - } else { + grpc_slice_buffer_trim_end(ep->read_slices, len - read_size, nullptr); + } + CallReadCb(ep, GRPC_ERROR_NONE); + EP_UNREF(ep, "read"); + } +} + +static void WriteAction(void* arg, grpc_error* error) { + CFStreamEndpoint* ep = static_cast<CFStreamEndpoint*>(arg); + GPR_ASSERT(ep->write_cb != nullptr); + if (error) { + grpc_slice_buffer_reset_and_unref_internal(ep->write_slices); + CallWriteCb(ep, GRPC_ERROR_REF(error)); + EP_UNREF(ep, "write"); + return; + } + + grpc_slice slice = grpc_slice_buffer_take_first(ep->write_slices); + size_t slice_len = GRPC_SLICE_LENGTH(slice); + CFIndex write_size = CFWriteStreamWrite( + ep->write_stream, GRPC_SLICE_START_PTR(slice), slice_len); + if (write_size == -1) { + grpc_slice_buffer_reset_and_unref_internal(ep->write_slices); + CFErrorRef stream_error = CFWriteStreamCopyError(ep->write_stream); + if (stream_error != nullptr) { + error = CFStreamAnnotateError( + GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "write failed."), ep); + CFRelease(stream_error); + } else { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("write failed."); + } + CallWriteCb(ep, error); + EP_UNREF(ep, "write"); + } else { if (write_size < static_cast<CFIndex>(GRPC_SLICE_LENGTH(slice))) { - grpc_slice_buffer_undo_take_first( - ep->write_slices, grpc_slice_sub(slice, write_size, slice_len)); - } - if (ep->write_slices->length > 0) { - ep->stream_sync->NotifyOnWrite(&ep->write_action); - } else { - CallWriteCb(ep, GRPC_ERROR_NONE); - EP_UNREF(ep, "write"); - } - - if (grpc_tcp_trace.enabled()) { - grpc_slice trace_slice = grpc_slice_sub(slice, 0, write_size); - char* dump = grpc_dump_slice(trace_slice, GPR_DUMP_HEX | GPR_DUMP_ASCII); + grpc_slice_buffer_undo_take_first( + ep->write_slices, grpc_slice_sub(slice, write_size, slice_len)); + } + if (ep->write_slices->length > 0) { + ep->stream_sync->NotifyOnWrite(&ep->write_action); + } else { + CallWriteCb(ep, GRPC_ERROR_NONE); + EP_UNREF(ep, "write"); + } + + if (grpc_tcp_trace.enabled()) { + grpc_slice trace_slice = grpc_slice_sub(slice, 0, write_size); + char* dump = grpc_dump_slice(trace_slice, GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_DEBUG, "WRITE %p (peer=%s): %s", ep, ep->peer_string.c_str(), dump); - gpr_free(dump); - grpc_slice_unref_internal(trace_slice); - } - } - grpc_slice_unref_internal(slice); -} - -static void CFStreamReadAllocationDone(void* arg, grpc_error* error) { - CFStreamEndpoint* ep = static_cast<CFStreamEndpoint*>(arg); - if (error == GRPC_ERROR_NONE) { - ep->stream_sync->NotifyOnRead(&ep->read_action); - } else { - grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); - CallReadCb(ep, error); - EP_UNREF(ep, "read"); - } -} - -static void CFStreamRead(grpc_endpoint* ep, grpc_slice_buffer* slices, + gpr_free(dump); + grpc_slice_unref_internal(trace_slice); + } + } + grpc_slice_unref_internal(slice); +} + +static void CFStreamReadAllocationDone(void* arg, grpc_error* error) { + CFStreamEndpoint* ep = static_cast<CFStreamEndpoint*>(arg); + if (error == GRPC_ERROR_NONE) { + ep->stream_sync->NotifyOnRead(&ep->read_action); + } else { + grpc_slice_buffer_reset_and_unref_internal(ep->read_slices); + CallReadCb(ep, error); + EP_UNREF(ep, "read"); + } +} + +static void CFStreamRead(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb, bool urgent) { - CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p read (%p, %p) length:%zu", ep_impl, - slices, cb, slices->length); - } - GPR_ASSERT(ep_impl->read_cb == nullptr); - ep_impl->read_cb = cb; - ep_impl->read_slices = slices; - grpc_slice_buffer_reset_and_unref_internal(slices); - EP_REF(ep_impl, "read"); + CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p read (%p, %p) length:%zu", ep_impl, + slices, cb, slices->length); + } + GPR_ASSERT(ep_impl->read_cb == nullptr); + ep_impl->read_cb = cb; + ep_impl->read_slices = slices; + grpc_slice_buffer_reset_and_unref_internal(slices); + EP_REF(ep_impl, "read"); if (grpc_resource_user_alloc_slices(&ep_impl->slice_allocator, GRPC_TCP_DEFAULT_READ_SLICE_SIZE, 1, ep_impl->read_slices)) { ep_impl->stream_sync->NotifyOnRead(&ep_impl->read_action); } -} - -static void CFStreamWrite(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* arg) { - CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p write (%p, %p) length:%zu", - ep_impl, slices, cb, slices->length); - } - GPR_ASSERT(ep_impl->write_cb == nullptr); - ep_impl->write_cb = cb; - ep_impl->write_slices = slices; - EP_REF(ep_impl, "write"); - ep_impl->stream_sync->NotifyOnWrite(&ep_impl->write_action); -} - -void CFStreamShutdown(grpc_endpoint* ep, grpc_error* why) { - CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p shutdown (%p)", ep_impl, why); - } - CFReadStreamClose(ep_impl->read_stream); - CFWriteStreamClose(ep_impl->write_stream); - ep_impl->stream_sync->Shutdown(why); - grpc_resource_user_shutdown(ep_impl->resource_user); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p shutdown DONE (%p)", ep_impl, why); - } -} - -void CFStreamDestroy(grpc_endpoint* ep) { - CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CFStream endpoint:%p destroy", ep_impl); - } - EP_UNREF(ep_impl, "destroy"); -} - -grpc_resource_user* CFStreamGetResourceUser(grpc_endpoint* ep) { - CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); - return ep_impl->resource_user; -} - +} + +static void CFStreamWrite(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, void* arg) { + CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p write (%p, %p) length:%zu", + ep_impl, slices, cb, slices->length); + } + GPR_ASSERT(ep_impl->write_cb == nullptr); + ep_impl->write_cb = cb; + ep_impl->write_slices = slices; + EP_REF(ep_impl, "write"); + ep_impl->stream_sync->NotifyOnWrite(&ep_impl->write_action); +} + +void CFStreamShutdown(grpc_endpoint* ep, grpc_error* why) { + CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p shutdown (%p)", ep_impl, why); + } + CFReadStreamClose(ep_impl->read_stream); + CFWriteStreamClose(ep_impl->write_stream); + ep_impl->stream_sync->Shutdown(why); + grpc_resource_user_shutdown(ep_impl->resource_user); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p shutdown DONE (%p)", ep_impl, why); + } +} + +void CFStreamDestroy(grpc_endpoint* ep) { + CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CFStream endpoint:%p destroy", ep_impl); + } + EP_UNREF(ep_impl, "destroy"); +} + +grpc_resource_user* CFStreamGetResourceUser(grpc_endpoint* ep) { + CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); + return ep_impl->resource_user; +} + y_absl::string_view CFStreamGetPeer(grpc_endpoint* ep) { - CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); + CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); return ep_impl->peer_string; -} - +} + y_absl::string_view CFStreamGetLocalAddress(grpc_endpoint* ep) { CFStreamEndpoint* ep_impl = reinterpret_cast<CFStreamEndpoint*>(ep); return ep_impl->local_address; } -int CFStreamGetFD(grpc_endpoint* ep) { return 0; } - -bool CFStreamCanTrackErr(grpc_endpoint* ep) { return false; } - -void CFStreamAddToPollset(grpc_endpoint* ep, grpc_pollset* pollset) {} -void CFStreamAddToPollsetSet(grpc_endpoint* ep, grpc_pollset_set* pollset) {} -void CFStreamDeleteFromPollsetSet(grpc_endpoint* ep, - grpc_pollset_set* pollset) {} - -static const grpc_endpoint_vtable vtable = {CFStreamRead, - CFStreamWrite, - CFStreamAddToPollset, - CFStreamAddToPollsetSet, - CFStreamDeleteFromPollsetSet, - CFStreamShutdown, - CFStreamDestroy, - CFStreamGetResourceUser, - CFStreamGetPeer, +int CFStreamGetFD(grpc_endpoint* ep) { return 0; } + +bool CFStreamCanTrackErr(grpc_endpoint* ep) { return false; } + +void CFStreamAddToPollset(grpc_endpoint* ep, grpc_pollset* pollset) {} +void CFStreamAddToPollsetSet(grpc_endpoint* ep, grpc_pollset_set* pollset) {} +void CFStreamDeleteFromPollsetSet(grpc_endpoint* ep, + grpc_pollset_set* pollset) {} + +static const grpc_endpoint_vtable vtable = {CFStreamRead, + CFStreamWrite, + CFStreamAddToPollset, + CFStreamAddToPollsetSet, + CFStreamDeleteFromPollsetSet, + CFStreamShutdown, + CFStreamDestroy, + CFStreamGetResourceUser, + CFStreamGetPeer, CFStreamGetLocalAddress, - CFStreamGetFD, - CFStreamCanTrackErr}; - -grpc_endpoint* grpc_cfstream_endpoint_create( - CFReadStreamRef read_stream, CFWriteStreamRef write_stream, - const char* peer_string, grpc_resource_quota* resource_quota, - CFStreamHandle* stream_sync) { + CFStreamGetFD, + CFStreamCanTrackErr}; + +grpc_endpoint* grpc_cfstream_endpoint_create( + CFReadStreamRef read_stream, CFWriteStreamRef write_stream, + const char* peer_string, grpc_resource_quota* resource_quota, + CFStreamHandle* stream_sync) { CFStreamEndpoint* ep_impl = new CFStreamEndpoint; - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, - "CFStream endpoint:%p create readStream:%p writeStream: %p", - ep_impl, read_stream, write_stream); - } - ep_impl->base.vtable = &vtable; - gpr_ref_init(&ep_impl->refcount, 1); - ep_impl->read_stream = read_stream; - ep_impl->write_stream = write_stream; - CFRetain(read_stream); - CFRetain(write_stream); - ep_impl->stream_sync = stream_sync; - CFSTREAM_HANDLE_REF(ep_impl->stream_sync, "endpoint create"); - + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, + "CFStream endpoint:%p create readStream:%p writeStream: %p", + ep_impl, read_stream, write_stream); + } + ep_impl->base.vtable = &vtable; + gpr_ref_init(&ep_impl->refcount, 1); + ep_impl->read_stream = read_stream; + ep_impl->write_stream = write_stream; + CFRetain(read_stream); + CFRetain(write_stream); + ep_impl->stream_sync = stream_sync; + CFSTREAM_HANDLE_REF(ep_impl->stream_sync, "endpoint create"); + ep_impl->peer_string = peer_string; grpc_resolved_address resolved_local_addr; resolved_local_addr.len = sizeof(resolved_local_addr.addr); @@ -381,21 +381,21 @@ grpc_endpoint* grpc_cfstream_endpoint_create( } else { ep_impl->local_address = grpc_sockaddr_to_uri(&resolved_local_addr); } - ep_impl->read_cb = nil; - ep_impl->write_cb = nil; - ep_impl->read_slices = nil; - ep_impl->write_slices = nil; - GRPC_CLOSURE_INIT(&ep_impl->read_action, ReadAction, - static_cast<void*>(ep_impl), grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&ep_impl->write_action, WriteAction, - static_cast<void*>(ep_impl), grpc_schedule_on_exec_ctx); - ep_impl->resource_user = - grpc_resource_user_create(resource_quota, peer_string); - grpc_resource_user_slice_allocator_init(&ep_impl->slice_allocator, - ep_impl->resource_user, - CFStreamReadAllocationDone, ep_impl); - - return &ep_impl->base; -} - -#endif /* GRPC_CFSTREAM_ENDPOINT */ + ep_impl->read_cb = nil; + ep_impl->write_cb = nil; + ep_impl->read_slices = nil; + ep_impl->write_slices = nil; + GRPC_CLOSURE_INIT(&ep_impl->read_action, ReadAction, + static_cast<void*>(ep_impl), grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&ep_impl->write_action, WriteAction, + static_cast<void*>(ep_impl), grpc_schedule_on_exec_ctx); + ep_impl->resource_user = + grpc_resource_user_create(resource_quota, peer_string); + grpc_resource_user_slice_allocator_init(&ep_impl->slice_allocator, + ep_impl->resource_user, + CFStreamReadAllocationDone, ep_impl); + + return &ep_impl->base; +} + +#endif /* GRPC_CFSTREAM_ENDPOINT */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.h b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.h index ef957c1f11..72e60dc8ca 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/endpoint_cfstream.h @@ -1,49 +1,49 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_IOMGR_ENDPOINT_CFSTREAM_H -#define GRPC_CORE_LIB_IOMGR_ENDPOINT_CFSTREAM_H -/* - Low level TCP "bottom half" implementation, for use by transports built on - top of a TCP connection. - - Note that this file does not (yet) include APIs for creating the socket in - the first place. - - All calls passing slice transfer ownership of a slice refcount unless - otherwise specified. -*/ - -#include <grpc/support/port_platform.h> - -#ifdef GRPC_CFSTREAM - -#import <CoreFoundation/CoreFoundation.h> - -#include "src/core/lib/debug/trace.h" -#include "src/core/lib/iomgr/cfstream_handle.h" -#include "src/core/lib/iomgr/endpoint.h" - -grpc_endpoint* grpc_cfstream_endpoint_create( - CFReadStreamRef read_stream, CFWriteStreamRef write_stream, - const char* peer_string, grpc_resource_quota* resource_quota, - CFStreamHandle* stream_sync); - -#endif /* GRPC_CFSTREAM */ - -#endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_CFSTREAM_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_IOMGR_ENDPOINT_CFSTREAM_H +#define GRPC_CORE_LIB_IOMGR_ENDPOINT_CFSTREAM_H +/* + Low level TCP "bottom half" implementation, for use by transports built on + top of a TCP connection. + + Note that this file does not (yet) include APIs for creating the socket in + the first place. + + All calls passing slice transfer ownership of a slice refcount unless + otherwise specified. +*/ + +#include <grpc/support/port_platform.h> + +#ifdef GRPC_CFSTREAM + +#import <CoreFoundation/CoreFoundation.h> + +#include "src/core/lib/debug/trace.h" +#include "src/core/lib/iomgr/cfstream_handle.h" +#include "src/core/lib/iomgr/endpoint.h" + +grpc_endpoint* grpc_cfstream_endpoint_create( + CFReadStreamRef read_stream, CFWriteStreamRef write_stream, + const char* peer_string, grpc_resource_quota* resource_quota, + CFStreamHandle* stream_sync); + +#endif /* GRPC_CFSTREAM */ + +#endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_CFSTREAM_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error.cc b/contrib/libs/grpc/src/core/lib/iomgr/error.cc index c4b5c73952..951a94ae7d 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/error.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/error.cc @@ -124,7 +124,7 @@ static const char* error_time_name(grpc_error_times key) { } #ifndef NDEBUG -grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line) { +grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line) { if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err, gpr_atm_no_barrier_load(&err->atomics.refs.count), @@ -134,7 +134,7 @@ grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line) { return err; } #else -grpc_error* grpc_error_do_ref(grpc_error* err) { +grpc_error* grpc_error_do_ref(grpc_error* err) { gpr_ref(&err->atomics.refs); return err; } @@ -171,7 +171,7 @@ static void error_destroy(grpc_error* err) { } #ifndef NDEBUG -void grpc_error_do_unref(grpc_error* err, const char* file, int line) { +void grpc_error_do_unref(grpc_error* err, const char* file, int line) { if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p: %" PRIdPTR " -> %" PRIdPTR " [%s:%d]", err, gpr_atm_no_barrier_load(&err->atomics.refs.count), @@ -182,7 +182,7 @@ void grpc_error_do_unref(grpc_error* err, const char* file, int line) { } } #else -void grpc_error_do_unref(grpc_error* err) { +void grpc_error_do_unref(grpc_error* err) { if (gpr_unref(&err->atomics.refs)) { error_destroy(err); } @@ -305,16 +305,16 @@ static void internal_add_error(grpc_error** err, grpc_error* new_err) { // It is very common to include and extra int and string in an error #define SURPLUS_CAPACITY (2 * SLOTS_PER_INT + SLOTS_PER_TIME) -static gpr_atm g_error_creation_allowed = true; - -void grpc_disable_error_creation() { - gpr_atm_no_barrier_store(&g_error_creation_allowed, false); -} - -void grpc_enable_error_creation() { - gpr_atm_no_barrier_store(&g_error_creation_allowed, true); -} - +static gpr_atm g_error_creation_allowed = true; + +void grpc_disable_error_creation() { + gpr_atm_no_barrier_store(&g_error_creation_allowed, false); +} + +void grpc_enable_error_creation() { + gpr_atm_no_barrier_store(&g_error_creation_allowed, true); +} + grpc_error* grpc_error_create(const char* file, int line, const grpc_slice& desc, grpc_error** referencing, size_t num_referencing) { @@ -329,12 +329,12 @@ grpc_error* grpc_error_create(const char* file, int line, return GRPC_ERROR_OOM; } #ifndef NDEBUG - if (!gpr_atm_no_barrier_load(&g_error_creation_allowed)) { - gpr_log(GPR_ERROR, - "Error creation occurred when error creation was disabled [%s:%d]", - file, line); - abort(); - } + if (!gpr_atm_no_barrier_load(&g_error_creation_allowed)) { + gpr_log(GPR_ERROR, + "Error creation occurred when error creation was disabled [%s:%d]", + file, line); + abort(); + } if (grpc_trace_error_refcount.enabled()) { gpr_log(GPR_DEBUG, "%p create [%s:%d]", err, file, line); } @@ -464,9 +464,9 @@ const special_error_status_map error_status_map[] = { bool grpc_error_get_int(grpc_error* err, grpc_error_ints which, intptr_t* p) { GPR_TIMER_SCOPE("grpc_error_get_int", 0); if (grpc_error_is_special(err)) { - if (which != GRPC_ERROR_INT_GRPC_STATUS) return false; - *p = error_status_map[reinterpret_cast<size_t>(err)].code; - return true; + if (which != GRPC_ERROR_INT_GRPC_STATUS) return false; + *p = error_status_map[reinterpret_cast<size_t>(err)].code; + return true; } uint8_t slot = err->ints[which]; if (slot != UINT8_MAX) { @@ -487,14 +487,14 @@ grpc_error* grpc_error_set_str(grpc_error* src, grpc_error_strs which, bool grpc_error_get_str(grpc_error* err, grpc_error_strs which, grpc_slice* str) { if (grpc_error_is_special(err)) { - if (which != GRPC_ERROR_STR_GRPC_MESSAGE) return false; + if (which != GRPC_ERROR_STR_GRPC_MESSAGE) return false; const special_error_status_map& msg = error_status_map[reinterpret_cast<size_t>(err)]; str->refcount = &grpc_core::kNoopRefcount; str->data.refcounted.bytes = reinterpret_cast<uint8_t*>(const_cast<char*>(msg.msg)); str->data.refcounted.length = msg.len; - return true; + return true; } uint8_t slot = err->strs[which]; if (slot != UINT8_MAX) { @@ -507,24 +507,24 @@ bool grpc_error_get_str(grpc_error* err, grpc_error_strs which, grpc_error* grpc_error_add_child(grpc_error* src, grpc_error* child) { GPR_TIMER_SCOPE("grpc_error_add_child", 0); - if (src != GRPC_ERROR_NONE) { - if (child == GRPC_ERROR_NONE) { - /* \a child is empty. Simply return the ref to \a src */ - return src; - } else if (child != src) { - grpc_error* new_err = copy_error_and_unref(src); - internal_add_error(&new_err, child); - return new_err; - } else { - /* \a src and \a child are the same. Drop one of the references and return - * the other */ - GRPC_ERROR_UNREF(child); - return src; - } - } else { - /* \a src is empty. Simply return the ref to \a child */ - return child; - } + if (src != GRPC_ERROR_NONE) { + if (child == GRPC_ERROR_NONE) { + /* \a child is empty. Simply return the ref to \a src */ + return src; + } else if (child != src) { + grpc_error* new_err = copy_error_and_unref(src); + internal_add_error(&new_err, child); + return new_err; + } else { + /* \a src and \a child are the same. Drop one of the references and return + * the other */ + GRPC_ERROR_UNREF(child); + return src; + } + } else { + /* \a src is empty. Simply return the ref to \a child */ + return child; + } } static const char* no_error_string = "\"No Error\""; @@ -779,7 +779,7 @@ grpc_error* grpc_os_error(const char* file, int line, int err, grpc_error_set_str( grpc_error_set_int( grpc_error_create(file, line, - grpc_slice_from_static_string(strerror(err)), + grpc_slice_from_static_string(strerror(err)), nullptr, 0), GRPC_ERROR_INT_ERRNO, err), GRPC_ERROR_STR_OS_ERROR, diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error.h b/contrib/libs/grpc/src/core/lib/iomgr/error.h index ac3ff87628..4af6301043 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/error.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/error.h @@ -122,21 +122,21 @@ typedef enum { /// polling engines) can safely use the lower bit for themselves. #define GRPC_ERROR_NONE ((grpc_error*)NULL) -#define GRPC_ERROR_RESERVED_1 ((grpc_error*)1) +#define GRPC_ERROR_RESERVED_1 ((grpc_error*)1) #define GRPC_ERROR_OOM ((grpc_error*)2) -#define GRPC_ERROR_RESERVED_2 ((grpc_error*)3) +#define GRPC_ERROR_RESERVED_2 ((grpc_error*)3) #define GRPC_ERROR_CANCELLED ((grpc_error*)4) -#define GRPC_ERROR_SPECIAL_MAX GRPC_ERROR_CANCELLED - -inline bool grpc_error_is_special(struct grpc_error* err) { - return err <= GRPC_ERROR_SPECIAL_MAX; -} - -// debug only toggles that allow for a sanity to check that ensures we will -// never create any errors in the per-RPC hotpath. -void grpc_disable_error_creation(); -void grpc_enable_error_creation(); - +#define GRPC_ERROR_SPECIAL_MAX GRPC_ERROR_CANCELLED + +inline bool grpc_error_is_special(struct grpc_error* err) { + return err <= GRPC_ERROR_SPECIAL_MAX; +} + +// debug only toggles that allow for a sanity to check that ensures we will +// never create any errors in the per-RPC hotpath. +void grpc_disable_error_creation(); +void grpc_enable_error_creation(); + const char* grpc_error_string(grpc_error* error); /// Create an error - but use GRPC_ERROR_CREATE instead @@ -171,29 +171,29 @@ grpc_error* grpc_error_create(const char* file, int line, grpc_error_create_from_vector(__FILE__, __LINE__, desc, error_list) #ifndef NDEBUG -grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line); -void grpc_error_do_unref(grpc_error* err, const char* file, int line); -inline grpc_error* grpc_error_ref(grpc_error* err, const char* file, int line) { - if (grpc_error_is_special(err)) return err; - return grpc_error_do_ref(err, file, line); -} -inline void grpc_error_unref(grpc_error* err, const char* file, int line) { - if (grpc_error_is_special(err)) return; - grpc_error_do_unref(err, file, line); -} +grpc_error* grpc_error_do_ref(grpc_error* err, const char* file, int line); +void grpc_error_do_unref(grpc_error* err, const char* file, int line); +inline grpc_error* grpc_error_ref(grpc_error* err, const char* file, int line) { + if (grpc_error_is_special(err)) return err; + return grpc_error_do_ref(err, file, line); +} +inline void grpc_error_unref(grpc_error* err, const char* file, int line) { + if (grpc_error_is_special(err)) return; + grpc_error_do_unref(err, file, line); +} #define GRPC_ERROR_REF(err) grpc_error_ref(err, __FILE__, __LINE__) #define GRPC_ERROR_UNREF(err) grpc_error_unref(err, __FILE__, __LINE__) #else -grpc_error* grpc_error_do_ref(grpc_error* err); -void grpc_error_do_unref(grpc_error* err); -inline grpc_error* grpc_error_ref(grpc_error* err) { - if (grpc_error_is_special(err)) return err; - return grpc_error_do_ref(err); -} -inline void grpc_error_unref(grpc_error* err) { - if (grpc_error_is_special(err)) return; - grpc_error_do_unref(err); -} +grpc_error* grpc_error_do_ref(grpc_error* err); +void grpc_error_do_unref(grpc_error* err); +inline grpc_error* grpc_error_ref(grpc_error* err) { + if (grpc_error_is_special(err)) return err; + return grpc_error_do_ref(err); +} +inline void grpc_error_unref(grpc_error* err) { + if (grpc_error_is_special(err)) return; + grpc_error_do_unref(err); +} #define GRPC_ERROR_REF(err) grpc_error_ref(err) #define GRPC_ERROR_UNREF(err) grpc_error_unref(err) #endif @@ -219,8 +219,8 @@ static grpc_error* grpc_error_create_from_vector(const char* file, int line, grpc_error* grpc_error_set_int(grpc_error* src, grpc_error_ints which, intptr_t value) GRPC_MUST_USE_RESULT; -/// It is an error to pass nullptr as `p`. Caller should allocate a dummy -/// intptr_t for `p`, even if the value of `p` is not used. +/// It is an error to pass nullptr as `p`. Caller should allocate a dummy +/// intptr_t for `p`, even if the value of `p` is not used. bool grpc_error_get_int(grpc_error* error, grpc_error_ints which, intptr_t* p); /// This call takes ownership of the slice; the error is responsible for /// eventually unref-ing it. @@ -235,16 +235,16 @@ bool grpc_error_get_str(grpc_error* error, grpc_error_strs which, /// error occurring. Allows root causing high level errors from lower level /// errors that contributed to them. The src error takes ownership of the /// child error. -/// -/// Edge Conditions - -/// 1) If either of \a src or \a child is GRPC_ERROR_NONE, returns a reference -/// to the other argument. 2) If both \a src and \a child are GRPC_ERROR_NONE, -/// returns GRPC_ERROR_NONE. 3) If \a src and \a child point to the same error, -/// returns a single reference. (Note that, 2 references should have been -/// received to the error in this case.) +/// +/// Edge Conditions - +/// 1) If either of \a src or \a child is GRPC_ERROR_NONE, returns a reference +/// to the other argument. 2) If both \a src and \a child are GRPC_ERROR_NONE, +/// returns GRPC_ERROR_NONE. 3) If \a src and \a child point to the same error, +/// returns a single reference. (Note that, 2 references should have been +/// received to the error in this case.) grpc_error* grpc_error_add_child(grpc_error* src, grpc_error* child) GRPC_MUST_USE_RESULT; - + grpc_error* grpc_os_error(const char* file, int line, int err, const char* call_name) GRPC_MUST_USE_RESULT; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.cc index 62f6bc1d40..84887d5196 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.cc @@ -1,53 +1,53 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#ifdef GRPC_CFSTREAM +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#ifdef GRPC_CFSTREAM #include <util/generic/string.h> #include "y_absl/strings/str_format.h" -#include <CoreFoundation/CoreFoundation.h> - -#include <grpc/support/alloc.h> - -#include "src/core/lib/iomgr/error.h" - -#define MAX_ERROR_DESCRIPTION 256 - -grpc_error* grpc_error_create_from_cferror(const char* file, int line, - void* arg, const char* custom_desc) { - CFErrorRef error = static_cast<CFErrorRef>(arg); - char buf_domain[MAX_ERROR_DESCRIPTION]; - char buf_desc[MAX_ERROR_DESCRIPTION]; - CFErrorDomain domain = CFErrorGetDomain((error)); - CFIndex code = CFErrorGetCode((error)); - CFStringRef desc = CFErrorCopyDescription((error)); - CFStringGetCString(domain, buf_domain, MAX_ERROR_DESCRIPTION, - kCFStringEncodingUTF8); - CFStringGetCString(desc, buf_desc, MAX_ERROR_DESCRIPTION, - kCFStringEncodingUTF8); +#include <CoreFoundation/CoreFoundation.h> + +#include <grpc/support/alloc.h> + +#include "src/core/lib/iomgr/error.h" + +#define MAX_ERROR_DESCRIPTION 256 + +grpc_error* grpc_error_create_from_cferror(const char* file, int line, + void* arg, const char* custom_desc) { + CFErrorRef error = static_cast<CFErrorRef>(arg); + char buf_domain[MAX_ERROR_DESCRIPTION]; + char buf_desc[MAX_ERROR_DESCRIPTION]; + CFErrorDomain domain = CFErrorGetDomain((error)); + CFIndex code = CFErrorGetCode((error)); + CFStringRef desc = CFErrorCopyDescription((error)); + CFStringGetCString(domain, buf_domain, MAX_ERROR_DESCRIPTION, + kCFStringEncodingUTF8); + CFStringGetCString(desc, buf_desc, MAX_ERROR_DESCRIPTION, + kCFStringEncodingUTF8); TString error_msg = y_absl::StrFormat("%s (error domain:%s, code:%ld, description:%s)", custom_desc, buf_domain, code, buf_desc); - CFRelease(desc); + CFRelease(desc); return grpc_error_create( file, line, grpc_slice_from_copied_string(error_msg.c_str()), NULL, 0); -} -#endif /* GRPC_CFSTREAM */ +} +#endif /* GRPC_CFSTREAM */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.h b/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.h index 06ab751329..52934e7d11 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/error_cfstream.h @@ -1,31 +1,31 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_IOMGR_ERROR_CFSTREAM_H -#define GRPC_CORE_LIB_IOMGR_ERROR_CFSTREAM_H - -#ifdef GRPC_CFSTREAM -// Create an error from Apple Core Foundation CFError object -#define GRPC_ERROR_CREATE_FROM_CFERROR(error, desc) \ - grpc_error_create_from_cferror(__FILE__, __LINE__, \ - static_cast<void*>((error)), (desc)) -grpc_error* grpc_error_create_from_cferror(const char* file, int line, - void* arg, const char* desc); -#endif /* GRPC_CFSTREAM */ - -#endif /* GRPC_CORE_LIB_IOMGR_ERROR_CFSTREAM_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_IOMGR_ERROR_CFSTREAM_H +#define GRPC_CORE_LIB_IOMGR_ERROR_CFSTREAM_H + +#ifdef GRPC_CFSTREAM +// Create an error from Apple Core Foundation CFError object +#define GRPC_ERROR_CREATE_FROM_CFERROR(error, desc) \ + grpc_error_create_from_cferror(__FILE__, __LINE__, \ + static_cast<void*>((error)), (desc)) +grpc_error* grpc_error_create_from_cferror(const char* file, int line, + void* arg, const char* desc); +#endif /* GRPC_CFSTREAM */ + +#endif /* GRPC_CORE_LIB_IOMGR_ERROR_CFSTREAM_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc index f09dcee0c0..15c215bbb6 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_epoll1_linux.cc @@ -137,26 +137,26 @@ static void epoll_set_shutdown() { * Fd Declarations */ -/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ -struct grpc_fork_fd_list { - grpc_fd* fd; - grpc_fd* next; - grpc_fd* prev; -}; - +/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ +struct grpc_fork_fd_list { + grpc_fd* fd; + grpc_fd* next; + grpc_fd* prev; +}; + struct grpc_fd { int fd; grpc_core::ManualConstructor<grpc_core::LockfreeEvent> read_closure; grpc_core::ManualConstructor<grpc_core::LockfreeEvent> write_closure; - grpc_core::ManualConstructor<grpc_core::LockfreeEvent> error_closure; + grpc_core::ManualConstructor<grpc_core::LockfreeEvent> error_closure; struct grpc_fd* freelist_next; - grpc_iomgr_object iomgr_object; + grpc_iomgr_object iomgr_object; - /* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ - grpc_fork_fd_list* fork_fd_list; + /* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ + grpc_fork_fd_list* fork_fd_list; }; static void fd_global_init(void); @@ -199,13 +199,13 @@ struct grpc_pollset_worker { #define MAX_NEIGHBORHOODS 1024 typedef struct pollset_neighborhood { - union { - char pad[GPR_CACHELINE_SIZE]; - struct { - gpr_mu mu; - grpc_pollset* active_root; - }; - }; + union { + char pad[GPR_CACHELINE_SIZE]; + struct { + gpr_mu mu; + grpc_pollset* active_root; + }; + }; } pollset_neighborhood; struct grpc_pollset { @@ -276,17 +276,17 @@ static bool append_error(grpc_error** composite, grpc_error* error, static grpc_fd* fd_freelist = nullptr; static gpr_mu fd_freelist_mu; -/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ -static grpc_fd* fork_fd_list_head = nullptr; -static gpr_mu fork_fd_list_mu; - +/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ +static grpc_fd* fork_fd_list_head = nullptr; +static gpr_mu fork_fd_list_mu; + static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } static void fd_global_shutdown(void) { - // TODO(guantaol): We don't have a reasonable explanation about this - // lock()/unlock() pattern. It can be a valid barrier if there is at most one - // pending lock() at this point. Otherwise, there is still a possibility of - // use-after-free race. Need to reason about the code and/or clean it up. + // TODO(guantaol): We don't have a reasonable explanation about this + // lock()/unlock() pattern. It can be a valid barrier if there is at most one + // pending lock() at this point. Otherwise, there is still a possibility of + // use-after-free race. Need to reason about the code and/or clean it up. gpr_mu_lock(&fd_freelist_mu); gpr_mu_unlock(&fd_freelist_mu); while (fd_freelist != nullptr) { @@ -297,39 +297,39 @@ static void fd_global_shutdown(void) { gpr_mu_destroy(&fd_freelist_mu); } -static void fork_fd_list_add_grpc_fd(grpc_fd* fd) { - if (grpc_core::Fork::Enabled()) { - gpr_mu_lock(&fork_fd_list_mu); - fd->fork_fd_list = - static_cast<grpc_fork_fd_list*>(gpr_malloc(sizeof(grpc_fork_fd_list))); - fd->fork_fd_list->next = fork_fd_list_head; - fd->fork_fd_list->prev = nullptr; - if (fork_fd_list_head != nullptr) { - fork_fd_list_head->fork_fd_list->prev = fd; - } - fork_fd_list_head = fd; - gpr_mu_unlock(&fork_fd_list_mu); - } -} - -static void fork_fd_list_remove_grpc_fd(grpc_fd* fd) { - if (grpc_core::Fork::Enabled()) { - gpr_mu_lock(&fork_fd_list_mu); - if (fork_fd_list_head == fd) { - fork_fd_list_head = fd->fork_fd_list->next; - } - if (fd->fork_fd_list->prev != nullptr) { - fd->fork_fd_list->prev->fork_fd_list->next = fd->fork_fd_list->next; - } - if (fd->fork_fd_list->next != nullptr) { - fd->fork_fd_list->next->fork_fd_list->prev = fd->fork_fd_list->prev; - } - gpr_free(fd->fork_fd_list); - gpr_mu_unlock(&fork_fd_list_mu); - } -} - -static grpc_fd* fd_create(int fd, const char* name, bool track_err) { +static void fork_fd_list_add_grpc_fd(grpc_fd* fd) { + if (grpc_core::Fork::Enabled()) { + gpr_mu_lock(&fork_fd_list_mu); + fd->fork_fd_list = + static_cast<grpc_fork_fd_list*>(gpr_malloc(sizeof(grpc_fork_fd_list))); + fd->fork_fd_list->next = fork_fd_list_head; + fd->fork_fd_list->prev = nullptr; + if (fork_fd_list_head != nullptr) { + fork_fd_list_head->fork_fd_list->prev = fd; + } + fork_fd_list_head = fd; + gpr_mu_unlock(&fork_fd_list_mu); + } +} + +static void fork_fd_list_remove_grpc_fd(grpc_fd* fd) { + if (grpc_core::Fork::Enabled()) { + gpr_mu_lock(&fork_fd_list_mu); + if (fork_fd_list_head == fd) { + fork_fd_list_head = fd->fork_fd_list->next; + } + if (fd->fork_fd_list->prev != nullptr) { + fd->fork_fd_list->prev->fork_fd_list->next = fd->fork_fd_list->next; + } + if (fd->fork_fd_list->next != nullptr) { + fd->fork_fd_list->next->fork_fd_list->prev = fd->fork_fd_list->prev; + } + gpr_free(fd->fork_fd_list); + gpr_mu_unlock(&fork_fd_list_mu); + } +} + +static grpc_fd* fd_create(int fd, const char* name, bool track_err) { grpc_fd* new_fd = nullptr; gpr_mu_lock(&fd_freelist_mu); @@ -343,18 +343,18 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) { new_fd = static_cast<grpc_fd*>(gpr_malloc(sizeof(grpc_fd))); new_fd->read_closure.Init(); new_fd->write_closure.Init(); - new_fd->error_closure.Init(); + new_fd->error_closure.Init(); } new_fd->fd = fd; new_fd->read_closure->InitEvent(); new_fd->write_closure->InitEvent(); - new_fd->error_closure->InitEvent(); + new_fd->error_closure->InitEvent(); new_fd->freelist_next = nullptr; TString fd_name = y_absl::StrCat(name, " fd=", fd); grpc_iomgr_register_object(&new_fd->iomgr_object, fd_name.c_str()); - fork_fd_list_add_grpc_fd(new_fd); + fork_fd_list_add_grpc_fd(new_fd); #ifndef NDEBUG if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) { gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, new_fd, fd_name.c_str()); @@ -363,13 +363,13 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) { struct epoll_event ev; ev.events = static_cast<uint32_t>(EPOLLIN | EPOLLOUT | EPOLLET); - /* Use the least significant bit of ev.data.ptr to store track_err. We expect - * the addresses to be word aligned. We need to store track_err to avoid - * synchronization issues when accessing it after receiving an event. - * Accessing fd would be a data race there because the fd might have been - * returned to the free list at that point. */ - ev.data.ptr = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(new_fd) | - (track_err ? 1 : 0)); + /* Use the least significant bit of ev.data.ptr to store track_err. We expect + * the addresses to be word aligned. We need to store track_err to avoid + * synchronization issues when accessing it after receiving an event. + * Accessing fd would be a data race there because the fd might have been + * returned to the free list at that point. */ + ev.data.ptr = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(new_fd) | + (track_err ? 1 : 0)); if (epoll_ctl(g_epoll_set.epfd, EPOLL_CTL_ADD, fd, &ev) != 0) { gpr_log(GPR_ERROR, "epoll_ctl failed: %s", strerror(errno)); } @@ -396,7 +396,7 @@ static void fd_shutdown_internal(grpc_fd* fd, grpc_error* why, } } fd->write_closure->SetShutdown(GRPC_ERROR_REF(why)); - fd->error_closure->SetShutdown(GRPC_ERROR_REF(why)); + fd->error_closure->SetShutdown(GRPC_ERROR_REF(why)); } GRPC_ERROR_UNREF(why); } @@ -407,7 +407,7 @@ static void fd_shutdown(grpc_fd* fd, grpc_error* why) { } static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, - const char* reason) { + const char* reason) { grpc_error* error = GRPC_ERROR_NONE; bool is_release_fd = (release_fd != nullptr); @@ -420,17 +420,17 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, descriptor fd->fd (but we still own the grpc_fd structure). */ if (is_release_fd) { *release_fd = fd->fd; - } else { + } else { close(fd->fd); } grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_done, GRPC_ERROR_REF(error)); grpc_iomgr_unregister_object(&fd->iomgr_object); - fork_fd_list_remove_grpc_fd(fd); + fork_fd_list_remove_grpc_fd(fd); fd->read_closure->DestroyEvent(); fd->write_closure->DestroyEvent(); - fd->error_closure->DestroyEvent(); + fd->error_closure->DestroyEvent(); gpr_mu_lock(&fd_freelist_mu); fd->freelist_next = fd_freelist; @@ -450,16 +450,16 @@ static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) { fd->write_closure->NotifyOn(closure); } -static void fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) { - fd->error_closure->NotifyOn(closure); +static void fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) { + fd->error_closure->NotifyOn(closure); } -static void fd_become_readable(grpc_fd* fd) { fd->read_closure->SetReady(); } - +static void fd_become_readable(grpc_fd* fd) { fd->read_closure->SetReady(); } + static void fd_become_writable(grpc_fd* fd) { fd->write_closure->SetReady(); } -static void fd_has_errors(grpc_fd* fd) { fd->error_closure->SetReady(); } - +static void fd_has_errors(grpc_fd* fd) { fd->error_closure->SetReady(); } + /******************************************************************************* * Pollset Definitions */ @@ -681,25 +681,25 @@ static grpc_error* process_epoll_events(grpc_pollset* /*pollset*/) { append_error(&error, grpc_wakeup_fd_consume_wakeup(&global_wakeup_fd), err_desc); } else { - grpc_fd* fd = reinterpret_cast<grpc_fd*>( - reinterpret_cast<intptr_t>(data_ptr) & ~static_cast<intptr_t>(1)); - bool track_err = - reinterpret_cast<intptr_t>(data_ptr) & static_cast<intptr_t>(1); - bool cancel = (ev->events & EPOLLHUP) != 0; - bool error = (ev->events & EPOLLERR) != 0; + grpc_fd* fd = reinterpret_cast<grpc_fd*>( + reinterpret_cast<intptr_t>(data_ptr) & ~static_cast<intptr_t>(1)); + bool track_err = + reinterpret_cast<intptr_t>(data_ptr) & static_cast<intptr_t>(1); + bool cancel = (ev->events & EPOLLHUP) != 0; + bool error = (ev->events & EPOLLERR) != 0; bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0; bool write_ev = (ev->events & EPOLLOUT) != 0; - bool err_fallback = error && !track_err; + bool err_fallback = error && !track_err; - if (error && !err_fallback) { - fd_has_errors(fd); + if (error && !err_fallback) { + fd_has_errors(fd); } - if (read_ev || cancel || err_fallback) { - fd_become_readable(fd); - } - - if (write_ev || cancel || err_fallback) { + if (read_ev || cancel || err_fallback) { + fd_become_readable(fd); + } + + if (write_ev || cancel || err_fallback) { fd_become_writable(fd); } } @@ -1248,10 +1248,10 @@ static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/, * Event engine binding */ -static bool is_any_background_poller_thread(void) { return false; } - -static void shutdown_background_closure(void) {} - +static bool is_any_background_poller_thread(void) { return false; } + +static void shutdown_background_closure(void) {} + static bool add_closure_to_background_poller(grpc_closure* /*closure*/, grpc_error* /*error*/) { return false; @@ -1261,16 +1261,16 @@ static void shutdown_engine(void) { fd_global_shutdown(); pollset_global_shutdown(); epoll_set_shutdown(); - if (grpc_core::Fork::Enabled()) { - gpr_mu_destroy(&fork_fd_list_mu); - grpc_core::Fork::SetResetChildPollingEngineFunc(nullptr); - } + if (grpc_core::Fork::Enabled()) { + gpr_mu_destroy(&fork_fd_list_mu); + grpc_core::Fork::SetResetChildPollingEngineFunc(nullptr); + } } static const grpc_event_engine_vtable vtable = { sizeof(grpc_pollset), - true, - false, + true, + false, fd_create, fd_wrapped_fd, @@ -1278,10 +1278,10 @@ static const grpc_event_engine_vtable vtable = { fd_shutdown, fd_notify_on_read, fd_notify_on_write, - fd_notify_on_error, - fd_become_readable, - fd_become_writable, - fd_has_errors, + fd_notify_on_error, + fd_become_readable, + fd_become_writable, + fd_has_errors, fd_is_shutdown, pollset_init, @@ -1300,27 +1300,27 @@ static const grpc_event_engine_vtable vtable = { pollset_set_add_fd, pollset_set_del_fd, - is_any_background_poller_thread, - shutdown_background_closure, + is_any_background_poller_thread, + shutdown_background_closure, shutdown_engine, add_closure_to_background_poller, }; -/* Called by the child process's post-fork handler to close open fds, including - * the global epoll fd. This allows gRPC to shutdown in the child process - * without interfering with connections or RPCs ongoing in the parent. */ -static void reset_event_manager_on_fork() { - gpr_mu_lock(&fork_fd_list_mu); - while (fork_fd_list_head != nullptr) { - close(fork_fd_list_head->fd); - fork_fd_list_head->fd = -1; - fork_fd_list_head = fork_fd_list_head->fork_fd_list->next; - } - gpr_mu_unlock(&fork_fd_list_mu); - shutdown_engine(); - grpc_init_epoll1_linux(true); -} - +/* Called by the child process's post-fork handler to close open fds, including + * the global epoll fd. This allows gRPC to shutdown in the child process + * without interfering with connections or RPCs ongoing in the parent. */ +static void reset_event_manager_on_fork() { + gpr_mu_lock(&fork_fd_list_mu); + while (fork_fd_list_head != nullptr) { + close(fork_fd_list_head->fd); + fork_fd_list_head->fd = -1; + fork_fd_list_head = fork_fd_list_head->fork_fd_list->next; + } + gpr_mu_unlock(&fork_fd_list_mu); + shutdown_engine(); + grpc_init_epoll1_linux(true); +} + /* It is possible that GLIBC has epoll but the underlying kernel doesn't. * Create epoll_fd (epoll_set_init() takes care of that) to make sure epoll * support is available */ @@ -1343,16 +1343,16 @@ const grpc_event_engine_vtable* grpc_init_epoll1_linux( return nullptr; } - if (grpc_core::Fork::Enabled()) { - gpr_mu_init(&fork_fd_list_mu); - grpc_core::Fork::SetResetChildPollingEngineFunc( - reset_event_manager_on_fork); - } + if (grpc_core::Fork::Enabled()) { + gpr_mu_init(&fork_fd_list_mu); + grpc_core::Fork::SetResetChildPollingEngineFunc( + reset_event_manager_on_fork); + } return &vtable; } #else /* defined(GRPC_LINUX_EPOLL) */ -#if defined(GRPC_POSIX_SOCKET_EV_EPOLL1) +#if defined(GRPC_POSIX_SOCKET_EV_EPOLL1) #include "src/core/lib/iomgr/ev_epoll1_linux.h" /* If GRPC_LINUX_EPOLL is not defined, it means epoll is not available. Return * NULL */ @@ -1360,5 +1360,5 @@ const grpc_event_engine_vtable* grpc_init_epoll1_linux( bool /*explicit_request*/) { return nullptr; } -#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLL1) */ +#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLL1) */ #endif /* !defined(GRPC_LINUX_EPOLL) */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc index 2dd9bbdffd..abb95de967 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_epollex_linux.cc @@ -33,7 +33,7 @@ #include <poll.h> #include <pthread.h> #include <string.h> -#include <sys/epoll.h> +#include <sys/epoll.h> #include <sys/socket.h> #include <sys/syscall.h> #include <unistd.h> @@ -67,7 +67,7 @@ //#define GRPC_EPOLLEX_CREATE_WORKERS_ON_HEAP 1 #define MAX_EPOLL_EVENTS 100 -#define MAX_FDS_IN_CACHE 32 +#define MAX_FDS_IN_CACHE 32 grpc_core::DebugOnlyTraceFlag grpc_trace_pollable_refcount(false, "pollable_refcount"); @@ -95,10 +95,10 @@ struct pollable { int epfd; grpc_wakeup_fd wakeup; - // The following are relevant only for type PO_FD - grpc_fd* owner_fd; // Set to the owner_fd if the type is PO_FD - gpr_mu owner_orphan_mu; // Synchronizes access to owner_orphaned field - bool owner_orphaned; // Is the owner fd orphaned + // The following are relevant only for type PO_FD + grpc_fd* owner_fd; // Set to the owner_fd if the type is PO_FD + gpr_mu owner_orphan_mu; // Synchronizes access to owner_orphaned field + bool owner_orphaned; // Is the owner fd orphaned grpc_pollset_set* pollset_set; pollable* next; @@ -161,32 +161,32 @@ static void pollable_unref(pollable* p, const grpc_core::DebugLocation& dbg_loc, */ struct grpc_fd { - grpc_fd(int fd, const char* name, bool track_err) - : fd(fd), track_err(track_err) { - gpr_mu_init(&orphan_mu); - gpr_mu_init(&pollable_mu); - read_closure.InitEvent(); - write_closure.InitEvent(); - error_closure.InitEvent(); - + grpc_fd(int fd, const char* name, bool track_err) + : fd(fd), track_err(track_err) { + gpr_mu_init(&orphan_mu); + gpr_mu_init(&pollable_mu); + read_closure.InitEvent(); + write_closure.InitEvent(); + error_closure.InitEvent(); + TString fd_name = y_absl::StrCat(name, " fd=", fd); grpc_iomgr_register_object(&iomgr_object, fd_name.c_str()); -#ifndef NDEBUG +#ifndef NDEBUG if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_fd_refcount)) { gpr_log(GPR_DEBUG, "FD %d %p create %s", fd, this, fd_name.c_str()); - } -#endif - } - - // This is really the dtor, but the poller threads waking up from - // epoll_wait() may access the (read|write|error)_closure after destruction. - // Since the object will be added to the free pool, this behavior is - // not going to cause issues, except spurious events if the FD is reused - // while the race happens. - void destroy() { - grpc_iomgr_unregister_object(&iomgr_object); - - POLLABLE_UNREF(pollable_obj, "fd_pollable"); + } +#endif + } + + // This is really the dtor, but the poller threads waking up from + // epoll_wait() may access the (read|write|error)_closure after destruction. + // Since the object will be added to the free pool, this behavior is + // not going to cause issues, except spurious events if the FD is reused + // while the race happens. + void destroy() { + grpc_iomgr_unregister_object(&iomgr_object); + + POLLABLE_UNREF(pollable_obj, "fd_pollable"); // To clear out the allocations of pollset_fds, we need to swap its // contents with a newly-constructed (and soon to be destructed) local @@ -196,61 +196,61 @@ struct grpc_fd { y_absl::InlinedVector<int, 1> pollset_fds_tmp; pollset_fds_tmp.swap(pollset_fds); - gpr_mu_destroy(&pollable_mu); - gpr_mu_destroy(&orphan_mu); - - read_closure.DestroyEvent(); - write_closure.DestroyEvent(); - error_closure.DestroyEvent(); - - invalidate(); - } - -#ifndef NDEBUG - /* Since an fd is never really destroyed (i.e gpr_free() is not called), it is - * hard-to-debug cases where fd fields are accessed even after calling - * fd_destroy(). The following invalidates fd fields to make catching such - * errors easier */ - void invalidate() { - fd = -1; - gpr_atm_no_barrier_store(&refst, -1); - memset(&orphan_mu, -1, sizeof(orphan_mu)); - memset(&pollable_mu, -1, sizeof(pollable_mu)); - pollable_obj = nullptr; - on_done_closure = nullptr; - memset(&iomgr_object, -1, sizeof(iomgr_object)); - track_err = false; - } -#else - void invalidate() {} -#endif - + gpr_mu_destroy(&pollable_mu); + gpr_mu_destroy(&orphan_mu); + + read_closure.DestroyEvent(); + write_closure.DestroyEvent(); + error_closure.DestroyEvent(); + + invalidate(); + } + +#ifndef NDEBUG + /* Since an fd is never really destroyed (i.e gpr_free() is not called), it is + * hard-to-debug cases where fd fields are accessed even after calling + * fd_destroy(). The following invalidates fd fields to make catching such + * errors easier */ + void invalidate() { + fd = -1; + gpr_atm_no_barrier_store(&refst, -1); + memset(&orphan_mu, -1, sizeof(orphan_mu)); + memset(&pollable_mu, -1, sizeof(pollable_mu)); + pollable_obj = nullptr; + on_done_closure = nullptr; + memset(&iomgr_object, -1, sizeof(iomgr_object)); + track_err = false; + } +#else + void invalidate() {} +#endif + int fd; - // refst format: - // bit 0 : 1=Active / 0=Orphaned - // bits 1-n : refcount - // Ref/Unref by two to avoid altering the orphaned bit - gpr_atm refst = 1; - + // refst format: + // bit 0 : 1=Active / 0=Orphaned + // bits 1-n : refcount + // Ref/Unref by two to avoid altering the orphaned bit + gpr_atm refst = 1; + gpr_mu orphan_mu; - // Protects pollable_obj and pollset_fds. + // Protects pollable_obj and pollset_fds. gpr_mu pollable_mu; y_absl::InlinedVector<int, 1> pollset_fds; // Used in PO_MULTI. pollable* pollable_obj = nullptr; // Used in PO_FD. - grpc_core::LockfreeEvent read_closure; - grpc_core::LockfreeEvent write_closure; - grpc_core::LockfreeEvent error_closure; + grpc_core::LockfreeEvent read_closure; + grpc_core::LockfreeEvent write_closure; + grpc_core::LockfreeEvent error_closure; - struct grpc_fd* freelist_next = nullptr; - grpc_closure* on_done_closure = nullptr; + struct grpc_fd* freelist_next = nullptr; + grpc_closure* on_done_closure = nullptr; - grpc_iomgr_object iomgr_object; + grpc_iomgr_object iomgr_object; - // Do we need to track EPOLLERR events separately? - bool track_err; + // Do we need to track EPOLLERR events separately? + bool track_err; }; static void fd_global_init(void); @@ -283,7 +283,7 @@ struct grpc_pollset_worker { struct grpc_pollset { gpr_mu mu; gpr_atm worker_count; - gpr_atm active_pollable_type; + gpr_atm active_pollable_type; pollable* active_pollable; bool kicked_without_poller; grpc_closure* shutdown_closure; @@ -371,11 +371,11 @@ static void ref_by(grpc_fd* fd, int n) { GPR_ASSERT(gpr_atm_no_barrier_fetch_add(&fd->refst, n) > 0); } -/* Uninitialize and add to the freelist */ +/* Uninitialize and add to the freelist */ static void fd_destroy(void* arg, grpc_error* /*error*/) { grpc_fd* fd = static_cast<grpc_fd*>(arg); - fd->destroy(); - + fd->destroy(); + /* Add the fd to the freelist */ gpr_mu_lock(&fd_freelist_mu); fd->freelist_next = fd_freelist; @@ -409,10 +409,10 @@ static void unref_by(grpc_fd* fd, int n) { static void fd_global_init(void) { gpr_mu_init(&fd_freelist_mu); } static void fd_global_shutdown(void) { - // TODO(guantaol): We don't have a reasonable explanation about this - // lock()/unlock() pattern. It can be a valid barrier if there is at most one - // pending lock() at this point. Otherwise, there is still a possibility of - // use-after-free race. Need to reason about the code and/or clean it up. + // TODO(guantaol): We don't have a reasonable explanation about this + // lock()/unlock() pattern. It can be a valid barrier if there is at most one + // pending lock() at this point. Otherwise, there is still a possibility of + // use-after-free race. Need to reason about the code and/or clean it up. gpr_mu_lock(&fd_freelist_mu); gpr_mu_unlock(&fd_freelist_mu); while (fd_freelist != nullptr) { @@ -423,7 +423,7 @@ static void fd_global_shutdown(void) { gpr_mu_destroy(&fd_freelist_mu); } -static grpc_fd* fd_create(int fd, const char* name, bool track_err) { +static grpc_fd* fd_create(int fd, const char* name, bool track_err) { grpc_fd* new_fd = nullptr; gpr_mu_lock(&fd_freelist_mu); @@ -437,7 +437,7 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) { new_fd = static_cast<grpc_fd*>(gpr_malloc(sizeof(grpc_fd))); } - return new (new_fd) grpc_fd(fd, name, track_err); + return new (new_fd) grpc_fd(fd, name, track_err); } static int fd_wrapped_fd(grpc_fd* fd) { @@ -446,46 +446,46 @@ static int fd_wrapped_fd(grpc_fd* fd) { } static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, - const char* reason) { - bool is_fd_closed = false; + const char* reason) { + bool is_fd_closed = false; gpr_mu_lock(&fd->orphan_mu); - // Get the fd->pollable_obj and set the owner_orphaned on that pollable to - // true so that the pollable will no longer access its owner_fd field. - gpr_mu_lock(&fd->pollable_mu); - pollable* pollable_obj = fd->pollable_obj; - - if (pollable_obj) { - gpr_mu_lock(&pollable_obj->owner_orphan_mu); - pollable_obj->owner_orphaned = true; - } - + // Get the fd->pollable_obj and set the owner_orphaned on that pollable to + // true so that the pollable will no longer access its owner_fd field. + gpr_mu_lock(&fd->pollable_mu); + pollable* pollable_obj = fd->pollable_obj; + + if (pollable_obj) { + gpr_mu_lock(&pollable_obj->owner_orphan_mu); + pollable_obj->owner_orphaned = true; + } + fd->on_done_closure = on_done; /* If release_fd is not NULL, we should be relinquishing control of the file descriptor fd->fd (but we still own the grpc_fd structure). */ if (release_fd != nullptr) { - // Remove the FD from all epolls sets, before releasing it. - // Otherwise, we will receive epoll events after we release the FD. - epoll_event ev_fd; - memset(&ev_fd, 0, sizeof(ev_fd)); + // Remove the FD from all epolls sets, before releasing it. + // Otherwise, we will receive epoll events after we release the FD. + epoll_event ev_fd; + memset(&ev_fd, 0, sizeof(ev_fd)); if (pollable_obj != nullptr) { // For PO_FD. epoll_ctl(pollable_obj->epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd); - } + } for (size_t i = 0; i < fd->pollset_fds.size(); ++i) { // For PO_MULTI. const int epfd = fd->pollset_fds[i]; epoll_ctl(epfd, EPOLL_CTL_DEL, fd->fd, &ev_fd); } *release_fd = fd->fd; - } else { + } else { close(fd->fd); is_fd_closed = true; } - // TODO(sreek): handle fd removal (where is_fd_closed=false) + // TODO(sreek): handle fd removal (where is_fd_closed=false) if (!is_fd_closed) { - GRPC_FD_TRACE("epoll_fd %p (%d) was orphaned but not closed.", fd, fd->fd); + GRPC_FD_TRACE("epoll_fd %p (%d) was orphaned but not closed.", fd, fd->fd); } /* Remove the active status but keep referenced. We want this grpc_fd struct @@ -494,64 +494,64 @@ static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, grpc_core::ExecCtx::Run(DEBUG_LOCATION, fd->on_done_closure, GRPC_ERROR_NONE); - if (pollable_obj) { - gpr_mu_unlock(&pollable_obj->owner_orphan_mu); - } - - gpr_mu_unlock(&fd->pollable_mu); + if (pollable_obj) { + gpr_mu_unlock(&pollable_obj->owner_orphan_mu); + } + + gpr_mu_unlock(&fd->pollable_mu); gpr_mu_unlock(&fd->orphan_mu); UNREF_BY(fd, 2, reason); /* Drop the reference */ } static bool fd_is_shutdown(grpc_fd* fd) { - return fd->read_closure.IsShutdown(); + return fd->read_closure.IsShutdown(); } /* Might be called multiple times */ static void fd_shutdown(grpc_fd* fd, grpc_error* why) { - if (fd->read_closure.SetShutdown(GRPC_ERROR_REF(why))) { - if (shutdown(fd->fd, SHUT_RDWR)) { - if (errno != ENOTCONN) { - gpr_log(GPR_ERROR, "Error shutting down fd %d. errno: %d", - grpc_fd_wrapped_fd(fd), errno); - } - } - fd->write_closure.SetShutdown(GRPC_ERROR_REF(why)); - fd->error_closure.SetShutdown(GRPC_ERROR_REF(why)); + if (fd->read_closure.SetShutdown(GRPC_ERROR_REF(why))) { + if (shutdown(fd->fd, SHUT_RDWR)) { + if (errno != ENOTCONN) { + gpr_log(GPR_ERROR, "Error shutting down fd %d. errno: %d", + grpc_fd_wrapped_fd(fd), errno); + } + } + fd->write_closure.SetShutdown(GRPC_ERROR_REF(why)); + fd->error_closure.SetShutdown(GRPC_ERROR_REF(why)); } GRPC_ERROR_UNREF(why); } static void fd_notify_on_read(grpc_fd* fd, grpc_closure* closure) { - fd->read_closure.NotifyOn(closure); + fd->read_closure.NotifyOn(closure); } static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) { - fd->write_closure.NotifyOn(closure); -} - -static void fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) { - fd->error_closure.NotifyOn(closure); -} - -static bool fd_has_pollset(grpc_fd* fd, grpc_pollset* pollset) { - const int epfd = pollset->active_pollable->epfd; - grpc_core::MutexLock lock(&fd->pollable_mu); - for (size_t i = 0; i < fd->pollset_fds.size(); ++i) { - if (fd->pollset_fds[i] == epfd) { - return true; - } - } - return false; -} - -static void fd_add_pollset(grpc_fd* fd, grpc_pollset* pollset) { - const int epfd = pollset->active_pollable->epfd; - grpc_core::MutexLock lock(&fd->pollable_mu); - fd->pollset_fds.push_back(epfd); + fd->write_closure.NotifyOn(closure); } +static void fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) { + fd->error_closure.NotifyOn(closure); +} + +static bool fd_has_pollset(grpc_fd* fd, grpc_pollset* pollset) { + const int epfd = pollset->active_pollable->epfd; + grpc_core::MutexLock lock(&fd->pollable_mu); + for (size_t i = 0; i < fd->pollset_fds.size(); ++i) { + if (fd->pollset_fds[i] == epfd) { + return true; + } + } + return false; +} + +static void fd_add_pollset(grpc_fd* fd, grpc_pollset* pollset) { + const int epfd = pollset->active_pollable->epfd; + grpc_core::MutexLock lock(&fd->pollable_mu); + fd->pollset_fds.push_back(epfd); +} + /******************************************************************************* * Pollable Definitions */ @@ -563,13 +563,13 @@ static grpc_error* pollable_create(pollable_type type, pollable** p) { if (epfd == -1) { return GRPC_OS_ERROR(errno, "epoll_create1"); } - GRPC_FD_TRACE("Pollable_create: created epfd: %d (type: %d)", epfd, type); + GRPC_FD_TRACE("Pollable_create: created epfd: %d (type: %d)", epfd, type); *p = static_cast<pollable*>(gpr_malloc(sizeof(**p))); grpc_error* err = grpc_wakeup_fd_init(&(*p)->wakeup); if (err != GRPC_ERROR_NONE) { - GRPC_FD_TRACE( - "Pollable_create: closed epfd: %d (type: %d). wakeupfd_init error", - epfd, type); + GRPC_FD_TRACE( + "Pollable_create: closed epfd: %d (type: %d). wakeupfd_init error", + epfd, type); close(epfd); gpr_free(*p); *p = nullptr; @@ -580,9 +580,9 @@ static grpc_error* pollable_create(pollable_type type, pollable** p) { ev.data.ptr = (void*)(1 | (intptr_t) & (*p)->wakeup); if (epoll_ctl(epfd, EPOLL_CTL_ADD, (*p)->wakeup.read_fd, &ev) != 0) { err = GRPC_OS_ERROR(errno, "epoll_ctl"); - GRPC_FD_TRACE( - "Pollable_create: closed epfd: %d (type: %d). epoll_ctl error", epfd, - type); + GRPC_FD_TRACE( + "Pollable_create: closed epfd: %d (type: %d). epoll_ctl error", epfd, + type); close(epfd); grpc_wakeup_fd_destroy(&(*p)->wakeup); gpr_free(*p); @@ -595,8 +595,8 @@ static grpc_error* pollable_create(pollable_type type, pollable** p) { gpr_mu_init(&(*p)->mu); (*p)->epfd = epfd; (*p)->owner_fd = nullptr; - gpr_mu_init(&(*p)->owner_orphan_mu); - (*p)->owner_orphaned = false; + gpr_mu_init(&(*p)->owner_orphan_mu); + (*p)->owner_orphaned = false; (*p)->pollset_set = nullptr; (*p)->next = (*p)->prev = *p; (*p)->root_worker = nullptr; @@ -616,13 +616,13 @@ static grpc_error* pollable_add_fd(pollable* p, grpc_fd* fd) { struct epoll_event ev_fd; ev_fd.events = static_cast<uint32_t>(EPOLLET | EPOLLIN | EPOLLOUT | EPOLLEXCLUSIVE); - /* Use the second least significant bit of ev_fd.data.ptr to store track_err - * to avoid synchronization issues when accessing it after receiving an event. - * Accessing fd would be a data race there because the fd might have been - * returned to the free list at that point. */ - ev_fd.data.ptr = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(fd) | - (fd->track_err ? 2 : 0)); - GRPC_STATS_INC_SYSCALL_EPOLL_CTL(); + /* Use the second least significant bit of ev_fd.data.ptr to store track_err + * to avoid synchronization issues when accessing it after receiving an event. + * Accessing fd would be a data race there because the fd might have been + * returned to the free list at that point. */ + ev_fd.data.ptr = reinterpret_cast<void*>(reinterpret_cast<intptr_t>(fd) | + (fd->track_err ? 2 : 0)); + GRPC_STATS_INC_SYSCALL_EPOLL_CTL(); if (epoll_ctl(epfd, EPOLL_CTL_ADD, fd->fd, &ev_fd) != 0) { switch (errno) { case EEXIST: @@ -680,7 +680,7 @@ static void pollset_maybe_finish_shutdown(grpc_pollset* pollset) { static grpc_error* kick_one_worker(grpc_pollset_worker* specific_worker) { GPR_TIMER_SCOPE("kick_one_worker", 0); pollable* p = specific_worker->pollable_obj; - grpc_core::MutexLock lock(&p->mu); + grpc_core::MutexLock lock(&p->mu); GPR_ASSERT(specific_worker != nullptr); if (specific_worker->kicked) { if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { @@ -789,7 +789,7 @@ static grpc_error* pollset_kick_all(grpc_pollset* pollset) { static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) { gpr_mu_init(&pollset->mu); gpr_atm_no_barrier_store(&pollset->worker_count, 0); - gpr_atm_no_barrier_store(&pollset->active_pollable_type, PO_EMPTY); + gpr_atm_no_barrier_store(&pollset->active_pollable_type, PO_EMPTY); pollset->active_pollable = POLLABLE_REF(g_empty_pollable, "pollset"); pollset->kicked_without_poller = false; pollset->shutdown_closure = nullptr; @@ -810,21 +810,21 @@ static int poll_deadline_to_millis_timeout(grpc_millis millis) { return static_cast<int>(delta); } -static void fd_become_readable(grpc_fd* fd) { fd->read_closure.SetReady(); } +static void fd_become_readable(grpc_fd* fd) { fd->read_closure.SetReady(); } -static void fd_become_writable(grpc_fd* fd) { fd->write_closure.SetReady(); } +static void fd_become_writable(grpc_fd* fd) { fd->write_closure.SetReady(); } -static void fd_has_errors(grpc_fd* fd) { fd->error_closure.SetReady(); } +static void fd_has_errors(grpc_fd* fd) { fd->error_closure.SetReady(); } -/* Get the pollable_obj attached to this fd. If none is attached, create a new - * pollable object (of type PO_FD), attach it to the fd and return it - * - * Note that if a pollable object is already attached to the fd, it may be of - * either PO_FD or PO_MULTI type */ -static grpc_error* get_fd_pollable(grpc_fd* fd, pollable** p) { +/* Get the pollable_obj attached to this fd. If none is attached, create a new + * pollable object (of type PO_FD), attach it to the fd and return it + * + * Note that if a pollable object is already attached to the fd, it may be of + * either PO_FD or PO_MULTI type */ +static grpc_error* get_fd_pollable(grpc_fd* fd, pollable** p) { gpr_mu_lock(&fd->pollable_mu); grpc_error* error = GRPC_ERROR_NONE; - static const char* err_desc = "get_fd_pollable"; + static const char* err_desc = "get_fd_pollable"; if (fd->pollable_obj == nullptr) { if (append_error(&error, pollable_create(PO_FD, &fd->pollable_obj), err_desc)) { @@ -887,28 +887,28 @@ static grpc_error* pollable_process_events(grpc_pollset* pollset, (intptr_t)data_ptr)), err_desc); } else { - grpc_fd* fd = - reinterpret_cast<grpc_fd*>(reinterpret_cast<intptr_t>(data_ptr) & ~2); - bool track_err = reinterpret_cast<intptr_t>(data_ptr) & 2; - bool cancel = (ev->events & EPOLLHUP) != 0; - bool error = (ev->events & EPOLLERR) != 0; + grpc_fd* fd = + reinterpret_cast<grpc_fd*>(reinterpret_cast<intptr_t>(data_ptr) & ~2); + bool track_err = reinterpret_cast<intptr_t>(data_ptr) & 2; + bool cancel = (ev->events & EPOLLHUP) != 0; + bool error = (ev->events & EPOLLERR) != 0; bool read_ev = (ev->events & (EPOLLIN | EPOLLPRI)) != 0; bool write_ev = (ev->events & EPOLLOUT) != 0; - bool err_fallback = error && !track_err; - + bool err_fallback = error && !track_err; + if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { gpr_log(GPR_INFO, "PS:%p got fd %p: cancel=%d read=%d " "write=%d", pollset, fd, cancel, read_ev, write_ev); } - if (error && !err_fallback) { - fd_has_errors(fd); - } - if (read_ev || cancel || err_fallback) { - fd_become_readable(fd); + if (error && !err_fallback) { + fd_has_errors(fd); } - if (write_ev || cancel || err_fallback) { + if (read_ev || cancel || err_fallback) { + fd_become_readable(fd); + } + if (write_ev || cancel || err_fallback) { fd_become_writable(fd); } } @@ -1112,7 +1112,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset, #endif if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { gpr_log(GPR_INFO, - "PS:%p work hdl=%p worker=%p now=%" PRId64 " deadline=%" PRId64 + "PS:%p work hdl=%p worker=%p now=%" PRId64 " deadline=%" PRId64 " kwp=%d pollable=%p", pollset, worker_hdl, WORKER_PTR, grpc_core::ExecCtx::Get()->Now(), deadline, pollset->kicked_without_poller, pollset->active_pollable); @@ -1158,7 +1158,7 @@ static grpc_error* pollset_transition_pollable_from_empty_to_fd_locked( } append_error(&error, pollset_kick_all(pollset), err_desc); POLLABLE_UNREF(pollset->active_pollable, "pollset"); - append_error(&error, get_fd_pollable(fd, &pollset->active_pollable), + append_error(&error, get_fd_pollable(fd, &pollset->active_pollable), err_desc); return error; } @@ -1202,8 +1202,8 @@ static grpc_error* pollset_add_fd_locked(grpc_pollset* pollset, grpc_fd* fd) { error = pollset_transition_pollable_from_empty_to_fd_locked(pollset, fd); break; case PO_FD: - gpr_mu_lock(&po_at_start->owner_orphan_mu); - if (po_at_start->owner_orphaned) { + gpr_mu_lock(&po_at_start->owner_orphan_mu); + if (po_at_start->owner_orphaned) { error = pollset_transition_pollable_from_empty_to_fd_locked(pollset, fd); } else { @@ -1211,7 +1211,7 @@ static grpc_error* pollset_add_fd_locked(grpc_pollset* pollset, grpc_fd* fd) { error = pollset_transition_pollable_from_fd_to_multi_locked(pollset, fd); } - gpr_mu_unlock(&po_at_start->owner_orphan_mu); + gpr_mu_unlock(&po_at_start->owner_orphan_mu); break; case PO_MULTI: error = pollable_add_fd(pollset->active_pollable, fd); @@ -1221,8 +1221,8 @@ static grpc_error* pollset_add_fd_locked(grpc_pollset* pollset, grpc_fd* fd) { POLLABLE_UNREF(pollset->active_pollable, "pollset"); pollset->active_pollable = po_at_start; } else { - gpr_atm_rel_store(&pollset->active_pollable_type, - pollset->active_pollable->type); + gpr_atm_rel_store(&pollset->active_pollable_type, + pollset->active_pollable->type); POLLABLE_UNREF(po_at_start, "pollset_add_fd"); } return error; @@ -1249,16 +1249,16 @@ static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset, append_error(&error, pollset_kick_all(pollset), err_desc); break; case PO_FD: - gpr_mu_lock(&po_at_start->owner_orphan_mu); - if (po_at_start->owner_orphaned) { - // Unlock before Unref'ing the pollable - gpr_mu_unlock(&po_at_start->owner_orphan_mu); + gpr_mu_lock(&po_at_start->owner_orphan_mu); + if (po_at_start->owner_orphaned) { + // Unlock before Unref'ing the pollable + gpr_mu_unlock(&po_at_start->owner_orphan_mu); POLLABLE_UNREF(pollset->active_pollable, "pollset"); error = pollable_create(PO_MULTI, &pollset->active_pollable); } else { error = pollset_transition_pollable_from_fd_to_multi_locked(pollset, nullptr); - gpr_mu_unlock(&po_at_start->owner_orphan_mu); + gpr_mu_unlock(&po_at_start->owner_orphan_mu); } break; case PO_MULTI: @@ -1269,8 +1269,8 @@ static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset, pollset->active_pollable = po_at_start; *pollable_obj = nullptr; } else { - gpr_atm_rel_store(&pollset->active_pollable_type, - pollset->active_pollable->type); + gpr_atm_rel_store(&pollset->active_pollable_type, + pollset->active_pollable->type); *pollable_obj = POLLABLE_REF(pollset->active_pollable, "pollset_set"); POLLABLE_UNREF(po_at_start, "pollset_as_multipollable"); } @@ -1279,23 +1279,23 @@ static grpc_error* pollset_as_multipollable_locked(grpc_pollset* pollset, static void pollset_add_fd(grpc_pollset* pollset, grpc_fd* fd) { GPR_TIMER_SCOPE("pollset_add_fd", 0); - + // We never transition from PO_MULTI to other modes (i.e., PO_FD or PO_EMPTY) - // and, thus, it is safe to simply store and check whether the FD has already - // been added to the active pollable previously. - if (gpr_atm_acq_load(&pollset->active_pollable_type) == PO_MULTI && - fd_has_pollset(fd, pollset)) { - return; - } - - grpc_core::MutexLock lock(&pollset->mu); + // and, thus, it is safe to simply store and check whether the FD has already + // been added to the active pollable previously. + if (gpr_atm_acq_load(&pollset->active_pollable_type) == PO_MULTI && + fd_has_pollset(fd, pollset)) { + return; + } + + grpc_core::MutexLock lock(&pollset->mu); grpc_error* error = pollset_add_fd_locked(pollset, fd); - - // If we are in PO_MULTI mode, we should update the pollsets of the FD. - if (gpr_atm_no_barrier_load(&pollset->active_pollable_type) == PO_MULTI) { - fd_add_pollset(fd, pollset); - } - + + // If we are in PO_MULTI mode, we should update the pollsets of the FD. + if (gpr_atm_no_barrier_load(&pollset->active_pollable_type) == PO_MULTI) { + fd_add_pollset(fd, pollset); + } + GRPC_LOG_IF_ERROR("pollset_add_fd", error); } @@ -1505,7 +1505,7 @@ static void pollset_set_add_pollset_set(grpc_pollset_set* a, gpr_mu_unlock(b_mu); } // try to do the least copying possible - // TODO(sreek): there's probably a better heuristic here + // TODO(sreek): there's probably a better heuristic here const size_t a_size = a->fd_count + a->pollset_count; const size_t b_size = b->fd_count + b->pollset_count; if (b_size > a_size) { @@ -1560,10 +1560,10 @@ static void pollset_set_del_pollset_set(grpc_pollset_set* /*bag*/, * Event engine binding */ -static bool is_any_background_poller_thread(void) { return false; } - -static void shutdown_background_closure(void) {} - +static bool is_any_background_poller_thread(void) { return false; } + +static void shutdown_background_closure(void) {} + static bool add_closure_to_background_poller(grpc_closure* /*closure*/, grpc_error* /*error*/) { return false; @@ -1576,8 +1576,8 @@ static void shutdown_engine(void) { static const grpc_event_engine_vtable vtable = { sizeof(grpc_pollset), - true, - false, + true, + false, fd_create, fd_wrapped_fd, @@ -1585,10 +1585,10 @@ static const grpc_event_engine_vtable vtable = { fd_shutdown, fd_notify_on_read, fd_notify_on_write, - fd_notify_on_error, - fd_become_readable, - fd_become_writable, - fd_has_errors, + fd_notify_on_error, + fd_become_readable, + fd_become_writable, + fd_has_errors, fd_is_shutdown, pollset_init, @@ -1607,8 +1607,8 @@ static const grpc_event_engine_vtable vtable = { pollset_set_add_fd, pollset_set_del_fd, - is_any_background_poller_thread, - shutdown_background_closure, + is_any_background_poller_thread, + shutdown_background_closure, shutdown_engine, add_closure_to_background_poller, }; @@ -1637,7 +1637,7 @@ const grpc_event_engine_vtable* grpc_init_epollex_linux( } #else /* defined(GRPC_LINUX_EPOLL_CREATE1) */ -#if defined(GRPC_POSIX_SOCKET_EV_EPOLLEX) +#if defined(GRPC_POSIX_SOCKET_EV_EPOLLEX) #include "src/core/lib/iomgr/ev_epollex_linux.h" /* If GRPC_LINUX_EPOLL_CREATE1 is not defined, it means epoll_create1 is not available. Return NULL */ @@ -1645,6 +1645,6 @@ const grpc_event_engine_vtable* grpc_init_epollex_linux( bool /*explicitly_requested*/) { return nullptr; } -#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLLEX) */ +#endif /* defined(GRPC_POSIX_SOCKET_EV_EPOLLEX) */ #endif /* !defined(GRPC_LINUX_EPOLL_CREATE1) */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc index a46ab7ea0d..92ef6f0c41 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_poll_posix.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_EV_POLL +#ifdef GRPC_POSIX_SOCKET_EV_POLL #include "src/core/lib/iomgr/ev_poll_posix.h" @@ -62,19 +62,19 @@ typedef struct grpc_fd_watcher { grpc_fd* fd; } grpc_fd_watcher; -typedef struct grpc_cached_wakeup_fd grpc_cached_wakeup_fd; - -/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ -struct grpc_fork_fd_list { - /* Only one of fd or cached_wakeup_fd will be set. The unused field will be - set to nullptr. */ - grpc_fd* fd; - grpc_cached_wakeup_fd* cached_wakeup_fd; - - grpc_fork_fd_list* next; - grpc_fork_fd_list* prev; -}; - +typedef struct grpc_cached_wakeup_fd grpc_cached_wakeup_fd; + +/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ +struct grpc_fork_fd_list { + /* Only one of fd or cached_wakeup_fd will be set. The unused field will be + set to nullptr. */ + grpc_fd* fd; + grpc_cached_wakeup_fd* cached_wakeup_fd; + + grpc_fork_fd_list* next; + grpc_fork_fd_list* prev; +}; + struct grpc_fd { int fd; /* refst format: @@ -124,17 +124,17 @@ struct grpc_fd { grpc_iomgr_object iomgr_object; - /* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ - grpc_fork_fd_list* fork_fd_list; + /* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ + grpc_fork_fd_list* fork_fd_list; }; /* True when GRPC_ENABLE_FORK_SUPPORT=1. */ -static bool track_fds_for_fork = false; - -/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ -static grpc_fork_fd_list* fork_fd_list_head = nullptr; -static gpr_mu fork_fd_list_mu; - +static bool track_fds_for_fork = false; + +/* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ +static grpc_fork_fd_list* fork_fd_list_head = nullptr; +static gpr_mu fork_fd_list_mu; + /* Begin polling on an fd. Registers that the given pollset is interested in this fd - so that if read or writability interest changes, the pollset can be kicked to pick up that @@ -153,7 +153,7 @@ static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset, MUST NOT be called with a pollset lock taken if got_read or got_write are 1, also does the become_{readable,writable} as appropriate. */ -static void fd_end_poll(grpc_fd_watcher* rec, int got_read, int got_write); +static void fd_end_poll(grpc_fd_watcher* rec, int got_read, int got_write); /* Return 1 if this fd is orphaned, 0 otherwise */ static bool fd_is_orphaned(grpc_fd* fd); @@ -181,9 +181,9 @@ static void fd_unref(grpc_fd* fd); typedef struct grpc_cached_wakeup_fd { grpc_wakeup_fd fd; struct grpc_cached_wakeup_fd* next; - - /* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ - grpc_fork_fd_list* fork_fd_list; + + /* Only used when GRPC_ENABLE_FORK_SUPPORT=1 */ + grpc_fork_fd_list* fork_fd_list; } grpc_cached_wakeup_fd; struct grpc_pollset_worker { @@ -259,61 +259,61 @@ struct grpc_pollset_set { }; /******************************************************************************* - * functions to track opened fds. No-ops unless track_fds_for_fork is true. + * functions to track opened fds. No-ops unless track_fds_for_fork is true. */ -static void fork_fd_list_remove_node(grpc_fork_fd_list* node) { - if (track_fds_for_fork) { - gpr_mu_lock(&fork_fd_list_mu); - if (fork_fd_list_head == node) { - fork_fd_list_head = node->next; - } - if (node->prev != nullptr) { - node->prev->next = node->next; - } - if (node->next != nullptr) { - node->next->prev = node->prev; - } - gpr_free(node); - gpr_mu_unlock(&fork_fd_list_mu); - } -} - -static void fork_fd_list_add_node(grpc_fork_fd_list* node) { - gpr_mu_lock(&fork_fd_list_mu); - node->next = fork_fd_list_head; - node->prev = nullptr; - if (fork_fd_list_head != nullptr) { - fork_fd_list_head->prev = node; - } - fork_fd_list_head = node; - gpr_mu_unlock(&fork_fd_list_mu); -} - -static void fork_fd_list_add_grpc_fd(grpc_fd* fd) { - if (track_fds_for_fork) { - fd->fork_fd_list = - static_cast<grpc_fork_fd_list*>(gpr_malloc(sizeof(grpc_fork_fd_list))); - fd->fork_fd_list->fd = fd; - fd->fork_fd_list->cached_wakeup_fd = nullptr; - fork_fd_list_add_node(fd->fork_fd_list); - } -} - -static void fork_fd_list_add_wakeup_fd(grpc_cached_wakeup_fd* fd) { - if (track_fds_for_fork) { - fd->fork_fd_list = - static_cast<grpc_fork_fd_list*>(gpr_malloc(sizeof(grpc_fork_fd_list))); - fd->fork_fd_list->cached_wakeup_fd = fd; - fd->fork_fd_list->fd = nullptr; - fork_fd_list_add_node(fd->fork_fd_list); - } -} - +static void fork_fd_list_remove_node(grpc_fork_fd_list* node) { + if (track_fds_for_fork) { + gpr_mu_lock(&fork_fd_list_mu); + if (fork_fd_list_head == node) { + fork_fd_list_head = node->next; + } + if (node->prev != nullptr) { + node->prev->next = node->next; + } + if (node->next != nullptr) { + node->next->prev = node->prev; + } + gpr_free(node); + gpr_mu_unlock(&fork_fd_list_mu); + } +} + +static void fork_fd_list_add_node(grpc_fork_fd_list* node) { + gpr_mu_lock(&fork_fd_list_mu); + node->next = fork_fd_list_head; + node->prev = nullptr; + if (fork_fd_list_head != nullptr) { + fork_fd_list_head->prev = node; + } + fork_fd_list_head = node; + gpr_mu_unlock(&fork_fd_list_mu); +} + +static void fork_fd_list_add_grpc_fd(grpc_fd* fd) { + if (track_fds_for_fork) { + fd->fork_fd_list = + static_cast<grpc_fork_fd_list*>(gpr_malloc(sizeof(grpc_fork_fd_list))); + fd->fork_fd_list->fd = fd; + fd->fork_fd_list->cached_wakeup_fd = nullptr; + fork_fd_list_add_node(fd->fork_fd_list); + } +} + +static void fork_fd_list_add_wakeup_fd(grpc_cached_wakeup_fd* fd) { + if (track_fds_for_fork) { + fd->fork_fd_list = + static_cast<grpc_fork_fd_list*>(gpr_malloc(sizeof(grpc_fork_fd_list))); + fd->fork_fd_list->cached_wakeup_fd = fd; + fd->fork_fd_list->fd = nullptr; + fork_fd_list_add_node(fd->fork_fd_list); + } +} + /******************************************************************************* * fd_posix.c */ - + #ifndef NDEBUG #define REF_BY(fd, n, reason) ref_by(fd, n, reason, __FILE__, __LINE__) #define UNREF_BY(fd, n, reason) unref_by(fd, n, reason, __FILE__, __LINE__) @@ -357,7 +357,7 @@ static void unref_by(grpc_fd* fd, int n) { if (old == n) { gpr_mu_destroy(&fd->mu); grpc_iomgr_unregister_object(&fd->iomgr_object); - fork_fd_list_remove_node(fd->fork_fd_list); + fork_fd_list_remove_node(fd->fork_fd_list); if (fd->shutdown) GRPC_ERROR_UNREF(fd->shutdown_error); gpr_free(fd); } else { @@ -365,10 +365,10 @@ static void unref_by(grpc_fd* fd, int n) { } } -static grpc_fd* fd_create(int fd, const char* name, bool track_err) { +static grpc_fd* fd_create(int fd, const char* name, bool track_err) { // Avoid unused-parameter warning for debug-only parameter (void)track_err; - GPR_DEBUG_ASSERT(track_err == false); + GPR_DEBUG_ASSERT(track_err == false); grpc_fd* r = static_cast<grpc_fd*>(gpr_malloc(sizeof(*r))); gpr_mu_init(&r->mu); gpr_atm_rel_store(&r->refst, 1); @@ -386,7 +386,7 @@ static grpc_fd* fd_create(int fd, const char* name, bool track_err) { TString name2 = y_absl::StrCat(name, " fd=", fd); grpc_iomgr_register_object(&r->iomgr_object, name2.c_str()); - fork_fd_list_add_grpc_fd(r); + fork_fd_list_add_grpc_fd(r); return r; } @@ -449,7 +449,7 @@ static int fd_wrapped_fd(grpc_fd* fd) { } static void fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, - const char* reason) { + const char* reason) { fd->on_done_closure = on_done; fd->released = release_fd != nullptr; if (release_fd != nullptr) { @@ -574,29 +574,29 @@ static void fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) { static void fd_notify_on_error(grpc_fd* /*fd*/, grpc_closure* closure) { if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { - gpr_log(GPR_ERROR, "Polling engine does not support tracking errors."); - } + gpr_log(GPR_ERROR, "Polling engine does not support tracking errors."); + } grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, GRPC_ERROR_CANCELLED); -} - -static void fd_set_readable(grpc_fd* fd) { - gpr_mu_lock(&fd->mu); - set_ready_locked(fd, &fd->read_closure); - gpr_mu_unlock(&fd->mu); -} - -static void fd_set_writable(grpc_fd* fd) { - gpr_mu_lock(&fd->mu); - set_ready_locked(fd, &fd->write_closure); - gpr_mu_unlock(&fd->mu); -} - +} + +static void fd_set_readable(grpc_fd* fd) { + gpr_mu_lock(&fd->mu); + set_ready_locked(fd, &fd->read_closure); + gpr_mu_unlock(&fd->mu); +} + +static void fd_set_writable(grpc_fd* fd) { + gpr_mu_lock(&fd->mu); + set_ready_locked(fd, &fd->write_closure); + gpr_mu_unlock(&fd->mu); +} + static void fd_set_error(grpc_fd* /*fd*/) { if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { - gpr_log(GPR_ERROR, "Polling engine does not support tracking errors."); - } -} - + gpr_log(GPR_ERROR, "Polling engine does not support tracking errors."); + } +} + static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset, grpc_pollset_worker* worker, uint32_t read_mask, uint32_t write_mask, grpc_fd_watcher* watcher) { @@ -648,7 +648,7 @@ static uint32_t fd_begin_poll(grpc_fd* fd, grpc_pollset* pollset, return mask; } -static void fd_end_poll(grpc_fd_watcher* watcher, int got_read, int got_write) { +static void fd_end_poll(grpc_fd_watcher* watcher, int got_read, int got_write) { int was_polling = 0; int kick = 0; grpc_fd* fd = watcher->fd; @@ -863,7 +863,7 @@ static void pollset_destroy(grpc_pollset* pollset) { GPR_ASSERT(!pollset_has_workers(pollset)); while (pollset->local_wakeup_cache) { grpc_cached_wakeup_fd* next = pollset->local_wakeup_cache->next; - fork_fd_list_remove_node(pollset->local_wakeup_cache->fork_fd_list); + fork_fd_list_remove_node(pollset->local_wakeup_cache->fork_fd_list); grpc_wakeup_fd_destroy(&pollset->local_wakeup_cache->fd); gpr_free(pollset->local_wakeup_cache); pollset->local_wakeup_cache = next; @@ -938,7 +938,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset, worker.wakeup_fd = static_cast<grpc_cached_wakeup_fd*>( gpr_malloc(sizeof(*worker.wakeup_fd))); error = grpc_wakeup_fd_init(&worker.wakeup_fd->fd); - fork_fd_list_add_wakeup_fd(worker.wakeup_fd); + fork_fd_list_add_wakeup_fd(worker.wakeup_fd); if (error != GRPC_ERROR_NONE) { GRPC_LOG_IF_ERROR("pollset_work", GRPC_ERROR_REF(error)); return error; @@ -1036,16 +1036,16 @@ static grpc_error* pollset_work(grpc_pollset* pollset, for (i = 1; i < pfd_count; i++) { if (watchers[i].fd == nullptr) { - fd_end_poll(&watchers[i], 0, 0); + fd_end_poll(&watchers[i], 0, 0); } else { // Wake up all the file descriptors, if we have an invalid one // we can identify it on the next pollset_work() - fd_end_poll(&watchers[i], 1, 1); + fd_end_poll(&watchers[i], 1, 1); } } } else if (r == 0) { for (i = 1; i < pfd_count; i++) { - fd_end_poll(&watchers[i], 0, 0); + fd_end_poll(&watchers[i], 0, 0); } } else { if (pfds[0].revents & POLLIN_CHECK) { @@ -1057,7 +1057,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset, } for (i = 1; i < pfd_count; i++) { if (watchers[i].fd == nullptr) { - fd_end_poll(&watchers[i], 0, 0); + fd_end_poll(&watchers[i], 0, 0); } else { if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { gpr_log(GPR_INFO, "%p got_event: %d r:%d w:%d [%d]", pollset, @@ -1071,7 +1071,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset, gpr_atm_no_barrier_store(&watchers[i].fd->pollhup, 1); } fd_end_poll(&watchers[i], pfds[i].revents & POLLIN_CHECK, - pfds[i].revents & POLLOUT_CHECK); + pfds[i].revents & POLLOUT_CHECK); } } } @@ -1329,10 +1329,10 @@ static void pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) { * event engine binding */ -static bool is_any_background_poller_thread(void) { return false; } - -static void shutdown_background_closure(void) {} - +static bool is_any_background_poller_thread(void) { return false; } + +static void shutdown_background_closure(void) {} + static bool add_closure_to_background_poller(grpc_closure* /*closure*/, grpc_error* /*error*/) { return false; @@ -1340,16 +1340,16 @@ static bool add_closure_to_background_poller(grpc_closure* /*closure*/, static void shutdown_engine(void) { pollset_global_shutdown(); - if (track_fds_for_fork) { - gpr_mu_destroy(&fork_fd_list_mu); - grpc_core::Fork::SetResetChildPollingEngineFunc(nullptr); - } + if (track_fds_for_fork) { + gpr_mu_destroy(&fork_fd_list_mu); + grpc_core::Fork::SetResetChildPollingEngineFunc(nullptr); + } } static const grpc_event_engine_vtable vtable = { sizeof(grpc_pollset), - false, - false, + false, + false, fd_create, fd_wrapped_fd, @@ -1357,10 +1357,10 @@ static const grpc_event_engine_vtable vtable = { fd_shutdown, fd_notify_on_read, fd_notify_on_write, - fd_notify_on_error, - fd_set_readable, - fd_set_writable, - fd_set_error, + fd_notify_on_error, + fd_set_readable, + fd_set_writable, + fd_set_error, fd_is_shutdown, pollset_init, @@ -1379,34 +1379,34 @@ static const grpc_event_engine_vtable vtable = { pollset_set_add_fd, pollset_set_del_fd, - is_any_background_poller_thread, - shutdown_background_closure, + is_any_background_poller_thread, + shutdown_background_closure, shutdown_engine, add_closure_to_background_poller, }; -/* Called by the child process's post-fork handler to close open fds, including - * worker wakeup fds. This allows gRPC to shutdown in the child process without - * interfering with connections or RPCs ongoing in the parent. */ -static void reset_event_manager_on_fork() { - gpr_mu_lock(&fork_fd_list_mu); - while (fork_fd_list_head != nullptr) { - if (fork_fd_list_head->fd != nullptr) { +/* Called by the child process's post-fork handler to close open fds, including + * worker wakeup fds. This allows gRPC to shutdown in the child process without + * interfering with connections or RPCs ongoing in the parent. */ +static void reset_event_manager_on_fork() { + gpr_mu_lock(&fork_fd_list_mu); + while (fork_fd_list_head != nullptr) { + if (fork_fd_list_head->fd != nullptr) { if (!fork_fd_list_head->fd->closed) { close(fork_fd_list_head->fd->fd); } - fork_fd_list_head->fd->fd = -1; - } else { - close(fork_fd_list_head->cached_wakeup_fd->fd.read_fd); - fork_fd_list_head->cached_wakeup_fd->fd.read_fd = -1; - close(fork_fd_list_head->cached_wakeup_fd->fd.write_fd); - fork_fd_list_head->cached_wakeup_fd->fd.write_fd = -1; - } - fork_fd_list_head = fork_fd_list_head->next; - } - gpr_mu_unlock(&fork_fd_list_mu); -} - + fork_fd_list_head->fd->fd = -1; + } else { + close(fork_fd_list_head->cached_wakeup_fd->fd.read_fd); + fork_fd_list_head->cached_wakeup_fd->fd.read_fd = -1; + close(fork_fd_list_head->cached_wakeup_fd->fd.write_fd); + fork_fd_list_head->cached_wakeup_fd->fd.write_fd = -1; + } + fork_fd_list_head = fork_fd_list_head->next; + } + gpr_mu_unlock(&fork_fd_list_mu); +} + const grpc_event_engine_vtable* grpc_init_poll_posix( bool /*explicit_request*/) { if (!grpc_has_wakeup_fd()) { @@ -1416,13 +1416,13 @@ const grpc_event_engine_vtable* grpc_init_poll_posix( if (!GRPC_LOG_IF_ERROR("pollset_global_init", pollset_global_init())) { return nullptr; } - if (grpc_core::Fork::Enabled()) { - track_fds_for_fork = true; - gpr_mu_init(&fork_fd_list_mu); - grpc_core::Fork::SetResetChildPollingEngineFunc( - reset_event_manager_on_fork); - } + if (grpc_core::Fork::Enabled()) { + track_fds_for_fork = true; + gpr_mu_init(&fork_fd_list_mu); + grpc_core::Fork::SetResetChildPollingEngineFunc( + reset_event_manager_on_fork); + } return &vtable; } -#endif /* GRPC_POSIX_SOCKET_EV_POLL */ +#endif /* GRPC_POSIX_SOCKET_EV_POLL */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc index 3d32359be4..e64f50e7fd 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_EV +#ifdef GRPC_POSIX_SOCKET_EV #include "src/core/lib/iomgr/ev_posix.h" @@ -36,18 +36,18 @@ #include "src/core/lib/iomgr/ev_epoll1_linux.h" #include "src/core/lib/iomgr/ev_epollex_linux.h" #include "src/core/lib/iomgr/ev_poll_posix.h" -#include "src/core/lib/iomgr/internal_errqueue.h" +#include "src/core/lib/iomgr/internal_errqueue.h" GPR_GLOBAL_CONFIG_DEFINE_STRING( grpc_poll_strategy, "all", "Declares which polling engines to try when starting gRPC. " "This is a comma-separated list of engines, which are tried in priority " "order first -> last.") - + grpc_core::DebugOnlyTraceFlag grpc_polling_trace( false, "polling"); /* Disabled by default */ -/* Traces fd create/close operations */ +/* Traces fd create/close operations */ grpc_core::DebugOnlyTraceFlag grpc_fd_trace(false, "fd_trace"); grpc_core::DebugOnlyTraceFlag grpc_trace_fd_refcount(false, "fd_refcount"); grpc_core::DebugOnlyTraceFlag grpc_polling_api_trace(false, "polling_api"); @@ -64,13 +64,13 @@ grpc_core::DebugOnlyTraceFlag grpc_polling_api_trace(false, "polling_api"); /** Default poll() function - a pointer so that it can be overridden by some * tests */ -#ifndef GPR_AIX +#ifndef GPR_AIX grpc_poll_function_type grpc_poll_function = poll; -#else -int aix_poll(struct pollfd fds[], nfds_t nfds, int timeout) { - return poll(fds, nfds, timeout); -} -grpc_poll_function_type grpc_poll_function = aix_poll; +#else +int aix_poll(struct pollfd fds[], nfds_t nfds, int timeout) { + return poll(fds, nfds, timeout); +} +grpc_poll_function_type grpc_poll_function = aix_poll; #endif // GPR_AIX grpc_wakeup_fd grpc_global_wakeup_fd; @@ -112,26 +112,26 @@ const grpc_event_engine_vtable* init_non_polling(bool explicit_request) { } } // namespace -#define ENGINE_HEAD_CUSTOM "head_custom" -#define ENGINE_TAIL_CUSTOM "tail_custom" - -// The global array of event-engine factories. Each entry is a pair with a name -// and an event-engine generator function (nullptr if there is no generator -// registered for this name). The middle entries are the engines predefined by -// open-source gRPC. The head entries represent an opportunity for specific -// high-priority custom pollers to be added by the initializer plugins of -// custom-built gRPC libraries. The tail entries represent the same, but for -// low-priority custom pollers. The actual poller selected is either the first -// available one in the list if no specific poller is requested, or the first -// specific poller that is requested by name in the GRPC_POLL_STRATEGY -// environment variable if that variable is set (which should be a -// comma-separated list of one or more event engine names) -static event_engine_factory g_factories[] = { - {ENGINE_HEAD_CUSTOM, nullptr}, {ENGINE_HEAD_CUSTOM, nullptr}, - {ENGINE_HEAD_CUSTOM, nullptr}, {ENGINE_HEAD_CUSTOM, nullptr}, - {"epollex", grpc_init_epollex_linux}, {"epoll1", grpc_init_epoll1_linux}, +#define ENGINE_HEAD_CUSTOM "head_custom" +#define ENGINE_TAIL_CUSTOM "tail_custom" + +// The global array of event-engine factories. Each entry is a pair with a name +// and an event-engine generator function (nullptr if there is no generator +// registered for this name). The middle entries are the engines predefined by +// open-source gRPC. The head entries represent an opportunity for specific +// high-priority custom pollers to be added by the initializer plugins of +// custom-built gRPC libraries. The tail entries represent the same, but for +// low-priority custom pollers. The actual poller selected is either the first +// available one in the list if no specific poller is requested, or the first +// specific poller that is requested by name in the GRPC_POLL_STRATEGY +// environment variable if that variable is set (which should be a +// comma-separated list of one or more event engine names) +static event_engine_factory g_factories[] = { + {ENGINE_HEAD_CUSTOM, nullptr}, {ENGINE_HEAD_CUSTOM, nullptr}, + {ENGINE_HEAD_CUSTOM, nullptr}, {ENGINE_HEAD_CUSTOM, nullptr}, + {"epollex", grpc_init_epollex_linux}, {"epoll1", grpc_init_epoll1_linux}, {"poll", grpc_init_poll_posix}, {"none", init_non_polling}, - {ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr}, + {ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr}, {ENGINE_TAIL_CUSTOM, nullptr}, }; @@ -166,7 +166,7 @@ static bool is(const char* want, const char* have) { static void try_engine(const char* engine) { for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) { - if (g_factories[i].factory != nullptr && is(engine, g_factories[i].name)) { + if (g_factories[i].factory != nullptr && is(engine, g_factories[i].name)) { if ((g_event_engine = g_factories[i].factory( 0 == strcmp(engine, g_factories[i].name)))) { g_poll_strategy_name = g_factories[i].name; @@ -177,32 +177,32 @@ static void try_engine(const char* engine) { } } -/* Call this before calling grpc_event_engine_init() */ -void grpc_register_event_engine_factory(const char* name, - event_engine_factory_fn factory, - bool add_at_head) { - const char* custom_match = - add_at_head ? ENGINE_HEAD_CUSTOM : ENGINE_TAIL_CUSTOM; - - // Overwrite an existing registration if already registered - for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) { - if (0 == strcmp(name, g_factories[i].name)) { - g_factories[i].factory = factory; - return; - } - } - - // Otherwise fill in an available custom slot - for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) { - if (0 == strcmp(g_factories[i].name, custom_match)) { - g_factories[i].name = name; - g_factories[i].factory = factory; - return; - } - } - - // Otherwise fail - GPR_ASSERT(false); +/* Call this before calling grpc_event_engine_init() */ +void grpc_register_event_engine_factory(const char* name, + event_engine_factory_fn factory, + bool add_at_head) { + const char* custom_match = + add_at_head ? ENGINE_HEAD_CUSTOM : ENGINE_TAIL_CUSTOM; + + // Overwrite an existing registration if already registered + for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) { + if (0 == strcmp(name, g_factories[i].name)) { + g_factories[i].factory = factory; + return; + } + } + + // Otherwise fill in an available custom slot + for (size_t i = 0; i < GPR_ARRAY_SIZE(g_factories); i++) { + if (0 == strcmp(g_factories[i].name, custom_match)) { + g_factories[i].name = name; + g_factories[i].factory = factory; + return; + } + } + + // Otherwise fail + GPR_ASSERT(false); } /*If grpc_event_engine_init() has been called, returns the poll_strategy_name. @@ -237,42 +237,42 @@ void grpc_event_engine_shutdown(void) { g_event_engine = nullptr; } -bool grpc_event_engine_can_track_errors(void) { - /* Only track errors if platform supports errqueue. */ - if (grpc_core::kernel_supports_errqueue()) { - return g_event_engine->can_track_err; - } - return false; +bool grpc_event_engine_can_track_errors(void) { + /* Only track errors if platform supports errqueue. */ + if (grpc_core::kernel_supports_errqueue()) { + return g_event_engine->can_track_err; + } + return false; } -bool grpc_event_engine_run_in_background(void) { +bool grpc_event_engine_run_in_background(void) { // g_event_engine is nullptr when using a custom iomgr. return g_event_engine != nullptr && g_event_engine->run_in_background; -} - -grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err) { - GRPC_POLLING_API_TRACE("fd_create(%d, %s, %d)", fd, name, track_err); - GRPC_FD_TRACE("fd_create(%d, %s, %d)", fd, name, track_err); - return g_event_engine->fd_create( - fd, name, track_err && grpc_event_engine_can_track_errors()); -} - +} + +grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err) { + GRPC_POLLING_API_TRACE("fd_create(%d, %s, %d)", fd, name, track_err); + GRPC_FD_TRACE("fd_create(%d, %s, %d)", fd, name, track_err); + return g_event_engine->fd_create( + fd, name, track_err && grpc_event_engine_can_track_errors()); +} + int grpc_fd_wrapped_fd(grpc_fd* fd) { return g_event_engine->fd_wrapped_fd(fd); } void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, - const char* reason) { - GRPC_POLLING_API_TRACE("fd_orphan(%d, %p, %p, %s)", grpc_fd_wrapped_fd(fd), - on_done, release_fd, reason); - GRPC_FD_TRACE("grpc_fd_orphan, fd:%d closed", grpc_fd_wrapped_fd(fd)); - - g_event_engine->fd_orphan(fd, on_done, release_fd, reason); + const char* reason) { + GRPC_POLLING_API_TRACE("fd_orphan(%d, %p, %p, %s)", grpc_fd_wrapped_fd(fd), + on_done, release_fd, reason); + GRPC_FD_TRACE("grpc_fd_orphan, fd:%d closed", grpc_fd_wrapped_fd(fd)); + + g_event_engine->fd_orphan(fd, on_done, release_fd, reason); } void grpc_fd_shutdown(grpc_fd* fd, grpc_error* why) { GRPC_POLLING_API_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd)); - GRPC_FD_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd)); + GRPC_FD_TRACE("fd_shutdown(%d)", grpc_fd_wrapped_fd(fd)); g_event_engine->fd_shutdown(fd, why); } @@ -288,16 +288,16 @@ void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure) { g_event_engine->fd_notify_on_write(fd, closure); } -void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) { - g_event_engine->fd_notify_on_error(fd, closure); -} - -void grpc_fd_set_readable(grpc_fd* fd) { g_event_engine->fd_set_readable(fd); } - -void grpc_fd_set_writable(grpc_fd* fd) { g_event_engine->fd_set_writable(fd); } - -void grpc_fd_set_error(grpc_fd* fd) { g_event_engine->fd_set_error(fd); } - +void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure) { + g_event_engine->fd_notify_on_error(fd, closure); +} + +void grpc_fd_set_readable(grpc_fd* fd) { g_event_engine->fd_set_readable(fd); } + +void grpc_fd_set_writable(grpc_fd* fd) { g_event_engine->fd_set_writable(fd); } + +void grpc_fd_set_error(grpc_fd* fd) { g_event_engine->fd_set_error(fd); } + static size_t pollset_size(void) { return g_event_engine->pollset_size; } static void pollset_init(grpc_pollset* pollset, gpr_mu** mu) { @@ -318,10 +318,10 @@ static void pollset_destroy(grpc_pollset* pollset) { static grpc_error* pollset_work(grpc_pollset* pollset, grpc_pollset_worker** worker, grpc_millis deadline) { - GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") begin", pollset, + GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") begin", pollset, deadline); grpc_error* err = g_event_engine->pollset_work(pollset, worker, deadline); - GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") end", pollset, + GRPC_POLLING_API_TRACE("pollset_work(%p, %" PRId64 ") end", pollset, deadline); return err; } @@ -401,17 +401,17 @@ void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd) { g_event_engine->pollset_set_del_fd(pollset_set, fd); } -bool grpc_is_any_background_poller_thread(void) { - return g_event_engine->is_any_background_poller_thread(); -} - +bool grpc_is_any_background_poller_thread(void) { + return g_event_engine->is_any_background_poller_thread(); +} + bool grpc_add_closure_to_background_poller(grpc_closure* closure, grpc_error* error) { return g_event_engine->add_closure_to_background_poller(closure, error); } -void grpc_shutdown_background_closure(void) { - g_event_engine->shutdown_background_closure(); -} - -#endif // GRPC_POSIX_SOCKET_EV +void grpc_shutdown_background_closure(void) { + g_event_engine->shutdown_background_closure(); +} + +#endif // GRPC_POSIX_SOCKET_EV diff --git a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h index 84edabce71..5a33c741e9 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/ev_posix.h @@ -36,29 +36,29 @@ extern grpc_core::DebugOnlyTraceFlag grpc_fd_trace; /* Disabled by default */ extern grpc_core::DebugOnlyTraceFlag grpc_polling_trace; /* Disabled by default */ -#define GRPC_FD_TRACE(format, ...) \ +#define GRPC_FD_TRACE(format, ...) \ if (GRPC_TRACE_FLAG_ENABLED(grpc_fd_trace)) { \ - gpr_log(GPR_INFO, "(fd-trace) " format, __VA_ARGS__); \ - } - + gpr_log(GPR_INFO, "(fd-trace) " format, __VA_ARGS__); \ + } + typedef struct grpc_fd grpc_fd; typedef struct grpc_event_engine_vtable { size_t pollset_size; - bool can_track_err; - bool run_in_background; + bool can_track_err; + bool run_in_background; - grpc_fd* (*fd_create)(int fd, const char* name, bool track_err); + grpc_fd* (*fd_create)(int fd, const char* name, bool track_err); int (*fd_wrapped_fd)(grpc_fd* fd); void (*fd_orphan)(grpc_fd* fd, grpc_closure* on_done, int* release_fd, - const char* reason); + const char* reason); void (*fd_shutdown)(grpc_fd* fd, grpc_error* why); void (*fd_notify_on_read)(grpc_fd* fd, grpc_closure* closure); void (*fd_notify_on_write)(grpc_fd* fd, grpc_closure* closure); - void (*fd_notify_on_error)(grpc_fd* fd, grpc_closure* closure); - void (*fd_set_readable)(grpc_fd* fd); - void (*fd_set_writable)(grpc_fd* fd); - void (*fd_set_error)(grpc_fd* fd); + void (*fd_notify_on_error)(grpc_fd* fd, grpc_closure* closure); + void (*fd_set_readable)(grpc_fd* fd); + void (*fd_set_writable)(grpc_fd* fd); + void (*fd_set_error)(grpc_fd* fd); bool (*fd_is_shutdown)(grpc_fd* fd); void (*pollset_init)(grpc_pollset* pollset, gpr_mu** mu); @@ -84,43 +84,43 @@ typedef struct grpc_event_engine_vtable { void (*pollset_set_add_fd)(grpc_pollset_set* pollset_set, grpc_fd* fd); void (*pollset_set_del_fd)(grpc_pollset_set* pollset_set, grpc_fd* fd); - bool (*is_any_background_poller_thread)(void); - void (*shutdown_background_closure)(void); + bool (*is_any_background_poller_thread)(void); + void (*shutdown_background_closure)(void); void (*shutdown_engine)(void); bool (*add_closure_to_background_poller)(grpc_closure* closure, grpc_error* error); } grpc_event_engine_vtable; -/* register a new event engine factory */ -void grpc_register_event_engine_factory( - const char* name, const grpc_event_engine_vtable* (*factory)(bool), - bool add_at_head); - +/* register a new event engine factory */ +void grpc_register_event_engine_factory( + const char* name, const grpc_event_engine_vtable* (*factory)(bool), + bool add_at_head); + void grpc_event_engine_init(void); void grpc_event_engine_shutdown(void); /* Return the name of the poll strategy */ const char* grpc_get_poll_strategy_name(); -/* Returns true if polling engine can track errors separately, false otherwise. - * If this is true, fd can be created with track_err set. After this, error - * events will be reported using fd_notify_on_error. If it is not set, errors - * will continue to be reported through fd_notify_on_read and - * fd_notify_on_write. - */ -bool grpc_event_engine_can_track_errors(); - -/* Returns true if polling engine runs in the background, false otherwise. - * Currently only 'epollbg' runs in the background. - */ -bool grpc_event_engine_run_in_background(); - +/* Returns true if polling engine can track errors separately, false otherwise. + * If this is true, fd can be created with track_err set. After this, error + * events will be reported using fd_notify_on_error. If it is not set, errors + * will continue to be reported through fd_notify_on_read and + * fd_notify_on_write. + */ +bool grpc_event_engine_can_track_errors(); + +/* Returns true if polling engine runs in the background, false otherwise. + * Currently only 'epollbg' runs in the background. + */ +bool grpc_event_engine_run_in_background(); + /* Create a wrapped file descriptor. Requires fd is a non-blocking file descriptor. - \a track_err if true means that error events would be tracked separately - using grpc_fd_notify_on_error. Currently, valid only for linux systems. + \a track_err if true means that error events would be tracked separately + using grpc_fd_notify_on_error. Currently, valid only for linux systems. This takes ownership of closing fd. */ -grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err); +grpc_fd* grpc_fd_create(int fd, const char* name, bool track_err); /* Return the wrapped fd, or -1 if it has been released or closed. */ int grpc_fd_wrapped_fd(grpc_fd* fd); @@ -133,7 +133,7 @@ int grpc_fd_wrapped_fd(grpc_fd* fd); notify_on_write. MUST NOT be called with a pollset lock taken */ void grpc_fd_orphan(grpc_fd* fd, grpc_closure* on_done, int* release_fd, - const char* reason); + const char* reason); /* Has grpc_fd_shutdown been called on an fd? */ bool grpc_fd_is_shutdown(grpc_fd* fd); @@ -159,25 +159,25 @@ void grpc_fd_notify_on_read(grpc_fd* fd, grpc_closure* closure); /* Exactly the same semantics as above, except based on writable events. */ void grpc_fd_notify_on_write(grpc_fd* fd, grpc_closure* closure); -/* Exactly the same semantics as above, except based on error events. track_err - * needs to have been set on grpc_fd_create */ -void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure); - -/* Forcibly set the fd to be readable, resulting in the closure registered with - * grpc_fd_notify_on_read being invoked. - */ -void grpc_fd_set_readable(grpc_fd* fd); - -/* Forcibly set the fd to be writable, resulting in the closure registered with - * grpc_fd_notify_on_write being invoked. - */ -void grpc_fd_set_writable(grpc_fd* fd); - -/* Forcibly set the fd to have errored, resulting in the closure registered with - * grpc_fd_notify_on_error being invoked. - */ -void grpc_fd_set_error(grpc_fd* fd); - +/* Exactly the same semantics as above, except based on error events. track_err + * needs to have been set on grpc_fd_create */ +void grpc_fd_notify_on_error(grpc_fd* fd, grpc_closure* closure); + +/* Forcibly set the fd to be readable, resulting in the closure registered with + * grpc_fd_notify_on_read being invoked. + */ +void grpc_fd_set_readable(grpc_fd* fd); + +/* Forcibly set the fd to be writable, resulting in the closure registered with + * grpc_fd_notify_on_write being invoked. + */ +void grpc_fd_set_writable(grpc_fd* fd); + +/* Forcibly set the fd to have errored, resulting in the closure registered with + * grpc_fd_notify_on_error being invoked. + */ +void grpc_fd_set_error(grpc_fd* fd); + /* pollset_posix functions */ /* Add an fd to a pollset */ @@ -188,18 +188,18 @@ void grpc_pollset_add_fd(grpc_pollset* pollset, struct grpc_fd* fd); void grpc_pollset_set_add_fd(grpc_pollset_set* pollset_set, grpc_fd* fd); void grpc_pollset_set_del_fd(grpc_pollset_set* pollset_set, grpc_fd* fd); -/* Returns true if the caller is a worker thread for any background poller. */ -bool grpc_is_any_background_poller_thread(); - +/* Returns true if the caller is a worker thread for any background poller. */ +bool grpc_is_any_background_poller_thread(); + /* Returns true if the closure is registered into the background poller. Note * that the closure may or may not run yet when this function returns, and the * closure should not be blocking or long-running. */ bool grpc_add_closure_to_background_poller(grpc_closure* closure, grpc_error* error); -/* Shut down all the closures registered in the background poller. */ -void grpc_shutdown_background_closure(); - +/* Shut down all the closures registered in the background poller. */ +void grpc_shutdown_background_closure(); + /* override to allow tests to hook poll() usage */ typedef int (*grpc_poll_function_type)(struct pollfd*, nfds_t, int); extern grpc_poll_function_type grpc_poll_function; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc index e392a9960b..5fcb831972 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.cc @@ -58,8 +58,8 @@ static grpc_millis timespan_to_millis_round_down(gpr_timespec ts) { double x = GPR_MS_PER_SEC * static_cast<double>(ts.tv_sec) + static_cast<double>(ts.tv_nsec) / GPR_NS_PER_MS; if (x < 0) return 0; - if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE; - return static_cast<grpc_millis>(x); + if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE; + return static_cast<grpc_millis>(x); } static grpc_millis timespec_to_millis_round_down(gpr_timespec ts) { @@ -72,8 +72,8 @@ static grpc_millis timespan_to_millis_round_up(gpr_timespec ts) { static_cast<double>(GPR_NS_PER_SEC - 1) / static_cast<double>(GPR_NS_PER_SEC); if (x < 0) return 0; - if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE; - return static_cast<grpc_millis>(x); + if (x > GRPC_MILLIS_INF_FUTURE) return GRPC_MILLIS_INF_FUTURE; + return static_cast<grpc_millis>(x); } static grpc_millis timespec_to_millis_round_up(gpr_timespec ts) { @@ -99,12 +99,12 @@ gpr_timespec grpc_millis_to_timespec(grpc_millis millis, } grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec ts) { - return timespec_to_millis_round_down( + return timespec_to_millis_round_down( gpr_convert_clock_type(ts, g_start_time.clock_type)); } grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec ts) { - return timespec_to_millis_round_up( + return timespec_to_millis_round_up( gpr_convert_clock_type(ts, g_start_time.clock_type)); } @@ -120,14 +120,14 @@ grpc_millis grpc_cycle_counter_to_millis_round_up(gpr_cycle_counter cycles) { namespace grpc_core { GPR_TLS_CLASS_DEF(ExecCtx::exec_ctx_); -GPR_TLS_CLASS_DEF(ApplicationCallbackExecCtx::callback_exec_ctx_); - -// WARNING: for testing purposes only! -void ExecCtx::TestOnlyGlobalInit(gpr_timespec new_val) { - g_start_time = new_val; - gpr_tls_init(&exec_ctx_); -} - +GPR_TLS_CLASS_DEF(ApplicationCallbackExecCtx::callback_exec_ctx_); + +// WARNING: for testing purposes only! +void ExecCtx::TestOnlyGlobalInit(gpr_timespec new_val) { + g_start_time = new_val; + gpr_tls_init(&exec_ctx_); +} + void ExecCtx::GlobalInit(void) { // gpr_now(GPR_CLOCK_MONOTONIC) incurs a syscall. We don't actually know the // exact cycle the time was captured, so we use the average of cycles before @@ -163,7 +163,7 @@ bool ExecCtx::Flush() { grpc_millis ExecCtx::Now() { if (!now_is_valid_) { - now_ = timespec_to_millis_round_down(gpr_now(GPR_CLOCK_MONOTONIC)); + now_ = timespec_to_millis_round_down(gpr_now(GPR_CLOCK_MONOTONIC)); now_is_valid_ = true; } return now_; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h index 6b4e184cad..c75b4dfd93 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/exec_ctx.h @@ -23,7 +23,7 @@ #include <limits> -#include <grpc/impl/codegen/grpc_types.h> +#include <grpc/impl/codegen/grpc_types.h> #include <grpc/support/atm.h> #include <grpc/support/cpu.h> #include <grpc/support/log.h> @@ -31,16 +31,16 @@ #include "src/core/lib/gpr/time_precise.h" #include "src/core/lib/gpr/tls.h" #include "src/core/lib/gprpp/debug_location.h" -#include "src/core/lib/gprpp/fork.h" +#include "src/core/lib/gprpp/fork.h" #include "src/core/lib/iomgr/closure.h" -typedef int64_t grpc_millis; +typedef int64_t grpc_millis; -#define GRPC_MILLIS_INF_FUTURE INT64_MAX -#define GRPC_MILLIS_INF_PAST INT64_MIN +#define GRPC_MILLIS_INF_FUTURE INT64_MAX +#define GRPC_MILLIS_INF_PAST INT64_MIN -/** A combiner represents a list of work to be executed later. - Forward declared here to avoid a circular dependency with combiner.h. */ +/** A combiner represents a list of work to be executed later. + Forward declared here to avoid a circular dependency with combiner.h. */ typedef struct grpc_combiner grpc_combiner; /* This exec_ctx is ready to return: either pre-populated, or cached as soon as @@ -49,14 +49,14 @@ typedef struct grpc_combiner grpc_combiner; /* The exec_ctx's thread is (potentially) owned by a call or channel: care should be given to not delete said call/channel from this exec_ctx */ #define GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP 2 -/* This exec ctx was initialized by an internal thread, and should not - be counted by fork handlers */ -#define GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 4 - -/* This application callback exec ctx was initialized by an internal thread, and - should not be counted by fork handlers */ -#define GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 1 - +/* This exec ctx was initialized by an internal thread, and should not + be counted by fork handlers */ +#define GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 4 + +/* This application callback exec ctx was initialized by an internal thread, and + should not be counted by fork handlers */ +#define GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD 1 + gpr_timespec grpc_millis_to_timespec(grpc_millis millis, gpr_clock_type clock); grpc_millis grpc_timespec_to_millis_round_down(gpr_timespec timespec); grpc_millis grpc_timespec_to_millis_round_up(gpr_timespec timespec); @@ -67,8 +67,8 @@ namespace grpc_core { class Combiner; /** Execution context. * A bag of data that collects information along a callstack. - * It is created on the stack at core entry points (public API or iomgr), and - * stored internally as a thread-local variable. + * It is created on the stack at core entry points (public API or iomgr), and + * stored internally as a thread-local variable. * * Generally, to create an exec_ctx instance, add the following line at the top * of the public API entry point or at the start of a thread's work function : @@ -79,7 +79,7 @@ class Combiner; * grpc_core::ExecCtx::Get() * * Specific responsibilities (this may grow in the future): - * - track a list of core work that needs to be delayed until the base of the + * - track a list of core work that needs to be delayed until the base of the * call stack (this provides a convenient mechanism to run callbacks * without worrying about locking issues) * - provide a decision maker (via IsReadyToFinish) that provides a @@ -90,44 +90,44 @@ class Combiner; * - Instance of this must ALWAYS be constructed on the stack, never * heap allocated. * - Do not pass exec_ctx as a parameter to a function. Always access it using - * grpc_core::ExecCtx::Get(). - * - NOTE: In the future, the convention is likely to change to allow only one - * ExecCtx on a thread's stack at the same time. The TODO below - * discusses this plan in more detail. - * - * TODO(yashykt): Only allow one "active" ExecCtx on a thread at the same time. - * Stage 1: If a new one is created on the stack, it should just - * pass-through to the underlying ExecCtx deeper in the thread's - * stack. - * Stage 2: Assert if a 2nd one is ever created on the stack - * since that implies a core re-entry outside of application - * callbacks. + * grpc_core::ExecCtx::Get(). + * - NOTE: In the future, the convention is likely to change to allow only one + * ExecCtx on a thread's stack at the same time. The TODO below + * discusses this plan in more detail. + * + * TODO(yashykt): Only allow one "active" ExecCtx on a thread at the same time. + * Stage 1: If a new one is created on the stack, it should just + * pass-through to the underlying ExecCtx deeper in the thread's + * stack. + * Stage 2: Assert if a 2nd one is ever created on the stack + * since that implies a core re-entry outside of application + * callbacks. */ class ExecCtx { public: /** Default Constructor */ - ExecCtx() : flags_(GRPC_EXEC_CTX_FLAG_IS_FINISHED) { - grpc_core::Fork::IncExecCtxCount(); - Set(this); - } + ExecCtx() : flags_(GRPC_EXEC_CTX_FLAG_IS_FINISHED) { + grpc_core::Fork::IncExecCtxCount(); + Set(this); + } /** Parameterised Constructor */ - ExecCtx(uintptr_t fl) : flags_(fl) { - if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) { - grpc_core::Fork::IncExecCtxCount(); - } - Set(this); - } + ExecCtx(uintptr_t fl) : flags_(fl) { + if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) { + grpc_core::Fork::IncExecCtxCount(); + } + Set(this); + } /** Destructor */ virtual ~ExecCtx() { flags_ |= GRPC_EXEC_CTX_FLAG_IS_FINISHED; Flush(); Set(last_exec_ctx_); - if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) { - grpc_core::Fork::DecExecCtxCount(); - } + if (!(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) { + grpc_core::Fork::DecExecCtxCount(); + } } /** Disallow copy and assignment operators */ @@ -165,14 +165,14 @@ class ExecCtx { /** Flush any work that has been enqueued onto this grpc_exec_ctx. * Caller must guarantee that no interfering locks are held. - * Returns true if work was performed, false otherwise. - */ + * Returns true if work was performed, false otherwise. + */ bool Flush(); /** Returns true if we'd like to leave this execution context as soon as - * possible: useful for deciding whether to do something more or not - * depending on outside context. - */ + * possible: useful for deciding whether to do something more or not + * depending on outside context. + */ bool IsReadyToFinish() { if ((flags_ & GRPC_EXEC_CTX_FLAG_IS_FINISHED) == 0) { if (CheckReadyToFinish()) { @@ -186,14 +186,14 @@ class ExecCtx { } /** Returns the stored current time relative to start if valid, - * otherwise refreshes the stored time, sets it valid and returns the new - * value. - */ + * otherwise refreshes the stored time, sets it valid and returns the new + * value. + */ grpc_millis Now(); /** Invalidates the stored time value. A new time value will be set on calling - * Now(). - */ + * Now(). + */ void InvalidateNow() { now_is_valid_ = false; } /** To be used only by shutdown code in iomgr */ @@ -203,22 +203,22 @@ class ExecCtx { } /** To be used only for testing. - * Sets the now value. + * Sets the now value. */ void TestOnlySetNow(grpc_millis new_val) { now_ = new_val; now_is_valid_ = true; } - static void TestOnlyGlobalInit(gpr_timespec new_val); - - /** Global initialization for ExecCtx. Called by iomgr. */ + static void TestOnlyGlobalInit(gpr_timespec new_val); + + /** Global initialization for ExecCtx. Called by iomgr. */ static void GlobalInit(void); - /** Global shutdown for ExecCtx. Called by iomgr. */ + /** Global shutdown for ExecCtx. Called by iomgr. */ static void GlobalShutdown(void) { gpr_tls_destroy(&exec_ctx_); } - /** Gets pointer to current exec_ctx. */ + /** Gets pointer to current exec_ctx. */ static ExecCtx* Get() { return reinterpret_cast<ExecCtx*>(gpr_tls_get(&exec_ctx_)); } @@ -233,19 +233,19 @@ class ExecCtx { static void RunList(const DebugLocation& location, grpc_closure_list* list); protected: - /** Check if ready to finish. */ + /** Check if ready to finish. */ virtual bool CheckReadyToFinish() { return false; } - /** Disallow delete on ExecCtx. */ + /** Disallow delete on ExecCtx. */ static void operator delete(void* /* p */) { abort(); } private: - /** Set exec_ctx_ to exec_ctx. */ + /** Set exec_ctx_ to exec_ctx. */ grpc_closure_list closure_list_ = GRPC_CLOSURE_LIST_INIT; CombinerData combiner_data_ = {nullptr, nullptr}; uintptr_t flags_; - + unsigned starting_cpu_ = std::numeric_limits<unsigned>::max(); bool now_is_valid_ = false; @@ -254,83 +254,83 @@ class ExecCtx { GPR_TLS_CLASS_DECL(exec_ctx_); ExecCtx* last_exec_ctx_ = Get(); }; - -/** Application-callback execution context. - * A bag of data that collects information along a callstack. - * It is created on the stack at core entry points, and stored internally - * as a thread-local variable. - * - * There are three key differences between this structure and ExecCtx: - * 1. ApplicationCallbackExecCtx builds a list of application-level - * callbacks, but ExecCtx builds a list of internal callbacks to invoke. - * 2. ApplicationCallbackExecCtx invokes its callbacks only at destruction; - * there is no explicit Flush method. - * 3. If more than one ApplicationCallbackExecCtx is created on the thread's - * stack, only the one closest to the base of the stack is actually - * active and this is the only one that enqueues application callbacks. - * (Unlike ExecCtx, it is not feasible to prevent multiple of these on the - * stack since the executing application callback may itself enter core. - * However, the new one created will just pass callbacks through to the - * base one and those will not be executed until the return to the - * destructor of the base one, preventing unlimited stack growth.) - * - * This structure exists because application callbacks may themselves cause a - * core re-entry (e.g., through a public API call) and if that call in turn - * causes another application-callback, there could be arbitrarily growing - * stacks of core re-entries. Instead, any application callbacks instead should - * not be invoked until other core work is done and other application callbacks - * have completed. To accomplish this, any application callback should be - * enqueued using grpc_core::ApplicationCallbackExecCtx::Enqueue . - * - * CONVENTIONS: - * - Instances of this must ALWAYS be constructed on the stack, never - * heap allocated. - * - Instances of this are generally constructed before ExecCtx when needed. - * The only exception is for ExecCtx's that are explicitly flushed and - * that survive beyond the scope of the function that can cause application - * callbacks to be invoked (e.g., in the timer thread). - * - * Generally, core entry points that may trigger application-level callbacks - * will have the following declarations: - * - * grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - * grpc_core::ExecCtx exec_ctx; - * - * This ordering is important to make sure that the ApplicationCallbackExecCtx - * is destroyed after the ExecCtx (to prevent the re-entry problem described - * above, as well as making sure that ExecCtx core callbacks are invoked first) - * - */ - -class ApplicationCallbackExecCtx { - public: - /** Default Constructor */ - ApplicationCallbackExecCtx() { Set(this, flags_); } - - /** Parameterised Constructor */ - ApplicationCallbackExecCtx(uintptr_t fl) : flags_(fl) { Set(this, flags_); } - - ~ApplicationCallbackExecCtx() { - if (reinterpret_cast<ApplicationCallbackExecCtx*>( - gpr_tls_get(&callback_exec_ctx_)) == this) { - while (head_ != nullptr) { - auto* f = head_; - head_ = f->internal_next; - if (f->internal_next == nullptr) { - tail_ = nullptr; - } - (*f->functor_run)(f, f->internal_success); - } - gpr_tls_set(&callback_exec_ctx_, reinterpret_cast<intptr_t>(nullptr)); - if (!(GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) { - grpc_core::Fork::DecExecCtxCount(); - } - } else { - GPR_DEBUG_ASSERT(head_ == nullptr); - GPR_DEBUG_ASSERT(tail_ == nullptr); - } - } - + +/** Application-callback execution context. + * A bag of data that collects information along a callstack. + * It is created on the stack at core entry points, and stored internally + * as a thread-local variable. + * + * There are three key differences between this structure and ExecCtx: + * 1. ApplicationCallbackExecCtx builds a list of application-level + * callbacks, but ExecCtx builds a list of internal callbacks to invoke. + * 2. ApplicationCallbackExecCtx invokes its callbacks only at destruction; + * there is no explicit Flush method. + * 3. If more than one ApplicationCallbackExecCtx is created on the thread's + * stack, only the one closest to the base of the stack is actually + * active and this is the only one that enqueues application callbacks. + * (Unlike ExecCtx, it is not feasible to prevent multiple of these on the + * stack since the executing application callback may itself enter core. + * However, the new one created will just pass callbacks through to the + * base one and those will not be executed until the return to the + * destructor of the base one, preventing unlimited stack growth.) + * + * This structure exists because application callbacks may themselves cause a + * core re-entry (e.g., through a public API call) and if that call in turn + * causes another application-callback, there could be arbitrarily growing + * stacks of core re-entries. Instead, any application callbacks instead should + * not be invoked until other core work is done and other application callbacks + * have completed. To accomplish this, any application callback should be + * enqueued using grpc_core::ApplicationCallbackExecCtx::Enqueue . + * + * CONVENTIONS: + * - Instances of this must ALWAYS be constructed on the stack, never + * heap allocated. + * - Instances of this are generally constructed before ExecCtx when needed. + * The only exception is for ExecCtx's that are explicitly flushed and + * that survive beyond the scope of the function that can cause application + * callbacks to be invoked (e.g., in the timer thread). + * + * Generally, core entry points that may trigger application-level callbacks + * will have the following declarations: + * + * grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + * grpc_core::ExecCtx exec_ctx; + * + * This ordering is important to make sure that the ApplicationCallbackExecCtx + * is destroyed after the ExecCtx (to prevent the re-entry problem described + * above, as well as making sure that ExecCtx core callbacks are invoked first) + * + */ + +class ApplicationCallbackExecCtx { + public: + /** Default Constructor */ + ApplicationCallbackExecCtx() { Set(this, flags_); } + + /** Parameterised Constructor */ + ApplicationCallbackExecCtx(uintptr_t fl) : flags_(fl) { Set(this, flags_); } + + ~ApplicationCallbackExecCtx() { + if (reinterpret_cast<ApplicationCallbackExecCtx*>( + gpr_tls_get(&callback_exec_ctx_)) == this) { + while (head_ != nullptr) { + auto* f = head_; + head_ = f->internal_next; + if (f->internal_next == nullptr) { + tail_ = nullptr; + } + (*f->functor_run)(f, f->internal_success); + } + gpr_tls_set(&callback_exec_ctx_, reinterpret_cast<intptr_t>(nullptr)); + if (!(GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags_)) { + grpc_core::Fork::DecExecCtxCount(); + } + } else { + GPR_DEBUG_ASSERT(head_ == nullptr); + GPR_DEBUG_ASSERT(tail_ == nullptr); + } + } + uintptr_t Flags() { return flags_; } static ApplicationCallbackExecCtx* Get() { @@ -338,45 +338,45 @@ class ApplicationCallbackExecCtx { gpr_tls_get(&callback_exec_ctx_)); } - static void Set(ApplicationCallbackExecCtx* exec_ctx, uintptr_t flags) { + static void Set(ApplicationCallbackExecCtx* exec_ctx, uintptr_t flags) { if (Get() == nullptr) { - if (!(GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags)) { - grpc_core::Fork::IncExecCtxCount(); - } - gpr_tls_set(&callback_exec_ctx_, reinterpret_cast<intptr_t>(exec_ctx)); - } - } - - static void Enqueue(grpc_experimental_completion_queue_functor* functor, - int is_success) { - functor->internal_success = is_success; - functor->internal_next = nullptr; - + if (!(GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD & flags)) { + grpc_core::Fork::IncExecCtxCount(); + } + gpr_tls_set(&callback_exec_ctx_, reinterpret_cast<intptr_t>(exec_ctx)); + } + } + + static void Enqueue(grpc_experimental_completion_queue_functor* functor, + int is_success) { + functor->internal_success = is_success; + functor->internal_next = nullptr; + ApplicationCallbackExecCtx* ctx = Get(); - - if (ctx->head_ == nullptr) { - ctx->head_ = functor; - } - if (ctx->tail_ != nullptr) { - ctx->tail_->internal_next = functor; - } - ctx->tail_ = functor; - } - - /** Global initialization for ApplicationCallbackExecCtx. Called by init. */ - static void GlobalInit(void) { gpr_tls_init(&callback_exec_ctx_); } - - /** Global shutdown for ApplicationCallbackExecCtx. Called by init. */ - static void GlobalShutdown(void) { gpr_tls_destroy(&callback_exec_ctx_); } - + + if (ctx->head_ == nullptr) { + ctx->head_ = functor; + } + if (ctx->tail_ != nullptr) { + ctx->tail_->internal_next = functor; + } + ctx->tail_ = functor; + } + + /** Global initialization for ApplicationCallbackExecCtx. Called by init. */ + static void GlobalInit(void) { gpr_tls_init(&callback_exec_ctx_); } + + /** Global shutdown for ApplicationCallbackExecCtx. Called by init. */ + static void GlobalShutdown(void) { gpr_tls_destroy(&callback_exec_ctx_); } + static bool Available() { return Get() != nullptr; } - private: - uintptr_t flags_{0u}; - grpc_experimental_completion_queue_functor* head_{nullptr}; - grpc_experimental_completion_queue_functor* tail_{nullptr}; - GPR_TLS_CLASS_DECL(callback_exec_ctx_); -}; + private: + uintptr_t flags_{0u}; + grpc_experimental_completion_queue_functor* head_{nullptr}; + grpc_experimental_completion_queue_functor* tail_{nullptr}; + GPR_TLS_CLASS_DECL(callback_exec_ctx_); +}; } // namespace grpc_core #endif /* GRPC_CORE_LIB_IOMGR_EXEC_CTX_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor.cc b/contrib/libs/grpc/src/core/lib/iomgr/executor.cc index 10b2f948ec..f96bfceb37 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/executor.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/executor.cc @@ -30,7 +30,7 @@ #include "src/core/lib/debug/stats.h" #include "src/core/lib/gpr/tls.h" #include "src/core/lib/gpr/useful.h" -#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/iomgr.h" @@ -50,89 +50,89 @@ } \ } while (0) -namespace grpc_core { -namespace { - +namespace grpc_core { +namespace { + GPR_TLS_DECL(g_this_thread_state); -Executor* executors[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)]; - -void default_enqueue_short(grpc_closure* closure, grpc_error* error) { - executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue( - closure, error, true /* is_short */); -} - -void default_enqueue_long(grpc_closure* closure, grpc_error* error) { - executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue( - closure, error, false /* is_short */); -} - -void resolver_enqueue_short(grpc_closure* closure, grpc_error* error) { - executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Enqueue( - closure, error, true /* is_short */); -} - -void resolver_enqueue_long(grpc_closure* closure, grpc_error* error) { - executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Enqueue( - closure, error, false /* is_short */); -} - +Executor* executors[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)]; + +void default_enqueue_short(grpc_closure* closure, grpc_error* error) { + executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue( + closure, error, true /* is_short */); +} + +void default_enqueue_long(grpc_closure* closure, grpc_error* error) { + executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Enqueue( + closure, error, false /* is_short */); +} + +void resolver_enqueue_short(grpc_closure* closure, grpc_error* error) { + executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Enqueue( + closure, error, true /* is_short */); +} + +void resolver_enqueue_long(grpc_closure* closure, grpc_error* error) { + executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Enqueue( + closure, error, false /* is_short */); +} + using EnqueueFunc = void (*)(grpc_closure* closure, grpc_error* error); - + const EnqueueFunc executor_enqueue_fns_[static_cast<size_t>(ExecutorType::NUM_EXECUTORS)] [static_cast<size_t>(ExecutorJobType::NUM_JOB_TYPES)] = {{default_enqueue_short, default_enqueue_long}, {resolver_enqueue_short, resolver_enqueue_long}}; - + size_t threads_limit_ = 0; -} // namespace - -TraceFlag executor_trace(false, "executor"); - -Executor::Executor(const char* name) : name_(name) { - adding_thread_lock_ = GPR_SPINLOCK_STATIC_INITIALIZER; - gpr_atm_rel_store(&num_threads_, 0); - max_threads_ = GPR_MAX(1, 2 * gpr_cpu_num_cores()); +} // namespace + +TraceFlag executor_trace(false, "executor"); + +Executor::Executor(const char* name) : name_(name) { + adding_thread_lock_ = GPR_SPINLOCK_STATIC_INITIALIZER; + gpr_atm_rel_store(&num_threads_, 0); + max_threads_ = GPR_MAX(1, 2 * gpr_cpu_num_cores()); if (threads_limit_) { max_threads_ = GPR_MIN(max_threads_, threads_limit_); } -} - +} + size_t Executor::SetThreadsLimit(size_t count) { size_t prev = threads_limit_; threads_limit_ = count; return prev; } -void Executor::Init() { SetThreading(true); } - -size_t Executor::RunClosures(const char* executor_name, - grpc_closure_list list) { +void Executor::Init() { SetThreading(true); } + +size_t Executor::RunClosures(const char* executor_name, + grpc_closure_list list) { size_t n = 0; - // In the executor, the ExecCtx for the thread is declared in the executor - // thread itself, but this is the point where we could start seeing - // application-level callbacks. No need to create a new ExecCtx, though, - // since there already is one and it is flushed (but not destructed) in this + // In the executor, the ExecCtx for the thread is declared in the executor + // thread itself, but this is the point where we could start seeing + // application-level callbacks. No need to create a new ExecCtx, though, + // since there already is one and it is flushed (but not destructed) in this // function itself. The ApplicationCallbackExecCtx will have its callbacks // invoked on its destruction, which will be after completing any closures in // the executor's closure list (which were explicitly scheduled onto the // executor). - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx( - GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); - + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx( + GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); + grpc_closure* c = list.head; while (c != nullptr) { grpc_closure* next = c->next_data.next; grpc_error* error = c->error_data.error; #ifndef NDEBUG - EXECUTOR_TRACE("(%s) run %p [created by %s:%d]", executor_name, c, - c->file_created, c->line_created); - c->scheduled = false; + EXECUTOR_TRACE("(%s) run %p [created by %s:%d]", executor_name, c, + c->file_created, c->line_created); + c->scheduled = false; #else - EXECUTOR_TRACE("(%s) run %p", executor_name, c); + EXECUTOR_TRACE("(%s) run %p", executor_name, c); #endif c->cb(c->cb_arg, error); GRPC_ERROR_UNREF(error); @@ -144,70 +144,70 @@ size_t Executor::RunClosures(const char* executor_name, return n; } -bool Executor::IsThreaded() const { - return gpr_atm_acq_load(&num_threads_) > 0; +bool Executor::IsThreaded() const { + return gpr_atm_acq_load(&num_threads_) > 0; } -void Executor::SetThreading(bool threading) { - gpr_atm curr_num_threads = gpr_atm_acq_load(&num_threads_); - EXECUTOR_TRACE("(%s) SetThreading(%d) begin", name_, threading); - +void Executor::SetThreading(bool threading) { + gpr_atm curr_num_threads = gpr_atm_acq_load(&num_threads_); + EXECUTOR_TRACE("(%s) SetThreading(%d) begin", name_, threading); + if (threading) { - if (curr_num_threads > 0) { + if (curr_num_threads > 0) { EXECUTOR_TRACE("(%s) SetThreading(true). curr_num_threads > 0", name_); - return; + return; + } + + GPR_ASSERT(num_threads_ == 0); + gpr_atm_rel_store(&num_threads_, 1); + thd_state_ = static_cast<ThreadState*>( + gpr_zalloc(sizeof(ThreadState) * max_threads_)); + + for (size_t i = 0; i < max_threads_; i++) { + gpr_mu_init(&thd_state_[i].mu); + gpr_cv_init(&thd_state_[i].cv); + thd_state_[i].id = i; + thd_state_[i].name = name_; + thd_state_[i].thd = grpc_core::Thread(); + thd_state_[i].elems = GRPC_CLOSURE_LIST_INIT; } - GPR_ASSERT(num_threads_ == 0); - gpr_atm_rel_store(&num_threads_, 1); - thd_state_ = static_cast<ThreadState*>( - gpr_zalloc(sizeof(ThreadState) * max_threads_)); - - for (size_t i = 0; i < max_threads_; i++) { - gpr_mu_init(&thd_state_[i].mu); - gpr_cv_init(&thd_state_[i].cv); - thd_state_[i].id = i; - thd_state_[i].name = name_; - thd_state_[i].thd = grpc_core::Thread(); - thd_state_[i].elems = GRPC_CLOSURE_LIST_INIT; + thd_state_[0].thd = + grpc_core::Thread(name_, &Executor::ThreadMain, &thd_state_[0]); + thd_state_[0].thd.Start(); + } else { // !threading + if (curr_num_threads == 0) { + EXECUTOR_TRACE("(%s) SetThreading(false). curr_num_threads == 0", name_); + return; } - - thd_state_[0].thd = - grpc_core::Thread(name_, &Executor::ThreadMain, &thd_state_[0]); - thd_state_[0].thd.Start(); - } else { // !threading - if (curr_num_threads == 0) { - EXECUTOR_TRACE("(%s) SetThreading(false). curr_num_threads == 0", name_); - return; + + for (size_t i = 0; i < max_threads_; i++) { + gpr_mu_lock(&thd_state_[i].mu); + thd_state_[i].shutdown = true; + gpr_cv_signal(&thd_state_[i].cv); + gpr_mu_unlock(&thd_state_[i].mu); } - - for (size_t i = 0; i < max_threads_; i++) { - gpr_mu_lock(&thd_state_[i].mu); - thd_state_[i].shutdown = true; - gpr_cv_signal(&thd_state_[i].cv); - gpr_mu_unlock(&thd_state_[i].mu); - } - - /* Ensure no thread is adding a new thread. Once this is past, then no - * thread will try to add a new one either (since shutdown is true) */ - gpr_spinlock_lock(&adding_thread_lock_); - gpr_spinlock_unlock(&adding_thread_lock_); - - curr_num_threads = gpr_atm_no_barrier_load(&num_threads_); - for (gpr_atm i = 0; i < curr_num_threads; i++) { - thd_state_[i].thd.Join(); - EXECUTOR_TRACE("(%s) Thread %" PRIdPTR " of %" PRIdPTR " joined", name_, - i + 1, curr_num_threads); + + /* Ensure no thread is adding a new thread. Once this is past, then no + * thread will try to add a new one either (since shutdown is true) */ + gpr_spinlock_lock(&adding_thread_lock_); + gpr_spinlock_unlock(&adding_thread_lock_); + + curr_num_threads = gpr_atm_no_barrier_load(&num_threads_); + for (gpr_atm i = 0; i < curr_num_threads; i++) { + thd_state_[i].thd.Join(); + EXECUTOR_TRACE("(%s) Thread %" PRIdPTR " of %" PRIdPTR " joined", name_, + i + 1, curr_num_threads); } - - gpr_atm_rel_store(&num_threads_, 0); - for (size_t i = 0; i < max_threads_; i++) { - gpr_mu_destroy(&thd_state_[i].mu); - gpr_cv_destroy(&thd_state_[i].cv); - RunClosures(thd_state_[i].name, thd_state_[i].elems); - } - - gpr_free(thd_state_); + + gpr_atm_rel_store(&num_threads_, 0); + for (size_t i = 0; i < max_threads_; i++) { + gpr_mu_destroy(&thd_state_[i].mu); + gpr_cv_destroy(&thd_state_[i].cv); + RunClosures(thd_state_[i].name, thd_state_[i].elems); + } + + gpr_free(thd_state_); // grpc_iomgr_shutdown_background_closure() will close all the registered // fds in the background poller, and wait for all pending closures to @@ -218,200 +218,200 @@ void Executor::SetThreading(bool threading) { grpc_iomgr_shutdown_background_closure(); } - EXECUTOR_TRACE("(%s) SetThreading(%d) done", name_, threading); + EXECUTOR_TRACE("(%s) SetThreading(%d) done", name_, threading); } -void Executor::Shutdown() { SetThreading(false); } +void Executor::Shutdown() { SetThreading(false); } -void Executor::ThreadMain(void* arg) { - ThreadState* ts = static_cast<ThreadState*>(arg); - gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(ts)); +void Executor::ThreadMain(void* arg) { + ThreadState* ts = static_cast<ThreadState*>(arg); + gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(ts)); - grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); + grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); size_t subtract_depth = 0; for (;;) { - EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: step (sub_depth=%" PRIdPTR ")", - ts->name, ts->id, subtract_depth); - + EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: step (sub_depth=%" PRIdPTR ")", + ts->name, ts->id, subtract_depth); + gpr_mu_lock(&ts->mu); ts->depth -= subtract_depth; - // Wait for closures to be enqueued or for the executor to be shutdown + // Wait for closures to be enqueued or for the executor to be shutdown while (grpc_closure_list_empty(ts->elems) && !ts->shutdown) { ts->queued_long_job = false; gpr_cv_wait(&ts->cv, &ts->mu, gpr_inf_future(GPR_CLOCK_MONOTONIC)); } - + if (ts->shutdown) { - EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: shutdown", ts->name, ts->id); + EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: shutdown", ts->name, ts->id); gpr_mu_unlock(&ts->mu); break; } - + GRPC_STATS_INC_EXECUTOR_QUEUE_DRAINED(); - grpc_closure_list closures = ts->elems; + grpc_closure_list closures = ts->elems; ts->elems = GRPC_CLOSURE_LIST_INIT; gpr_mu_unlock(&ts->mu); - EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: execute", ts->name, ts->id); - + EXECUTOR_TRACE("(%s) [%" PRIdPTR "]: execute", ts->name, ts->id); + grpc_core::ExecCtx::Get()->InvalidateNow(); - subtract_depth = RunClosures(ts->name, closures); + subtract_depth = RunClosures(ts->name, closures); } gpr_tls_set(&g_this_thread_state, reinterpret_cast<intptr_t>(nullptr)); } -void Executor::Enqueue(grpc_closure* closure, grpc_error* error, - bool is_short) { +void Executor::Enqueue(grpc_closure* closure, grpc_error* error, + bool is_short) { bool retry_push; if (is_short) { GRPC_STATS_INC_EXECUTOR_SCHEDULED_SHORT_ITEMS(); } else { GRPC_STATS_INC_EXECUTOR_SCHEDULED_LONG_ITEMS(); } - + do { retry_push = false; size_t cur_thread_count = - static_cast<size_t>(gpr_atm_acq_load(&num_threads_)); - - // If the number of threads is zero(i.e either the executor is not threaded - // or already shutdown), then queue the closure on the exec context itself + static_cast<size_t>(gpr_atm_acq_load(&num_threads_)); + + // If the number of threads is zero(i.e either the executor is not threaded + // or already shutdown), then queue the closure on the exec context itself if (cur_thread_count == 0) { #ifndef NDEBUG - EXECUTOR_TRACE("(%s) schedule %p (created %s:%d) inline", name_, closure, - closure->file_created, closure->line_created); + EXECUTOR_TRACE("(%s) schedule %p (created %s:%d) inline", name_, closure, + closure->file_created, closure->line_created); #else - EXECUTOR_TRACE("(%s) schedule %p inline", name_, closure); + EXECUTOR_TRACE("(%s) schedule %p inline", name_, closure); #endif grpc_closure_list_append(grpc_core::ExecCtx::Get()->closure_list(), closure, error); return; } - + if (grpc_iomgr_add_closure_to_background_poller(closure, error)) { return; } - ThreadState* ts = (ThreadState*)gpr_tls_get(&g_this_thread_state); + ThreadState* ts = (ThreadState*)gpr_tls_get(&g_this_thread_state); if (ts == nullptr) { - ts = &thd_state_[GPR_HASH_POINTER(grpc_core::ExecCtx::Get(), - cur_thread_count)]; + ts = &thd_state_[GPR_HASH_POINTER(grpc_core::ExecCtx::Get(), + cur_thread_count)]; } else { GRPC_STATS_INC_EXECUTOR_SCHEDULED_TO_SELF(); } - ThreadState* orig_ts = ts; - bool try_new_thread = false; - + ThreadState* orig_ts = ts; + bool try_new_thread = false; + for (;;) { #ifndef NDEBUG - EXECUTOR_TRACE( - "(%s) try to schedule %p (%s) (created %s:%d) to thread " - "%" PRIdPTR, - name_, closure, is_short ? "short" : "long", closure->file_created, - closure->line_created, ts->id); + EXECUTOR_TRACE( + "(%s) try to schedule %p (%s) (created %s:%d) to thread " + "%" PRIdPTR, + name_, closure, is_short ? "short" : "long", closure->file_created, + closure->line_created, ts->id); #else - EXECUTOR_TRACE("(%s) try to schedule %p (%s) to thread %" PRIdPTR, name_, - closure, is_short ? "short" : "long", ts->id); + EXECUTOR_TRACE("(%s) try to schedule %p (%s) to thread %" PRIdPTR, name_, + closure, is_short ? "short" : "long", ts->id); #endif - + gpr_mu_lock(&ts->mu); if (ts->queued_long_job) { // if there's a long job queued, we never queue anything else to this // queue (since long jobs can take 'infinite' time and we need to - // guarantee no starvation). Spin through queues and try again + // guarantee no starvation). Spin through queues and try again gpr_mu_unlock(&ts->mu); - size_t idx = ts->id; - ts = &thd_state_[(idx + 1) % cur_thread_count]; + size_t idx = ts->id; + ts = &thd_state_[(idx + 1) % cur_thread_count]; if (ts == orig_ts) { - // We cycled through all the threads. Retry enqueue again by creating - // a new thread - // - // TODO (sreek): There is a potential issue here. We are - // unconditionally setting try_new_thread to true here. What if the - // executor is shutdown OR if cur_thread_count is already equal to - // max_threads ? - // (Fortunately, this is not an issue yet (as of july 2018) because - // there is only one instance of long job in gRPC and hence we will - // not hit this code path) + // We cycled through all the threads. Retry enqueue again by creating + // a new thread + // + // TODO (sreek): There is a potential issue here. We are + // unconditionally setting try_new_thread to true here. What if the + // executor is shutdown OR if cur_thread_count is already equal to + // max_threads ? + // (Fortunately, this is not an issue yet (as of july 2018) because + // there is only one instance of long job in gRPC and hence we will + // not hit this code path) retry_push = true; try_new_thread = true; break; } - - continue; // Try the next thread-state + + continue; // Try the next thread-state } - - // == Found the thread state (i.e thread) to enqueue this closure! == - - // Also, if this thread has been waiting for closures, wake it up. - // - If grpc_closure_list_empty() is true and the Executor is not - // shutdown, it means that the thread must be waiting in ThreadMain() - // - Note that gpr_cv_signal() won't immediately wakeup the thread. That - // happens after we release the mutex &ts->mu a few lines below + + // == Found the thread state (i.e thread) to enqueue this closure! == + + // Also, if this thread has been waiting for closures, wake it up. + // - If grpc_closure_list_empty() is true and the Executor is not + // shutdown, it means that the thread must be waiting in ThreadMain() + // - Note that gpr_cv_signal() won't immediately wakeup the thread. That + // happens after we release the mutex &ts->mu a few lines below if (grpc_closure_list_empty(ts->elems) && !ts->shutdown) { GRPC_STATS_INC_EXECUTOR_WAKEUP_INITIATED(); gpr_cv_signal(&ts->cv); } - + grpc_closure_list_append(&ts->elems, closure, error); - - // If we already queued more than MAX_DEPTH number of closures on this - // thread, use this as a hint to create more threads + + // If we already queued more than MAX_DEPTH number of closures on this + // thread, use this as a hint to create more threads ts->depth++; try_new_thread = ts->depth > MAX_DEPTH && - cur_thread_count < max_threads_ && !ts->shutdown; - - ts->queued_long_job = !is_short; - + cur_thread_count < max_threads_ && !ts->shutdown; + + ts->queued_long_job = !is_short; + gpr_mu_unlock(&ts->mu); break; } - if (try_new_thread && gpr_spinlock_trylock(&adding_thread_lock_)) { - cur_thread_count = static_cast<size_t>(gpr_atm_acq_load(&num_threads_)); - if (cur_thread_count < max_threads_) { - // Increment num_threads (safe to do a store instead of a cas because we - // always increment num_threads under the 'adding_thread_lock') - gpr_atm_rel_store(&num_threads_, cur_thread_count + 1); - - thd_state_[cur_thread_count].thd = grpc_core::Thread( - name_, &Executor::ThreadMain, &thd_state_[cur_thread_count]); - thd_state_[cur_thread_count].thd.Start(); + if (try_new_thread && gpr_spinlock_trylock(&adding_thread_lock_)) { + cur_thread_count = static_cast<size_t>(gpr_atm_acq_load(&num_threads_)); + if (cur_thread_count < max_threads_) { + // Increment num_threads (safe to do a store instead of a cas because we + // always increment num_threads under the 'adding_thread_lock') + gpr_atm_rel_store(&num_threads_, cur_thread_count + 1); + + thd_state_[cur_thread_count].thd = grpc_core::Thread( + name_, &Executor::ThreadMain, &thd_state_[cur_thread_count]); + thd_state_[cur_thread_count].thd.Start(); } - gpr_spinlock_unlock(&adding_thread_lock_); + gpr_spinlock_unlock(&adding_thread_lock_); } - + if (retry_push) { GRPC_STATS_INC_EXECUTOR_PUSH_RETRIES(); } } while (retry_push); } -// Executor::InitAll() and Executor::ShutdownAll() functions are called in the -// the grpc_init() and grpc_shutdown() code paths which are protected by a -// global mutex. So it is okay to assume that these functions are thread-safe -void Executor::InitAll() { - EXECUTOR_TRACE0("Executor::InitAll() enter"); - - // Return if Executor::InitAll() is already called earlier - if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] != nullptr) { - GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] != - nullptr); - return; - } - - executors[static_cast<size_t>(ExecutorType::DEFAULT)] = +// Executor::InitAll() and Executor::ShutdownAll() functions are called in the +// the grpc_init() and grpc_shutdown() code paths which are protected by a +// global mutex. So it is okay to assume that these functions are thread-safe +void Executor::InitAll() { + EXECUTOR_TRACE0("Executor::InitAll() enter"); + + // Return if Executor::InitAll() is already called earlier + if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] != nullptr) { + GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] != + nullptr); + return; + } + + executors[static_cast<size_t>(ExecutorType::DEFAULT)] = new Executor("default-executor"); - executors[static_cast<size_t>(ExecutorType::RESOLVER)] = + executors[static_cast<size_t>(ExecutorType::RESOLVER)] = new Executor("resolver-executor"); - - executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Init(); - executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Init(); - - EXECUTOR_TRACE0("Executor::InitAll() done"); + + executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Init(); + executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Init(); + + EXECUTOR_TRACE0("Executor::InitAll() done"); } void Executor::Run(grpc_closure* closure, grpc_error* error, @@ -420,61 +420,61 @@ void Executor::Run(grpc_closure* closure, grpc_error* error, [static_cast<size_t>(job_type)](closure, error); } -void Executor::ShutdownAll() { - EXECUTOR_TRACE0("Executor::ShutdownAll() enter"); - - // Return if Executor:SshutdownAll() is already called earlier - if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] == nullptr) { - GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] == - nullptr); - return; - } - - executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Shutdown(); - executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Shutdown(); - - // Delete the executor objects. - // - // NOTE: It is important to call Shutdown() on all executors first before +void Executor::ShutdownAll() { + EXECUTOR_TRACE0("Executor::ShutdownAll() enter"); + + // Return if Executor:SshutdownAll() is already called earlier + if (executors[static_cast<size_t>(ExecutorType::DEFAULT)] == nullptr) { + GPR_ASSERT(executors[static_cast<size_t>(ExecutorType::RESOLVER)] == + nullptr); + return; + } + + executors[static_cast<size_t>(ExecutorType::DEFAULT)]->Shutdown(); + executors[static_cast<size_t>(ExecutorType::RESOLVER)]->Shutdown(); + + // Delete the executor objects. + // + // NOTE: It is important to call Shutdown() on all executors first before // calling delete because it is possible for one executor (that is not - // shutdown yet) to call Enqueue() on a different executor which is already - // shutdown. This is legal and in such cases, the Enqueue() operation - // effectively "fails" and enqueues that closure on the calling thread's - // exec_ctx. - // - // By ensuring that all executors are shutdown first, we are also ensuring - // that no thread is active across all executors. - + // shutdown yet) to call Enqueue() on a different executor which is already + // shutdown. This is legal and in such cases, the Enqueue() operation + // effectively "fails" and enqueues that closure on the calling thread's + // exec_ctx. + // + // By ensuring that all executors are shutdown first, we are also ensuring + // that no thread is active across all executors. + delete executors[static_cast<size_t>(ExecutorType::DEFAULT)]; delete executors[static_cast<size_t>(ExecutorType::RESOLVER)]; - executors[static_cast<size_t>(ExecutorType::DEFAULT)] = nullptr; - executors[static_cast<size_t>(ExecutorType::RESOLVER)] = nullptr; - - EXECUTOR_TRACE0("Executor::ShutdownAll() done"); -} - -bool Executor::IsThreaded(ExecutorType executor_type) { - GPR_ASSERT(executor_type < ExecutorType::NUM_EXECUTORS); - return executors[static_cast<size_t>(executor_type)]->IsThreaded(); + executors[static_cast<size_t>(ExecutorType::DEFAULT)] = nullptr; + executors[static_cast<size_t>(ExecutorType::RESOLVER)] = nullptr; + + EXECUTOR_TRACE0("Executor::ShutdownAll() done"); } - -bool Executor::IsThreadedDefault() { - return Executor::IsThreaded(ExecutorType::DEFAULT); -} - -void Executor::SetThreadingAll(bool enable) { - EXECUTOR_TRACE("Executor::SetThreadingAll(%d) called", enable); - for (size_t i = 0; i < static_cast<size_t>(ExecutorType::NUM_EXECUTORS); - i++) { - executors[i]->SetThreading(enable); - } -} - -void Executor::SetThreadingDefault(bool enable) { - EXECUTOR_TRACE("Executor::SetThreadingDefault(%d) called", enable); - executors[static_cast<size_t>(ExecutorType::DEFAULT)]->SetThreading(enable); -} - + +bool Executor::IsThreaded(ExecutorType executor_type) { + GPR_ASSERT(executor_type < ExecutorType::NUM_EXECUTORS); + return executors[static_cast<size_t>(executor_type)]->IsThreaded(); +} + +bool Executor::IsThreadedDefault() { + return Executor::IsThreaded(ExecutorType::DEFAULT); +} + +void Executor::SetThreadingAll(bool enable) { + EXECUTOR_TRACE("Executor::SetThreadingAll(%d) called", enable); + for (size_t i = 0; i < static_cast<size_t>(ExecutorType::NUM_EXECUTORS); + i++) { + executors[i]->SetThreading(enable); + } +} + +void Executor::SetThreadingDefault(bool enable) { + EXECUTOR_TRACE("Executor::SetThreadingDefault(%d) called", enable); + executors[static_cast<size_t>(ExecutorType::DEFAULT)]->SetThreading(enable); +} + void grpc_executor_global_init() { gpr_tls_init(&g_this_thread_state); } -} // namespace grpc_core +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/iomgr/executor.h b/contrib/libs/grpc/src/core/lib/iomgr/executor.h index ae523ff212..5a97762a39 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/executor.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/executor.h @@ -21,105 +21,105 @@ #include <grpc/support/port_platform.h> -#include "src/core/lib/gpr/spinlock.h" -#include "src/core/lib/gprpp/thd.h" +#include "src/core/lib/gpr/spinlock.h" +#include "src/core/lib/gprpp/thd.h" #include "src/core/lib/iomgr/closure.h" -namespace grpc_core { - -struct ThreadState { - gpr_mu mu; - size_t id; // For debugging purposes - const char* name; // Thread state name - gpr_cv cv; - grpc_closure_list elems; - size_t depth; // Number of closures in the closure list - bool shutdown; - bool queued_long_job; - grpc_core::Thread thd; -}; - -enum class ExecutorType { - DEFAULT = 0, - RESOLVER, - - NUM_EXECUTORS // Add new values above this -}; - -enum class ExecutorJobType { - SHORT = 0, - LONG, - NUM_JOB_TYPES // Add new values above this -}; - -class Executor { - public: - Executor(const char* executor_name); - - void Init(); - - /** Is the executor multi-threaded? */ - bool IsThreaded() const; - +namespace grpc_core { + +struct ThreadState { + gpr_mu mu; + size_t id; // For debugging purposes + const char* name; // Thread state name + gpr_cv cv; + grpc_closure_list elems; + size_t depth; // Number of closures in the closure list + bool shutdown; + bool queued_long_job; + grpc_core::Thread thd; +}; + +enum class ExecutorType { + DEFAULT = 0, + RESOLVER, + + NUM_EXECUTORS // Add new values above this +}; + +enum class ExecutorJobType { + SHORT = 0, + LONG, + NUM_JOB_TYPES // Add new values above this +}; + +class Executor { + public: + Executor(const char* executor_name); + + void Init(); + + /** Is the executor multi-threaded? */ + bool IsThreaded() const; + /* Enable/disable threading - must be called after Init and Shutdown(). Never * call SetThreading(false) in the middle of an application */ - void SetThreading(bool threading); - - /** Shutdown the executor, running all pending work as part of the call */ - void Shutdown(); - - /** Enqueue the closure onto the executor. is_short is true if the closure is - * a short job (i.e expected to not block and complete quickly) */ - void Enqueue(grpc_closure* closure, grpc_error* error, bool is_short); - - // TODO(sreek): Currently we have two executors (available globally): The - // default executor and the resolver executor. - // - // Some of the functions below operate on the DEFAULT executor only while some - // operate of ALL the executors. This is a bit confusing and should be cleaned - // up in future (where we make all the following functions take ExecutorType - // and/or JobType) - - // Initialize ALL the executors - static void InitAll(); - + void SetThreading(bool threading); + + /** Shutdown the executor, running all pending work as part of the call */ + void Shutdown(); + + /** Enqueue the closure onto the executor. is_short is true if the closure is + * a short job (i.e expected to not block and complete quickly) */ + void Enqueue(grpc_closure* closure, grpc_error* error, bool is_short); + + // TODO(sreek): Currently we have two executors (available globally): The + // default executor and the resolver executor. + // + // Some of the functions below operate on the DEFAULT executor only while some + // operate of ALL the executors. This is a bit confusing and should be cleaned + // up in future (where we make all the following functions take ExecutorType + // and/or JobType) + + // Initialize ALL the executors + static void InitAll(); + static void Run(grpc_closure* closure, grpc_error* error, ExecutorType executor_type = ExecutorType::DEFAULT, ExecutorJobType job_type = ExecutorJobType::SHORT); - // Shutdown ALL the executors - static void ShutdownAll(); - - // Set the threading mode for ALL the executors - static void SetThreadingAll(bool enable); - - // Set the threading mode for ALL the executors - static void SetThreadingDefault(bool enable); - - // Return if a given executor is running in threaded mode (i.e if - // SetThreading(true) was called previously on that executor) - static bool IsThreaded(ExecutorType executor_type); - - // Return if the DEFAULT executor is threaded - static bool IsThreadedDefault(); - + // Shutdown ALL the executors + static void ShutdownAll(); + + // Set the threading mode for ALL the executors + static void SetThreadingAll(bool enable); + + // Set the threading mode for ALL the executors + static void SetThreadingDefault(bool enable); + + // Return if a given executor is running in threaded mode (i.e if + // SetThreading(true) was called previously on that executor) + static bool IsThreaded(ExecutorType executor_type); + + // Return if the DEFAULT executor is threaded + static bool IsThreadedDefault(); + // Set the maximum numbers of executor treads static size_t SetThreadsLimit(size_t count); - private: - static size_t RunClosures(const char* executor_name, grpc_closure_list list); - static void ThreadMain(void* arg); - - const char* name_; - ThreadState* thd_state_; - size_t max_threads_; - gpr_atm num_threads_; - gpr_spinlock adding_thread_lock_; -}; - + private: + static size_t RunClosures(const char* executor_name, grpc_closure_list list); + static void ThreadMain(void* arg); + + const char* name_; + ThreadState* thd_state_; + size_t max_threads_; + gpr_atm num_threads_; + gpr_spinlock adding_thread_lock_; +}; + // Global initializer for executor void grpc_executor_global_init(); -} // namespace grpc_core - +} // namespace grpc_core + #endif /* GRPC_CORE_LIB_IOMGR_EXECUTOR_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc index 82654b5a88..17017c74fd 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/fork_posix.cc @@ -29,10 +29,10 @@ #include <string.h> #include <grpc/fork.h> -#include <grpc/grpc.h> +#include <grpc/grpc.h> #include <grpc/support/log.h> -#include "src/core/lib/gprpp/fork.h" +#include "src/core/lib/gprpp/fork.h" #include "src/core/lib/gprpp/thd.h" #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/executor.h" @@ -44,20 +44,20 @@ * AROUND VERY SPECIFIC USE CASES. */ -namespace { -bool skipped_handler = true; -bool registered_handlers = false; -} // namespace - +namespace { +bool skipped_handler = true; +bool registered_handlers = false; +} // namespace + void grpc_prefork() { - skipped_handler = true; - // This may be called after core shuts down, so verify initialized before - // instantiating an ExecCtx. - if (!grpc_is_initialized()) { - return; - } - grpc_core::ExecCtx exec_ctx; - if (!grpc_core::Fork::Enabled()) { + skipped_handler = true; + // This may be called after core shuts down, so verify initialized before + // instantiating an ExecCtx. + if (!grpc_is_initialized()) { + return; + } + grpc_core::ExecCtx exec_ctx; + if (!grpc_core::Fork::Enabled()) { gpr_log(GPR_ERROR, "Fork support not enabled; try running with the " "environment variable GRPC_ENABLE_FORK_SUPPORT=1"); @@ -67,51 +67,51 @@ void grpc_prefork() { if (poll_strategy_name == nullptr || (strcmp(poll_strategy_name, "epoll1") != 0 && strcmp(poll_strategy_name, "poll") != 0)) { - gpr_log(GPR_INFO, - "Fork support is only compatible with the epoll1 and poll polling " - "strategies"); - } - if (!grpc_core::Fork::BlockExecCtx()) { - gpr_log(GPR_INFO, - "Other threads are currently calling into gRPC, skipping fork() " - "handlers"); - return; + gpr_log(GPR_INFO, + "Fork support is only compatible with the epoll1 and poll polling " + "strategies"); } - grpc_timer_manager_set_threading(false); - grpc_core::Executor::SetThreadingAll(false); - grpc_core::ExecCtx::Get()->Flush(); - grpc_core::Fork::AwaitThreads(); - skipped_handler = false; + if (!grpc_core::Fork::BlockExecCtx()) { + gpr_log(GPR_INFO, + "Other threads are currently calling into gRPC, skipping fork() " + "handlers"); + return; + } + grpc_timer_manager_set_threading(false); + grpc_core::Executor::SetThreadingAll(false); + grpc_core::ExecCtx::Get()->Flush(); + grpc_core::Fork::AwaitThreads(); + skipped_handler = false; } void grpc_postfork_parent() { - if (!skipped_handler) { - grpc_core::Fork::AllowExecCtx(); - grpc_core::ExecCtx exec_ctx; + if (!skipped_handler) { + grpc_core::Fork::AllowExecCtx(); + grpc_core::ExecCtx exec_ctx; grpc_timer_manager_set_threading(true); - grpc_core::Executor::SetThreadingAll(true); + grpc_core::Executor::SetThreadingAll(true); } } void grpc_postfork_child() { - if (!skipped_handler) { - grpc_core::Fork::AllowExecCtx(); - grpc_core::ExecCtx exec_ctx; - grpc_core::Fork::child_postfork_func reset_polling_engine = - grpc_core::Fork::GetResetChildPollingEngineFunc(); - if (reset_polling_engine != nullptr) { - reset_polling_engine(); - } + if (!skipped_handler) { + grpc_core::Fork::AllowExecCtx(); + grpc_core::ExecCtx exec_ctx; + grpc_core::Fork::child_postfork_func reset_polling_engine = + grpc_core::Fork::GetResetChildPollingEngineFunc(); + if (reset_polling_engine != nullptr) { + reset_polling_engine(); + } grpc_timer_manager_set_threading(true); - grpc_core::Executor::SetThreadingAll(true); + grpc_core::Executor::SetThreadingAll(true); } } void grpc_fork_handlers_auto_register() { - if (grpc_core::Fork::Enabled() & !registered_handlers) { + if (grpc_core::Fork::Enabled() & !registered_handlers) { #ifdef GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK pthread_atfork(grpc_prefork, grpc_postfork_parent, grpc_postfork_child); - registered_handlers = true; + registered_handlers = true; #endif // GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK } } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex.h b/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex.h index ed9612dcb9..a4e02157c1 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex.h @@ -1,30 +1,30 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_IOMGR_GRPC_IF_NAMETOINDEX_H -#define GRPC_CORE_LIB_IOMGR_GRPC_IF_NAMETOINDEX_H - -#include <grpc/support/port_platform.h> - -#include <stddef.h> - -/* Returns the interface index corresponding to the interface "name" provided. - * Returns non-zero upon success, and zero upon failure. */ -uint32_t grpc_if_nametoindex(char* name); - -#endif /* GRPC_CORE_LIB_IOMGR_GRPC_IF_NAMETOINDEX_H */ +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_IOMGR_GRPC_IF_NAMETOINDEX_H +#define GRPC_CORE_LIB_IOMGR_GRPC_IF_NAMETOINDEX_H + +#include <grpc/support/port_platform.h> + +#include <stddef.h> + +/* Returns the interface index corresponding to the interface "name" provided. + * Returns non-zero upon success, and zero upon failure. */ +uint32_t grpc_if_nametoindex(char* name); + +#endif /* GRPC_CORE_LIB_IOMGR_GRPC_IF_NAMETOINDEX_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_posix.cc index f1ba20dcec..afae029b86 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_posix.cc @@ -1,42 +1,42 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#if GRPC_IF_NAMETOINDEX == 1 && defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) - -#include "src/core/lib/iomgr/grpc_if_nametoindex.h" - -#include <errno.h> -#include <net/if.h> - -#include <grpc/support/log.h> - -uint32_t grpc_if_nametoindex(char* name) { - uint32_t out = if_nametoindex(name); - if (out == 0) { - gpr_log(GPR_DEBUG, "if_nametoindex failed for name %s. errno %d", name, - errno); - } - return out; -} - -#endif /* GRPC_IF_NAMETOINDEX == 1 && \ - defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) */ +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#if GRPC_IF_NAMETOINDEX == 1 && defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) + +#include "src/core/lib/iomgr/grpc_if_nametoindex.h" + +#include <errno.h> +#include <net/if.h> + +#include <grpc/support/log.h> + +uint32_t grpc_if_nametoindex(char* name) { + uint32_t out = if_nametoindex(name); + if (out == 0) { + gpr_log(GPR_DEBUG, "if_nametoindex failed for name %s. errno %d", name, + errno); + } + return out; +} + +#endif /* GRPC_IF_NAMETOINDEX == 1 && \ + defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc b/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc index 08644cccf3..fa7c878bab 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc @@ -1,38 +1,38 @@ -/* - * - * Copyright 2016 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#if GRPC_IF_NAMETOINDEX == 0 || !defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) - -#include "src/core/lib/iomgr/grpc_if_nametoindex.h" - -#include <grpc/support/log.h> - -uint32_t grpc_if_nametoindex(char* name) { - gpr_log(GPR_DEBUG, - "Not attempting to convert interface name %s to index for current " - "platform.", - name); - return 0; -} - -#endif /* GRPC_IF_NAMETOINDEX == 0 || \ - !defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) */ +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#if GRPC_IF_NAMETOINDEX == 0 || !defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) + +#include "src/core/lib/iomgr/grpc_if_nametoindex.h" + +#include <grpc/support/log.h> + +uint32_t grpc_if_nametoindex(char* name) { + gpr_log(GPR_DEBUG, + "Not attempting to convert interface name %s to index for current " + "platform.", + name); + return 0; +} + +#endif /* GRPC_IF_NAMETOINDEX == 0 || \ + !defined(GRPC_POSIX_SOCKET_IF_NAMETOINDEX) */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc b/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc index b68c66b757..00b62bc074 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.cc @@ -1,67 +1,67 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#include <grpc/impl/codegen/log.h> -#include "src/core/lib/iomgr/internal_errqueue.h" - -#ifdef GRPC_POSIX_SOCKET_TCP - -#include <errno.h> -#include <stdlib.h> -#include <string.h> -#include <sys/utsname.h> - -namespace grpc_core { -static bool errqueue_supported = false; - -bool kernel_supports_errqueue() { return errqueue_supported; } - -void grpc_errqueue_init() { +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#include <grpc/impl/codegen/log.h> +#include "src/core/lib/iomgr/internal_errqueue.h" + +#ifdef GRPC_POSIX_SOCKET_TCP + +#include <errno.h> +#include <stdlib.h> +#include <string.h> +#include <sys/utsname.h> + +namespace grpc_core { +static bool errqueue_supported = false; + +bool kernel_supports_errqueue() { return errqueue_supported; } + +void grpc_errqueue_init() { /* Both-compile time and run-time linux kernel versions should be at least 4.0.0 - */ + */ #ifdef GRPC_LINUX_ERRQUEUE - struct utsname buffer; - if (uname(&buffer) != 0) { - gpr_log(GPR_ERROR, "uname: %s", strerror(errno)); - return; - } - char* release = buffer.release; - if (release == nullptr) { - return; - } - - if (strtol(release, nullptr, 10) >= 4) { - errqueue_supported = true; - } else { - gpr_log(GPR_DEBUG, "ERRQUEUE support not enabled"); - } + struct utsname buffer; + if (uname(&buffer) != 0) { + gpr_log(GPR_ERROR, "uname: %s", strerror(errno)); + return; + } + char* release = buffer.release; + if (release == nullptr) { + return; + } + + if (strtol(release, nullptr, 10) >= 4) { + errqueue_supported = true; + } else { + gpr_log(GPR_DEBUG, "ERRQUEUE support not enabled"); + } #endif /* GRPC_LINUX_ERRQUEUE */ -} -} /* namespace grpc_core */ - -#else - -namespace grpc_core { -void grpc_errqueue_init() {} -} /* namespace grpc_core */ - -#endif /* GRPC_POSIX_SOCKET_TCP */ +} +} /* namespace grpc_core */ + +#else + +namespace grpc_core { +void grpc_errqueue_init() {} +} /* namespace grpc_core */ + +#endif /* GRPC_POSIX_SOCKET_TCP */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.h b/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.h index b9fe411769..45dfb9a93a 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/internal_errqueue.h @@ -1,191 +1,191 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -/* This file contains constants defined in <linux/errqueue.h> and - * <linux/net_tstamp.h> so as to allow collecting network timestamps in the - * kernel. This file allows tcp_posix.cc to compile on platforms that do not - * have <linux/errqueue.h> and <linux/net_tstamp.h>. - */ - -#ifndef GRPC_CORE_LIB_IOMGR_INTERNAL_ERRQUEUE_H -#define GRPC_CORE_LIB_IOMGR_INTERNAL_ERRQUEUE_H - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#ifdef GRPC_POSIX_SOCKET_TCP - -#include <sys/types.h> -#include <time.h> - -#ifdef GRPC_LINUX_ERRQUEUE -#include <linux/errqueue.h> -#include <linux/net_tstamp.h> -#include <linux/netlink.h> -#include <sys/socket.h> -#endif /* GRPC_LINUX_ERRQUEUE */ - -namespace grpc_core { - -#ifdef GRPC_LINUX_ERRQUEUE - -/* Redefining scm_timestamping in the same way that <linux/errqueue.h> defines - * it, so that code compiles on systems that don't have it. */ -struct scm_timestamping { - struct timespec ts[3]; -}; -/* Also redefine timestamp types */ -/* The timestamp type for when the driver passed skb to NIC, or HW. */ -constexpr int SCM_TSTAMP_SND = 0; -/* The timestamp type for when data entered the packet scheduler. */ -constexpr int SCM_TSTAMP_SCHED = 1; -/* The timestamp type for when data acknowledged by peer. */ -constexpr int SCM_TSTAMP_ACK = 2; - -/* Control message type containing OPT_STATS */ -#ifndef SCM_TIMESTAMPING_OPT_STATS -#define SCM_TIMESTAMPING_OPT_STATS 54 -#endif - -/* Redefine required constants from <linux/net_tstamp.h> */ -constexpr uint32_t SOF_TIMESTAMPING_TX_SOFTWARE = 1u << 1; -constexpr uint32_t SOF_TIMESTAMPING_SOFTWARE = 1u << 4; -constexpr uint32_t SOF_TIMESTAMPING_OPT_ID = 1u << 7; -constexpr uint32_t SOF_TIMESTAMPING_TX_SCHED = 1u << 8; -constexpr uint32_t SOF_TIMESTAMPING_TX_ACK = 1u << 9; -constexpr uint32_t SOF_TIMESTAMPING_OPT_TSONLY = 1u << 11; -constexpr uint32_t SOF_TIMESTAMPING_OPT_STATS = 1u << 12; - -constexpr uint32_t kTimestampingSocketOptions = - SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_OPT_ID | - SOF_TIMESTAMPING_OPT_TSONLY | SOF_TIMESTAMPING_OPT_STATS; -constexpr uint32_t kTimestampingRecordingOptions = - SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | - SOF_TIMESTAMPING_TX_ACK; - -/* Netlink attribute types used for TCP opt stats. */ -enum TCPOptStats { - TCP_NLA_PAD, - TCP_NLA_BUSY, /* Time (usec) busy sending data. */ - TCP_NLA_RWND_LIMITED, /* Time (usec) limited by receive window. */ - TCP_NLA_SNDBUF_LIMITED, /* Time (usec) limited by send buffer. */ - TCP_NLA_DATA_SEGS_OUT, /* Data pkts sent including retransmission. */ - TCP_NLA_TOTAL_RETRANS, /* Data pkts retransmitted. */ - TCP_NLA_PACING_RATE, /* Pacing rate in Bps. */ - TCP_NLA_DELIVERY_RATE, /* Delivery rate in Bps. */ - TCP_NLA_SND_CWND, /* Sending congestion window. */ - TCP_NLA_REORDERING, /* Reordering metric. */ - TCP_NLA_MIN_RTT, /* minimum RTT. */ - TCP_NLA_RECUR_RETRANS, /* Recurring retransmits for the current pkt. */ - TCP_NLA_DELIVERY_RATE_APP_LMT, /* Delivery rate application limited? */ - TCP_NLA_SNDQ_SIZE, /* Data (bytes) pending in send queue */ - TCP_NLA_CA_STATE, /* ca_state of socket */ - TCP_NLA_SND_SSTHRESH, /* Slow start size threshold */ - TCP_NLA_DELIVERED, /* Data pkts delivered incl. out-of-order */ - TCP_NLA_DELIVERED_CE, /* Like above but only ones w/ CE marks */ - TCP_NLA_BYTES_SENT, /* Data bytes sent including retransmission */ - TCP_NLA_BYTES_RETRANS, /* Data bytes retransmitted */ - TCP_NLA_DSACK_DUPS, /* DSACK blocks received */ - TCP_NLA_REORD_SEEN, /* reordering events seen */ - TCP_NLA_SRTT, /* smoothed RTT in usecs */ -}; - -/* tcp_info from from linux/tcp.h */ -struct tcp_info { - uint8_t tcpi_state; - uint8_t tcpi_ca_state; - uint8_t tcpi_retransmits; - uint8_t tcpi_probes; - uint8_t tcpi_backoff; - uint8_t tcpi_options; - uint8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4; - uint8_t tcpi_delivery_rate_app_limited : 1; - uint32_t tcpi_rto; - uint32_t tcpi_ato; - uint32_t tcpi_snd_mss; - uint32_t tcpi_rcv_mss; - uint32_t tcpi_unacked; - uint32_t tcpi_sacked; - uint32_t tcpi_lost; - uint32_t tcpi_retrans; - uint32_t tcpi_fackets; - /* Times. */ - uint32_t tcpi_last_data_sent; - uint32_t tcpi_last_ack_sent; /* Not remembered, sorry. */ - uint32_t tcpi_last_data_recv; - uint32_t tcpi_last_ack_recv; - /* Metrics. */ - uint32_t tcpi_pmtu; - uint32_t tcpi_rcv_ssthresh; - uint32_t tcpi_rtt; - uint32_t tcpi_rttvar; - uint32_t tcpi_snd_ssthresh; - uint32_t tcpi_snd_cwnd; - uint32_t tcpi_advmss; - uint32_t tcpi_reordering; - uint32_t tcpi_rcv_rtt; - uint32_t tcpi_rcv_space; - uint32_t tcpi_total_retrans; - uint64_t tcpi_pacing_rate; - uint64_t tcpi_max_pacing_rate; - uint64_t tcpi_bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked */ - uint64_t tcpi_bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived */ - - uint32_t tcpi_segs_out; /* RFC4898 tcpEStatsPerfSegsOut */ - uint32_t tcpi_segs_in; /* RFC4898 tcpEStatsPerfSegsIn */ - uint32_t tcpi_notsent_bytes; - uint32_t tcpi_min_rtt; - - uint32_t tcpi_data_segs_in; /* RFC4898 tcpEStatsDataSegsIn */ - uint32_t tcpi_data_segs_out; /* RFC4898 tcpEStatsDataSegsOut */ - - uint64_t tcpi_delivery_rate; - uint64_t tcpi_busy_time; /* Time (usec) busy sending data */ - uint64_t tcpi_rwnd_limited; /* Time (usec) limited by receive window */ - uint64_t tcpi_sndbuf_limited; /* Time (usec) limited by send buffer */ - - uint32_t tcpi_delivered; - uint32_t tcpi_delivered_ce; - uint64_t tcpi_bytes_sent; /* RFC4898 tcpEStatsPerfHCDataOctetsOut */ - uint64_t tcpi_bytes_retrans; /* RFC4898 tcpEStatsPerfOctetsRetrans */ - uint32_t tcpi_dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups */ - uint32_t tcpi_reord_seen; /* reordering events seen */ - socklen_t length; /* Length of struct returned by kernel */ -}; - -#ifndef TCP_INFO -#define TCP_INFO 11 -#endif -#endif /* GRPC_LINUX_ERRQUEUE */ - -/* Returns true if kernel is capable of supporting errqueue and timestamping. - * Currently allowing only linux kernels above 4.0.0 - */ -bool kernel_supports_errqueue(); - -} /* namespace grpc_core */ - -#endif /* GRPC_POSIX_SOCKET_TCP */ - -namespace grpc_core { -/* Initializes errqueue support */ -void grpc_errqueue_init(); -} /* namespace grpc_core */ - -#endif /* GRPC_CORE_LIB_IOMGR_INTERNAL_ERRQUEUE_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* This file contains constants defined in <linux/errqueue.h> and + * <linux/net_tstamp.h> so as to allow collecting network timestamps in the + * kernel. This file allows tcp_posix.cc to compile on platforms that do not + * have <linux/errqueue.h> and <linux/net_tstamp.h>. + */ + +#ifndef GRPC_CORE_LIB_IOMGR_INTERNAL_ERRQUEUE_H +#define GRPC_CORE_LIB_IOMGR_INTERNAL_ERRQUEUE_H + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_POSIX_SOCKET_TCP + +#include <sys/types.h> +#include <time.h> + +#ifdef GRPC_LINUX_ERRQUEUE +#include <linux/errqueue.h> +#include <linux/net_tstamp.h> +#include <linux/netlink.h> +#include <sys/socket.h> +#endif /* GRPC_LINUX_ERRQUEUE */ + +namespace grpc_core { + +#ifdef GRPC_LINUX_ERRQUEUE + +/* Redefining scm_timestamping in the same way that <linux/errqueue.h> defines + * it, so that code compiles on systems that don't have it. */ +struct scm_timestamping { + struct timespec ts[3]; +}; +/* Also redefine timestamp types */ +/* The timestamp type for when the driver passed skb to NIC, or HW. */ +constexpr int SCM_TSTAMP_SND = 0; +/* The timestamp type for when data entered the packet scheduler. */ +constexpr int SCM_TSTAMP_SCHED = 1; +/* The timestamp type for when data acknowledged by peer. */ +constexpr int SCM_TSTAMP_ACK = 2; + +/* Control message type containing OPT_STATS */ +#ifndef SCM_TIMESTAMPING_OPT_STATS +#define SCM_TIMESTAMPING_OPT_STATS 54 +#endif + +/* Redefine required constants from <linux/net_tstamp.h> */ +constexpr uint32_t SOF_TIMESTAMPING_TX_SOFTWARE = 1u << 1; +constexpr uint32_t SOF_TIMESTAMPING_SOFTWARE = 1u << 4; +constexpr uint32_t SOF_TIMESTAMPING_OPT_ID = 1u << 7; +constexpr uint32_t SOF_TIMESTAMPING_TX_SCHED = 1u << 8; +constexpr uint32_t SOF_TIMESTAMPING_TX_ACK = 1u << 9; +constexpr uint32_t SOF_TIMESTAMPING_OPT_TSONLY = 1u << 11; +constexpr uint32_t SOF_TIMESTAMPING_OPT_STATS = 1u << 12; + +constexpr uint32_t kTimestampingSocketOptions = + SOF_TIMESTAMPING_SOFTWARE | SOF_TIMESTAMPING_OPT_ID | + SOF_TIMESTAMPING_OPT_TSONLY | SOF_TIMESTAMPING_OPT_STATS; +constexpr uint32_t kTimestampingRecordingOptions = + SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | + SOF_TIMESTAMPING_TX_ACK; + +/* Netlink attribute types used for TCP opt stats. */ +enum TCPOptStats { + TCP_NLA_PAD, + TCP_NLA_BUSY, /* Time (usec) busy sending data. */ + TCP_NLA_RWND_LIMITED, /* Time (usec) limited by receive window. */ + TCP_NLA_SNDBUF_LIMITED, /* Time (usec) limited by send buffer. */ + TCP_NLA_DATA_SEGS_OUT, /* Data pkts sent including retransmission. */ + TCP_NLA_TOTAL_RETRANS, /* Data pkts retransmitted. */ + TCP_NLA_PACING_RATE, /* Pacing rate in Bps. */ + TCP_NLA_DELIVERY_RATE, /* Delivery rate in Bps. */ + TCP_NLA_SND_CWND, /* Sending congestion window. */ + TCP_NLA_REORDERING, /* Reordering metric. */ + TCP_NLA_MIN_RTT, /* minimum RTT. */ + TCP_NLA_RECUR_RETRANS, /* Recurring retransmits for the current pkt. */ + TCP_NLA_DELIVERY_RATE_APP_LMT, /* Delivery rate application limited? */ + TCP_NLA_SNDQ_SIZE, /* Data (bytes) pending in send queue */ + TCP_NLA_CA_STATE, /* ca_state of socket */ + TCP_NLA_SND_SSTHRESH, /* Slow start size threshold */ + TCP_NLA_DELIVERED, /* Data pkts delivered incl. out-of-order */ + TCP_NLA_DELIVERED_CE, /* Like above but only ones w/ CE marks */ + TCP_NLA_BYTES_SENT, /* Data bytes sent including retransmission */ + TCP_NLA_BYTES_RETRANS, /* Data bytes retransmitted */ + TCP_NLA_DSACK_DUPS, /* DSACK blocks received */ + TCP_NLA_REORD_SEEN, /* reordering events seen */ + TCP_NLA_SRTT, /* smoothed RTT in usecs */ +}; + +/* tcp_info from from linux/tcp.h */ +struct tcp_info { + uint8_t tcpi_state; + uint8_t tcpi_ca_state; + uint8_t tcpi_retransmits; + uint8_t tcpi_probes; + uint8_t tcpi_backoff; + uint8_t tcpi_options; + uint8_t tcpi_snd_wscale : 4, tcpi_rcv_wscale : 4; + uint8_t tcpi_delivery_rate_app_limited : 1; + uint32_t tcpi_rto; + uint32_t tcpi_ato; + uint32_t tcpi_snd_mss; + uint32_t tcpi_rcv_mss; + uint32_t tcpi_unacked; + uint32_t tcpi_sacked; + uint32_t tcpi_lost; + uint32_t tcpi_retrans; + uint32_t tcpi_fackets; + /* Times. */ + uint32_t tcpi_last_data_sent; + uint32_t tcpi_last_ack_sent; /* Not remembered, sorry. */ + uint32_t tcpi_last_data_recv; + uint32_t tcpi_last_ack_recv; + /* Metrics. */ + uint32_t tcpi_pmtu; + uint32_t tcpi_rcv_ssthresh; + uint32_t tcpi_rtt; + uint32_t tcpi_rttvar; + uint32_t tcpi_snd_ssthresh; + uint32_t tcpi_snd_cwnd; + uint32_t tcpi_advmss; + uint32_t tcpi_reordering; + uint32_t tcpi_rcv_rtt; + uint32_t tcpi_rcv_space; + uint32_t tcpi_total_retrans; + uint64_t tcpi_pacing_rate; + uint64_t tcpi_max_pacing_rate; + uint64_t tcpi_bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked */ + uint64_t tcpi_bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived */ + + uint32_t tcpi_segs_out; /* RFC4898 tcpEStatsPerfSegsOut */ + uint32_t tcpi_segs_in; /* RFC4898 tcpEStatsPerfSegsIn */ + uint32_t tcpi_notsent_bytes; + uint32_t tcpi_min_rtt; + + uint32_t tcpi_data_segs_in; /* RFC4898 tcpEStatsDataSegsIn */ + uint32_t tcpi_data_segs_out; /* RFC4898 tcpEStatsDataSegsOut */ + + uint64_t tcpi_delivery_rate; + uint64_t tcpi_busy_time; /* Time (usec) busy sending data */ + uint64_t tcpi_rwnd_limited; /* Time (usec) limited by receive window */ + uint64_t tcpi_sndbuf_limited; /* Time (usec) limited by send buffer */ + + uint32_t tcpi_delivered; + uint32_t tcpi_delivered_ce; + uint64_t tcpi_bytes_sent; /* RFC4898 tcpEStatsPerfHCDataOctetsOut */ + uint64_t tcpi_bytes_retrans; /* RFC4898 tcpEStatsPerfOctetsRetrans */ + uint32_t tcpi_dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups */ + uint32_t tcpi_reord_seen; /* reordering events seen */ + socklen_t length; /* Length of struct returned by kernel */ +}; + +#ifndef TCP_INFO +#define TCP_INFO 11 +#endif +#endif /* GRPC_LINUX_ERRQUEUE */ + +/* Returns true if kernel is capable of supporting errqueue and timestamping. + * Currently allowing only linux kernels above 4.0.0 + */ +bool kernel_supports_errqueue(); + +} /* namespace grpc_core */ + +#endif /* GRPC_POSIX_SOCKET_TCP */ + +namespace grpc_core { +/* Initializes errqueue support */ +void grpc_errqueue_init(); +} /* namespace grpc_core */ + +#endif /* GRPC_CORE_LIB_IOMGR_INTERNAL_ERRQUEUE_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc index 29a05ee309..cffb3b9400 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iocp_windows.cc @@ -89,15 +89,15 @@ grpc_iocp_work_status grpc_iocp_work(grpc_millis deadline) { } else { abort(); } - if (socket->shutdown_called) { + if (socket->shutdown_called) { info->bytes_transferred = 0; - info->wsa_error = WSA_OPERATION_ABORTED; - } else { - success = WSAGetOverlappedResult(socket->socket, &info->overlapped, &bytes, - FALSE, &flags); + info->wsa_error = WSA_OPERATION_ABORTED; + } else { + success = WSAGetOverlappedResult(socket->socket, &info->overlapped, &bytes, + FALSE, &flags); info->bytes_transferred = bytes; - info->wsa_error = success ? 0 : WSAGetLastError(); - } + info->wsa_error = success ? 0 : WSAGetLastError(); + } GPR_ASSERT(overlapped == &info->overlapped); grpc_socket_become_ready(socket, info); return GRPC_IOCP_WORK_WORK; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc index 802e3bdcb4..621bd49335 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.cc @@ -33,10 +33,10 @@ #include "src/core/lib/gpr/useful.h" #include "src/core/lib/gprpp/global_config.h" #include "src/core/lib/gprpp/thd.h" -#include "src/core/lib/iomgr/buffer_list.h" +#include "src/core/lib/iomgr/buffer_list.h" #include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/executor.h" -#include "src/core/lib/iomgr/internal_errqueue.h" +#include "src/core/lib/iomgr/internal_errqueue.h" #include "src/core/lib/iomgr/iomgr_internal.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/timer_manager.h" @@ -57,12 +57,12 @@ void grpc_iomgr_init() { g_shutdown = 0; gpr_mu_init(&g_mu); gpr_cv_init(&g_rcv); - grpc_core::Executor::InitAll(); + grpc_core::Executor::InitAll(); g_root_object.next = g_root_object.prev = &g_root_object; g_root_object.name = (char*)"root"; grpc_iomgr_platform_init(); grpc_timer_list_init(); - grpc_core::grpc_errqueue_init(); + grpc_core::grpc_errqueue_init(); g_grpc_abort_on_leaks = GPR_GLOBAL_CONFIG_GET(grpc_abort_on_leaks); } @@ -77,8 +77,8 @@ static size_t count_objects(void) { return n; } -size_t grpc_iomgr_count_objects_for_testing(void) { return count_objects(); } - +size_t grpc_iomgr_count_objects_for_testing(void) { return count_objects(); } + static void dump_objects(const char* kind) { grpc_iomgr_object* obj; for (obj = g_root_object.next; obj != &g_root_object; obj = obj->next) { @@ -94,7 +94,7 @@ void grpc_iomgr_shutdown() { { grpc_timer_manager_shutdown(); grpc_iomgr_platform_flush(); - grpc_core::Executor::ShutdownAll(); + grpc_core::Executor::ShutdownAll(); gpr_mu_lock(&g_mu); g_shutdown = 1; @@ -160,14 +160,14 @@ void grpc_iomgr_shutdown() { gpr_cv_destroy(&g_rcv); } -void grpc_iomgr_shutdown_background_closure() { - grpc_iomgr_platform_shutdown_background_closure(); -} - -bool grpc_iomgr_is_any_background_poller_thread() { - return grpc_iomgr_platform_is_any_background_poller_thread(); -} - +void grpc_iomgr_shutdown_background_closure() { + grpc_iomgr_platform_shutdown_background_closure(); +} + +bool grpc_iomgr_is_any_background_poller_thread() { + return grpc_iomgr_platform_is_any_background_poller_thread(); +} + bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure, grpc_error* error) { return grpc_iomgr_platform_add_closure_to_background_poller(closure, error); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h index e02f15e551..b9ad48d117 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr.h @@ -24,8 +24,8 @@ #include "src/core/lib/iomgr/closure.h" #include "src/core/lib/iomgr/port.h" -#include <stdlib.h> - +#include <stdlib.h> + /** Initializes the iomgr. */ void grpc_iomgr_init(); @@ -36,25 +36,25 @@ void grpc_iomgr_start(); * exec_ctx. */ void grpc_iomgr_shutdown(); -/** Signals the intention to shutdown all the closures registered in the - * background poller. */ -void grpc_iomgr_shutdown_background_closure(); - -/* Returns true if polling engine runs in the background, false otherwise. - * Currently only 'epollbg' runs in the background. - */ -bool grpc_iomgr_run_in_background(); - -/** Returns true if the caller is a worker thread for any background poller. */ -bool grpc_iomgr_is_any_background_poller_thread(); - +/** Signals the intention to shutdown all the closures registered in the + * background poller. */ +void grpc_iomgr_shutdown_background_closure(); + +/* Returns true if polling engine runs in the background, false otherwise. + * Currently only 'epollbg' runs in the background. + */ +bool grpc_iomgr_run_in_background(); + +/** Returns true if the caller is a worker thread for any background poller. */ +bool grpc_iomgr_is_any_background_poller_thread(); + /** Returns true if the closure is registered into the background poller. Note * that the closure may or may not run yet when this function returns, and the * closure should not be blocking or long-running. */ bool grpc_iomgr_add_closure_to_background_poller(grpc_closure* closure, grpc_error* error); -/* Exposed only for testing */ -size_t grpc_iomgr_count_objects_for_testing(); - +/* Exposed only for testing */ +size_t grpc_iomgr_count_objects_for_testing(); + #endif /* GRPC_CORE_LIB_IOMGR_IOMGR_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc index 684044a5bb..663ab63174 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_custom.cc @@ -34,16 +34,16 @@ gpr_thd_id g_init_thread; static void iomgr_platform_init(void) { grpc_core::ExecCtx exec_ctx; - grpc_core::Executor::SetThreadingAll(false); + grpc_core::Executor::SetThreadingAll(false); g_init_thread = gpr_thd_currentid(); grpc_pollset_global_init(); } static void iomgr_platform_flush(void) {} static void iomgr_platform_shutdown(void) { grpc_pollset_global_shutdown(); } -static void iomgr_platform_shutdown_background_closure(void) {} -static bool iomgr_platform_is_any_background_poller_thread(void) { - return false; -} +static void iomgr_platform_shutdown_background_closure(void) {} +static bool iomgr_platform_is_any_background_poller_thread(void) { + return false; +} static bool iomgr_platform_add_closure_to_background_poller( grpc_closure* /*closure*/, grpc_error* /*error*/) { return false; @@ -55,7 +55,7 @@ static grpc_iomgr_platform_vtable vtable = { iomgr_platform_init, iomgr_platform_flush, iomgr_platform_shutdown, - iomgr_platform_shutdown_background_closure, + iomgr_platform_shutdown_background_closure, iomgr_platform_is_any_background_poller_thread, iomgr_platform_add_closure_to_background_poller}; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc index 896d9fce67..17647952bc 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.cc @@ -41,14 +41,14 @@ void grpc_iomgr_platform_init() { iomgr_platform_vtable->init(); } void grpc_iomgr_platform_flush() { iomgr_platform_vtable->flush(); } void grpc_iomgr_platform_shutdown() { iomgr_platform_vtable->shutdown(); } - -void grpc_iomgr_platform_shutdown_background_closure() { - iomgr_platform_vtable->shutdown_background_closure(); -} - -bool grpc_iomgr_platform_is_any_background_poller_thread() { - return iomgr_platform_vtable->is_any_background_poller_thread(); -} + +void grpc_iomgr_platform_shutdown_background_closure() { + iomgr_platform_vtable->shutdown_background_closure(); +} + +bool grpc_iomgr_platform_is_any_background_poller_thread() { + return iomgr_platform_vtable->is_any_background_poller_thread(); +} bool grpc_iomgr_platform_add_closure_to_background_poller(grpc_closure* closure, grpc_error* error) { diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h index 17607f98f1..c0bed172b1 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_internal.h @@ -35,8 +35,8 @@ typedef struct grpc_iomgr_platform_vtable { void (*init)(void); void (*flush)(void); void (*shutdown)(void); - void (*shutdown_background_closure)(void); - bool (*is_any_background_poller_thread)(void); + void (*shutdown_background_closure)(void); + bool (*is_any_background_poller_thread)(void); bool (*add_closure_to_background_poller)(grpc_closure* closure, grpc_error* error); } grpc_iomgr_platform_vtable; @@ -56,12 +56,12 @@ void grpc_iomgr_platform_flush(void); /** tear down all platform specific global iomgr structures */ void grpc_iomgr_platform_shutdown(void); -/** shut down all the closures registered in the background poller */ -void grpc_iomgr_platform_shutdown_background_closure(void); - +/** shut down all the closures registered in the background poller */ +void grpc_iomgr_platform_shutdown_background_closure(void); + /** return true if the caller is a worker thread for any background poller */ -bool grpc_iomgr_platform_is_any_background_poller_thread(void); - +bool grpc_iomgr_platform_is_any_background_poller_thread(void); + /** Return true if the closure is registered into the background poller. Note * that the closure may or may not run yet when this function returns, and the * closure should not be blocking or long-running. */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc index de22d20a63..6361a23fa7 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_IOMGR +#ifdef GRPC_POSIX_SOCKET_IOMGR #include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/ev_posix.h" @@ -51,14 +51,14 @@ static void iomgr_platform_shutdown(void) { grpc_wakeup_fd_global_destroy(); } -static void iomgr_platform_shutdown_background_closure(void) { - grpc_shutdown_background_closure(); -} - -static bool iomgr_platform_is_any_background_poller_thread(void) { - return grpc_is_any_background_poller_thread(); -} - +static void iomgr_platform_shutdown_background_closure(void) { + grpc_shutdown_background_closure(); +} + +static bool iomgr_platform_is_any_background_poller_thread(void) { + return grpc_is_any_background_poller_thread(); +} + static bool iomgr_platform_add_closure_to_background_poller( grpc_closure* closure, grpc_error* error) { return grpc_add_closure_to_background_poller(closure, error); @@ -68,7 +68,7 @@ static grpc_iomgr_platform_vtable vtable = { iomgr_platform_init, iomgr_platform_flush, iomgr_platform_shutdown, - iomgr_platform_shutdown_background_closure, + iomgr_platform_shutdown_background_closure, iomgr_platform_is_any_background_poller_thread, iomgr_platform_add_closure_to_background_poller}; @@ -82,8 +82,8 @@ void grpc_set_default_iomgr_platform() { grpc_set_iomgr_platform_vtable(&vtable); } -bool grpc_iomgr_run_in_background() { - return grpc_event_engine_run_in_background(); -} - -#endif /* GRPC_POSIX_SOCKET_IOMGR */ +bool grpc_iomgr_run_in_background() { + return grpc_event_engine_run_in_background(); +} + +#endif /* GRPC_POSIX_SOCKET_IOMGR */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc index 30c44edb5d..a3799bcb92 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_posix_cfstream.cc @@ -1,21 +1,21 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + /// CFStream is build-enabled on iOS by default and disabled by default on other /// platforms (see port_platform.h). To enable CFStream build on another /// platform, the users need to define macro "GRPC_CFSTREAM=1" when building @@ -30,34 +30,34 @@ /// dispatch queues. The caveat of this pollset is that users may not be able to /// run a gRPC server in the same process. -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#ifdef GRPC_CFSTREAM_IOMGR - -#include "src/core/lib/debug/trace.h" +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_CFSTREAM_IOMGR + +#include "src/core/lib/debug/trace.h" #include "src/core/lib/iomgr/ev_apple.h" -#include "src/core/lib/iomgr/ev_posix.h" -#include "src/core/lib/iomgr/iomgr_internal.h" -#include "src/core/lib/iomgr/iomgr_posix.h" -#include "src/core/lib/iomgr/resolve_address.h" -#include "src/core/lib/iomgr/tcp_client.h" -#include "src/core/lib/iomgr/tcp_posix.h" -#include "src/core/lib/iomgr/tcp_server.h" -#include "src/core/lib/iomgr/timer.h" - -static const char* grpc_cfstream_env_var = "grpc_cfstream"; +#include "src/core/lib/iomgr/ev_posix.h" +#include "src/core/lib/iomgr/iomgr_internal.h" +#include "src/core/lib/iomgr/iomgr_posix.h" +#include "src/core/lib/iomgr/resolve_address.h" +#include "src/core/lib/iomgr/tcp_client.h" +#include "src/core/lib/iomgr/tcp_posix.h" +#include "src/core/lib/iomgr/tcp_server.h" +#include "src/core/lib/iomgr/timer.h" + +static const char* grpc_cfstream_env_var = "grpc_cfstream"; static const char* grpc_cfstream_run_loop_env_var = "GRPC_CFSTREAM_RUN_LOOP"; - -extern grpc_tcp_server_vtable grpc_posix_tcp_server_vtable; -extern grpc_tcp_client_vtable grpc_posix_tcp_client_vtable; -extern grpc_tcp_client_vtable grpc_cfstream_client_vtable; -extern grpc_timer_vtable grpc_generic_timer_vtable; -extern grpc_pollset_vtable grpc_posix_pollset_vtable; -extern grpc_pollset_set_vtable grpc_posix_pollset_set_vtable; -extern grpc_address_resolver_vtable grpc_posix_resolver_vtable; - + +extern grpc_tcp_server_vtable grpc_posix_tcp_server_vtable; +extern grpc_tcp_client_vtable grpc_posix_tcp_client_vtable; +extern grpc_tcp_client_vtable grpc_cfstream_client_vtable; +extern grpc_timer_vtable grpc_generic_timer_vtable; +extern grpc_pollset_vtable grpc_posix_pollset_vtable; +extern grpc_pollset_set_vtable grpc_posix_pollset_set_vtable; +extern grpc_address_resolver_vtable grpc_posix_resolver_vtable; + static void apple_iomgr_platform_init(void) { grpc_pollset_global_init(); } static void apple_iomgr_platform_flush(void) {} @@ -85,40 +85,40 @@ static grpc_iomgr_platform_vtable apple_vtable = { apple_iomgr_platform_is_any_background_poller_thread, apple_iomgr_platform_add_closure_to_background_poller}; -static void iomgr_platform_init(void) { - grpc_wakeup_fd_global_init(); - grpc_event_engine_init(); -} - -static void iomgr_platform_flush(void) {} - -static void iomgr_platform_shutdown(void) { - grpc_event_engine_shutdown(); - grpc_wakeup_fd_global_destroy(); -} - -static void iomgr_platform_shutdown_background_closure(void) { - grpc_shutdown_background_closure(); -} - -static bool iomgr_platform_is_any_background_poller_thread(void) { - return grpc_is_any_background_poller_thread(); -} - +static void iomgr_platform_init(void) { + grpc_wakeup_fd_global_init(); + grpc_event_engine_init(); +} + +static void iomgr_platform_flush(void) {} + +static void iomgr_platform_shutdown(void) { + grpc_event_engine_shutdown(); + grpc_wakeup_fd_global_destroy(); +} + +static void iomgr_platform_shutdown_background_closure(void) { + grpc_shutdown_background_closure(); +} + +static bool iomgr_platform_is_any_background_poller_thread(void) { + return grpc_is_any_background_poller_thread(); +} + static bool iomgr_platform_add_closure_to_background_poller( grpc_closure* closure, grpc_error* error) { return grpc_add_closure_to_background_poller(closure, error); } -static grpc_iomgr_platform_vtable vtable = { +static grpc_iomgr_platform_vtable vtable = { iomgr_platform_init, iomgr_platform_flush, iomgr_platform_shutdown, - iomgr_platform_shutdown_background_closure, + iomgr_platform_shutdown_background_closure, iomgr_platform_is_any_background_poller_thread, iomgr_platform_add_closure_to_background_poller}; - -void grpc_set_default_iomgr_platform() { + +void grpc_set_default_iomgr_platform() { char* enable_cfstream_str = getenv(grpc_cfstream_env_var); bool enable_cfstream = enable_cfstream_str == nullptr || enable_cfstream_str[0] != '0'; @@ -148,10 +148,10 @@ void grpc_set_default_iomgr_platform() { grpc_set_pollset_set_vtable(&grpc_apple_pollset_set_vtable); grpc_set_iomgr_platform_vtable(&apple_vtable); } - grpc_set_timer_impl(&grpc_generic_timer_vtable); - grpc_set_resolver_impl(&grpc_posix_resolver_vtable); -} - + grpc_set_timer_impl(&grpc_generic_timer_vtable); + grpc_set_resolver_impl(&grpc_posix_resolver_vtable); +} + bool grpc_iomgr_run_in_background() { char* enable_cfstream_str = getenv(grpc_cfstream_env_var); bool enable_cfstream = @@ -168,4 +168,4 @@ bool grpc_iomgr_run_in_background() { } } -#endif /* GRPC_CFSTREAM_IOMGR */ +#endif /* GRPC_CFSTREAM_IOMGR */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc index 728d404081..03d10eb07f 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/iomgr_windows.cc @@ -72,12 +72,12 @@ static void iomgr_platform_shutdown(void) { winsock_shutdown(); } -static void iomgr_platform_shutdown_background_closure(void) {} - -static bool iomgr_platform_is_any_background_poller_thread(void) { - return false; -} - +static void iomgr_platform_shutdown_background_closure(void) {} + +static bool iomgr_platform_is_any_background_poller_thread(void) { + return false; +} + static bool iomgr_platform_add_closure_to_background_poller( grpc_closure* closure, grpc_error* error) { return false; @@ -87,7 +87,7 @@ static grpc_iomgr_platform_vtable vtable = { iomgr_platform_init, iomgr_platform_flush, iomgr_platform_shutdown, - iomgr_platform_shutdown_background_closure, + iomgr_platform_shutdown_background_closure, iomgr_platform_is_any_background_poller_thread, iomgr_platform_add_closure_to_background_poller}; @@ -101,6 +101,6 @@ void grpc_set_default_iomgr_platform() { grpc_set_iomgr_platform_vtable(&vtable); } -bool grpc_iomgr_run_in_background() { return false; } - +bool grpc_iomgr_run_in_background() { return false; } + #endif /* GRPC_WINSOCK_SOCKET */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc b/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc index abc901efbe..5c5ac9d9cb 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/is_epollexclusive_available.cc @@ -27,7 +27,7 @@ #include <grpc/support/log.h> #include <errno.h> -#include <sys/epoll.h> +#include <sys/epoll.h> #include <sys/eventfd.h> #include <unistd.h> diff --git a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc index 4b28af4ba4..bb0031b979 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/lockfree_event.cc @@ -90,11 +90,11 @@ void LockfreeEvent::DestroyEvent() { void LockfreeEvent::NotifyOn(grpc_closure* closure) { while (true) { - /* This load needs to be an acquire load because this can be a shutdown - * error that we might need to reference. Adding acquire semantics makes - * sure that the shutdown error has been initialized properly before us - * referencing it. */ - gpr_atm curr = gpr_atm_acq_load(&state_); + /* This load needs to be an acquire load because this can be a shutdown + * error that we might need to reference. Adding acquire semantics makes + * sure that the shutdown error has been initialized properly before us + * referencing it. */ + gpr_atm curr = gpr_atm_acq_load(&state_); if (GRPC_TRACE_FLAG_ENABLED(grpc_polling_trace)) { gpr_log(GPR_DEBUG, "LockfreeEvent::NotifyOn: %p curr=%p closure=%p", this, (void*)curr, closure); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc index dea07cae53..3ba40dec23 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.cc @@ -61,11 +61,11 @@ bool grpc_polling_entity_is_empty(const grpc_polling_entity* pollent) { void grpc_polling_entity_add_to_pollset_set(grpc_polling_entity* pollent, grpc_pollset_set* pss_dst) { if (pollent->tag == GRPC_POLLS_POLLSET) { - // CFStream does not use file destriptors. When CFStream is used, the fd - // pollset is possible to be null. - if (pollent->pollent.pollset != nullptr) { - grpc_pollset_set_add_pollset(pss_dst, pollent->pollent.pollset); - } + // CFStream does not use file destriptors. When CFStream is used, the fd + // pollset is possible to be null. + if (pollent->pollent.pollset != nullptr) { + grpc_pollset_set_add_pollset(pss_dst, pollent->pollent.pollset); + } } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) { GPR_ASSERT(pollent->pollent.pollset_set != nullptr); grpc_pollset_set_add_pollset_set(pss_dst, pollent->pollent.pollset_set); @@ -78,14 +78,14 @@ void grpc_polling_entity_add_to_pollset_set(grpc_polling_entity* pollent, void grpc_polling_entity_del_from_pollset_set(grpc_polling_entity* pollent, grpc_pollset_set* pss_dst) { if (pollent->tag == GRPC_POLLS_POLLSET) { -#ifdef GRPC_CFSTREAM - if (pollent->pollent.pollset != nullptr) { - grpc_pollset_set_del_pollset(pss_dst, pollent->pollent.pollset); - } -#else +#ifdef GRPC_CFSTREAM + if (pollent->pollent.pollset != nullptr) { + grpc_pollset_set_del_pollset(pss_dst, pollent->pollent.pollset); + } +#else GPR_ASSERT(pollent->pollent.pollset != nullptr); grpc_pollset_set_del_pollset(pss_dst, pollent->pollent.pollset); -#endif +#endif } else if (pollent->tag == GRPC_POLLS_POLLSET_SET) { GPR_ASSERT(pollent->pollent.pollset_set != nullptr); grpc_pollset_set_del_pollset_set(pss_dst, pollent->pollent.pollset_set); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h index 6f4c5bdd66..9178457a23 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/polling_entity.h @@ -34,13 +34,13 @@ typedef enum grpc_pollset_tag { * functions that accept a pollset XOR a pollset_set to do so through an * abstract interface. No ownership is taken. */ -struct grpc_polling_entity { +struct grpc_polling_entity { union { - grpc_pollset* pollset = nullptr; + grpc_pollset* pollset = nullptr; grpc_pollset_set* pollset_set; } pollent; - grpc_pollset_tag tag = GRPC_POLLS_NONE; -}; + grpc_pollset_tag tag = GRPC_POLLS_NONE; +}; grpc_polling_entity grpc_polling_entity_create_from_pollset_set( grpc_pollset_set* pollset_set); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc index 98c8e64e2f..bca09f2029 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/pollset_custom.cc @@ -69,7 +69,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset, GRPC_CUSTOM_IOMGR_ASSERT_SAME_THREAD(); gpr_mu_unlock(&pollset->mu); grpc_millis now = grpc_core::ExecCtx::Get()->Now(); - grpc_millis timeout = 0; + grpc_millis timeout = 0; if (deadline > now) { timeout = deadline - now; } @@ -77,7 +77,7 @@ static grpc_error* pollset_work(grpc_pollset* pollset, // control back to the application grpc_core::ExecCtx* curr = grpc_core::ExecCtx::Get(); grpc_core::ExecCtx::Set(nullptr); - poller_vtable->poll(static_cast<size_t>(timeout)); + poller_vtable->poll(static_cast<size_t>(timeout)); grpc_core::ExecCtx::Set(curr); grpc_core::ExecCtx::Get()->InvalidateNow(); if (grpc_core::ExecCtx::Get()->HasWork()) { diff --git a/contrib/libs/grpc/src/core/lib/iomgr/port.h b/contrib/libs/grpc/src/core/lib/iomgr/port.h index 2a8d67b261..f5454710b8 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/port.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/port.h @@ -56,11 +56,11 @@ /* Linux has TCP_INQ support since 4.18, but it is safe to set the socket option on older kernels. */ #define GRPC_HAVE_TCP_INQ 1 -#ifdef LINUX_VERSION_CODE -#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) -#define GRPC_LINUX_ERRQUEUE 1 -#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) */ -#endif /* LINUX_VERSION_CODE */ +#ifdef LINUX_VERSION_CODE +#if LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) +#define GRPC_LINUX_ERRQUEUE 1 +#endif /* LINUX_VERSION_CODE >= KERNEL_VERSION(4, 0, 0) */ +#endif /* LINUX_VERSION_CODE */ #define GRPC_LINUX_MULTIPOLL_WITH_EPOLL 1 #define GRPC_POSIX_FORK 1 #define GRPC_POSIX_HOST_NAME_MAX 1 @@ -105,29 +105,29 @@ #define GRPC_MSG_IOVLEN_TYPE int #define GRPC_POSIX_FORK 1 #define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 -#ifdef GRPC_CFSTREAM -#define GRPC_CFSTREAM_IOMGR 1 -#define GRPC_CFSTREAM_CLIENT 1 -#define GRPC_CFSTREAM_ENDPOINT 1 +#ifdef GRPC_CFSTREAM +#define GRPC_CFSTREAM_IOMGR 1 +#define GRPC_CFSTREAM_CLIENT 1 +#define GRPC_CFSTREAM_ENDPOINT 1 #define GRPC_APPLE_EV 1 -#define GRPC_POSIX_SOCKET_ARES_EV_DRIVER 1 -#define GRPC_POSIX_SOCKET_EV 1 -#define GRPC_POSIX_SOCKET_EV_EPOLL1 1 -#define GRPC_POSIX_SOCKET_EV_EPOLLEX 1 -#define GRPC_POSIX_SOCKET_EV_POLL 1 +#define GRPC_POSIX_SOCKET_ARES_EV_DRIVER 1 +#define GRPC_POSIX_SOCKET_EV 1 +#define GRPC_POSIX_SOCKET_EV_EPOLL1 1 +#define GRPC_POSIX_SOCKET_EV_EPOLLEX 1 +#define GRPC_POSIX_SOCKET_EV_POLL 1 #define GRPC_POSIX_SOCKET_IF_NAMETOINDEX 1 -#define GRPC_POSIX_SOCKET_RESOLVE_ADDRESS 1 -#define GRPC_POSIX_SOCKET_SOCKADDR 1 -#define GRPC_POSIX_SOCKET_SOCKET_FACTORY 1 -#define GRPC_POSIX_SOCKET_TCP 1 -#define GRPC_POSIX_SOCKET_TCP_CLIENT 1 -#define GRPC_POSIX_SOCKET_TCP_SERVER 1 -#define GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON 1 +#define GRPC_POSIX_SOCKET_RESOLVE_ADDRESS 1 +#define GRPC_POSIX_SOCKET_SOCKADDR 1 +#define GRPC_POSIX_SOCKET_SOCKET_FACTORY 1 +#define GRPC_POSIX_SOCKET_TCP 1 +#define GRPC_POSIX_SOCKET_TCP_CLIENT 1 +#define GRPC_POSIX_SOCKET_TCP_SERVER 1 +#define GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON 1 #define GRPC_POSIX_SOCKET_UDP_SERVER 1 -#define GRPC_POSIX_SOCKET_UTILS_COMMON 1 -#else +#define GRPC_POSIX_SOCKET_UTILS_COMMON 1 +#else #define GRPC_POSIX_SOCKET 1 -#endif +#endif #define GRPC_POSIX_SOCKETUTILS 1 #define GRPC_POSIX_SYSCONF 1 #define GRPC_POSIX_WAKEUP_FD 1 @@ -150,18 +150,18 @@ #define GRPC_POSIX_SOCKET 1 #define GRPC_POSIX_SOCKETUTILS 1 #define GRPC_POSIX_WAKEUP_FD 1 -#elif defined(GPR_SOLARIS) -#define GRPC_HAVE_UNIX_SOCKET 1 -#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 -#define GRPC_POSIX_SOCKET 1 -#define GRPC_POSIX_SOCKETUTILS 1 -#define GRPC_POSIX_WAKEUP_FD 1 -#elif defined(GPR_AIX) -#define GRPC_HAVE_UNIX_SOCKET 1 -#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 -#define GRPC_POSIX_SOCKET 1 -#define GRPC_POSIX_SOCKETUTILS 1 -#define GRPC_POSIX_WAKEUP_FD 1 +#elif defined(GPR_SOLARIS) +#define GRPC_HAVE_UNIX_SOCKET 1 +#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 +#define GRPC_POSIX_SOCKET 1 +#define GRPC_POSIX_SOCKETUTILS 1 +#define GRPC_POSIX_WAKEUP_FD 1 +#elif defined(GPR_AIX) +#define GRPC_HAVE_UNIX_SOCKET 1 +#define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 +#define GRPC_POSIX_SOCKET 1 +#define GRPC_POSIX_SOCKETUTILS 1 +#define GRPC_POSIX_WAKEUP_FD 1 #elif defined(GPR_NACL) #define GRPC_HAVE_ARPA_NAMESER 1 #define GRPC_POSIX_NO_SPECIAL_WAKEUP_FD 1 @@ -189,31 +189,31 @@ #endif #if defined(GRPC_POSIX_SOCKET) + defined(GRPC_WINSOCK_SOCKET) + \ - defined(GRPC_CUSTOM_SOCKET) + defined(GRPC_CFSTREAM) != \ + defined(GRPC_CUSTOM_SOCKET) + defined(GRPC_CFSTREAM) != \ 1 #error \ "Must define exactly one of GRPC_POSIX_SOCKET, GRPC_WINSOCK_SOCKET, GRPC_CUSTOM_SOCKET" #endif -#ifdef GRPC_POSIX_SOCKET -#define GRPC_POSIX_SOCKET_ARES_EV_DRIVER 1 -#define GRPC_POSIX_SOCKET_EV 1 -#define GRPC_POSIX_SOCKET_EV_EPOLLEX 1 -#define GRPC_POSIX_SOCKET_EV_POLL 1 -#define GRPC_POSIX_SOCKET_EV_EPOLL1 1 -#define GRPC_POSIX_SOCKET_IF_NAMETOINDEX 1 -#define GRPC_POSIX_SOCKET_IOMGR 1 -#define GRPC_POSIX_SOCKET_RESOLVE_ADDRESS 1 -#define GRPC_POSIX_SOCKET_SOCKADDR 1 -#define GRPC_POSIX_SOCKET_SOCKET_FACTORY 1 -#define GRPC_POSIX_SOCKET_TCP 1 -#define GRPC_POSIX_SOCKET_TCP_CLIENT 1 -#define GRPC_POSIX_SOCKET_TCP_SERVER 1 -#define GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON 1 +#ifdef GRPC_POSIX_SOCKET +#define GRPC_POSIX_SOCKET_ARES_EV_DRIVER 1 +#define GRPC_POSIX_SOCKET_EV 1 +#define GRPC_POSIX_SOCKET_EV_EPOLLEX 1 +#define GRPC_POSIX_SOCKET_EV_POLL 1 +#define GRPC_POSIX_SOCKET_EV_EPOLL1 1 +#define GRPC_POSIX_SOCKET_IF_NAMETOINDEX 1 +#define GRPC_POSIX_SOCKET_IOMGR 1 +#define GRPC_POSIX_SOCKET_RESOLVE_ADDRESS 1 +#define GRPC_POSIX_SOCKET_SOCKADDR 1 +#define GRPC_POSIX_SOCKET_SOCKET_FACTORY 1 +#define GRPC_POSIX_SOCKET_TCP 1 +#define GRPC_POSIX_SOCKET_TCP_CLIENT 1 +#define GRPC_POSIX_SOCKET_TCP_SERVER 1 +#define GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON 1 #define GRPC_POSIX_SOCKET_UDP_SERVER 1 -#define GRPC_POSIX_SOCKET_UTILS_COMMON 1 -#endif - +#define GRPC_POSIX_SOCKET_UTILS_COMMON 1 +#endif + #if defined(GRPC_POSIX_HOST_NAME_MAX) && defined(GRPC_POSIX_SYSCONF) #error "Cannot define both GRPC_POSIX_HOST_NAME_MAX and GRPC_POSIX_SYSCONF" #endif diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h index 57126c7c93..05a66ec1c5 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address.h @@ -33,7 +33,7 @@ #include <ws2tcpip.h> #endif -#if defined(GRPC_POSIX_SOCKET) || defined(GRPC_CFSTREAM) +#if defined(GRPC_POSIX_SOCKET) || defined(GRPC_CFSTREAM) #include <sys/socket.h> #endif @@ -63,7 +63,7 @@ void grpc_set_resolver_impl(grpc_address_resolver_vtable* vtable); /* Asynchronously resolve addr. Use default_port if a port isn't designated in addr, otherwise use the port in addr. */ -/* TODO(apolcyn): add a timeout here */ +/* TODO(apolcyn): add a timeout here */ void grpc_resolve_address(const char* addr, const char* default_port, grpc_pollset_set* interested_parties, grpc_closure* on_done, diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc index 4f29087391..1cdcffce59 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/resolve_address_posix.cc @@ -19,7 +19,7 @@ #include <grpc/support/port_platform.h> #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS +#ifdef GRPC_POSIX_SOCKET_RESOLVE_ADDRESS #include "src/core/lib/iomgr/sockaddr.h" @@ -105,7 +105,7 @@ static grpc_error* posix_blocking_resolve_address( grpc_error_set_str( grpc_error_set_str( grpc_error_set_int( - GRPC_ERROR_CREATE_FROM_STATIC_STRING(gai_strerror(s)), + GRPC_ERROR_CREATE_FROM_STATIC_STRING(gai_strerror(s)), GRPC_ERROR_INT_ERRNO, s), GRPC_ERROR_STR_OS_ERROR, grpc_slice_from_static_string(gai_strerror(s))), @@ -147,7 +147,7 @@ struct request { grpc_closure request_closure; void* arg; }; -/* Callback to be passed to grpc Executor to asynch-ify +/* Callback to be passed to grpc Executor to asynch-ify * grpc_blocking_resolve_address */ static void do_request_thread(void* rp, grpc_error* /*error*/) { request* r = static_cast<request*>(rp); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc index f416e096f4..0406b21e24 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.cc @@ -93,16 +93,16 @@ struct grpc_resource_user { grpc_closure_list on_allocated; /* True if we are currently trying to allocate from the quota, false if not */ bool allocating; - /* The amount of memory (in bytes) that has been requested from this user - * asynchronously but hasn't been granted yet. */ + /* The amount of memory (in bytes) that has been requested from this user + * asynchronously but hasn't been granted yet. */ int64_t outstanding_allocations; /* True if we are currently trying to add ourselves to the non-free quota list, false otherwise */ bool added_to_free_pool; - /* The number of threads currently allocated to this resource user */ - gpr_atm num_threads_allocated; - + /* The number of threads currently allocated to this resource user */ + gpr_atm num_threads_allocated; + /* Reclaimers: index 0 is the benign reclaimer, 1 is the destructive reclaimer */ grpc_closure* reclaimers[2]; @@ -139,39 +139,39 @@ struct grpc_resource_quota { int64_t size; /* Amount of free memory in the resource quota */ int64_t free_pool; - /* Used size of memory in the resource quota. Updated as soon as the resource - * users start to allocate or free the memory. */ - gpr_atm used; + /* Used size of memory in the resource quota. Updated as soon as the resource + * users start to allocate or free the memory. */ + gpr_atm used; gpr_atm last_size; - /* Mutex to protect max_threads and num_threads_allocated */ - /* Note: We could have used gpr_atm for max_threads and num_threads_allocated - * and avoid having this mutex; but in that case, each invocation of the - * function grpc_resource_user_allocate_threads() would have had to do at - * least two atomic loads (for max_threads and num_threads_allocated) followed - * by a CAS (on num_threads_allocated). - * Moreover, we expect grpc_resource_user_allocate_threads() to be often - * called concurrently thereby increasing the chances of failing the CAS - * operation. This additional complexity is not worth the tiny perf gain we - * may (or may not) have by using atomics */ - gpr_mu thread_count_mu; - - /* Max number of threads allowed */ - int max_threads; - - /* Number of threads currently allocated via this resource_quota object */ - int num_threads_allocated; - + /* Mutex to protect max_threads and num_threads_allocated */ + /* Note: We could have used gpr_atm for max_threads and num_threads_allocated + * and avoid having this mutex; but in that case, each invocation of the + * function grpc_resource_user_allocate_threads() would have had to do at + * least two atomic loads (for max_threads and num_threads_allocated) followed + * by a CAS (on num_threads_allocated). + * Moreover, we expect grpc_resource_user_allocate_threads() to be often + * called concurrently thereby increasing the chances of failing the CAS + * operation. This additional complexity is not worth the tiny perf gain we + * may (or may not) have by using atomics */ + gpr_mu thread_count_mu; + + /* Max number of threads allowed */ + int max_threads; + + /* Number of threads currently allocated via this resource_quota object */ + int num_threads_allocated; + /* 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; @@ -381,7 +381,7 @@ static bool rq_reclaim_from_per_user_free_pool( while ((resource_user = rulist_pop_head(resource_quota, GRPC_RULIST_NON_EMPTY_FREE_POOL))) { gpr_mu_lock(&resource_user->mu); - resource_user->added_to_free_pool = false; + resource_user->added_to_free_pool = false; if (resource_user->free_pool > 0) { int64_t amt = resource_user->free_pool; resource_user->free_pool = 0; @@ -398,12 +398,12 @@ static bool rq_reclaim_from_per_user_free_pool( return true; } else { if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) { - gpr_log(GPR_INFO, - "RQ %s %s: failed to reclaim_from_per_user_free_pool; " - "free_pool = %" PRId64 "; rq_free_pool = %" PRId64, + gpr_log(GPR_INFO, + "RQ %s %s: failed to reclaim_from_per_user_free_pool; " + "free_pool = %" PRId64 "; rq_free_pool = %" PRId64, resource_quota->name.c_str(), resource_user->name.c_str(), - resource_user->free_pool, resource_quota->free_pool); - } + resource_user->free_pool, resource_quota->free_pool); + } gpr_mu_unlock(&resource_user->mu); } } @@ -571,11 +571,11 @@ static void ru_shutdown(void* ru, grpc_error* /*error*/) { static void ru_destroy(void* ru, grpc_error* /*error*/) { grpc_resource_user* resource_user = static_cast<grpc_resource_user*>(ru); GPR_ASSERT(gpr_atm_no_barrier_load(&resource_user->refs) == 0); - // Free all the remaining thread quota - grpc_resource_user_free_threads(resource_user, - static_cast<int>(gpr_atm_no_barrier_load( - &resource_user->num_threads_allocated))); - + // Free all the remaining thread quota + grpc_resource_user_free_threads(resource_user, + static_cast<int>(gpr_atm_no_barrier_load( + &resource_user->num_threads_allocated))); + for (int i = 0; i < GRPC_RULIST_COUNT; i++) { rulist_remove(resource_user, static_cast<grpc_rulist>(i)); } @@ -648,11 +648,11 @@ grpc_resource_quota* grpc_resource_quota_create(const char* name) { resource_quota->combiner = grpc_combiner_create(); resource_quota->free_pool = INT64_MAX; resource_quota->size = INT64_MAX; - resource_quota->used = 0; + resource_quota->used = 0; gpr_atm_no_barrier_store(&resource_quota->last_size, GPR_ATM_MAX); - gpr_mu_init(&resource_quota->thread_count_mu); - resource_quota->max_threads = INT_MAX; - resource_quota->num_threads_allocated = 0; + gpr_mu_init(&resource_quota->thread_count_mu); + resource_quota->max_threads = INT_MAX; + resource_quota->num_threads_allocated = 0; resource_quota->step_scheduled = false; resource_quota->reclaiming = false; gpr_atm_no_barrier_store(&resource_quota->memory_usage_estimation, 0); @@ -674,10 +674,10 @@ grpc_resource_quota* grpc_resource_quota_create(const char* name) { void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota) { if (gpr_unref(&resource_quota->refs)) { - // No outstanding thread quota - GPR_ASSERT(resource_quota->num_threads_allocated == 0); + // No outstanding thread quota + GPR_ASSERT(resource_quota->num_threads_allocated == 0); GRPC_COMBINER_UNREF(resource_quota->combiner, "resource_quota"); - gpr_mu_destroy(&resource_quota->thread_count_mu); + gpr_mu_destroy(&resource_quota->thread_count_mu); delete resource_quota; } } @@ -707,15 +707,15 @@ double grpc_resource_quota_get_memory_pressure( } /* Public API */ -void grpc_resource_quota_set_max_threads(grpc_resource_quota* resource_quota, - int new_max_threads) { - GPR_ASSERT(new_max_threads >= 0); - gpr_mu_lock(&resource_quota->thread_count_mu); - resource_quota->max_threads = new_max_threads; - gpr_mu_unlock(&resource_quota->thread_count_mu); -} - -/* Public API */ +void grpc_resource_quota_set_max_threads(grpc_resource_quota* resource_quota, + int new_max_threads) { + GPR_ASSERT(new_max_threads >= 0); + gpr_mu_lock(&resource_quota->thread_count_mu); + resource_quota->max_threads = new_max_threads; + gpr_mu_unlock(&resource_quota->thread_count_mu); +} + +/* Public API */ void grpc_resource_quota_resize(grpc_resource_quota* resource_quota, size_t size) { grpc_core::ExecCtx exec_ctx; @@ -738,7 +738,7 @@ size_t grpc_resource_quota_peek_size(grpc_resource_quota* resource_quota) { */ grpc_resource_quota* grpc_resource_quota_from_channel_args( - const grpc_channel_args* channel_args, bool create) { + const grpc_channel_args* channel_args, bool create) { 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) { @@ -750,7 +750,7 @@ grpc_resource_quota* grpc_resource_quota_from_channel_args( } } } - return create ? grpc_resource_quota_create(nullptr) : nullptr; + return create ? grpc_resource_quota_create(nullptr) : nullptr; } static void* rq_copy(void* rq) { @@ -795,7 +795,7 @@ grpc_resource_user* grpc_resource_user_create( grpc_closure_list_init(&resource_user->on_allocated); resource_user->allocating = false; resource_user->added_to_free_pool = false; - gpr_atm_no_barrier_store(&resource_user->num_threads_allocated, 0); + gpr_atm_no_barrier_store(&resource_user->num_threads_allocated, 0); resource_user->reclaimers[0] = nullptr; resource_user->reclaimers[1] = nullptr; resource_user->new_reclaimers[0] = nullptr; @@ -849,43 +849,43 @@ void grpc_resource_user_shutdown(grpc_resource_user* resource_user) { } } -bool grpc_resource_user_allocate_threads(grpc_resource_user* resource_user, - int thread_count) { - GPR_ASSERT(thread_count >= 0); - bool is_success = false; - gpr_mu_lock(&resource_user->resource_quota->thread_count_mu); - grpc_resource_quota* rq = resource_user->resource_quota; - if (rq->num_threads_allocated + thread_count <= rq->max_threads) { - rq->num_threads_allocated += thread_count; - gpr_atm_no_barrier_fetch_add(&resource_user->num_threads_allocated, - thread_count); - is_success = true; - } - gpr_mu_unlock(&resource_user->resource_quota->thread_count_mu); - return is_success; -} - -void grpc_resource_user_free_threads(grpc_resource_user* resource_user, - int thread_count) { - GPR_ASSERT(thread_count >= 0); - gpr_mu_lock(&resource_user->resource_quota->thread_count_mu); - grpc_resource_quota* rq = resource_user->resource_quota; - rq->num_threads_allocated -= thread_count; - int old_count = static_cast<int>(gpr_atm_no_barrier_fetch_add( - &resource_user->num_threads_allocated, -thread_count)); - if (old_count < thread_count || rq->num_threads_allocated < 0) { - gpr_log(GPR_ERROR, - "Releasing more threads (%d) than currently allocated (rq threads: " - "%d, ru threads: %d)", - thread_count, rq->num_threads_allocated + thread_count, old_count); - abort(); - } - gpr_mu_unlock(&resource_user->resource_quota->thread_count_mu); -} - +bool grpc_resource_user_allocate_threads(grpc_resource_user* resource_user, + int thread_count) { + GPR_ASSERT(thread_count >= 0); + bool is_success = false; + gpr_mu_lock(&resource_user->resource_quota->thread_count_mu); + grpc_resource_quota* rq = resource_user->resource_quota; + if (rq->num_threads_allocated + thread_count <= rq->max_threads) { + rq->num_threads_allocated += thread_count; + gpr_atm_no_barrier_fetch_add(&resource_user->num_threads_allocated, + thread_count); + is_success = true; + } + gpr_mu_unlock(&resource_user->resource_quota->thread_count_mu); + return is_success; +} + +void grpc_resource_user_free_threads(grpc_resource_user* resource_user, + int thread_count) { + GPR_ASSERT(thread_count >= 0); + gpr_mu_lock(&resource_user->resource_quota->thread_count_mu); + grpc_resource_quota* rq = resource_user->resource_quota; + rq->num_threads_allocated -= thread_count; + int old_count = static_cast<int>(gpr_atm_no_barrier_fetch_add( + &resource_user->num_threads_allocated, -thread_count)); + if (old_count < thread_count || rq->num_threads_allocated < 0) { + gpr_log(GPR_ERROR, + "Releasing more threads (%d) than currently allocated (rq threads: " + "%d, ru threads: %d)", + thread_count, rq->num_threads_allocated + thread_count, old_count); + abort(); + } + gpr_mu_unlock(&resource_user->resource_quota->thread_count_mu); +} + static bool resource_user_alloc_locked(grpc_resource_user* resource_user, - size_t size, - grpc_closure* optional_on_done) { + size_t size, + grpc_closure* optional_on_done) { ru_ref_by(resource_user, static_cast<gpr_atm>(size)); resource_user->free_pool -= static_cast<int64_t>(size); if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) { @@ -906,47 +906,47 @@ static bool resource_user_alloc_locked(grpc_resource_user* resource_user, &resource_user->allocate_closure, GRPC_ERROR_NONE); } return false; -} - -bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user, - size_t size) { - if (gpr_atm_no_barrier_load(&resource_user->shutdown)) return false; - gpr_mu_lock(&resource_user->mu); - grpc_resource_quota* resource_quota = resource_user->resource_quota; - bool cas_success; - do { - gpr_atm used = gpr_atm_no_barrier_load(&resource_quota->used); - gpr_atm new_used = used + size; - if (static_cast<size_t>(new_used) > - grpc_resource_quota_peek_size(resource_quota)) { - gpr_mu_unlock(&resource_user->mu); - return false; - } - cas_success = gpr_atm_full_cas(&resource_quota->used, used, new_used); - } while (!cas_success); - resource_user_alloc_locked(resource_user, size, nullptr); +} + +bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user, + size_t size) { + if (gpr_atm_no_barrier_load(&resource_user->shutdown)) return false; + gpr_mu_lock(&resource_user->mu); + grpc_resource_quota* resource_quota = resource_user->resource_quota; + bool cas_success; + do { + gpr_atm used = gpr_atm_no_barrier_load(&resource_quota->used); + gpr_atm new_used = used + size; + if (static_cast<size_t>(new_used) > + grpc_resource_quota_peek_size(resource_quota)) { + gpr_mu_unlock(&resource_user->mu); + return false; + } + cas_success = gpr_atm_full_cas(&resource_quota->used, used, new_used); + } while (!cas_success); + resource_user_alloc_locked(resource_user, size, nullptr); gpr_mu_unlock(&resource_user->mu); - return true; + return true; } bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size, - grpc_closure* optional_on_done) { - // TODO(juanlishen): Maybe return immediately if shutting down. Deferring this - // because some tests become flaky after the change. - gpr_mu_lock(&resource_user->mu); - grpc_resource_quota* resource_quota = resource_user->resource_quota; - gpr_atm_no_barrier_fetch_add(&resource_quota->used, size); + grpc_closure* optional_on_done) { + // TODO(juanlishen): Maybe return immediately if shutting down. Deferring this + // because some tests become flaky after the change. + gpr_mu_lock(&resource_user->mu); + grpc_resource_quota* resource_quota = resource_user->resource_quota; + gpr_atm_no_barrier_fetch_add(&resource_quota->used, size); const bool ret = resource_user_alloc_locked(resource_user, size, optional_on_done); - gpr_mu_unlock(&resource_user->mu); + gpr_mu_unlock(&resource_user->mu); return ret; -} - +} + void grpc_resource_user_free(grpc_resource_user* resource_user, size_t size) { gpr_mu_lock(&resource_user->mu); - grpc_resource_quota* resource_quota = resource_user->resource_quota; - gpr_atm prior = gpr_atm_no_barrier_fetch_add(&resource_quota->used, -size); - GPR_ASSERT(prior >= static_cast<long>(size)); + grpc_resource_quota* resource_quota = resource_user->resource_quota; + gpr_atm prior = gpr_atm_no_barrier_fetch_add(&resource_quota->used, -size); + GPR_ASSERT(prior >= static_cast<long>(size)); bool was_zero_or_negative = resource_user->free_pool <= 0; resource_user->free_pool += static_cast<int64_t>(size); if (GRPC_TRACE_FLAG_ENABLED(grpc_resource_quota_trace)) { @@ -1002,9 +1002,9 @@ bool grpc_resource_user_alloc_slices( gpr_atm_no_barrier_load(&slice_allocator->resource_user->shutdown))) { grpc_core::ExecCtx::Run( DEBUG_LOCATION, &slice_allocator->on_allocated, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resource user shutdown")); + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Resource user shutdown")); return false; - } + } slice_allocator->length = length; slice_allocator->count = count; slice_allocator->dest = dest; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h index ec89a92020..6124294dfd 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/resource_quota.h @@ -65,16 +65,16 @@ extern grpc_core::TraceFlag grpc_resource_quota_trace; -// TODO(juanlishen): This is a hack. We need to do real accounting instead of -// hard coding. -constexpr size_t GRPC_RESOURCE_QUOTA_CALL_SIZE = 15 * 1024; -constexpr size_t GRPC_RESOURCE_QUOTA_CHANNEL_SIZE = 50 * 1024; - +// TODO(juanlishen): This is a hack. We need to do real accounting instead of +// hard coding. +constexpr size_t GRPC_RESOURCE_QUOTA_CALL_SIZE = 15 * 1024; +constexpr size_t GRPC_RESOURCE_QUOTA_CHANNEL_SIZE = 50 * 1024; + grpc_resource_quota* grpc_resource_quota_ref_internal( grpc_resource_quota* resource_quota); void grpc_resource_quota_unref_internal(grpc_resource_quota* resource_quota); grpc_resource_quota* grpc_resource_quota_from_channel_args( - const grpc_channel_args* channel_args, bool create = true); + const grpc_channel_args* channel_args, bool create = true); /* Return a number indicating current memory pressure: 0.0 ==> no memory usage @@ -98,38 +98,38 @@ void grpc_resource_user_ref(grpc_resource_user* resource_user); void grpc_resource_user_unref(grpc_resource_user* resource_user); void grpc_resource_user_shutdown(grpc_resource_user* resource_user); -/* Attempts to get quota from the resource_user to create 'thread_count' number - * of threads. Returns true if successful (i.e the caller is now free to create - * 'thread_count' number of threads) or false if quota is not available */ -bool grpc_resource_user_allocate_threads(grpc_resource_user* resource_user, - int thread_count); -/* Releases 'thread_count' worth of quota back to the resource user. The quota - * should have been previously obtained successfully by calling - * grpc_resource_user_allocate_threads(). - * - * Note: There need not be an exact one-to-one correspondence between - * grpc_resource_user_allocate_threads() and grpc_resource_user_free_threads() - * calls. The only requirement is that the number of threads allocated should - * all be eventually released */ -void grpc_resource_user_free_threads(grpc_resource_user* resource_user, - int thread_count); - -/* Allocates from the resource user 'size' worth of memory if this won't exceed - * the resource quota's total size. Returns whether the allocation is done - * successfully. If allocated successfully, the memory should be freed by the - * caller eventually. */ -bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user, - size_t size); -/* Allocates from the resource user 'size' worth of memory. - * If optional_on_done is NULL, then allocate immediately. This may push the - * quota over-limit, at which point reclamation will kick in. The caller is - * always responsible to free the memory eventually. +/* Attempts to get quota from the resource_user to create 'thread_count' number + * of threads. Returns true if successful (i.e the caller is now free to create + * 'thread_count' number of threads) or false if quota is not available */ +bool grpc_resource_user_allocate_threads(grpc_resource_user* resource_user, + int thread_count); +/* Releases 'thread_count' worth of quota back to the resource user. The quota + * should have been previously obtained successfully by calling + * grpc_resource_user_allocate_threads(). + * + * Note: There need not be an exact one-to-one correspondence between + * grpc_resource_user_allocate_threads() and grpc_resource_user_free_threads() + * calls. The only requirement is that the number of threads allocated should + * all be eventually released */ +void grpc_resource_user_free_threads(grpc_resource_user* resource_user, + int thread_count); + +/* Allocates from the resource user 'size' worth of memory if this won't exceed + * the resource quota's total size. Returns whether the allocation is done + * successfully. If allocated successfully, the memory should be freed by the + * caller eventually. */ +bool grpc_resource_user_safe_alloc(grpc_resource_user* resource_user, + size_t size); +/* Allocates from the resource user 'size' worth of memory. + * If optional_on_done is NULL, then allocate immediately. This may push the + * quota over-limit, at which point reclamation will kick in. The caller is + * always responsible to free the memory eventually. * Returns true if the allocation was successful. Otherwise, if optional_on_done * is non-NULL, it will be scheduled without error when the allocation has been * granted by the quota, and the caller is responsible to free the memory * eventually. Or it may be scheduled with an error, in which case the caller * fails to allocate the memory and shouldn't free the memory. - */ + */ bool grpc_resource_user_alloc(grpc_resource_user* resource_user, size_t size, grpc_closure* optional_on_done) GRPC_MUST_USE_RESULT; diff --git a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h index 3cedd9082d..1efcd832f5 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/sockaddr_posix.h @@ -23,7 +23,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_SOCKADDR +#ifdef GRPC_POSIX_SOCKET_SOCKADDR #include <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc index 57137769c8..fa912143a4 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_factory_posix.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_SOCKET_FACTORY +#ifdef GRPC_POSIX_SOCKET_SOCKET_FACTORY #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/useful.h" diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc index a448c9f61c..4e15c79604 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.cc @@ -57,7 +57,7 @@ int grpc_socket_mutator_compare(grpc_socket_mutator* a, void grpc_socket_mutator_unref(grpc_socket_mutator* mutator) { if (gpr_unref(&mutator->refcount)) { - mutator->vtable->destroy(mutator); + mutator->vtable->destroy(mutator); } } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h index 9f77a3b266..59629f822f 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h @@ -33,7 +33,7 @@ struct grpc_socket_mutator_vtable { /** Compare socket mutator \a a and \a b */ int (*compare)(grpc_socket_mutator* a, grpc_socket_mutator* b); /** Destroys the socket mutator instance */ - void (*destroy)(grpc_socket_mutator* mutator); + void (*destroy)(grpc_socket_mutator* mutator); }; /** The Socket Mutator interface allows changes on socket options */ struct grpc_socket_mutator { diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h index 14bb081e93..b918128ef0 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils.h @@ -23,21 +23,21 @@ #include <stddef.h> -// TODO(juanlishen): The following functions might be simple enough to implement -// ourselves, so that they don't cause any portability hassle. - +// TODO(juanlishen): The following functions might be simple enough to implement +// ourselves, so that they don't cause any portability hassle. + /* A wrapper for htons on POSIX and Windows */ uint16_t grpc_htons(uint16_t hostshort); /* A wrapper for ntohs on POSIX and WINDOWS */ uint16_t grpc_ntohs(uint16_t netshort); -/* A wrapper for htonl on POSIX and Windows */ -uint32_t grpc_htonl(uint32_t hostlong); - -/* A wrapper for ntohl on POSIX and WINDOWS */ -uint32_t grpc_ntohl(uint32_t netlong); - +/* A wrapper for htonl on POSIX and Windows */ +uint32_t grpc_htonl(uint32_t hostlong); + +/* A wrapper for ntohl on POSIX and WINDOWS */ +uint32_t grpc_ntohl(uint32_t netlong); + /* A wrapper for inet_pton on POSIX and WINDOWS */ int grpc_inet_pton(int af, const char* src, void* dst); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc index 8a8d4d3a22..a207975977 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_common_posix.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_UTILS_COMMON +#ifdef GRPC_POSIX_SOCKET_UTILS_COMMON #include "src/core/lib/iomgr/socket_utils.h" #include "src/core/lib/iomgr/socket_utils_posix.h" @@ -47,7 +47,7 @@ #include <grpc/support/log.h> #include <grpc/support/sync.h> -#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/sockaddr.h" #include "src/core/lib/iomgr/sockaddr_utils.h" @@ -59,10 +59,10 @@ extern "C" bool IsReusePortAvailable(); #define SO_REUSEPORT 15 #endif -#ifndef TCP_USER_TIMEOUT -#define TCP_USER_TIMEOUT 18 /* How long for loss retry before timeout */ -#endif - +#ifndef TCP_USER_TIMEOUT +#define TCP_USER_TIMEOUT 18 /* How long for loss retry before timeout */ +#endif + /* set a socket to use zerocopy */ grpc_error* grpc_set_socket_zerocopy(int fd) { #ifdef GRPC_LINUX_ERRQUEUE @@ -76,7 +76,7 @@ grpc_error* grpc_set_socket_zerocopy(int fd) { return GRPC_OS_ERROR(ENOSYS, "setsockopt(SO_ZEROCOPY)"); #endif } - + /* set a socket to non blocking mode */ grpc_error* grpc_set_socket_nonblocking(int fd, int non_blocking) { int oldflags = fcntl(fd, F_GETFL, 0); @@ -257,19 +257,19 @@ grpc_error* grpc_set_socket_low_latency(int fd, int low_latency) { return GRPC_ERROR_NONE; } -/* The default values for TCP_USER_TIMEOUT are currently configured to be in - * line with the default values of KEEPALIVE_TIMEOUT as proposed in - * https://github.com/grpc/proposal/blob/master/A18-tcp-user-timeout.md */ -#define DEFAULT_CLIENT_TCP_USER_TIMEOUT_MS 20000 /* 20 seconds */ -#define DEFAULT_SERVER_TCP_USER_TIMEOUT_MS 20000 /* 20 seconds */ - -static int g_default_client_tcp_user_timeout_ms = - DEFAULT_CLIENT_TCP_USER_TIMEOUT_MS; -static int g_default_server_tcp_user_timeout_ms = - DEFAULT_SERVER_TCP_USER_TIMEOUT_MS; -static bool g_default_client_tcp_user_timeout_enabled = false; -static bool g_default_server_tcp_user_timeout_enabled = true; - +/* The default values for TCP_USER_TIMEOUT are currently configured to be in + * line with the default values of KEEPALIVE_TIMEOUT as proposed in + * https://github.com/grpc/proposal/blob/master/A18-tcp-user-timeout.md */ +#define DEFAULT_CLIENT_TCP_USER_TIMEOUT_MS 20000 /* 20 seconds */ +#define DEFAULT_SERVER_TCP_USER_TIMEOUT_MS 20000 /* 20 seconds */ + +static int g_default_client_tcp_user_timeout_ms = + DEFAULT_CLIENT_TCP_USER_TIMEOUT_MS; +static int g_default_server_tcp_user_timeout_ms = + DEFAULT_SERVER_TCP_USER_TIMEOUT_MS; +static bool g_default_client_tcp_user_timeout_enabled = false; +static bool g_default_server_tcp_user_timeout_enabled = true; + #if GPR_LINUX == 1 // For Linux, it will be detected to support TCP_USER_TIMEOUT #ifndef TCP_USER_TIMEOUT @@ -291,23 +291,23 @@ static bool g_default_server_tcp_user_timeout_enabled = true; static std::atomic<int> g_socket_supports_tcp_user_timeout( SOCKET_SUPPORTS_TCP_USER_TIMEOUT_DEFAULT); -void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client) { - if (is_client) { - g_default_client_tcp_user_timeout_enabled = enable; - if (timeout > 0) { - g_default_client_tcp_user_timeout_ms = timeout; - } - } else { - g_default_server_tcp_user_timeout_enabled = enable; - if (timeout > 0) { - g_default_server_tcp_user_timeout_ms = timeout; - } - } -} - -/* Set TCP_USER_TIMEOUT */ -grpc_error* grpc_set_socket_tcp_user_timeout( - int fd, const grpc_channel_args* channel_args, bool is_client) { +void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client) { + if (is_client) { + g_default_client_tcp_user_timeout_enabled = enable; + if (timeout > 0) { + g_default_client_tcp_user_timeout_ms = timeout; + } + } else { + g_default_server_tcp_user_timeout_enabled = enable; + if (timeout > 0) { + g_default_server_tcp_user_timeout_ms = timeout; + } + } +} + +/* Set TCP_USER_TIMEOUT */ +grpc_error* grpc_set_socket_tcp_user_timeout( + int fd, const grpc_channel_args* channel_args, bool is_client) { // Use conditionally-important parameter to avoid warning (void)fd; (void)channel_args; @@ -344,7 +344,7 @@ grpc_error* grpc_set_socket_tcp_user_timeout( continue; } timeout = value; - } + } } } if (enable) { @@ -363,8 +363,8 @@ grpc_error* grpc_set_socket_tcp_user_timeout( "TCP_USER_TIMEOUT is available. TCP_USER_TIMEOUT will be " "used thereafter"); g_socket_supports_tcp_user_timeout.store(1); - } - } + } + } if (g_socket_supports_tcp_user_timeout.load() > 0) { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { gpr_log(GPR_INFO, "Enabling TCP_USER_TIMEOUT with a timeout of %d ms", @@ -387,15 +387,15 @@ grpc_error* grpc_set_socket_tcp_user_timeout( return GRPC_ERROR_NONE; } } - } + } } else { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { gpr_log(GPR_INFO, "TCP_USER_TIMEOUT not supported for this platform"); - } - } - return GRPC_ERROR_NONE; -} - + } + } + return GRPC_ERROR_NONE; +} + /* set a socket using a grpc_socket_mutator */ grpc_error* grpc_set_socket_with_mutator(int fd, grpc_socket_mutator* mutator) { GPR_ASSERT(mutator); @@ -507,10 +507,10 @@ uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); } uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); } -uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); } - -uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); } - +uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); } + +uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); } + int grpc_inet_pton(int af, const char* src, void* dst) { return inet_pton(af, src, dst); } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h index b4dc909d1e..d550a40223 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_posix.h @@ -65,13 +65,13 @@ grpc_error* grpc_set_socket_low_latency(int fd, int low_latency); /* set SO_REUSEPORT */ grpc_error* grpc_set_socket_reuse_port(int fd, int reuse); -/* Configure the default values for TCP_USER_TIMEOUT */ -void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client); - -/* Set TCP_USER_TIMEOUT */ -grpc_error* grpc_set_socket_tcp_user_timeout( - int fd, const grpc_channel_args* channel_args, bool is_client); - +/* Configure the default values for TCP_USER_TIMEOUT */ +void config_default_tcp_user_timeout(bool enable, int timeout, bool is_client); + +/* Set TCP_USER_TIMEOUT */ +grpc_error* grpc_set_socket_tcp_user_timeout( + int fd, const grpc_channel_args* channel_args, bool is_client); + /* Returns true if this system can create AF_INET6 sockets bound to ::1. The value is probed once, and cached for the life of the process. diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc index 96f193ddcc..f18478cb6d 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_uv.cc @@ -33,10 +33,10 @@ uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); } uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); } -uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); } - -uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); } - +uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); } + +uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); } + int grpc_inet_pton(int af, const char* src, void* dst) { return inet_pton(af, src, dst); } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc index 9137ab98e6..776f9676cb 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_utils_windows.cc @@ -31,10 +31,10 @@ uint16_t grpc_htons(uint16_t hostshort) { return htons(hostshort); } uint16_t grpc_ntohs(uint16_t netshort) { return ntohs(netshort); } -uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); } - -uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); } - +uint32_t grpc_htonl(uint32_t hostlong) { return htonl(hostlong); } + +uint32_t grpc_ntohl(uint32_t netlong) { return ntohl(netlong); } + int grpc_inet_pton(int af, const char* src, void* dst) { return inet_pton(af, src, dst); } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc index f117653c49..4f268e8617 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.cc @@ -41,7 +41,7 @@ #include "src/core/lib/iomgr/iomgr_internal.h" #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/pollset_windows.h" -#include "src/core/lib/iomgr/sockaddr_windows.h" +#include "src/core/lib/iomgr/sockaddr_windows.h" #include "src/core/lib/iomgr/socket_windows.h" static DWORD s_wsa_socket_flags; @@ -57,10 +57,10 @@ grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name) { return r; } -SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket) { - return socket->socket; -} - +SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket) { + return socket->socket; +} + /* Schedule a shutdown of the socket operations. Will call the pending operations to abort them. We need to do that this way because of the various callsites of that function, which happens to be in various @@ -158,34 +158,34 @@ void grpc_socket_become_ready(grpc_winsocket* socket, if (should_destroy) destroy(socket); } -static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT; -static bool g_ipv6_loopback_available = false; - -static void probe_ipv6_once(void) { - SOCKET s = socket(AF_INET6, SOCK_STREAM, 0); - g_ipv6_loopback_available = 0; - if (s == INVALID_SOCKET) { - gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed."); - } else { - grpc_sockaddr_in6 addr; - memset(&addr, 0, sizeof(addr)); - addr.sin6_family = AF_INET6; - addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */ - if (bind(s, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) { - g_ipv6_loopback_available = 1; - } else { - gpr_log(GPR_INFO, - "Disabling AF_INET6 sockets because ::1 is not available."); - } - closesocket(s); - } -} - -int grpc_ipv6_loopback_available(void) { - gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once); - return g_ipv6_loopback_available; -} - +static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT; +static bool g_ipv6_loopback_available = false; + +static void probe_ipv6_once(void) { + SOCKET s = socket(AF_INET6, SOCK_STREAM, 0); + g_ipv6_loopback_available = 0; + if (s == INVALID_SOCKET) { + gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed."); + } else { + grpc_sockaddr_in6 addr; + memset(&addr, 0, sizeof(addr)); + addr.sin6_family = AF_INET6; + addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */ + if (bind(s, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) { + g_ipv6_loopback_available = 1; + } else { + gpr_log(GPR_INFO, + "Disabling AF_INET6 sockets because ::1 is not available."); + } + closesocket(s); + } +} + +int grpc_ipv6_loopback_available(void) { + gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once); + return g_ipv6_loopback_available; +} + DWORD grpc_get_default_wsa_socket_flags() { return s_wsa_socket_flags; } void grpc_wsa_socket_flags_init() { diff --git a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h index 78f79453c6..a8cf29efce 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/socket_windows.h @@ -96,8 +96,8 @@ typedef struct grpc_winsocket { it will be responsible for closing it. */ grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name); -SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket); - +SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket); + /* Initiate an asynchronous shutdown of the socket. Will call off any pending operation to cancel them. */ void grpc_winsocket_shutdown(grpc_winsocket* socket); @@ -114,10 +114,10 @@ void grpc_socket_notify_on_read(grpc_winsocket* winsocket, void grpc_socket_become_ready(grpc_winsocket* winsocket, grpc_winsocket_callback_info* ci); -/* Returns true if this system can create AF_INET6 sockets bound to ::1. - The value is probed once, and cached for the life of the process. */ -int grpc_ipv6_loopback_available(void); - +/* Returns true if this system can create AF_INET6 sockets bound to ::1. + The value is probed once, and cached for the life of the process. */ +int grpc_ipv6_loopback_available(void); + void grpc_wsa_socket_flags_init(); DWORD grpc_get_default_wsa_socket_flags(); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc index eafa885e2c..714cd82b35 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_cfstream.cc @@ -1,213 +1,213 @@ - -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/iomgr/port.h" - -#ifdef GRPC_CFSTREAM_CLIENT - -#include <CoreFoundation/CoreFoundation.h> - -#include <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/sync.h> - -#include <netinet/in.h> - -#include "src/core/lib/channel/channel_args.h" + +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_CFSTREAM_CLIENT + +#include <CoreFoundation/CoreFoundation.h> + +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/sync.h> + +#include <netinet/in.h> + +#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gprpp/host_port.h" -#include "src/core/lib/iomgr/cfstream_handle.h" -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/endpoint_cfstream.h" -#include "src/core/lib/iomgr/error.h" -#include "src/core/lib/iomgr/error_cfstream.h" -#include "src/core/lib/iomgr/sockaddr_utils.h" -#include "src/core/lib/iomgr/tcp_client.h" -#include "src/core/lib/iomgr/timer.h" - -extern grpc_core::TraceFlag grpc_tcp_trace; - +#include "src/core/lib/iomgr/cfstream_handle.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/endpoint_cfstream.h" +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/error_cfstream.h" +#include "src/core/lib/iomgr/sockaddr_utils.h" +#include "src/core/lib/iomgr/tcp_client.h" +#include "src/core/lib/iomgr/timer.h" + +extern grpc_core::TraceFlag grpc_tcp_trace; + struct CFStreamConnect { - gpr_mu mu; - gpr_refcount refcount; - - CFReadStreamRef read_stream; - CFWriteStreamRef write_stream; - CFStreamHandle* stream_handle; - - grpc_timer alarm; - grpc_closure on_alarm; - grpc_closure on_open; - - bool read_stream_open; - bool write_stream_open; - bool failed; - - grpc_closure* closure; - grpc_endpoint** endpoint; - int refs; + gpr_mu mu; + gpr_refcount refcount; + + CFReadStreamRef read_stream; + CFWriteStreamRef write_stream; + CFStreamHandle* stream_handle; + + grpc_timer alarm; + grpc_closure on_alarm; + grpc_closure on_open; + + bool read_stream_open; + bool write_stream_open; + bool failed; + + grpc_closure* closure; + grpc_endpoint** endpoint; + int refs; TString addr_name; - grpc_resource_quota* resource_quota; + grpc_resource_quota* resource_quota; }; - -static void CFStreamConnectCleanup(CFStreamConnect* connect) { - grpc_resource_quota_unref_internal(connect->resource_quota); - CFSTREAM_HANDLE_UNREF(connect->stream_handle, "async connect clean up"); - CFRelease(connect->read_stream); - CFRelease(connect->write_stream); - gpr_mu_destroy(&connect->mu); + +static void CFStreamConnectCleanup(CFStreamConnect* connect) { + grpc_resource_quota_unref_internal(connect->resource_quota); + CFSTREAM_HANDLE_UNREF(connect->stream_handle, "async connect clean up"); + CFRelease(connect->read_stream); + CFRelease(connect->write_stream); + gpr_mu_destroy(&connect->mu); delete connect; -} - -static void OnAlarm(void* arg, grpc_error* error) { - CFStreamConnect* connect = static_cast<CFStreamConnect*>(arg); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CLIENT_CONNECT :%p OnAlarm, error:%p", connect, error); - } - gpr_mu_lock(&connect->mu); - grpc_closure* closure = connect->closure; - connect->closure = nil; - const bool done = (--connect->refs == 0); - gpr_mu_unlock(&connect->mu); - // Only schedule a callback once, by either OnAlarm or OnOpen. The - // first one issues callback while the second one does cleanup. - if (done) { - CFStreamConnectCleanup(connect); - } else { - grpc_error* error = - GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out"); +} + +static void OnAlarm(void* arg, grpc_error* error) { + CFStreamConnect* connect = static_cast<CFStreamConnect*>(arg); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT :%p OnAlarm, error:%p", connect, error); + } + gpr_mu_lock(&connect->mu); + grpc_closure* closure = connect->closure; + connect->closure = nil; + const bool done = (--connect->refs == 0); + gpr_mu_unlock(&connect->mu); + // Only schedule a callback once, by either OnAlarm or OnOpen. The + // first one issues callback while the second one does cleanup. + if (done) { + CFStreamConnectCleanup(connect); + } else { + grpc_error* error = + GRPC_ERROR_CREATE_FROM_STATIC_STRING("connect() timed out"); grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); - } -} - -static void OnOpen(void* arg, grpc_error* error) { - CFStreamConnect* connect = static_cast<CFStreamConnect*>(arg); - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CLIENT_CONNECT :%p OnOpen, error:%p", connect, error); - } - gpr_mu_lock(&connect->mu); - grpc_timer_cancel(&connect->alarm); - grpc_closure* closure = connect->closure; - connect->closure = nil; - - bool done = (--connect->refs == 0); - grpc_endpoint** endpoint = connect->endpoint; - - // Only schedule a callback once, by either OnAlarm or OnOpen. The - // first one issues callback while the second one does cleanup. - if (done) { - gpr_mu_unlock(&connect->mu); - CFStreamConnectCleanup(connect); - } else { - if (error == GRPC_ERROR_NONE) { - CFErrorRef stream_error = CFReadStreamCopyError(connect->read_stream); - if (stream_error == NULL) { - stream_error = CFWriteStreamCopyError(connect->write_stream); - } - if (stream_error) { - error = GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "connect() error"); - CFRelease(stream_error); - } - if (error == GRPC_ERROR_NONE) { - *endpoint = grpc_cfstream_endpoint_create( + } +} + +static void OnOpen(void* arg, grpc_error* error) { + CFStreamConnect* connect = static_cast<CFStreamConnect*>(arg); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT :%p OnOpen, error:%p", connect, error); + } + gpr_mu_lock(&connect->mu); + grpc_timer_cancel(&connect->alarm); + grpc_closure* closure = connect->closure; + connect->closure = nil; + + bool done = (--connect->refs == 0); + grpc_endpoint** endpoint = connect->endpoint; + + // Only schedule a callback once, by either OnAlarm or OnOpen. The + // first one issues callback while the second one does cleanup. + if (done) { + gpr_mu_unlock(&connect->mu); + CFStreamConnectCleanup(connect); + } else { + if (error == GRPC_ERROR_NONE) { + CFErrorRef stream_error = CFReadStreamCopyError(connect->read_stream); + if (stream_error == NULL) { + stream_error = CFWriteStreamCopyError(connect->write_stream); + } + if (stream_error) { + error = GRPC_ERROR_CREATE_FROM_CFERROR(stream_error, "connect() error"); + CFRelease(stream_error); + } + if (error == GRPC_ERROR_NONE) { + *endpoint = grpc_cfstream_endpoint_create( connect->read_stream, connect->write_stream, connect->addr_name.c_str(), connect->resource_quota, connect->stream_handle); - } - } else { - GRPC_ERROR_REF(error); - } - gpr_mu_unlock(&connect->mu); + } + } else { + GRPC_ERROR_REF(error); + } + gpr_mu_unlock(&connect->mu); grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); - } -} - -static void ParseResolvedAddress(const grpc_resolved_address* addr, - CFStringRef* host, int* port) { + } +} + +static void ParseResolvedAddress(const grpc_resolved_address* addr, + CFStringRef* host, int* port) { TString host_port = grpc_sockaddr_to_string(addr, true); TString host_string; TString port_string; grpc_core::SplitHostPort(host_port, &host_string, &port_string); *host = CFStringCreateWithCString(NULL, host_string.c_str(), kCFStringEncodingUTF8); - *port = grpc_sockaddr_get_port(addr); -} - -static void CFStreamClientConnect(grpc_closure* closure, grpc_endpoint** ep, - grpc_pollset_set* interested_parties, - const grpc_channel_args* channel_args, - const grpc_resolved_address* resolved_addr, - grpc_millis deadline) { + *port = grpc_sockaddr_get_port(addr); +} + +static void CFStreamClientConnect(grpc_closure* closure, grpc_endpoint** ep, + grpc_pollset_set* interested_parties, + const grpc_channel_args* channel_args, + const grpc_resolved_address* resolved_addr, + grpc_millis deadline) { CFStreamConnect* connect = new CFStreamConnect(); - connect->closure = closure; - connect->endpoint = ep; - connect->addr_name = grpc_sockaddr_to_uri(resolved_addr); - // connect->resource_quota = resource_quota; - connect->refs = 2; // One for the connect operation, one for the timer. - gpr_ref_init(&connect->refcount, 1); - gpr_mu_init(&connect->mu); - - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %p, %s: asynchronously connecting", + connect->closure = closure; + connect->endpoint = ep; + connect->addr_name = grpc_sockaddr_to_uri(resolved_addr); + // connect->resource_quota = resource_quota; + connect->refs = 2; // One for the connect operation, one for the timer. + gpr_ref_init(&connect->refcount, 1); + gpr_mu_init(&connect->mu); + + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %p, %s: asynchronously connecting", connect, connect->addr_name.c_str()); - } - - grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL); - if (channel_args != NULL) { - for (size_t i = 0; i < channel_args->num_args; i++) { - if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { - grpc_resource_quota_unref_internal(resource_quota); - resource_quota = grpc_resource_quota_ref_internal( - (grpc_resource_quota*)channel_args->args[i].value.pointer.p); - } - } - } - connect->resource_quota = resource_quota; - - CFReadStreamRef read_stream; - CFWriteStreamRef write_stream; - - CFStringRef host; - int port; - ParseResolvedAddress(resolved_addr, &host, &port); - CFStreamCreatePairWithSocketToHost(NULL, host, port, &read_stream, - &write_stream); - CFRelease(host); - connect->read_stream = read_stream; - connect->write_stream = write_stream; - connect->stream_handle = - CFStreamHandle::CreateStreamHandle(read_stream, write_stream); - GRPC_CLOSURE_INIT(&connect->on_open, OnOpen, static_cast<void*>(connect), - grpc_schedule_on_exec_ctx); - connect->stream_handle->NotifyOnOpen(&connect->on_open); - GRPC_CLOSURE_INIT(&connect->on_alarm, OnAlarm, connect, - grpc_schedule_on_exec_ctx); - gpr_mu_lock(&connect->mu); - CFReadStreamOpen(read_stream); - CFWriteStreamOpen(write_stream); - grpc_timer_init(&connect->alarm, deadline, &connect->on_alarm); - gpr_mu_unlock(&connect->mu); -} - -grpc_tcp_client_vtable grpc_cfstream_client_vtable = {CFStreamClientConnect}; - -#endif /* GRPC_CFSTREAM_CLIENT */ + } + + grpc_resource_quota* resource_quota = grpc_resource_quota_create(NULL); + if (channel_args != NULL) { + for (size_t i = 0; i < channel_args->num_args; i++) { + if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { + grpc_resource_quota_unref_internal(resource_quota); + resource_quota = grpc_resource_quota_ref_internal( + (grpc_resource_quota*)channel_args->args[i].value.pointer.p); + } + } + } + connect->resource_quota = resource_quota; + + CFReadStreamRef read_stream; + CFWriteStreamRef write_stream; + + CFStringRef host; + int port; + ParseResolvedAddress(resolved_addr, &host, &port); + CFStreamCreatePairWithSocketToHost(NULL, host, port, &read_stream, + &write_stream); + CFRelease(host); + connect->read_stream = read_stream; + connect->write_stream = write_stream; + connect->stream_handle = + CFStreamHandle::CreateStreamHandle(read_stream, write_stream); + GRPC_CLOSURE_INIT(&connect->on_open, OnOpen, static_cast<void*>(connect), + grpc_schedule_on_exec_ctx); + connect->stream_handle->NotifyOnOpen(&connect->on_open); + GRPC_CLOSURE_INIT(&connect->on_alarm, OnAlarm, connect, + grpc_schedule_on_exec_ctx); + gpr_mu_lock(&connect->mu); + CFReadStreamOpen(read_stream); + CFWriteStreamOpen(write_stream); + grpc_timer_init(&connect->alarm, deadline, &connect->on_alarm); + gpr_mu_unlock(&connect->mu); +} + +grpc_tcp_client_vtable grpc_cfstream_client_vtable = {CFStreamClientConnect}; + +#endif /* GRPC_CFSTREAM_CLIENT */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc index dbcf62c94f..553c38b466 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_custom.cc @@ -80,8 +80,8 @@ static void on_alarm(void* acp, grpc_error* error) { } } -static void custom_connect_callback_internal(grpc_custom_socket* socket, - grpc_error* error) { +static void custom_connect_callback_internal(grpc_custom_socket* socket, + grpc_error* error) { grpc_custom_tcp_connect* connect = socket->connector; int done; grpc_closure* closure = connect->closure; @@ -98,19 +98,19 @@ static void custom_connect_callback_internal(grpc_custom_socket* socket, grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); } -static void custom_connect_callback(grpc_custom_socket* socket, - grpc_error* error) { +static void custom_connect_callback(grpc_custom_socket* socket, + grpc_error* error) { grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - if (grpc_core::ExecCtx::Get() == nullptr) { - /* If we are being run on a thread which does not have an exec_ctx created - * yet, we should create one. */ - grpc_core::ExecCtx exec_ctx; - custom_connect_callback_internal(socket, error); - } else { - custom_connect_callback_internal(socket, error); - } -} - + if (grpc_core::ExecCtx::Get() == nullptr) { + /* If we are being run on a thread which does not have an exec_ctx created + * yet, we should create one. */ + grpc_core::ExecCtx exec_ctx; + custom_connect_callback_internal(socket, error); + } else { + custom_connect_callback_internal(socket, error); + } +} + static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep, grpc_pollset_set* interested_parties, const grpc_channel_args* channel_args, @@ -149,9 +149,9 @@ static void tcp_connect(grpc_closure* closure, grpc_endpoint** ep, socket, connect->addr_name.c_str()); } - GRPC_CLOSURE_INIT(&connect->on_alarm, on_alarm, socket, - grpc_schedule_on_exec_ctx); - grpc_timer_init(&connect->alarm, deadline, &connect->on_alarm); + GRPC_CLOSURE_INIT(&connect->on_alarm, on_alarm, socket, + grpc_schedule_on_exec_ctx); + grpc_timer_init(&connect->alarm, deadline, &connect->on_alarm); grpc_custom_socket_vtable->connect( socket, (const grpc_sockaddr*)resolved_addr->addr, resolved_addr->len, custom_connect_callback); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc index 401ddd2f68..590e2b2eeb 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_client_posix.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_TCP_CLIENT +#ifdef GRPC_POSIX_SOCKET_TCP_CLIENT #include "src/core/lib/iomgr/tcp_client_posix.h" @@ -46,7 +46,7 @@ #include "src/core/lib/iomgr/tcp_posix.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/iomgr/unix_sockets_posix.h" -#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/slice/slice_internal.h" extern grpc_core::TraceFlag grpc_tcp_trace; @@ -77,11 +77,11 @@ static grpc_error* prepare_socket(const grpc_resolved_address* addr, int fd, if (!grpc_is_unix_socket(addr)) { err = grpc_set_socket_low_latency(fd, 1); if (err != GRPC_ERROR_NONE) goto error; - err = grpc_set_socket_reuse_addr(fd, 1); - if (err != GRPC_ERROR_NONE) goto error; - err = grpc_set_socket_tcp_user_timeout(fd, channel_args, - true /* is_client */); - if (err != GRPC_ERROR_NONE) goto error; + err = grpc_set_socket_reuse_addr(fd, 1); + if (err != GRPC_ERROR_NONE) goto error; + err = grpc_set_socket_tcp_user_timeout(fd, channel_args, + true /* is_client */); + if (err != GRPC_ERROR_NONE) goto error; } err = grpc_set_socket_no_sigpipe_if_possible(fd); if (err != GRPC_ERROR_NONE) goto error; @@ -210,7 +210,7 @@ static void on_writable(void* acp, grpc_error* error) { finish: if (fd != nullptr) { grpc_pollset_set_del_fd(ac->interested_parties, fd); - grpc_fd_orphan(fd, nullptr, nullptr, "tcp_client_orphan"); + grpc_fd_orphan(fd, nullptr, nullptr, "tcp_client_orphan"); fd = nullptr; } done = (--ac->refs == 0); @@ -230,7 +230,7 @@ finish: error = grpc_error_set_str(error, GRPC_ERROR_STR_TARGET_ADDRESS, addr_str_slice /* takes ownership */); } else { - grpc_slice_unref_internal(addr_str_slice); + grpc_slice_unref_internal(addr_str_slice); } if (done) { // This is safe even outside the lock, because "done", the sentinel, is @@ -297,7 +297,7 @@ void grpc_tcp_client_create_from_prepared_fd( error = grpc_error_set_str( error, GRPC_ERROR_STR_TARGET_ADDRESS, grpc_slice_from_cpp_string(grpc_sockaddr_to_uri(addr))); - grpc_fd_orphan(fdobj, nullptr, nullptr, "tcp_client_connect_error"); + grpc_fd_orphan(fdobj, nullptr, nullptr, "tcp_client_connect_error"); grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); return; } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc index 3e562da508..47700504af 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_custom.cc @@ -337,7 +337,7 @@ static grpc_resource_user* endpoint_get_resource_user(grpc_endpoint* ep) { static int endpoint_get_fd(grpc_endpoint* /*ep*/) { return -1; } static bool endpoint_can_track_err(grpc_endpoint* /*ep*/) { return false; } - + static grpc_endpoint_vtable vtable = {endpoint_read, endpoint_write, endpoint_add_to_pollset, @@ -348,8 +348,8 @@ static grpc_endpoint_vtable vtable = {endpoint_read, endpoint_get_resource_user, endpoint_get_peer, endpoint_get_local_address, - endpoint_get_fd, - endpoint_can_track_err}; + endpoint_get_fd, + endpoint_can_track_err}; grpc_endpoint* custom_tcp_endpoint_create(grpc_custom_socket* socket, grpc_resource_quota* resource_quota, diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc index b1cd892964..df653a8d56 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.cc @@ -20,16 +20,16 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_TCP +#ifdef GRPC_POSIX_SOCKET_TCP #include "src/core/lib/iomgr/tcp_posix.h" #include <errno.h> -#include <limits.h> -#include <netinet/in.h> +#include <limits.h> +#include <netinet/in.h> #include <netinet/tcp.h> #include <stdbool.h> -#include <stdio.h> +#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> @@ -51,7 +51,7 @@ #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/useful.h" #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/iomgr/buffer_list.h" +#include "src/core/lib/iomgr/buffer_list.h" #include "src/core/lib/iomgr/ev_posix.h" #include "src/core/lib/iomgr/executor.h" #include "src/core/lib/iomgr/sockaddr_utils.h" @@ -357,9 +357,9 @@ struct grpc_tcp { grpc_endpoint base; grpc_fd* em_fd; int fd; - /* Used by the endpoint read function to distinguish the very first read call - * from the rest */ - bool is_first_read; + /* Used by the endpoint read function to distinguish the very first read call + * from the rest */ + bool is_first_read; double target_length; double bytes_read_this_round; grpc_core::RefCount refcount; @@ -386,36 +386,36 @@ struct grpc_tcp { grpc_closure read_done_closure; grpc_closure write_done_closure; - grpc_closure error_closure; + grpc_closure error_closure; TString peer_string; TString local_address; grpc_resource_user* resource_user; grpc_resource_user_slice_allocator slice_allocator; - - grpc_core::TracedBuffer* tb_head; /* List of traced buffers */ - gpr_mu tb_mu; /* Lock for access to list of traced buffers */ - - /* grpc_endpoint_write takes an argument which if non-null means that the - * transport layer wants the TCP layer to collect timestamps for this write. - * This arg is forwarded to the timestamps callback function when the ACK - * timestamp is received from the kernel. This arg is a (void *) which allows - * users of this API to pass in a pointer to any kind of structure. This - * structure could actually be a tag or any book-keeping object that the user - * can use to distinguish between different traced writes. The only - * requirement from the TCP endpoint layer is that this arg should be non-null - * if the user wants timestamps for the write. */ - void* outgoing_buffer_arg; - /* A counter which starts at 0. It is initialized the first time the socket - * options for collecting timestamps are set, and is incremented with each - * byte sent. */ - int bytes_counter; - bool socket_ts_enabled; /* True if timestamping options are set on the socket - */ - bool ts_capable; /* Cache whether we can set timestamping options */ - gpr_atm stop_error_notification; /* Set to 1 if we do not want to be notified - on errors anymore */ + + grpc_core::TracedBuffer* tb_head; /* List of traced buffers */ + gpr_mu tb_mu; /* Lock for access to list of traced buffers */ + + /* grpc_endpoint_write takes an argument which if non-null means that the + * transport layer wants the TCP layer to collect timestamps for this write. + * This arg is forwarded to the timestamps callback function when the ACK + * timestamp is received from the kernel. This arg is a (void *) which allows + * users of this API to pass in a pointer to any kind of structure. This + * structure could actually be a tag or any book-keeping object that the user + * can use to distinguish between different traced writes. The only + * requirement from the TCP endpoint layer is that this arg should be non-null + * if the user wants timestamps for the write. */ + void* outgoing_buffer_arg; + /* A counter which starts at 0. It is initialized the first time the socket + * options for collecting timestamps are set, and is incremented with each + * byte sent. */ + int bytes_counter; + bool socket_ts_enabled; /* True if timestamping options are set on the socket + */ + bool ts_capable; /* Cache whether we can set timestamping options */ + gpr_atm stop_error_notification; /* Set to 1 if we do not want to be notified + on errors anymore */ TcpZerocopySendCtx tcp_zerocopy_send_ctx; TcpZerocopySendRecord* current_zerocopy_send = nullptr; }; @@ -424,7 +424,7 @@ struct backup_poller { gpr_mu* pollset_mu; grpc_closure run_poller; }; - + } // namespace static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* tcp); @@ -489,7 +489,7 @@ static void run_poller(void* bp, grpc_error* /*error_ignored*/) { static void drop_uncovered(grpc_tcp* /*tcp*/) { backup_poller* p = (backup_poller*)gpr_atm_acq_load(&g_backup_poller); gpr_atm old_count = - gpr_atm_full_fetch_add(&g_uncovered_notifications_pending, -1); + gpr_atm_full_fetch_add(&g_uncovered_notifications_pending, -1); if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { gpr_log(GPR_INFO, "BACKUP_POLLER:%p uncover cnt %d->%d", p, static_cast<int>(old_count), static_cast<int>(old_count) - 1); @@ -497,13 +497,13 @@ static void drop_uncovered(grpc_tcp* /*tcp*/) { GPR_ASSERT(old_count != 1); } -// gRPC API considers a Write operation to be done the moment it clears ‘flow -// control’ i.e., not necessarily sent on the wire. This means that the -// application MIGHT not call `grpc_completion_queue_next/pluck` in a timely -// manner when its `Write()` API is acked. -// -// We need to ensure that the fd is 'covered' (i.e being monitored by some -// polling thread and progress is made) and hence add it to a backup poller here +// gRPC API considers a Write operation to be done the moment it clears ‘flow +// control’ i.e., not necessarily sent on the wire. This means that the +// application MIGHT not call `grpc_completion_queue_next/pluck` in a timely +// manner when its `Write()` API is acked. +// +// We need to ensure that the fd is 'covered' (i.e being monitored by some +// polling thread and progress is made) and hence add it to a backup poller here static void cover_self(grpc_tcp* tcp) { backup_poller* p; gpr_atm old_count = @@ -552,8 +552,8 @@ static void notify_on_write(grpc_tcp* tcp) { gpr_log(GPR_INFO, "TCP:%p notify_on_write", tcp); } if (!grpc_event_engine_run_in_background()) { - cover_self(tcp); - } + cover_self(tcp); + } grpc_fd_notify_on_write(tcp->em_fd, &tcp->write_done_closure); } @@ -624,17 +624,17 @@ static void tcp_shutdown(grpc_endpoint* ep, grpc_error* why) { static void tcp_free(grpc_tcp* tcp) { grpc_fd_orphan(tcp->em_fd, tcp->release_fd_cb, tcp->release_fd, - "tcp_unref_orphan"); + "tcp_unref_orphan"); grpc_slice_buffer_destroy_internal(&tcp->last_read_buffer); grpc_resource_user_unref(tcp->resource_user); - /* The lock is not really necessary here, since all refs have been released */ - gpr_mu_lock(&tcp->tb_mu); - grpc_core::TracedBuffer::Shutdown( - &tcp->tb_head, tcp->outgoing_buffer_arg, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("endpoint destroyed")); - gpr_mu_unlock(&tcp->tb_mu); - tcp->outgoing_buffer_arg = nullptr; - gpr_mu_destroy(&tcp->tb_mu); + /* The lock is not really necessary here, since all refs have been released */ + gpr_mu_lock(&tcp->tb_mu); + grpc_core::TracedBuffer::Shutdown( + &tcp->tb_head, tcp->outgoing_buffer_arg, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("endpoint destroyed")); + gpr_mu_unlock(&tcp->tb_mu); + tcp->outgoing_buffer_arg = nullptr; + gpr_mu_destroy(&tcp->tb_mu); delete tcp; } @@ -667,11 +667,11 @@ static void tcp_ref(grpc_tcp* tcp) { tcp->refcount.Ref(); } static void tcp_destroy(grpc_endpoint* ep) { grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep); grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer); - if (grpc_event_engine_can_track_errors()) { + if (grpc_event_engine_can_track_errors()) { ZerocopyDisableAndWaitForRemaining(tcp); - gpr_atm_no_barrier_store(&tcp->stop_error_notification, true); - grpc_fd_set_error(tcp->em_fd); - } + gpr_atm_no_barrier_store(&tcp->stop_error_notification, true); + grpc_fd_set_error(tcp->em_fd); + } TCP_UNREF(tcp, "destroy"); } @@ -685,13 +685,13 @@ static void call_read_cb(grpc_tcp* tcp, grpc_error* error) { gpr_log(GPR_INFO, "READ %p (peer=%s) error=%s", tcp, tcp->peer_string.c_str(), str); - if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) { - for (i = 0; i < tcp->incoming_buffer->count; i++) { - char* dump = grpc_dump_slice(tcp->incoming_buffer->slices[i], - GPR_DUMP_HEX | GPR_DUMP_ASCII); - gpr_log(GPR_DEBUG, "DATA: %s", dump); - gpr_free(dump); - } + if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) { + for (i = 0; i < tcp->incoming_buffer->count; i++) { + char* dump = grpc_dump_slice(tcp->incoming_buffer->slices[i], + GPR_DUMP_HEX | GPR_DUMP_ASCII); + gpr_log(GPR_DEBUG, "DATA: %s", dump); + gpr_free(dump); + } } } @@ -909,10 +909,10 @@ static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer, grpc_slice_buffer_reset_and_unref_internal(incoming_buffer); grpc_slice_buffer_swap(incoming_buffer, &tcp->last_read_buffer); TCP_REF(tcp, "read"); - if (tcp->is_first_read) { - /* Endpoint read called for the very first time. Register read callback with - * the polling engine */ - tcp->is_first_read = false; + if (tcp->is_first_read) { + /* Endpoint read called for the very first time. Register read callback with + * the polling engine */ + tcp->is_first_read = false; notify_on_read(tcp); } else if (!urgent && tcp->inq == 0) { /* Upper layer asked to read more but we know there is no pending data @@ -920,49 +920,49 @@ static void tcp_read(grpc_endpoint* ep, grpc_slice_buffer* incoming_buffer, */ notify_on_read(tcp); } else { - /* Not the first time. We may or may not have more bytes available. In any - * case call tcp->read_done_closure (i.e tcp_handle_read()) which does the - * right thing (i.e calls tcp_do_read() which either reads the available - * bytes or calls notify_on_read() to be notified when new bytes become - * available */ + /* Not the first time. We may or may not have more bytes available. In any + * case call tcp->read_done_closure (i.e tcp_handle_read()) which does the + * right thing (i.e calls tcp_do_read() which either reads the available + * bytes or calls notify_on_read() to be notified when new bytes become + * available */ grpc_core::Closure::Run(DEBUG_LOCATION, &tcp->read_done_closure, GRPC_ERROR_NONE); } } -/* A wrapper around sendmsg. It sends \a msg over \a fd and returns the number - * of bytes sent. */ +/* A wrapper around sendmsg. It sends \a msg over \a fd and returns the number + * of bytes sent. */ ssize_t tcp_send(int fd, const struct msghdr* msg, int additional_flags = 0) { - GPR_TIMER_SCOPE("sendmsg", 1); - ssize_t sent_length; - do { - /* TODO(klempner): Cork if this is a partial write */ - GRPC_STATS_INC_SYSCALL_WRITE(); + GPR_TIMER_SCOPE("sendmsg", 1); + ssize_t sent_length; + do { + /* TODO(klempner): Cork if this is a partial write */ + GRPC_STATS_INC_SYSCALL_WRITE(); sent_length = sendmsg(fd, msg, SENDMSG_FLAGS | additional_flags); - } while (sent_length < 0 && errno == EINTR); - return sent_length; -} - -/** This is to be called if outgoing_buffer_arg is not null. On linux platforms, - * this will call sendmsg with socket options set to collect timestamps inside - * the kernel. On return, sent_length is set to the return value of the sendmsg - * call. Returns false if setting the socket options failed. This is not - * implemented for non-linux platforms currently, and crashes out. - */ -static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg, - size_t sending_length, + } while (sent_length < 0 && errno == EINTR); + return sent_length; +} + +/** This is to be called if outgoing_buffer_arg is not null. On linux platforms, + * this will call sendmsg with socket options set to collect timestamps inside + * the kernel. On return, sent_length is set to the return value of the sendmsg + * call. Returns false if setting the socket options failed. This is not + * implemented for non-linux platforms currently, and crashes out. + */ +static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg, + size_t sending_length, ssize_t* sent_length, int additional_flags = 0); - -/** The callback function to be invoked when we get an error on the socket. */ -static void tcp_handle_error(void* arg /* grpc_tcp */, grpc_error* error); - + +/** The callback function to be invoked when we get an error on the socket. */ +static void tcp_handle_error(void* arg /* grpc_tcp */, grpc_error* error); + static TcpZerocopySendRecord* tcp_get_send_zerocopy_record( grpc_tcp* tcp, grpc_slice_buffer* buf); -#ifdef GRPC_LINUX_ERRQUEUE +#ifdef GRPC_LINUX_ERRQUEUE static bool process_errors(grpc_tcp* tcp); - + static TcpZerocopySendRecord* tcp_get_send_zerocopy_record( grpc_tcp* tcp, grpc_slice_buffer* buf) { TcpZerocopySendRecord* zerocopy_send_record = nullptr; @@ -993,51 +993,51 @@ static void ZerocopyDisableAndWaitForRemaining(grpc_tcp* tcp) { } } -static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg, - size_t sending_length, +static bool tcp_write_with_timestamps(grpc_tcp* tcp, struct msghdr* msg, + size_t sending_length, ssize_t* sent_length, int additional_flags) { - if (!tcp->socket_ts_enabled) { - uint32_t opt = grpc_core::kTimestampingSocketOptions; - if (setsockopt(tcp->fd, SOL_SOCKET, SO_TIMESTAMPING, - static_cast<void*>(&opt), sizeof(opt)) != 0) { + if (!tcp->socket_ts_enabled) { + uint32_t opt = grpc_core::kTimestampingSocketOptions; + if (setsockopt(tcp->fd, SOL_SOCKET, SO_TIMESTAMPING, + static_cast<void*>(&opt), sizeof(opt)) != 0) { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { - gpr_log(GPR_ERROR, "Failed to set timestamping options on the socket."); - } - return false; - } - tcp->bytes_counter = -1; - tcp->socket_ts_enabled = true; - } - /* Set control message to indicate that you want timestamps. */ - union { - char cmsg_buf[CMSG_SPACE(sizeof(uint32_t))]; - struct cmsghdr align; - } u; - cmsghdr* cmsg = reinterpret_cast<cmsghdr*>(u.cmsg_buf); - cmsg->cmsg_level = SOL_SOCKET; - cmsg->cmsg_type = SO_TIMESTAMPING; - cmsg->cmsg_len = CMSG_LEN(sizeof(uint32_t)); - *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = - grpc_core::kTimestampingRecordingOptions; - msg->msg_control = u.cmsg_buf; - msg->msg_controllen = CMSG_SPACE(sizeof(uint32_t)); - - /* If there was an error on sendmsg the logic in tcp_flush will handle it. */ + gpr_log(GPR_ERROR, "Failed to set timestamping options on the socket."); + } + return false; + } + tcp->bytes_counter = -1; + tcp->socket_ts_enabled = true; + } + /* Set control message to indicate that you want timestamps. */ + union { + char cmsg_buf[CMSG_SPACE(sizeof(uint32_t))]; + struct cmsghdr align; + } u; + cmsghdr* cmsg = reinterpret_cast<cmsghdr*>(u.cmsg_buf); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SO_TIMESTAMPING; + cmsg->cmsg_len = CMSG_LEN(sizeof(uint32_t)); + *reinterpret_cast<int*>(CMSG_DATA(cmsg)) = + grpc_core::kTimestampingRecordingOptions; + msg->msg_control = u.cmsg_buf; + msg->msg_controllen = CMSG_SPACE(sizeof(uint32_t)); + + /* If there was an error on sendmsg the logic in tcp_flush will handle it. */ ssize_t length = tcp_send(tcp->fd, msg, additional_flags); - *sent_length = length; - /* Only save timestamps if all the bytes were taken by sendmsg. */ - if (sending_length == static_cast<size_t>(length)) { - gpr_mu_lock(&tcp->tb_mu); - grpc_core::TracedBuffer::AddNewEntry( - &tcp->tb_head, static_cast<uint32_t>(tcp->bytes_counter + length), - tcp->fd, tcp->outgoing_buffer_arg); - gpr_mu_unlock(&tcp->tb_mu); - tcp->outgoing_buffer_arg = nullptr; - } - return true; -} - + *sent_length = length; + /* Only save timestamps if all the bytes were taken by sendmsg. */ + if (sending_length == static_cast<size_t>(length)) { + gpr_mu_lock(&tcp->tb_mu); + grpc_core::TracedBuffer::AddNewEntry( + &tcp->tb_head, static_cast<uint32_t>(tcp->bytes_counter + length), + tcp->fd, tcp->outgoing_buffer_arg); + gpr_mu_unlock(&tcp->tb_mu); + tcp->outgoing_buffer_arg = nullptr; + } + return true; +} + static void UnrefMaybePutZerocopySendRecord(grpc_tcp* tcp, TcpZerocopySendRecord* record, uint32_t seq, const char* tag); @@ -1075,67 +1075,67 @@ static bool CmsgIsZeroCopy(const cmsghdr& cmsg) { return serr->ee_errno == 0 && serr->ee_origin == SO_EE_ORIGIN_ZEROCOPY; } -/** Reads \a cmsg to derive timestamps from the control messages. If a valid - * timestamp is found, the traced buffer list is updated with this timestamp. - * The caller of this function should be looping on the control messages found - * in \a msg. \a cmsg should point to the control message that the caller wants - * processed. - * On return, a pointer to a control message is returned. On the next iteration, - * CMSG_NXTHDR(msg, ret_val) should be passed as \a cmsg. */ -struct cmsghdr* process_timestamp(grpc_tcp* tcp, msghdr* msg, - struct cmsghdr* cmsg) { - auto next_cmsg = CMSG_NXTHDR(msg, cmsg); - cmsghdr* opt_stats = nullptr; - if (next_cmsg == nullptr) { +/** Reads \a cmsg to derive timestamps from the control messages. If a valid + * timestamp is found, the traced buffer list is updated with this timestamp. + * The caller of this function should be looping on the control messages found + * in \a msg. \a cmsg should point to the control message that the caller wants + * processed. + * On return, a pointer to a control message is returned. On the next iteration, + * CMSG_NXTHDR(msg, ret_val) should be passed as \a cmsg. */ +struct cmsghdr* process_timestamp(grpc_tcp* tcp, msghdr* msg, + struct cmsghdr* cmsg) { + auto next_cmsg = CMSG_NXTHDR(msg, cmsg); + cmsghdr* opt_stats = nullptr; + if (next_cmsg == nullptr) { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { - gpr_log(GPR_ERROR, "Received timestamp without extended error"); - } - return cmsg; - } - - /* Check if next_cmsg is an OPT_STATS msg */ - if (next_cmsg->cmsg_level == SOL_SOCKET && - next_cmsg->cmsg_type == SCM_TIMESTAMPING_OPT_STATS) { - opt_stats = next_cmsg; - next_cmsg = CMSG_NXTHDR(msg, opt_stats); - if (next_cmsg == nullptr) { + gpr_log(GPR_ERROR, "Received timestamp without extended error"); + } + return cmsg; + } + + /* Check if next_cmsg is an OPT_STATS msg */ + if (next_cmsg->cmsg_level == SOL_SOCKET && + next_cmsg->cmsg_type == SCM_TIMESTAMPING_OPT_STATS) { + opt_stats = next_cmsg; + next_cmsg = CMSG_NXTHDR(msg, opt_stats); + if (next_cmsg == nullptr) { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { - gpr_log(GPR_ERROR, "Received timestamp without extended error"); - } - return opt_stats; - } - } - - if (!(next_cmsg->cmsg_level == SOL_IP || next_cmsg->cmsg_level == SOL_IPV6) || - !(next_cmsg->cmsg_type == IP_RECVERR || - next_cmsg->cmsg_type == IPV6_RECVERR)) { + gpr_log(GPR_ERROR, "Received timestamp without extended error"); + } + return opt_stats; + } + } + + if (!(next_cmsg->cmsg_level == SOL_IP || next_cmsg->cmsg_level == SOL_IPV6) || + !(next_cmsg->cmsg_type == IP_RECVERR || + next_cmsg->cmsg_type == IPV6_RECVERR)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { - gpr_log(GPR_ERROR, "Unexpected control message"); - } - return cmsg; - } - - auto tss = - reinterpret_cast<struct grpc_core::scm_timestamping*>(CMSG_DATA(cmsg)); - auto serr = reinterpret_cast<struct sock_extended_err*>(CMSG_DATA(next_cmsg)); - if (serr->ee_errno != ENOMSG || - serr->ee_origin != SO_EE_ORIGIN_TIMESTAMPING) { - gpr_log(GPR_ERROR, "Unexpected control message"); - return cmsg; - } - /* The error handling can potentially be done on another thread so we need - * to protect the traced buffer list. A lock free list might be better. Using - * a simple mutex for now. */ - gpr_mu_lock(&tcp->tb_mu); - grpc_core::TracedBuffer::ProcessTimestamp(&tcp->tb_head, serr, opt_stats, - tss); - gpr_mu_unlock(&tcp->tb_mu); - return next_cmsg; -} - -/** For linux platforms, reads the socket's error queue and processes error - * messages from the queue. - */ + gpr_log(GPR_ERROR, "Unexpected control message"); + } + return cmsg; + } + + auto tss = + reinterpret_cast<struct grpc_core::scm_timestamping*>(CMSG_DATA(cmsg)); + auto serr = reinterpret_cast<struct sock_extended_err*>(CMSG_DATA(next_cmsg)); + if (serr->ee_errno != ENOMSG || + serr->ee_origin != SO_EE_ORIGIN_TIMESTAMPING) { + gpr_log(GPR_ERROR, "Unexpected control message"); + return cmsg; + } + /* The error handling can potentially be done on another thread so we need + * to protect the traced buffer list. A lock free list might be better. Using + * a simple mutex for now. */ + gpr_mu_lock(&tcp->tb_mu); + grpc_core::TracedBuffer::ProcessTimestamp(&tcp->tb_head, serr, opt_stats, + tss); + gpr_mu_unlock(&tcp->tb_mu); + return next_cmsg; +} + +/** For linux platforms, reads the socket's error queue and processes error + * messages from the queue. + */ static bool process_errors(grpc_tcp* tcp) { bool processed_err = false; struct iovec iov; @@ -1161,29 +1161,29 @@ static bool process_errors(grpc_tcp* tcp) { msg.msg_control = aligned_buf.rbuf; msg.msg_controllen = sizeof(aligned_buf.rbuf); int r, saved_errno; - while (true) { - do { - r = recvmsg(tcp->fd, &msg, MSG_ERRQUEUE); - saved_errno = errno; - } while (r < 0 && saved_errno == EINTR); - - if (r == -1 && saved_errno == EAGAIN) { + while (true) { + do { + r = recvmsg(tcp->fd, &msg, MSG_ERRQUEUE); + saved_errno = errno; + } while (r < 0 && saved_errno == EINTR); + + if (r == -1 && saved_errno == EAGAIN) { return processed_err; /* No more errors to process */ - } - if (r == -1) { + } + if (r == -1) { return processed_err; - } + } if (GPR_UNLIKELY((msg.msg_flags & MSG_CTRUNC) != 0)) { - gpr_log(GPR_ERROR, "Error message was truncated."); - } - - if (msg.msg_controllen == 0) { - /* There was no control message found. It was probably spurious. */ + gpr_log(GPR_ERROR, "Error message was truncated."); + } + + if (msg.msg_controllen == 0) { + /* There was no control message found. It was probably spurious. */ return processed_err; - } - bool seen = false; - for (auto cmsg = CMSG_FIRSTHDR(&msg); cmsg && cmsg->cmsg_len; - cmsg = CMSG_NXTHDR(&msg, cmsg)) { + } + bool seen = false; + for (auto cmsg = CMSG_FIRSTHDR(&msg); cmsg && cmsg->cmsg_len; + cmsg = CMSG_NXTHDR(&msg, cmsg)) { if (CmsgIsZeroCopy(*cmsg)) { process_zerocopy(tcp, cmsg); seen = true; @@ -1197,46 +1197,46 @@ static bool process_errors(grpc_tcp* tcp) { /* Got a control message that is not a timestamp or zerocopy. Don't know * how to handle this. */ if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { - gpr_log(GPR_INFO, - "unknown control message cmsg_level:%d cmsg_type:%d", - cmsg->cmsg_level, cmsg->cmsg_type); - } + gpr_log(GPR_INFO, + "unknown control message cmsg_level:%d cmsg_type:%d", + cmsg->cmsg_level, cmsg->cmsg_type); + } return processed_err; - } - } - if (!seen) { + } + } + if (!seen) { return processed_err; - } - } -} - -static void tcp_handle_error(void* arg /* grpc_tcp */, grpc_error* error) { - grpc_tcp* tcp = static_cast<grpc_tcp*>(arg); + } + } +} + +static void tcp_handle_error(void* arg /* grpc_tcp */, grpc_error* error) { + grpc_tcp* tcp = static_cast<grpc_tcp*>(arg); if (GRPC_TRACE_FLAG_ENABLED(grpc_tcp_trace)) { - gpr_log(GPR_INFO, "TCP:%p got_error: %s", tcp, grpc_error_string(error)); - } - - if (error != GRPC_ERROR_NONE || - static_cast<bool>(gpr_atm_acq_load(&tcp->stop_error_notification))) { - /* We aren't going to register to hear on error anymore, so it is safe to - * unref. */ - TCP_UNREF(tcp, "error-tracking"); - return; - } - - /* We are still interested in collecting timestamps, so let's try reading - * them. */ + gpr_log(GPR_INFO, "TCP:%p got_error: %s", tcp, grpc_error_string(error)); + } + + if (error != GRPC_ERROR_NONE || + static_cast<bool>(gpr_atm_acq_load(&tcp->stop_error_notification))) { + /* We aren't going to register to hear on error anymore, so it is safe to + * unref. */ + TCP_UNREF(tcp, "error-tracking"); + return; + } + + /* We are still interested in collecting timestamps, so let's try reading + * them. */ bool processed = process_errors(tcp); - /* This might not a timestamps error. Set the read and write closures to be - * ready. */ + /* This might not a timestamps error. Set the read and write closures to be + * ready. */ if (!processed) { grpc_fd_set_readable(tcp->em_fd); grpc_fd_set_writable(tcp->em_fd); } - grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure); -} - -#else /* GRPC_LINUX_ERRQUEUE */ + grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure); +} + +#else /* GRPC_LINUX_ERRQUEUE */ static TcpZerocopySendRecord* tcp_get_send_zerocopy_record( grpc_tcp* tcp, grpc_slice_buffer* buf) { return nullptr; @@ -1248,36 +1248,36 @@ static bool tcp_write_with_timestamps(grpc_tcp* /*tcp*/, struct msghdr* /*msg*/, size_t /*sending_length*/, ssize_t* /*sent_length*/, int /*additional_flags*/) { - gpr_log(GPR_ERROR, "Write with timestamps not supported for this platform"); - GPR_ASSERT(0); - return false; -} - + gpr_log(GPR_ERROR, "Write with timestamps not supported for this platform"); + GPR_ASSERT(0); + return false; +} + static void tcp_handle_error(void* /*arg*/ /* grpc_tcp */, grpc_error* /*error*/) { - gpr_log(GPR_ERROR, "Error handling is not supported for this platform"); - GPR_ASSERT(0); -} -#endif /* GRPC_LINUX_ERRQUEUE */ - -/* If outgoing_buffer_arg is filled, shuts down the list early, so that any - * release operations needed can be performed on the arg */ -void tcp_shutdown_buffer_list(grpc_tcp* tcp) { - if (tcp->outgoing_buffer_arg) { - gpr_mu_lock(&tcp->tb_mu); - grpc_core::TracedBuffer::Shutdown( - &tcp->tb_head, tcp->outgoing_buffer_arg, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("TracedBuffer list shutdown")); - gpr_mu_unlock(&tcp->tb_mu); - tcp->outgoing_buffer_arg = nullptr; - } -} - -#if defined(IOV_MAX) && IOV_MAX < 1000 -#define MAX_WRITE_IOVEC IOV_MAX -#else + gpr_log(GPR_ERROR, "Error handling is not supported for this platform"); + GPR_ASSERT(0); +} +#endif /* GRPC_LINUX_ERRQUEUE */ + +/* If outgoing_buffer_arg is filled, shuts down the list early, so that any + * release operations needed can be performed on the arg */ +void tcp_shutdown_buffer_list(grpc_tcp* tcp) { + if (tcp->outgoing_buffer_arg) { + gpr_mu_lock(&tcp->tb_mu); + grpc_core::TracedBuffer::Shutdown( + &tcp->tb_head, tcp->outgoing_buffer_arg, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("TracedBuffer list shutdown")); + gpr_mu_unlock(&tcp->tb_mu); + tcp->outgoing_buffer_arg = nullptr; + } +} + +#if defined(IOV_MAX) && IOV_MAX < 1000 +#define MAX_WRITE_IOVEC IOV_MAX +#else #define MAX_WRITE_IOVEC 1000 -#endif +#endif msg_iovlen_type TcpZerocopySendRecord::PopulateIovs(size_t* unwind_slice_idx, size_t* unwind_byte_idx, size_t* sending_length, @@ -1410,7 +1410,7 @@ static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) { struct msghdr msg; struct iovec iov[MAX_WRITE_IOVEC]; msg_iovlen_type iov_size; - ssize_t sent_length = 0; + ssize_t sent_length = 0; size_t sending_length; size_t trailing; size_t unwind_slice_idx; @@ -1445,27 +1445,27 @@ static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) { msg.msg_iov = iov; msg.msg_iovlen = iov_size; msg.msg_flags = 0; - bool tried_sending_message = false; - if (tcp->outgoing_buffer_arg != nullptr) { - if (!tcp->ts_capable || - !tcp_write_with_timestamps(tcp, &msg, sending_length, &sent_length)) { - /* We could not set socket options to collect Fathom timestamps. - * Fallback on writing without timestamps. */ - tcp->ts_capable = false; - tcp_shutdown_buffer_list(tcp); - } else { - tried_sending_message = true; - } - } - if (!tried_sending_message) { - msg.msg_control = nullptr; - msg.msg_controllen = 0; - - GRPC_STATS_INC_TCP_WRITE_SIZE(sending_length); - GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(iov_size); - - sent_length = tcp_send(tcp->fd, &msg); - } + bool tried_sending_message = false; + if (tcp->outgoing_buffer_arg != nullptr) { + if (!tcp->ts_capable || + !tcp_write_with_timestamps(tcp, &msg, sending_length, &sent_length)) { + /* We could not set socket options to collect Fathom timestamps. + * Fallback on writing without timestamps. */ + tcp->ts_capable = false; + tcp_shutdown_buffer_list(tcp); + } else { + tried_sending_message = true; + } + } + if (!tried_sending_message) { + msg.msg_control = nullptr; + msg.msg_controllen = 0; + + GRPC_STATS_INC_TCP_WRITE_SIZE(sending_length); + GRPC_STATS_INC_TCP_WRITE_IOV_SIZE(iov_size); + + sent_length = tcp_send(tcp->fd, &msg); + } if (sent_length < 0) { if (errno == EAGAIN) { @@ -1479,18 +1479,18 @@ static bool tcp_flush(grpc_tcp* tcp, grpc_error** error) { } else if (errno == EPIPE) { *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp); grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer); - tcp_shutdown_buffer_list(tcp); + tcp_shutdown_buffer_list(tcp); return true; } else { *error = tcp_annotate_error(GRPC_OS_ERROR(errno, "sendmsg"), tcp); grpc_slice_buffer_reset_and_unref_internal(tcp->outgoing_buffer); - tcp_shutdown_buffer_list(tcp); + tcp_shutdown_buffer_list(tcp); return true; } } GPR_ASSERT(tcp->outgoing_byte_idx == 0); - tcp->bytes_counter += sent_length; + tcp->bytes_counter += sent_length; trailing = sending_length - static_cast<size_t>(sent_length); while (trailing > 0) { size_t slice_length; @@ -1556,7 +1556,7 @@ static void tcp_handle_write(void* arg /* grpc_tcp */, grpc_error* error) { } static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf, - grpc_closure* cb, void* arg) { + grpc_closure* cb, void* arg) { GPR_TIMER_SCOPE("tcp_write", 0); grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep); grpc_error* error = GRPC_ERROR_NONE; @@ -1567,12 +1567,12 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf, for (i = 0; i < buf->count; i++) { gpr_log(GPR_INFO, "WRITE %p (peer=%s)", tcp, tcp->peer_string.c_str()); - if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) { - char* data = - grpc_dump_slice(buf->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); - gpr_log(GPR_DEBUG, "DATA: %s", data); - gpr_free(data); - } + if (gpr_should_log(GPR_LOG_SEVERITY_DEBUG)) { + char* data = + grpc_dump_slice(buf->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); + gpr_log(GPR_DEBUG, "DATA: %s", data); + gpr_free(data); + } } } @@ -1586,7 +1586,7 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf, ? tcp_annotate_error(GRPC_ERROR_CREATE_FROM_STATIC_STRING("EOF"), tcp) : GRPC_ERROR_NONE); - tcp_shutdown_buffer_list(tcp); + tcp_shutdown_buffer_list(tcp); return; } @@ -1597,9 +1597,9 @@ static void tcp_write(grpc_endpoint* ep, grpc_slice_buffer* buf, tcp->outgoing_byte_idx = 0; } tcp->outgoing_buffer_arg = arg; - if (arg) { - GPR_ASSERT(grpc_event_engine_can_track_errors()); - } + if (arg) { + GPR_ASSERT(grpc_event_engine_can_track_errors()); + } bool flush_result = zerocopy_send_record != nullptr @@ -1660,22 +1660,22 @@ static grpc_resource_user* tcp_get_resource_user(grpc_endpoint* ep) { return tcp->resource_user; } -static bool tcp_can_track_err(grpc_endpoint* ep) { - grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep); - if (!grpc_event_engine_can_track_errors()) { - return false; - } - struct sockaddr addr; - socklen_t len = sizeof(addr); - if (getsockname(tcp->fd, &addr, &len) < 0) { - return false; - } - if (addr.sa_family == AF_INET || addr.sa_family == AF_INET6) { - return true; - } - return false; -} - +static bool tcp_can_track_err(grpc_endpoint* ep) { + grpc_tcp* tcp = reinterpret_cast<grpc_tcp*>(ep); + if (!grpc_event_engine_can_track_errors()) { + return false; + } + struct sockaddr addr; + socklen_t len = sizeof(addr); + if (getsockname(tcp->fd, &addr, &len) < 0) { + return false; + } + if (addr.sa_family == AF_INET || addr.sa_family == AF_INET6) { + return true; + } + return false; +} + static const grpc_endpoint_vtable vtable = {tcp_read, tcp_write, tcp_add_to_pollset, @@ -1686,8 +1686,8 @@ static const grpc_endpoint_vtable vtable = {tcp_read, tcp_get_resource_user, tcp_get_peer, tcp_get_local_address, - tcp_get_fd, - tcp_can_track_err}; + tcp_get_fd, + tcp_can_track_err}; #define MAX_CHUNK_SIZE 32 * 1024 * 1024 @@ -1779,12 +1779,12 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd, tcp->min_read_chunk_size = tcp_min_read_chunk_size; tcp->max_read_chunk_size = tcp_max_read_chunk_size; tcp->bytes_read_this_round = 0; - /* Will be set to false by the very first endpoint read function */ - tcp->is_first_read = true; - tcp->bytes_counter = -1; - tcp->socket_ts_enabled = false; - tcp->ts_capable = true; - tcp->outgoing_buffer_arg = nullptr; + /* Will be set to false by the very first endpoint read function */ + tcp->is_first_read = true; + tcp->bytes_counter = -1; + tcp->socket_ts_enabled = false; + tcp->ts_capable = true; + tcp->outgoing_buffer_arg = nullptr; if (tcp_tx_zerocopy_enabled && !tcp->tcp_zerocopy_send_ctx.memory_limited()) { #ifdef GRPC_LINUX_ERRQUEUE const int enable = 1; @@ -1806,8 +1806,8 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd, grpc_resource_user_slice_allocator_init( &tcp->slice_allocator, tcp->resource_user, tcp_read_allocation_done, tcp); grpc_resource_quota_unref_internal(resource_quota); - gpr_mu_init(&tcp->tb_mu); - tcp->tb_head = nullptr; + gpr_mu_init(&tcp->tb_mu); + tcp->tb_head = nullptr; GRPC_CLOSURE_INIT(&tcp->read_done_closure, tcp_handle_read, tcp, grpc_schedule_on_exec_ctx); if (grpc_event_engine_run_in_background()) { @@ -1833,17 +1833,17 @@ grpc_endpoint* grpc_tcp_create(grpc_fd* em_fd, #else tcp->inq_capable = false; #endif /* GRPC_HAVE_TCP_INQ */ - /* Start being notified on errors if event engine can track errors. */ - if (grpc_event_engine_can_track_errors()) { - /* Grab a ref to tcp so that we can safely access the tcp struct when - * processing errors. We unref when we no longer want to track errors - * separately. */ - TCP_REF(tcp, "error-tracking"); - gpr_atm_rel_store(&tcp->stop_error_notification, 0); - GRPC_CLOSURE_INIT(&tcp->error_closure, tcp_handle_error, tcp, - grpc_schedule_on_exec_ctx); - grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure); - } + /* Start being notified on errors if event engine can track errors. */ + if (grpc_event_engine_can_track_errors()) { + /* Grab a ref to tcp so that we can safely access the tcp struct when + * processing errors. We unref when we no longer want to track errors + * separately. */ + TCP_REF(tcp, "error-tracking"); + gpr_atm_rel_store(&tcp->stop_error_notification, 0); + GRPC_CLOSURE_INIT(&tcp->error_closure, tcp_handle_error, tcp, + grpc_schedule_on_exec_ctx); + grpc_fd_notify_on_error(tcp->em_fd, &tcp->error_closure); + } return &tcp->base; } @@ -1861,13 +1861,13 @@ void grpc_tcp_destroy_and_release_fd(grpc_endpoint* ep, int* fd, tcp->release_fd = fd; tcp->release_fd_cb = done; grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer); - if (grpc_event_engine_can_track_errors()) { - /* Stop errors notification. */ + if (grpc_event_engine_can_track_errors()) { + /* Stop errors notification. */ ZerocopyDisableAndWaitForRemaining(tcp); - gpr_atm_no_barrier_store(&tcp->stop_error_notification, true); - grpc_fd_set_error(tcp->em_fd); - } + gpr_atm_no_barrier_store(&tcp->stop_error_notification, true); + grpc_fd_set_error(tcp->em_fd); + } TCP_UNREF(tcp, "destroy"); } -#endif /* GRPC_POSIX_SOCKET_TCP */ +#endif /* GRPC_POSIX_SOCKET_TCP */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h index eff825cb92..cf1011027b 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_posix.h @@ -31,10 +31,10 @@ #include <grpc/support/port_platform.h> -#include "src/core/lib/iomgr/port.h" - +#include "src/core/lib/iomgr/port.h" + #include "src/core/lib/debug/trace.h" -#include "src/core/lib/iomgr/buffer_list.h" +#include "src/core/lib/iomgr/buffer_list.h" #include "src/core/lib/iomgr/endpoint.h" #include "src/core/lib/iomgr/ev_posix.h" diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc index b3f3febe63..380f0c0f5d 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_posix.cc @@ -25,7 +25,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_TCP_SERVER +#ifdef GRPC_POSIX_SOCKET_TCP_SERVER #include <errno.h> #include <fcntl.h> @@ -158,7 +158,7 @@ static void deactivated_all_ports(grpc_tcp_server* s) { GRPC_CLOSURE_INIT(&sp->destroyed_closure, destroyed_port, s, grpc_schedule_on_exec_ctx); grpc_fd_orphan(sp->emfd, &sp->destroyed_closure, nullptr, - "tcp_listener_shutdown"); + "tcp_listener_shutdown"); } gpr_mu_unlock(&s->mu); } else { @@ -251,7 +251,7 @@ static void on_read(void* arg, grpc_error* err) { [static_cast<size_t>(gpr_atm_no_barrier_fetch_add( &sp->server->next_pollset_to_assign, 1)) % sp->server->pollsets->size()]; - + grpc_pollset_add_fd(read_notifier_pollset, fdobj); // Create acceptor. @@ -362,8 +362,8 @@ static grpc_error* clone_port(grpc_tcp_listener* listener, unsigned count) { err = grpc_create_dualstack_socket(&listener->addr, SOCK_STREAM, 0, &dsmode, &fd); if (err != GRPC_ERROR_NONE) return err; - err = grpc_tcp_server_prepare_socket(listener->server, fd, &listener->addr, - true, &port); + err = grpc_tcp_server_prepare_socket(listener->server, fd, &listener->addr, + true, &port); if (err != GRPC_ERROR_NONE) return err; listener->server->nports++; addr_str = grpc_sockaddr_to_string(&listener->addr, true); @@ -628,4 +628,4 @@ grpc_tcp_server_vtable grpc_posix_tcp_server_vtable = { tcp_server_ref, tcp_server_shutdown_starting_add, tcp_server_unref, tcp_server_shutdown_listeners}; -#endif /* GRPC_POSIX_SOCKET_TCP_SERVER */ +#endif /* GRPC_POSIX_SOCKET_TCP_SERVER */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h index 6b8a5f9f20..7f5b55a193 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix.h @@ -115,7 +115,7 @@ grpc_error* grpc_tcp_server_add_all_local_addrs(grpc_tcp_server* s, int* out_port); /* Prepare a recently-created socket for listening. */ -grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server*, int fd, +grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server*, int fd, const grpc_resolved_address* addr, bool so_reuseport, int* port); /* Ruturn true if the platform supports ifaddrs */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc index 46bc18e5a0..0d322c773f 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_server_utils_posix_common.cc @@ -20,7 +20,7 @@ #include "src/core/lib/iomgr/port.h" -#ifdef GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON +#ifdef GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON #include "src/core/lib/iomgr/tcp_server_utils_posix.h" @@ -88,7 +88,7 @@ static grpc_error* add_socket_to_server(grpc_tcp_server* s, int fd, int port = -1; grpc_error* err = - grpc_tcp_server_prepare_socket(s, fd, addr, s->so_reuseport, &port); + grpc_tcp_server_prepare_socket(s, fd, addr, s->so_reuseport, &port); if (err == GRPC_ERROR_NONE) { GPR_ASSERT(port > 0); TString addr_str = grpc_sockaddr_to_string(addr, true); @@ -143,7 +143,7 @@ grpc_error* grpc_tcp_server_add_addr(grpc_tcp_server* s, } /* Prepare a recently-created socket for listening. */ -grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server* s, int fd, +grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server* s, int fd, const grpc_resolved_address* addr, bool so_reuseport, int* port) { grpc_resolved_address sockname_temp; @@ -173,16 +173,16 @@ grpc_error* grpc_tcp_server_prepare_socket(grpc_tcp_server* s, int fd, if (err != GRPC_ERROR_NONE) goto error; err = grpc_set_socket_reuse_addr(fd, 1); if (err != GRPC_ERROR_NONE) goto error; - err = grpc_set_socket_tcp_user_timeout(fd, s->channel_args, - false /* is_client */); - if (err != GRPC_ERROR_NONE) goto error; + err = grpc_set_socket_tcp_user_timeout(fd, s->channel_args, + false /* is_client */); + if (err != GRPC_ERROR_NONE) goto error; } err = grpc_set_socket_no_sigpipe_if_possible(fd); if (err != GRPC_ERROR_NONE) goto error; err = grpc_apply_socket_mutator_in_args(fd, s->channel_args); if (err != GRPC_ERROR_NONE) goto error; - + if (bind(fd, reinterpret_cast<grpc_sockaddr*>(const_cast<char*>(addr->addr)), addr->len) < 0) { err = GRPC_OS_ERROR(errno, "bind"); @@ -218,4 +218,4 @@ error: return ret; } -#endif /* GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON */ +#endif /* GRPC_POSIX_SOCKET_TCP_SERVER_UTILS_COMMON */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc index 3d410a2d3f..48613d7c42 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.cc @@ -41,7 +41,7 @@ #include "src/core/lib/iomgr/tcp_windows.h" #include "src/core/lib/iomgr/timer.h" #include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/slice/slice_string_helpers.h" +#include "src/core/lib/slice/slice_string_helpers.h" #if defined(__MSYS__) && defined(GPR_ARCH_64) /* Nasty workaround for nasty bug when using the 64 bits msys compiler @@ -53,7 +53,7 @@ extern grpc_core::TraceFlag grpc_tcp_trace; -grpc_error* grpc_tcp_set_non_block(SOCKET sock) { +grpc_error* grpc_tcp_set_non_block(SOCKET sock) { int status; uint32_t param = 1; DWORD ret; @@ -88,7 +88,7 @@ static grpc_error* enable_socket_low_latency(SOCKET sock) { grpc_error* grpc_tcp_prepare_socket(SOCKET sock) { grpc_error* err; - err = grpc_tcp_set_non_block(sock); + err = grpc_tcp_set_non_block(sock); if (err != GRPC_ERROR_NONE) return err; err = set_dualstack(sock); if (err != GRPC_ERROR_NONE) return err; @@ -110,10 +110,10 @@ typedef struct grpc_tcp { grpc_closure* read_cb; grpc_closure* write_cb; - - /* garbage after the last read */ - grpc_slice_buffer last_read_buffer; - + + /* garbage after the last read */ + grpc_slice_buffer last_read_buffer; + grpc_slice_buffer* write_slices; grpc_slice_buffer* read_slices; @@ -132,7 +132,7 @@ typedef struct grpc_tcp { static void tcp_free(grpc_tcp* tcp) { grpc_winsocket_destroy(tcp->socket); gpr_mu_destroy(&tcp->mu); - grpc_slice_buffer_destroy_internal(&tcp->last_read_buffer); + grpc_slice_buffer_destroy_internal(&tcp->last_read_buffer); grpc_resource_user_unref(tcp->resource_user); if (tcp->shutting_down) GRPC_ERROR_UNREF(tcp->shutdown_error); delete tcp; @@ -183,10 +183,10 @@ static void on_read(void* tcpp, grpc_error* error) { grpc_winsocket* socket = tcp->socket; grpc_winsocket_callback_info* info = &socket->read_info; - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_INFO, "TCP:%p on_read", tcp); - } - + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_INFO, "TCP:%p on_read", tcp); + } + GRPC_ERROR_REF(error); if (error == GRPC_ERROR_NONE) { @@ -194,35 +194,35 @@ static void on_read(void* tcpp, grpc_error* error) { char* utf8_message = gpr_format_message(info->wsa_error); error = GRPC_ERROR_CREATE_FROM_COPIED_STRING(utf8_message); gpr_free(utf8_message); - grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices); + grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices); } else { if (info->bytes_transferred != 0 && !tcp->shutting_down) { GPR_ASSERT((size_t)info->bytes_transferred <= tcp->read_slices->length); if (static_cast<size_t>(info->bytes_transferred) != - tcp->read_slices->length) { - grpc_slice_buffer_trim_end( - tcp->read_slices, - tcp->read_slices->length - + tcp->read_slices->length) { + grpc_slice_buffer_trim_end( + tcp->read_slices, + tcp->read_slices->length - static_cast<size_t>(info->bytes_transferred), - &tcp->last_read_buffer); - } + &tcp->last_read_buffer); + } GPR_ASSERT((size_t)info->bytes_transferred == tcp->read_slices->length); - - if (grpc_tcp_trace.enabled()) { - size_t i; - for (i = 0; i < tcp->read_slices->count; i++) { - char* dump = grpc_dump_slice(tcp->read_slices->slices[i], - GPR_DUMP_HEX | GPR_DUMP_ASCII); + + if (grpc_tcp_trace.enabled()) { + size_t i; + for (i = 0; i < tcp->read_slices->count; i++) { + char* dump = grpc_dump_slice(tcp->read_slices->slices[i], + GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_INFO, "READ %p (peer=%s): %s", tcp, tcp->peer_string.c_str(), dump); - gpr_free(dump); - } - } + gpr_free(dump); + } + } } else { - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_INFO, "TCP:%p unref read_slice", tcp); - } - grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices); + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_INFO, "TCP:%p unref read_slice", tcp); + } + grpc_slice_buffer_reset_and_unref_internal(tcp->read_slices); error = tcp->shutting_down ? GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( "TCP stream shutting down", &tcp->shutdown_error, 1) @@ -236,8 +236,8 @@ static void on_read(void* tcpp, grpc_error* error) { grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error); } -#define DEFAULT_TARGET_READ_SIZE 8192 -#define MAX_WSABUF_COUNT 16 +#define DEFAULT_TARGET_READ_SIZE 8192 +#define MAX_WSABUF_COUNT 16 static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices, grpc_closure* cb, bool urgent) { grpc_tcp* tcp = (grpc_tcp*)ep; @@ -246,13 +246,13 @@ static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices, int status; DWORD bytes_read = 0; DWORD flags = 0; - WSABUF buffers[MAX_WSABUF_COUNT]; - size_t i; - - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_INFO, "TCP:%p win_read", tcp); - } + WSABUF buffers[MAX_WSABUF_COUNT]; + size_t i; + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_INFO, "TCP:%p win_read", tcp); + } + if (tcp->shutting_down) { grpc_core::ExecCtx::Run( DEBUG_LOCATION, cb, @@ -264,27 +264,27 @@ static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices, tcp->read_cb = cb; tcp->read_slices = read_slices; grpc_slice_buffer_reset_and_unref_internal(read_slices); - grpc_slice_buffer_swap(read_slices, &tcp->last_read_buffer); - - if (tcp->read_slices->length < DEFAULT_TARGET_READ_SIZE / 2 && - tcp->read_slices->count < MAX_WSABUF_COUNT) { - // TODO(jtattermusch): slice should be allocated using resource quota - grpc_slice_buffer_add(tcp->read_slices, - GRPC_SLICE_MALLOC(DEFAULT_TARGET_READ_SIZE)); - } - - GPR_ASSERT(tcp->read_slices->count <= MAX_WSABUF_COUNT); - for (i = 0; i < tcp->read_slices->count; i++) { - buffers[i].len = (ULONG)GRPC_SLICE_LENGTH( - tcp->read_slices->slices[i]); // we know slice size fits in 32bit. - buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[i]); - } + grpc_slice_buffer_swap(read_slices, &tcp->last_read_buffer); + + if (tcp->read_slices->length < DEFAULT_TARGET_READ_SIZE / 2 && + tcp->read_slices->count < MAX_WSABUF_COUNT) { + // TODO(jtattermusch): slice should be allocated using resource quota + grpc_slice_buffer_add(tcp->read_slices, + GRPC_SLICE_MALLOC(DEFAULT_TARGET_READ_SIZE)); + } + + GPR_ASSERT(tcp->read_slices->count <= MAX_WSABUF_COUNT); + for (i = 0; i < tcp->read_slices->count; i++) { + buffers[i].len = (ULONG)GRPC_SLICE_LENGTH( + tcp->read_slices->slices[i]); // we know slice size fits in 32bit. + buffers[i].buf = (char*)GRPC_SLICE_START_PTR(tcp->read_slices->slices[i]); + } TCP_REF(tcp, "read"); /* First let's try a synchronous, non-blocking read. */ - status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count, - &bytes_read, &flags, NULL, NULL); + status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count, + &bytes_read, &flags, NULL, NULL); info->wsa_error = status == 0 ? 0 : WSAGetLastError(); /* Did we get data immediately ? Yay. */ @@ -296,8 +296,8 @@ static void win_read(grpc_endpoint* ep, grpc_slice_buffer* read_slices, /* Otherwise, let's retry, by queuing a read. */ memset(&tcp->socket->read_info.overlapped, 0, sizeof(OVERLAPPED)); - status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count, - &bytes_read, &flags, &info->overlapped, NULL); + status = WSARecv(tcp->socket->socket, buffers, (DWORD)tcp->read_slices->count, + &bytes_read, &flags, &info->overlapped, NULL); if (status != 0) { int wsa_error = WSAGetLastError(); @@ -319,10 +319,10 @@ static void on_write(void* tcpp, grpc_error* error) { grpc_winsocket_callback_info* info = &handle->write_info; grpc_closure* cb; - if (grpc_tcp_trace.enabled()) { - gpr_log(GPR_INFO, "TCP:%p on_write", tcp); - } - + if (grpc_tcp_trace.enabled()) { + gpr_log(GPR_INFO, "TCP:%p on_write", tcp); + } + GRPC_ERROR_REF(error); gpr_mu_lock(&tcp->mu); @@ -344,29 +344,29 @@ static void on_write(void* tcpp, grpc_error* error) { /* Initiates a write. */ static void win_write(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* arg) { + grpc_closure* cb, void* arg) { grpc_tcp* tcp = (grpc_tcp*)ep; grpc_winsocket* socket = tcp->socket; grpc_winsocket_callback_info* info = &socket->write_info; unsigned i; DWORD bytes_sent; int status; - WSABUF local_buffers[MAX_WSABUF_COUNT]; + WSABUF local_buffers[MAX_WSABUF_COUNT]; WSABUF* allocated = NULL; WSABUF* buffers = local_buffers; size_t len; - if (grpc_tcp_trace.enabled()) { - size_t i; - for (i = 0; i < slices->count; i++) { - char* data = - grpc_dump_slice(slices->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); + if (grpc_tcp_trace.enabled()) { + size_t i; + for (i = 0; i < slices->count; i++) { + char* data = + grpc_dump_slice(slices->slices[i], GPR_DUMP_HEX | GPR_DUMP_ASCII); gpr_log(GPR_INFO, "WRITE %p (peer=%s): %s", tcp, tcp->peer_string.c_str(), data); - gpr_free(data); - } - } - + gpr_free(data); + } + } + if (tcp->shutting_down) { grpc_core::ExecCtx::Run( DEBUG_LOCATION, cb, @@ -472,7 +472,7 @@ static void win_shutdown(grpc_endpoint* ep, grpc_error* why) { static void win_destroy(grpc_endpoint* ep) { grpc_tcp* tcp = (grpc_tcp*)ep; - grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer); + grpc_slice_buffer_reset_and_unref_internal(&tcp->last_read_buffer); TCP_UNREF(tcp, "destroy"); } @@ -493,8 +493,8 @@ static grpc_resource_user* win_get_resource_user(grpc_endpoint* ep) { static int win_get_fd(grpc_endpoint* ep) { return -1; } -static bool win_can_track_err(grpc_endpoint* ep) { return false; } - +static bool win_can_track_err(grpc_endpoint* ep) { return false; } + static grpc_endpoint_vtable vtable = {win_read, win_write, win_add_to_pollset, @@ -505,8 +505,8 @@ static grpc_endpoint_vtable vtable = {win_read, win_get_resource_user, win_get_peer, win_get_local_address, - win_get_fd, - win_can_track_err}; + win_get_fd, + win_can_track_err}; grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket, grpc_channel_args* channel_args, @@ -539,7 +539,7 @@ grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket, tcp->local_address = grpc_sockaddr_to_uri(&resolved_local_addr); } tcp->peer_string = peer_string; - grpc_slice_buffer_init(&tcp->last_read_buffer); + grpc_slice_buffer_init(&tcp->last_read_buffer); tcp->resource_user = grpc_resource_user_create(resource_quota, peer_string); grpc_resource_quota_unref_internal(resource_quota); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h index 04ef8102b6..07f983d7d2 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/tcp_windows.h @@ -46,8 +46,8 @@ grpc_endpoint* grpc_tcp_create(grpc_winsocket* socket, grpc_error* grpc_tcp_prepare_socket(SOCKET sock); -grpc_error* grpc_tcp_set_non_block(SOCKET sock); - +grpc_error* grpc_tcp_set_non_block(SOCKET sock); + #endif #endif /* GRPC_CORE_LIB_IOMGR_TCP_WINDOWS_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer.h b/contrib/libs/grpc/src/core/lib/iomgr/timer.h index 11da149652..29eef0042f 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/timer.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/timer.h @@ -28,7 +28,7 @@ #include "src/core/lib/iomgr/iomgr.h" typedef struct grpc_timer { - grpc_millis deadline; + grpc_millis deadline; // Uninitialized if not using heap, or INVALID_HEAP_INDEX if not in heap. uint32_t heap_index; bool pending; @@ -62,11 +62,11 @@ typedef struct grpc_timer_vtable { /* Initialize *timer. When expired or canceled, closure will be called with error set to indicate if it expired (GRPC_ERROR_NONE) or was canceled - (GRPC_ERROR_CANCELLED). *closure is guaranteed to be called exactly once, and + (GRPC_ERROR_CANCELLED). *closure is guaranteed to be called exactly once, and application code should check the error to determine how it was invoked. The application callback is also responsible for maintaining information about - when to free up any user-level state. Behavior is undefined for a deadline of - GRPC_MILLIS_INF_FUTURE. */ + when to free up any user-level state. Behavior is undefined for a deadline of + GRPC_MILLIS_INF_FUTURE. */ void grpc_timer_init(grpc_timer* timer, grpc_millis deadline, grpc_closure* closure); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc index fb0e50c53c..d5811cbecd 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_generic.cc @@ -37,7 +37,7 @@ #include "src/core/lib/gpr/spinlock.h" #include "src/core/lib/gpr/tls.h" #include "src/core/lib/gpr/useful.h" -#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/iomgr/time_averaged_stats.h" #include "src/core/lib/iomgr/timer_heap.h" @@ -51,22 +51,22 @@ grpc_core::TraceFlag grpc_timer_trace(false, "timer"); grpc_core::TraceFlag grpc_timer_check_trace(false, "timer_check"); /* A "timer shard". Contains a 'heap' and a 'list' of timers. All timers with - * deadlines earlier than 'queue_deadline_cap' are maintained in the heap and + * deadlines earlier than 'queue_deadline_cap' are maintained in the heap and * others are maintained in the list (unordered). This helps to keep the number * of elements in the heap low. * * The 'queue_deadline_cap' gets recomputed periodically based on the timer * stats maintained in 'stats' and the relevant timers are then moved from the - * 'list' to 'heap'. + * 'list' to 'heap'. */ struct timer_shard { gpr_mu mu; grpc_time_averaged_stats stats; - /* All and only timers with deadlines < this will be in the heap. */ - grpc_millis queue_deadline_cap; - /* The deadline of the next timer due in this shard. */ - grpc_millis min_deadline; - /* Index of this timer_shard in the g_shard_queue. */ + /* All and only timers with deadlines < this will be in the heap. */ + grpc_millis queue_deadline_cap; + /* The deadline of the next timer due in this shard. */ + grpc_millis min_deadline; + /* Index of this timer_shard in the g_shard_queue. */ uint32_t shard_queue_index; /* This holds all timers with deadlines < queue_deadline_cap. Timers in this list have the top bit of their deadline set to 0. */ @@ -87,7 +87,7 @@ static timer_shard** g_shard_queue; #ifndef NDEBUG -/* == DEBUG ONLY: hash table for duplicate timer detection == */ +/* == DEBUG ONLY: hash table for duplicate timer detection == */ #define NUM_HASH_BUCKETS 1009 /* Prime number close to 1000 */ @@ -179,7 +179,7 @@ static void remove_from_ht(grpc_timer* t) { t->hash_table_next = nullptr; } -/* If a timer is added to a timer shard (either heap or a list), it must +/* If a timer is added to a timer shard (either heap or a list), it must * be pending. A timer is added to hash table only-if it is added to the * timer shard. * Therefore, if timer->pending is false, it cannot be in hash table */ @@ -212,23 +212,23 @@ static void validate_non_pending_timer(grpc_timer* t) { #endif -#if GPR_ARCH_64 -/* NOTE: TODO(sreek) - Currently the thread local storage support in grpc is - for intptr_t which means on 32-bit machines it is not wide enough to hold - grpc_millis which is 64-bit. Adding thread local support for 64 bit values - is a lot of work for very little gain. So we are currently restricting this - optimization to only 64 bit machines */ - +#if GPR_ARCH_64 +/* NOTE: TODO(sreek) - Currently the thread local storage support in grpc is + for intptr_t which means on 32-bit machines it is not wide enough to hold + grpc_millis which is 64-bit. Adding thread local support for 64 bit values + is a lot of work for very little gain. So we are currently restricting this + optimization to only 64 bit machines */ + /* Thread local variable that stores the deadline of the next timer the thread * has last-seen. This is an optimization to prevent the thread from checking * shared_mutables.min_timer (which requires acquiring shared_mutables.mu lock, * an expensive operation) */ GPR_TLS_DECL(g_last_seen_min_timer); -#endif +#endif struct shared_mutables { /* The deadline of the next timer due across all timer shards */ - grpc_millis min_timer; + grpc_millis min_timer; /* Allow only one run_some_expired_timers at once */ gpr_spinlock checker_mu; bool initialized; @@ -238,18 +238,18 @@ struct shared_mutables { static struct shared_mutables g_shared_mutables; -static grpc_millis saturating_add(grpc_millis a, grpc_millis b) { - if (a > GRPC_MILLIS_INF_FUTURE - b) { - return GRPC_MILLIS_INF_FUTURE; +static grpc_millis saturating_add(grpc_millis a, grpc_millis b) { + if (a > GRPC_MILLIS_INF_FUTURE - b) { + return GRPC_MILLIS_INF_FUTURE; } return a + b; } -static grpc_timer_check_result run_some_expired_timers(grpc_millis now, - grpc_millis* next, +static grpc_timer_check_result run_some_expired_timers(grpc_millis now, + grpc_millis* next, grpc_error* error); -static grpc_millis compute_min_deadline(timer_shard* shard) { +static grpc_millis compute_min_deadline(timer_shard* shard) { return grpc_timer_heap_is_empty(&shard->heap) ? saturating_add(shard->queue_deadline_cap, 1) : grpc_timer_heap_top(&shard->heap)->deadline; @@ -258,7 +258,7 @@ static grpc_millis compute_min_deadline(timer_shard* shard) { static void timer_list_init() { uint32_t i; - g_num_shards = GPR_CLAMP(2 * gpr_cpu_num_cores(), 1, 32); + g_num_shards = GPR_CLAMP(2 * gpr_cpu_num_cores(), 1, 32); g_shards = static_cast<timer_shard*>(gpr_zalloc(g_num_shards * sizeof(*g_shards))); g_shard_queue = static_cast<timer_shard**>( @@ -268,11 +268,11 @@ static void timer_list_init() { g_shared_mutables.checker_mu = GPR_SPINLOCK_INITIALIZER; gpr_mu_init(&g_shared_mutables.mu); g_shared_mutables.min_timer = grpc_core::ExecCtx::Get()->Now(); - -#if GPR_ARCH_64 + +#if GPR_ARCH_64 gpr_tls_init(&g_last_seen_min_timer); gpr_tls_set(&g_last_seen_min_timer, 0); -#endif +#endif for (i = 0; i < g_num_shards; i++) { timer_shard* shard = &g_shards[i]; @@ -293,7 +293,7 @@ static void timer_list_init() { static void timer_list_shutdown() { size_t i; run_some_expired_timers( - GRPC_MILLIS_INF_FUTURE, nullptr, + GRPC_MILLIS_INF_FUTURE, nullptr, GRPC_ERROR_CREATE_FROM_STATIC_STRING("Timer list shutdown")); for (i = 0; i < g_num_shards; i++) { timer_shard* shard = &g_shards[i]; @@ -301,11 +301,11 @@ static void timer_list_shutdown() { grpc_timer_heap_destroy(&shard->heap); } gpr_mu_destroy(&g_shared_mutables.mu); - -#if GPR_ARCH_64 + +#if GPR_ARCH_64 gpr_tls_destroy(&g_last_seen_min_timer); -#endif - +#endif + gpr_free(g_shards); gpr_free(g_shard_queue); g_shared_mutables.initialized = false; @@ -364,7 +364,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline, #endif if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) { - gpr_log(GPR_INFO, "TIMER %p: SET %" PRId64 " now %" PRId64 " call %p[%p]", + gpr_log(GPR_INFO, "TIMER %p: SET %" PRId64 " now %" PRId64 " call %p[%p]", timer, deadline, grpc_core::ExecCtx::Get()->Now(), closure, closure->cb); } @@ -402,7 +402,7 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline, } if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) { gpr_log(GPR_INFO, - " .. add to shard %d with queue_deadline_cap=%" PRId64 + " .. add to shard %d with queue_deadline_cap=%" PRId64 " => is_first_timer=%s", static_cast<int>(shard - g_shards), shard->queue_deadline_cap, is_first_timer ? "true" : "false"); @@ -423,27 +423,27 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline, if (is_first_timer) { gpr_mu_lock(&g_shared_mutables.mu); if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_trace)) { - gpr_log(GPR_INFO, " .. old shard min_deadline=%" PRId64, + gpr_log(GPR_INFO, " .. old shard min_deadline=%" PRId64, shard->min_deadline); } if (deadline < shard->min_deadline) { - grpc_millis old_min_deadline = g_shard_queue[0]->min_deadline; + grpc_millis old_min_deadline = g_shard_queue[0]->min_deadline; shard->min_deadline = deadline; note_deadline_change(shard); if (shard->shard_queue_index == 0 && deadline < old_min_deadline) { -#if GPR_ARCH_64 - // TODO: sreek - Using c-style cast here. static_cast<> gives an error - // (on mac platforms complaining that gpr_atm* is (long *) while - // (&g_shared_mutables.min_timer) is a (long long *). The cast should be - // safe since we know that both are pointer types and 64-bit wide. - gpr_atm_no_barrier_store((gpr_atm*)(&g_shared_mutables.min_timer), - deadline); -#else - // On 32-bit systems, gpr_atm_no_barrier_store does not work on 64-bit - // types (like grpc_millis). So all reads and writes to - // g_shared_mutables.min_timer varialbe under g_shared_mutables.mu - g_shared_mutables.min_timer = deadline; -#endif +#if GPR_ARCH_64 + // TODO: sreek - Using c-style cast here. static_cast<> gives an error + // (on mac platforms complaining that gpr_atm* is (long *) while + // (&g_shared_mutables.min_timer) is a (long long *). The cast should be + // safe since we know that both are pointer types and 64-bit wide. + gpr_atm_no_barrier_store((gpr_atm*)(&g_shared_mutables.min_timer), + deadline); +#else + // On 32-bit systems, gpr_atm_no_barrier_store does not work on 64-bit + // types (like grpc_millis). So all reads and writes to + // g_shared_mutables.min_timer varialbe under g_shared_mutables.mu + g_shared_mutables.min_timer = deadline; +#endif grpc_kick_poller(); } } @@ -452,10 +452,10 @@ static void timer_init(grpc_timer* timer, grpc_millis deadline, } static void timer_consume_kick(void) { -#if GPR_ARCH_64 - /* Force re-evaluation of last seen min */ +#if GPR_ARCH_64 + /* Force re-evaluation of last seen min */ gpr_tls_set(&g_last_seen_min_timer, 0); -#endif +#endif } static void timer_cancel(grpc_timer* timer) { @@ -493,7 +493,7 @@ static void timer_cancel(grpc_timer* timer) { 'queue_deadline_cap') into into shard->heap. Returns 'true' if shard->heap has at least ONE element REQUIRES: shard->mu locked */ -static bool refill_heap(timer_shard* shard, grpc_millis now) { +static bool refill_heap(timer_shard* shard, grpc_millis now) { /* Compute the new queue window width and bound by the limits: */ double computed_deadline_delta = grpc_time_averaged_stats_update_average(&shard->stats) * @@ -506,10 +506,10 @@ static bool refill_heap(timer_shard* shard, grpc_millis now) { /* Compute the new cap and put all timers under it into the queue: */ shard->queue_deadline_cap = saturating_add(GPR_MAX(now, shard->queue_deadline_cap), - static_cast<grpc_millis>(deadline_delta * 1000.0)); + static_cast<grpc_millis>(deadline_delta * 1000.0)); if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { - gpr_log(GPR_INFO, " .. shard[%d]->queue_deadline_cap --> %" PRId64, + gpr_log(GPR_INFO, " .. shard[%d]->queue_deadline_cap --> %" PRId64, static_cast<int>(shard - g_shards), shard->queue_deadline_cap); } for (timer = shard->list.next; timer != &shard->list; timer = next) { @@ -517,7 +517,7 @@ static bool refill_heap(timer_shard* shard, grpc_millis now) { if (timer->deadline < shard->queue_deadline_cap) { if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { - gpr_log(GPR_INFO, " .. add timer with deadline %" PRId64 " to heap", + gpr_log(GPR_INFO, " .. add timer with deadline %" PRId64 " to heap", timer->deadline); } list_remove(timer); @@ -530,7 +530,7 @@ static bool refill_heap(timer_shard* shard, grpc_millis now) { /* This pops the next non-cancelled timer with deadline <= now from the queue, or returns NULL if there isn't one. REQUIRES: shard->mu locked */ -static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) { +static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) { grpc_timer* timer; for (;;) { if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { @@ -545,7 +545,7 @@ static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) { timer = grpc_timer_heap_top(&shard->heap); if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { gpr_log(GPR_INFO, - " .. check top timer deadline=%" PRId64 " now=%" PRId64, + " .. check top timer deadline=%" PRId64 " now=%" PRId64, timer->deadline, now); } if (timer->deadline > now) return nullptr; @@ -560,8 +560,8 @@ static grpc_timer* pop_one(timer_shard* shard, grpc_millis now) { } /* REQUIRES: shard->mu unlocked */ -static size_t pop_timers(timer_shard* shard, grpc_millis now, - grpc_millis* new_min_deadline, grpc_error* error) { +static size_t pop_timers(timer_shard* shard, grpc_millis now, + grpc_millis* new_min_deadline, grpc_error* error) { size_t n = 0; grpc_timer* timer; gpr_mu_lock(&shard->mu); @@ -580,27 +580,27 @@ static size_t pop_timers(timer_shard* shard, grpc_millis now, return n; } -static grpc_timer_check_result run_some_expired_timers(grpc_millis now, - grpc_millis* next, +static grpc_timer_check_result run_some_expired_timers(grpc_millis now, + grpc_millis* next, grpc_error* error) { grpc_timer_check_result result = GRPC_TIMERS_NOT_CHECKED; -#if GPR_ARCH_64 - // TODO: sreek - Using c-style cast here. static_cast<> gives an error (on - // mac platforms complaining that gpr_atm* is (long *) while - // (&g_shared_mutables.min_timer) is a (long long *). The cast should be - // safe since we know that both are pointer types and 64-bit wide - grpc_millis min_timer = static_cast<grpc_millis>( - gpr_atm_no_barrier_load((gpr_atm*)(&g_shared_mutables.min_timer))); +#if GPR_ARCH_64 + // TODO: sreek - Using c-style cast here. static_cast<> gives an error (on + // mac platforms complaining that gpr_atm* is (long *) while + // (&g_shared_mutables.min_timer) is a (long long *). The cast should be + // safe since we know that both are pointer types and 64-bit wide + grpc_millis min_timer = static_cast<grpc_millis>( + gpr_atm_no_barrier_load((gpr_atm*)(&g_shared_mutables.min_timer))); gpr_tls_set(&g_last_seen_min_timer, min_timer); -#else - // On 32-bit systems, gpr_atm_no_barrier_load does not work on 64-bit types - // (like grpc_millis). So all reads and writes to g_shared_mutables.min_timer - // are done under g_shared_mutables.mu - gpr_mu_lock(&g_shared_mutables.mu); - grpc_millis min_timer = g_shared_mutables.min_timer; - gpr_mu_unlock(&g_shared_mutables.mu); -#endif +#else + // On 32-bit systems, gpr_atm_no_barrier_load does not work on 64-bit types + // (like grpc_millis). So all reads and writes to g_shared_mutables.min_timer + // are done under g_shared_mutables.mu + gpr_mu_lock(&g_shared_mutables.mu); + grpc_millis min_timer = g_shared_mutables.min_timer; + gpr_mu_unlock(&g_shared_mutables.mu); +#endif if (now < min_timer) { if (next != nullptr) *next = GPR_MIN(*next, min_timer); return GRPC_TIMERS_CHECKED_AND_EMPTY; @@ -611,15 +611,15 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now, result = GRPC_TIMERS_CHECKED_AND_EMPTY; if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { - gpr_log(GPR_INFO, " .. shard[%d]->min_deadline = %" PRId64, + gpr_log(GPR_INFO, " .. shard[%d]->min_deadline = %" PRId64, static_cast<int>(g_shard_queue[0] - g_shards), g_shard_queue[0]->min_deadline); } while (g_shard_queue[0]->min_deadline < now || - (now != GRPC_MILLIS_INF_FUTURE && - g_shard_queue[0]->min_deadline == now)) { - grpc_millis new_min_deadline; + (now != GRPC_MILLIS_INF_FUTURE && + g_shard_queue[0]->min_deadline == now)) { + grpc_millis new_min_deadline; /* For efficiency, we pop as many available timers as we can from the shard. This may violate perfect timer deadline ordering, but that @@ -631,8 +631,8 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now, if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { gpr_log(GPR_INFO, " .. result --> %d" - ", shard[%d]->min_deadline %" PRId64 " --> %" PRId64 - ", now=%" PRId64, + ", shard[%d]->min_deadline %" PRId64 " --> %" PRId64 + ", now=%" PRId64, result, static_cast<int>(g_shard_queue[0] - g_shards), g_shard_queue[0]->min_deadline, new_min_deadline, now); } @@ -650,19 +650,19 @@ static grpc_timer_check_result run_some_expired_timers(grpc_millis now, *next = GPR_MIN(*next, g_shard_queue[0]->min_deadline); } -#if GPR_ARCH_64 - // TODO: sreek - Using c-style cast here. static_cast<> gives an error (on - // mac platforms complaining that gpr_atm* is (long *) while - // (&g_shared_mutables.min_timer) is a (long long *). The cast should be - // safe since we know that both are pointer types and 64-bit wide - gpr_atm_no_barrier_store((gpr_atm*)(&g_shared_mutables.min_timer), +#if GPR_ARCH_64 + // TODO: sreek - Using c-style cast here. static_cast<> gives an error (on + // mac platforms complaining that gpr_atm* is (long *) while + // (&g_shared_mutables.min_timer) is a (long long *). The cast should be + // safe since we know that both are pointer types and 64-bit wide + gpr_atm_no_barrier_store((gpr_atm*)(&g_shared_mutables.min_timer), g_shard_queue[0]->min_deadline); -#else - // On 32-bit systems, gpr_atm_no_barrier_store does not work on 64-bit - // types (like grpc_millis). So all reads and writes to - // g_shared_mutables.min_timer are done under g_shared_mutables.mu - g_shared_mutables.min_timer = g_shard_queue[0]->min_deadline; -#endif +#else + // On 32-bit systems, gpr_atm_no_barrier_store does not work on 64-bit + // types (like grpc_millis). So all reads and writes to + // g_shared_mutables.min_timer are done under g_shared_mutables.mu + g_shared_mutables.min_timer = g_shard_queue[0]->min_deadline; +#endif gpr_mu_unlock(&g_shared_mutables.mu); gpr_spinlock_unlock(&g_shared_mutables.checker_mu); } @@ -676,28 +676,28 @@ static grpc_timer_check_result timer_check(grpc_millis* next) { // prelude grpc_millis now = grpc_core::ExecCtx::Get()->Now(); -#if GPR_ARCH_64 +#if GPR_ARCH_64 /* fetch from a thread-local first: this avoids contention on a globally mutable cacheline in the common case */ grpc_millis min_timer = gpr_tls_get(&g_last_seen_min_timer); -#else - // On 32-bit systems, we currently do not have thread local support for 64-bit - // types. In this case, directly read from g_shared_mutables.min_timer. - // Also, note that on 32-bit systems, gpr_atm_no_barrier_store does not work - // on 64-bit types (like grpc_millis). So all reads and writes to - // g_shared_mutables.min_timer are done under g_shared_mutables.mu - gpr_mu_lock(&g_shared_mutables.mu); - grpc_millis min_timer = g_shared_mutables.min_timer; - gpr_mu_unlock(&g_shared_mutables.mu); -#endif - +#else + // On 32-bit systems, we currently do not have thread local support for 64-bit + // types. In this case, directly read from g_shared_mutables.min_timer. + // Also, note that on 32-bit systems, gpr_atm_no_barrier_store does not work + // on 64-bit types (like grpc_millis). So all reads and writes to + // g_shared_mutables.min_timer are done under g_shared_mutables.mu + gpr_mu_lock(&g_shared_mutables.mu); + grpc_millis min_timer = g_shared_mutables.min_timer; + gpr_mu_unlock(&g_shared_mutables.mu); +#endif + if (now < min_timer) { if (next != nullptr) { *next = GPR_MIN(*next, min_timer); } if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { - gpr_log(GPR_INFO, "TIMER CHECK SKIP: now=%" PRId64 " min_timer=%" PRId64, - now, min_timer); + gpr_log(GPR_INFO, "TIMER CHECK SKIP: now=%" PRId64 " min_timer=%" PRId64, + now, min_timer); } return GRPC_TIMERS_CHECKED_AND_EMPTY; } @@ -715,17 +715,17 @@ static grpc_timer_check_result timer_check(grpc_millis* next) { } else { next_str = y_absl::StrCat(*next); } -#if GPR_ARCH_64 +#if GPR_ARCH_64 gpr_log(GPR_INFO, - "TIMER CHECK BEGIN: now=%" PRId64 " next=%s tls_min=%" PRId64 - " glob_min=%" PRId64, + "TIMER CHECK BEGIN: now=%" PRId64 " next=%s tls_min=%" PRId64 + " glob_min=%" PRId64, now, next_str.c_str(), min_timer, - static_cast<grpc_millis>(gpr_atm_no_barrier_load( - (gpr_atm*)(&g_shared_mutables.min_timer)))); -#else - gpr_log(GPR_INFO, "TIMER CHECK BEGIN: now=%" PRId64 " next=%s min=%" PRId64, + static_cast<grpc_millis>(gpr_atm_no_barrier_load( + (gpr_atm*)(&g_shared_mutables.min_timer)))); +#else + gpr_log(GPR_INFO, "TIMER CHECK BEGIN: now=%" PRId64 " next=%s min=%" PRId64, now, next_str.c_str(), min_timer); -#endif +#endif } // actual code grpc_timer_check_result r = diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc index 2c6a599149..543d3ca4ca 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.cc @@ -95,7 +95,7 @@ void grpc_timer_heap_init(grpc_timer_heap* heap) { void grpc_timer_heap_destroy(grpc_timer_heap* heap) { gpr_free(heap->timers); } -bool grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer) { +bool grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer) { if (heap->timer_count == heap->timer_capacity) { heap->timer_capacity = GPR_MAX(heap->timer_capacity + 1, heap->timer_capacity * 3 / 2); @@ -122,7 +122,7 @@ void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer) { note_changed_priority(heap, heap->timers[i]); } -bool grpc_timer_heap_is_empty(grpc_timer_heap* heap) { +bool grpc_timer_heap_is_empty(grpc_timer_heap* heap) { return heap->timer_count == 0; } diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h index 2b08c65108..43da19343b 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_heap.h @@ -28,8 +28,8 @@ struct grpc_timer_heap { uint32_t timer_count; uint32_t timer_capacity; }; -/* return true if the new timer is the first timer in the heap */ -bool grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer); +/* return true if the new timer is the first timer in the heap */ +bool grpc_timer_heap_add(grpc_timer_heap* heap, grpc_timer* timer); void grpc_timer_heap_init(grpc_timer_heap* heap); void grpc_timer_heap_destroy(grpc_timer_heap* heap); @@ -38,6 +38,6 @@ void grpc_timer_heap_remove(grpc_timer_heap* heap, grpc_timer* timer); grpc_timer* grpc_timer_heap_top(grpc_timer_heap* heap); void grpc_timer_heap_pop(grpc_timer_heap* heap); -bool grpc_timer_heap_is_empty(grpc_timer_heap* heap); +bool grpc_timer_heap_is_empty(grpc_timer_heap* heap); #endif /* GRPC_CORE_LIB_IOMGR_TIMER_HEAP_H */ diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc index 96d502c510..c32af8bb15 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.cc @@ -95,29 +95,29 @@ static void start_timer_thread_and_unlock(void) { void grpc_timer_manager_tick() { grpc_core::ExecCtx exec_ctx; - grpc_timer_check(nullptr); + grpc_timer_check(nullptr); } static void run_some_timers() { - // In the case of timers, the ExecCtx for the thread is declared - // in the timer thread itself, but this is the point where we - // could start seeing application-level callbacks. No need to - // create a new ExecCtx, though, since there already is one and it is - // flushed (but not destructed) in this function itself - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx( - GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); - + // In the case of timers, the ExecCtx for the thread is declared + // in the timer thread itself, but this is the point where we + // could start seeing application-level callbacks. No need to + // create a new ExecCtx, though, since there already is one and it is + // flushed (but not destructed) in this function itself + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx( + GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); + // if there's something to execute... gpr_mu_lock(&g_mu); // remove a waiter from the pool, and start another thread if necessary --g_waiter_count; if (g_waiter_count == 0 && g_threaded) { - // The number of timer threads is always increasing until all the threads - // are stopped. In rare cases, if a large number of timers fire - // simultaneously, we may end up using a large number of threads. + // The number of timer threads is always increasing until all the threads + // are stopped. In rare cases, if a large number of timers fire + // simultaneously, we may end up using a large number of threads. start_timer_thread_and_unlock(); } else { - // if there's no thread waiting with a timeout, kick an existing untimed + // if there's no thread waiting with a timeout, kick an existing untimed // waiter so that the next deadline is not missed if (!g_has_timed_waiter) { if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { @@ -185,7 +185,7 @@ static bool wait_until(grpc_millis next) { if (GRPC_TRACE_FLAG_ENABLED(grpc_timer_check_trace)) { grpc_millis wait_time = next - grpc_core::ExecCtx::Get()->Now(); - gpr_log(GPR_INFO, "sleep for a %" PRId64 " milliseconds", wait_time); + gpr_log(GPR_INFO, "sleep for a %" PRId64 " milliseconds", wait_time); } } else { // g_timed_waiter == true && next >= g_timed_waiter_deadline next = GRPC_MILLIS_INF_FUTURE; @@ -250,7 +250,7 @@ static void timer_main_loop() { gpr_log(GPR_INFO, "timers not checked: expect another thread to"); } next = GRPC_MILLIS_INF_FUTURE; - // fallthrough + // fallthrough case GRPC_TIMERS_CHECKED_AND_EMPTY: if (!wait_until(next)) { return; @@ -280,7 +280,7 @@ static void timer_thread_cleanup(completed_thread* ct) { static void timer_thread(void* completed_thread_ptr) { // this threads exec_ctx: we try to run things through to completion here // since it's easy to spin up new threads - grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); + grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_INTERNAL_THREAD); timer_main_loop(); timer_thread_cleanup(static_cast<completed_thread*>(completed_thread_ptr)); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h index d407cbbc2b..7e895303e1 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h +++ b/contrib/libs/grpc/src/core/lib/iomgr/timer_manager.h @@ -23,8 +23,8 @@ #include <stdbool.h> -/* Timer Manager tries to keep only one thread waiting for the next timeout at - all times, and thus effectively preventing the thundering herd problem. */ +/* Timer Manager tries to keep only one thread waiting for the next timeout at + all times, and thus effectively preventing the thundering herd problem. */ void grpc_timer_manager_init(void); void grpc_timer_manager_shutdown(void); diff --git a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc index 1e7734d681..1e6f99ac4f 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/udp_server.cc @@ -301,7 +301,7 @@ void GrpcUdpListener::OrphanFd() { grpc_schedule_on_exec_ctx); /* Because at this point, all listening sockets have been shutdown already, no * need to call OnFdAboutToOrphan() to notify the handler again. */ - grpc_fd_orphan(emfd_, &destroyed_closure_, nullptr, "udp_listener_shutdown"); + grpc_fd_orphan(emfd_, &destroyed_closure_, nullptr, "udp_listener_shutdown"); } void grpc_udp_server_destroy(grpc_udp_server* s, grpc_closure* on_done) { diff --git a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc index d68c9ada1f..8adc7a01aa 100644 --- a/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc +++ b/contrib/libs/grpc/src/core/lib/iomgr/wakeup_fd_eventfd.cc @@ -32,9 +32,9 @@ #include "src/core/lib/profiling/timers.h" static grpc_error* eventfd_create(grpc_wakeup_fd* fd_info) { - fd_info->read_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); - fd_info->write_fd = -1; - if (fd_info->read_fd < 0) { + fd_info->read_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + fd_info->write_fd = -1; + if (fd_info->read_fd < 0) { return GRPC_OS_ERROR(errno, "eventfd"); } return GRPC_ERROR_NONE; diff --git a/contrib/libs/grpc/src/core/lib/json/json.h b/contrib/libs/grpc/src/core/lib/json/json.h index f426fbf1dd..52bbd87588 100644 --- a/contrib/libs/grpc/src/core/lib/json/json.h +++ b/contrib/libs/grpc/src/core/lib/json/json.h @@ -84,7 +84,7 @@ class Json { string_value_ = string; return *this; } - + // Same thing for C-style strings, both const and mutable. Json(const char* string, bool is_number = false) : Json(TString(string), is_number) {} diff --git a/contrib/libs/grpc/src/core/lib/security/context/security_context.cc b/contrib/libs/grpc/src/core/lib/security/context/security_context.cc index ef60165899..0d64f863a8 100644 --- a/contrib/libs/grpc/src/core/lib/security/context/security_context.cc +++ b/contrib/libs/grpc/src/core/lib/security/context/security_context.cc @@ -23,8 +23,8 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/arena.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" @@ -52,11 +52,11 @@ grpc_call_error grpc_call_set_credentials(grpc_call* call, ctx = static_cast<grpc_client_security_context*>( grpc_call_context_get(call, GRPC_CONTEXT_SECURITY)); if (ctx == nullptr) { - ctx = grpc_client_security_context_create(grpc_call_get_arena(call), creds); + ctx = grpc_client_security_context_create(grpc_call_get_arena(call), creds); grpc_call_context_set(call, GRPC_CONTEXT_SECURITY, ctx, grpc_client_security_context_destroy); } else { - ctx->creds = creds != nullptr ? creds->Ref() : nullptr; + ctx->creds = creds != nullptr ? creds->Ref() : nullptr; } return GRPC_CALL_OK; @@ -66,42 +66,42 @@ grpc_auth_context* grpc_call_auth_context(grpc_call* call) { void* sec_ctx = grpc_call_context_get(call, GRPC_CONTEXT_SECURITY); GRPC_API_TRACE("grpc_call_auth_context(call=%p)", 1, (call)); if (sec_ctx == nullptr) return nullptr; - if (grpc_call_is_client(call)) { - auto* sc = static_cast<grpc_client_security_context*>(sec_ctx); - if (sc->auth_context == nullptr) { - return nullptr; - } else { - return sc->auth_context - ->Ref(DEBUG_LOCATION, "grpc_call_auth_context client") - .release(); - } - } else { - auto* sc = static_cast<grpc_server_security_context*>(sec_ctx); - if (sc->auth_context == nullptr) { - return nullptr; - } else { - return sc->auth_context - ->Ref(DEBUG_LOCATION, "grpc_call_auth_context server") - .release(); - } - } + if (grpc_call_is_client(call)) { + auto* sc = static_cast<grpc_client_security_context*>(sec_ctx); + if (sc->auth_context == nullptr) { + return nullptr; + } else { + return sc->auth_context + ->Ref(DEBUG_LOCATION, "grpc_call_auth_context client") + .release(); + } + } else { + auto* sc = static_cast<grpc_server_security_context*>(sec_ctx); + if (sc->auth_context == nullptr) { + return nullptr; + } else { + return sc->auth_context + ->Ref(DEBUG_LOCATION, "grpc_call_auth_context server") + .release(); + } + } } void grpc_auth_context_release(grpc_auth_context* context) { GRPC_API_TRACE("grpc_auth_context_release(context=%p)", 1, (context)); - if (context == nullptr) return; - context->Unref(DEBUG_LOCATION, "grpc_auth_context_unref"); + if (context == nullptr) return; + context->Unref(DEBUG_LOCATION, "grpc_auth_context_unref"); } /* --- grpc_client_security_context --- */ -grpc_client_security_context::~grpc_client_security_context() { - auth_context.reset(DEBUG_LOCATION, "client_security_context"); - if (extension.instance != nullptr && extension.destroy != nullptr) { - extension.destroy(extension.instance); - } -} - -grpc_client_security_context* grpc_client_security_context_create( +grpc_client_security_context::~grpc_client_security_context() { + auth_context.reset(DEBUG_LOCATION, "client_security_context"); + if (extension.instance != nullptr && extension.destroy != nullptr) { + extension.destroy(extension.instance); + } +} + +grpc_client_security_context* grpc_client_security_context_create( grpc_core::Arena* arena, grpc_call_credentials* creds) { return arena->New<grpc_client_security_context>( creds != nullptr ? creds->Ref() : nullptr); @@ -111,18 +111,18 @@ void grpc_client_security_context_destroy(void* ctx) { grpc_core::ExecCtx exec_ctx; grpc_client_security_context* c = static_cast<grpc_client_security_context*>(ctx); - c->~grpc_client_security_context(); + c->~grpc_client_security_context(); } /* --- grpc_server_security_context --- */ -grpc_server_security_context::~grpc_server_security_context() { - auth_context.reset(DEBUG_LOCATION, "server_security_context"); - if (extension.instance != nullptr && extension.destroy != nullptr) { - extension.destroy(extension.instance); - } -} - -grpc_server_security_context* grpc_server_security_context_create( +grpc_server_security_context::~grpc_server_security_context() { + auth_context.reset(DEBUG_LOCATION, "server_security_context"); + if (extension.instance != nullptr && extension.destroy != nullptr) { + extension.destroy(extension.instance); + } +} + +grpc_server_security_context* grpc_server_security_context_create( grpc_core::Arena* arena) { return arena->New<grpc_server_security_context>(); } @@ -130,7 +130,7 @@ grpc_server_security_context* grpc_server_security_context_create( void grpc_server_security_context_destroy(void* ctx) { grpc_server_security_context* c = static_cast<grpc_server_security_context*>(ctx); - c->~grpc_server_security_context(); + c->~grpc_server_security_context(); } /* --- grpc_auth_context --- */ @@ -141,7 +141,7 @@ const char* grpc_auth_context_peer_identity_property_name( const grpc_auth_context* ctx) { GRPC_API_TRACE("grpc_auth_context_peer_identity_property_name(ctx=%p)", 1, (ctx)); - return ctx->peer_identity_property_name(); + return ctx->peer_identity_property_name(); } int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context* ctx, @@ -157,13 +157,13 @@ int grpc_auth_context_set_peer_identity_property_name(grpc_auth_context* ctx, name != nullptr ? name : "NULL"); return 0; } - ctx->set_peer_identity_property_name(prop->name); + ctx->set_peer_identity_property_name(prop->name); return 1; } int grpc_auth_context_peer_is_authenticated(const grpc_auth_context* ctx) { GRPC_API_TRACE("grpc_auth_context_peer_is_authenticated(ctx=%p)", 1, (ctx)); - return ctx->is_authenticated(); + return ctx->is_authenticated(); } grpc_auth_property_iterator grpc_auth_context_property_iterator( @@ -179,17 +179,17 @@ const grpc_auth_property* grpc_auth_property_iterator_next( grpc_auth_property_iterator* it) { GRPC_API_TRACE("grpc_auth_property_iterator_next(it=%p)", 1, (it)); if (it == nullptr || it->ctx == nullptr) return nullptr; - while (it->index == it->ctx->properties().count) { - if (it->ctx->chained() == nullptr) return nullptr; - it->ctx = it->ctx->chained(); + while (it->index == it->ctx->properties().count) { + if (it->ctx->chained() == nullptr) return nullptr; + it->ctx = it->ctx->chained(); it->index = 0; } if (it->name == nullptr) { - return &it->ctx->properties().array[it->index++]; + return &it->ctx->properties().array[it->index++]; } else { - while (it->index < it->ctx->properties().count) { - const grpc_auth_property* prop = - &it->ctx->properties().array[it->index++]; + while (it->index < it->ctx->properties().count) { + const grpc_auth_property* prop = + &it->ctx->properties().array[it->index++]; GPR_ASSERT(prop->name != nullptr); if (strcmp(it->name, prop->name) == 0) { return prop; @@ -216,29 +216,29 @@ grpc_auth_property_iterator grpc_auth_context_peer_identity( GRPC_API_TRACE("grpc_auth_context_peer_identity(ctx=%p)", 1, (ctx)); if (ctx == nullptr) return empty_iterator; return grpc_auth_context_find_properties_by_name( - ctx, ctx->peer_identity_property_name()); + ctx, ctx->peer_identity_property_name()); } -void grpc_auth_context::ensure_capacity() { - if (properties_.count == properties_.capacity) { - properties_.capacity = - GPR_MAX(properties_.capacity + 8, properties_.capacity * 2); - properties_.array = static_cast<grpc_auth_property*>(gpr_realloc( - properties_.array, properties_.capacity * sizeof(grpc_auth_property))); +void grpc_auth_context::ensure_capacity() { + if (properties_.count == properties_.capacity) { + properties_.capacity = + GPR_MAX(properties_.capacity + 8, properties_.capacity * 2); + properties_.array = static_cast<grpc_auth_property*>(gpr_realloc( + properties_.array, properties_.capacity * sizeof(grpc_auth_property))); } } -void grpc_auth_context::add_property(const char* name, const char* value, - size_t value_length) { - ensure_capacity(); - grpc_auth_property* prop = &properties_.array[properties_.count++]; - prop->name = gpr_strdup(name); - prop->value = static_cast<char*>(gpr_malloc(value_length + 1)); - memcpy(prop->value, value, value_length); - prop->value[value_length] = '\0'; - prop->value_length = value_length; -} - +void grpc_auth_context::add_property(const char* name, const char* value, + size_t value_length) { + ensure_capacity(); + grpc_auth_property* prop = &properties_.array[properties_.count++]; + prop->name = gpr_strdup(name); + prop->value = static_cast<char*>(gpr_malloc(value_length + 1)); + memcpy(prop->value, value, value_length); + prop->value[value_length] = '\0'; + prop->value_length = value_length; +} + void grpc_auth_context_add_property(grpc_auth_context* ctx, const char* name, const char* value, size_t value_length) { GRPC_API_TRACE( @@ -247,16 +247,16 @@ void grpc_auth_context_add_property(grpc_auth_context* ctx, const char* name, 6, (ctx, name, (int)value_length, (int)value_length, value, (unsigned long)value_length)); - ctx->add_property(name, value, value_length); -} - -void grpc_auth_context::add_cstring_property(const char* name, - const char* value) { - ensure_capacity(); - grpc_auth_property* prop = &properties_.array[properties_.count++]; + ctx->add_property(name, value, value_length); +} + +void grpc_auth_context::add_cstring_property(const char* name, + const char* value) { + ensure_capacity(); + grpc_auth_property* prop = &properties_.array[properties_.count++]; prop->name = gpr_strdup(name); - prop->value = gpr_strdup(value); - prop->value_length = strlen(value); + prop->value = gpr_strdup(value); + prop->value_length = strlen(value); } void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx, @@ -265,7 +265,7 @@ void grpc_auth_context_add_cstring_property(grpc_auth_context* ctx, GRPC_API_TRACE( "grpc_auth_context_add_cstring_property(ctx=%p, name=%s, value=%s)", 3, (ctx, name, value)); - ctx->add_cstring_property(name, value); + ctx->add_cstring_property(name, value); } void grpc_auth_property_reset(grpc_auth_property* property) { @@ -275,17 +275,17 @@ void grpc_auth_property_reset(grpc_auth_property* property) { } static void auth_context_pointer_arg_destroy(void* p) { - if (p != nullptr) { - static_cast<grpc_auth_context*>(p)->Unref(DEBUG_LOCATION, - "auth_context_pointer_arg"); - } + if (p != nullptr) { + static_cast<grpc_auth_context*>(p)->Unref(DEBUG_LOCATION, + "auth_context_pointer_arg"); + } } static void* auth_context_pointer_arg_copy(void* p) { - auto* ctx = static_cast<grpc_auth_context*>(p); - return ctx == nullptr - ? nullptr - : ctx->Ref(DEBUG_LOCATION, "auth_context_pointer_arg").release(); + auto* ctx = static_cast<grpc_auth_context*>(p); + return ctx == nullptr + ? nullptr + : ctx->Ref(DEBUG_LOCATION, "auth_context_pointer_arg").release(); } static int auth_context_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); } diff --git a/contrib/libs/grpc/src/core/lib/security/context/security_context.h b/contrib/libs/grpc/src/core/lib/security/context/security_context.h index b1991089ae..89a6807de3 100644 --- a/contrib/libs/grpc/src/core/lib/security/context/security_context.h +++ b/contrib/libs/grpc/src/core/lib/security/context/security_context.h @@ -22,8 +22,8 @@ #include <grpc/support/port_platform.h> #include "src/core/lib/gprpp/arena.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/security/credentials/credentials.h" @@ -35,91 +35,91 @@ extern grpc_core::DebugOnlyTraceFlag grpc_trace_auth_context_refcount; /* Property names are always NULL terminated. */ -struct grpc_auth_property_array { - grpc_auth_property* array = nullptr; - size_t count = 0; - size_t capacity = 0; -}; - -void grpc_auth_property_reset(grpc_auth_property* property); - -// This type is forward declared as a C struct and we cannot define it as a -// class. Otherwise, compiler will complain about type mismatch due to -// -Wmismatched-tags. -struct grpc_auth_context - : public grpc_core::RefCounted<grpc_auth_context, - grpc_core::NonPolymorphicRefCount> { - public: - explicit grpc_auth_context( - grpc_core::RefCountedPtr<grpc_auth_context> chained) - : grpc_core::RefCounted<grpc_auth_context, - grpc_core::NonPolymorphicRefCount>( - &grpc_trace_auth_context_refcount), - chained_(std::move(chained)) { - if (chained_ != nullptr) { - peer_identity_property_name_ = chained_->peer_identity_property_name_; - } - } - - ~grpc_auth_context() { - chained_.reset(DEBUG_LOCATION, "chained"); - if (properties_.array != nullptr) { - for (size_t i = 0; i < properties_.count; i++) { - grpc_auth_property_reset(&properties_.array[i]); - } - gpr_free(properties_.array); - } - } - - const grpc_auth_context* chained() const { return chained_.get(); } - const grpc_auth_property_array& properties() const { return properties_; } - - bool is_authenticated() const { - return peer_identity_property_name_ != nullptr; - } - const char* peer_identity_property_name() const { - return peer_identity_property_name_; - } - void set_peer_identity_property_name(const char* name) { - peer_identity_property_name_ = name; - } - - void ensure_capacity(); - void add_property(const char* name, const char* value, size_t value_length); - void add_cstring_property(const char* name, const char* value); - - private: - grpc_core::RefCountedPtr<grpc_auth_context> chained_; - grpc_auth_property_array properties_; - const char* peer_identity_property_name_ = nullptr; +struct grpc_auth_property_array { + grpc_auth_property* array = nullptr; + size_t count = 0; + size_t capacity = 0; }; +void grpc_auth_property_reset(grpc_auth_property* property); + +// This type is forward declared as a C struct and we cannot define it as a +// class. Otherwise, compiler will complain about type mismatch due to +// -Wmismatched-tags. +struct grpc_auth_context + : public grpc_core::RefCounted<grpc_auth_context, + grpc_core::NonPolymorphicRefCount> { + public: + explicit grpc_auth_context( + grpc_core::RefCountedPtr<grpc_auth_context> chained) + : grpc_core::RefCounted<grpc_auth_context, + grpc_core::NonPolymorphicRefCount>( + &grpc_trace_auth_context_refcount), + chained_(std::move(chained)) { + if (chained_ != nullptr) { + peer_identity_property_name_ = chained_->peer_identity_property_name_; + } + } + + ~grpc_auth_context() { + chained_.reset(DEBUG_LOCATION, "chained"); + if (properties_.array != nullptr) { + for (size_t i = 0; i < properties_.count; i++) { + grpc_auth_property_reset(&properties_.array[i]); + } + gpr_free(properties_.array); + } + } + + const grpc_auth_context* chained() const { return chained_.get(); } + const grpc_auth_property_array& properties() const { return properties_; } + + bool is_authenticated() const { + return peer_identity_property_name_ != nullptr; + } + const char* peer_identity_property_name() const { + return peer_identity_property_name_; + } + void set_peer_identity_property_name(const char* name) { + peer_identity_property_name_ = name; + } + + void ensure_capacity(); + void add_property(const char* name, const char* value, size_t value_length); + void add_cstring_property(const char* name, const char* value); + + private: + grpc_core::RefCountedPtr<grpc_auth_context> chained_; + grpc_auth_property_array properties_; + const char* peer_identity_property_name_ = nullptr; +}; + /* --- grpc_security_context_extension --- Extension to the security context that may be set in a filter and accessed later by a higher level method on a grpc_call object. */ -struct grpc_security_context_extension { - void* instance = nullptr; - void (*destroy)(void*) = nullptr; -}; +struct grpc_security_context_extension { + void* instance = nullptr; + void (*destroy)(void*) = nullptr; +}; /* --- grpc_client_security_context --- Internal client-side security context. */ -struct grpc_client_security_context { - explicit grpc_client_security_context( - grpc_core::RefCountedPtr<grpc_call_credentials> creds) - : creds(std::move(creds)) {} - ~grpc_client_security_context(); - - grpc_core::RefCountedPtr<grpc_call_credentials> creds; - grpc_core::RefCountedPtr<grpc_auth_context> auth_context; +struct grpc_client_security_context { + explicit grpc_client_security_context( + grpc_core::RefCountedPtr<grpc_call_credentials> creds) + : creds(std::move(creds)) {} + ~grpc_client_security_context(); + + grpc_core::RefCountedPtr<grpc_call_credentials> creds; + grpc_core::RefCountedPtr<grpc_auth_context> auth_context; grpc_security_context_extension extension; -}; +}; -grpc_client_security_context* grpc_client_security_context_create( +grpc_client_security_context* grpc_client_security_context_create( grpc_core::Arena* arena, grpc_call_credentials* creds); void grpc_client_security_context_destroy(void* ctx); @@ -127,15 +127,15 @@ void grpc_client_security_context_destroy(void* ctx); Internal server-side security context. */ -struct grpc_server_security_context { - grpc_server_security_context() = default; - ~grpc_server_security_context(); - - grpc_core::RefCountedPtr<grpc_auth_context> auth_context; +struct grpc_server_security_context { + grpc_server_security_context() = default; + ~grpc_server_security_context(); + + grpc_core::RefCountedPtr<grpc_auth_context> auth_context; grpc_security_context_extension extension; -}; +}; -grpc_server_security_context* grpc_server_security_context_create( +grpc_server_security_context* grpc_server_security_context_create( grpc_core::Arena* arena); void grpc_server_security_context_destroy(void* ctx); diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc index 1bc76d9c0c..e3b4b33059 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.cc @@ -28,56 +28,56 @@ #include <grpc/support/string_util.h> #include "src/core/lib/security/credentials/alts/check_gcp_environment.h" -#include "src/core/lib/security/security_connector/alts/alts_security_connector.h" +#include "src/core/lib/security/security_connector/alts/alts_security_connector.h" #define GRPC_CREDENTIALS_TYPE_ALTS "Alts" -#define GRPC_ALTS_HANDSHAKER_SERVICE_URL "metadata.google.internal.:8080" - -grpc_alts_credentials::grpc_alts_credentials( - const grpc_alts_credentials_options* options, - const char* handshaker_service_url) - : grpc_channel_credentials(GRPC_CREDENTIALS_TYPE_ALTS), - options_(grpc_alts_credentials_options_copy(options)), - handshaker_service_url_(handshaker_service_url == nullptr - ? gpr_strdup(GRPC_ALTS_HANDSHAKER_SERVICE_URL) +#define GRPC_ALTS_HANDSHAKER_SERVICE_URL "metadata.google.internal.:8080" + +grpc_alts_credentials::grpc_alts_credentials( + const grpc_alts_credentials_options* options, + const char* handshaker_service_url) + : grpc_channel_credentials(GRPC_CREDENTIALS_TYPE_ALTS), + options_(grpc_alts_credentials_options_copy(options)), + handshaker_service_url_(handshaker_service_url == nullptr + ? gpr_strdup(GRPC_ALTS_HANDSHAKER_SERVICE_URL) : gpr_strdup(handshaker_service_url)) { grpc_alts_set_rpc_protocol_versions(&options_->rpc_versions); } -grpc_alts_credentials::~grpc_alts_credentials() { - grpc_alts_credentials_options_destroy(options_); - gpr_free(handshaker_service_url_); +grpc_alts_credentials::~grpc_alts_credentials() { + grpc_alts_credentials_options_destroy(options_); + gpr_free(handshaker_service_url_); } -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_alts_credentials::create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_alts_credentials::create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, const char* target_name, const grpc_channel_args* /*args*/, grpc_channel_args** /*new_args*/) { return grpc_alts_channel_security_connector_create( - this->Ref(), std::move(call_creds), target_name); + this->Ref(), std::move(call_creds), target_name); } -grpc_alts_server_credentials::grpc_alts_server_credentials( - const grpc_alts_credentials_options* options, - const char* handshaker_service_url) - : grpc_server_credentials(GRPC_CREDENTIALS_TYPE_ALTS), - options_(grpc_alts_credentials_options_copy(options)), - handshaker_service_url_(handshaker_service_url == nullptr - ? gpr_strdup(GRPC_ALTS_HANDSHAKER_SERVICE_URL) +grpc_alts_server_credentials::grpc_alts_server_credentials( + const grpc_alts_credentials_options* options, + const char* handshaker_service_url) + : grpc_server_credentials(GRPC_CREDENTIALS_TYPE_ALTS), + options_(grpc_alts_credentials_options_copy(options)), + handshaker_service_url_(handshaker_service_url == nullptr + ? gpr_strdup(GRPC_ALTS_HANDSHAKER_SERVICE_URL) : gpr_strdup(handshaker_service_url)) { grpc_alts_set_rpc_protocol_versions(&options_->rpc_versions); } - -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_alts_server_credentials::create_security_connector() { - return grpc_alts_server_security_connector_create(this->Ref()); + +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_alts_server_credentials::create_security_connector() { + return grpc_alts_server_security_connector_create(this->Ref()); } -grpc_alts_server_credentials::~grpc_alts_server_credentials() { - grpc_alts_credentials_options_destroy(options_); - gpr_free(handshaker_service_url_); -} +grpc_alts_server_credentials::~grpc_alts_server_credentials() { + grpc_alts_credentials_options_destroy(options_); + gpr_free(handshaker_service_url_); +} grpc_channel_credentials* grpc_alts_credentials_create_customized( const grpc_alts_credentials_options* options, diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h index cc6d5222b1..043f5ed9b6 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/alts_credentials.h @@ -27,46 +27,46 @@ #include "src/core/lib/security/credentials/credentials.h" /* Main struct for grpc ALTS channel credential. */ -class grpc_alts_credentials final : public grpc_channel_credentials { - public: - grpc_alts_credentials(const grpc_alts_credentials_options* options, - const char* handshaker_service_url); - ~grpc_alts_credentials() override; - - grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, - const char* target_name, const grpc_channel_args* args, - grpc_channel_args** new_args) override; - - const grpc_alts_credentials_options* options() const { return options_; } - grpc_alts_credentials_options* mutable_options() { return options_; } - const char* handshaker_service_url() const { return handshaker_service_url_; } - - private: - grpc_alts_credentials_options* options_; - char* handshaker_service_url_; -}; - +class grpc_alts_credentials final : public grpc_channel_credentials { + public: + grpc_alts_credentials(const grpc_alts_credentials_options* options, + const char* handshaker_service_url); + ~grpc_alts_credentials() override; + + grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, + const char* target_name, const grpc_channel_args* args, + grpc_channel_args** new_args) override; + + const grpc_alts_credentials_options* options() const { return options_; } + grpc_alts_credentials_options* mutable_options() { return options_; } + const char* handshaker_service_url() const { return handshaker_service_url_; } + + private: + grpc_alts_credentials_options* options_; + char* handshaker_service_url_; +}; + /* Main struct for grpc ALTS server credential. */ -class grpc_alts_server_credentials final : public grpc_server_credentials { - public: - grpc_alts_server_credentials(const grpc_alts_credentials_options* options, - const char* handshaker_service_url); - ~grpc_alts_server_credentials() override; - - grpc_core::RefCountedPtr<grpc_server_security_connector> - create_security_connector() override; - - const grpc_alts_credentials_options* options() const { return options_; } - grpc_alts_credentials_options* mutable_options() { return options_; } - const char* handshaker_service_url() const { return handshaker_service_url_; } - - private: - grpc_alts_credentials_options* options_; - char* handshaker_service_url_; -}; - +class grpc_alts_server_credentials final : public grpc_server_credentials { + public: + grpc_alts_server_credentials(const grpc_alts_credentials_options* options, + const char* handshaker_service_url); + ~grpc_alts_server_credentials() override; + + grpc_core::RefCountedPtr<grpc_server_security_connector> + create_security_connector() override; + + const grpc_alts_credentials_options* options() const { return options_; } + grpc_alts_credentials_options* mutable_options() { return options_; } + const char* handshaker_service_url() const { return handshaker_service_url_; } + + private: + grpc_alts_credentials_options* options_; + char* handshaker_service_url_; +}; + /** * This method creates an ALTS channel credential object with customized * information provided by caller. diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc index 8454fd7558..eff66317f9 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc @@ -41,9 +41,9 @@ namespace internal { bool check_bios_data(const char* bios_data_file) { char* bios_data = read_bios_file(bios_data_file); - bool result = - bios_data && ((!strcmp(bios_data, GRPC_ALTS_EXPECT_NAME_GOOGLE)) || - (!strcmp(bios_data, GRPC_ALTS_EXPECT_NAME_GCE))); + bool result = + bios_data && ((!strcmp(bios_data, GRPC_ALTS_EXPECT_NAME_GOOGLE)) || + (!strcmp(bios_data, GRPC_ALTS_EXPECT_NAME_GCE))); gpr_free(bios_data); return result; } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc index b71f66a536..f839aa8b35 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc @@ -25,8 +25,8 @@ #include <grpc/support/log.h> bool grpc_alts_is_running_on_gcp() { - gpr_log(GPR_INFO, - "ALTS: Platforms other than Linux and Windows are not supported"); + gpr_log(GPR_INFO, + "ALTS: Platforms other than Linux and Windows are not supported"); return false; } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc index 118d18d119..f1f4fe1a84 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc @@ -72,8 +72,8 @@ static void target_service_account_destroy( static const grpc_alts_credentials_options_vtable vtable = { alts_client_options_copy, alts_client_options_destroy}; -grpc_alts_credentials_options* grpc_alts_credentials_client_options_create( - void) { +grpc_alts_credentials_options* grpc_alts_credentials_client_options_create( + void) { auto client_options = static_cast<grpc_alts_credentials_client_options*>( gpr_zalloc(sizeof(grpc_alts_credentials_client_options))); client_options->base.vtable = &vtable; diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc index 72c654211f..c374cefd43 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc @@ -36,8 +36,8 @@ static void alts_server_options_destroy( static const grpc_alts_credentials_options_vtable vtable = { alts_server_options_copy, alts_server_options_destroy}; -grpc_alts_credentials_options* grpc_alts_credentials_server_options_create( - void) { +grpc_alts_credentials_options* grpc_alts_credentials_server_options_create( + void) { grpc_alts_credentials_server_options* server_options = static_cast<grpc_alts_credentials_server_options*>( gpr_zalloc(sizeof(*server_options))); diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc index a6c82d4774..0e02a1adbd 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.cc @@ -20,13 +20,13 @@ #include "src/core/lib/security/credentials/composite/composite_credentials.h" -#include <cstring> -#include <new> +#include <cstring> +#include <new> #include <vector> #include "y_absl/strings/str_cat.h" #include "y_absl/strings/str_join.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/polling_entity.h" #include "src/core/lib/surface/api_trace.h" @@ -36,44 +36,44 @@ /* -- Composite call credentials. -- */ -static void composite_call_metadata_cb(void* arg, grpc_error* error); - -namespace { -struct grpc_composite_call_credentials_metadata_context { - grpc_composite_call_credentials_metadata_context( - grpc_composite_call_credentials* composite_creds, - grpc_polling_entity* pollent, grpc_auth_metadata_context auth_md_context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata) - : composite_creds(composite_creds), - pollent(pollent), - auth_md_context(auth_md_context), - md_array(md_array), - on_request_metadata(on_request_metadata) { - GRPC_CLOSURE_INIT(&internal_on_request_metadata, composite_call_metadata_cb, - this, grpc_schedule_on_exec_ctx); - } - +static void composite_call_metadata_cb(void* arg, grpc_error* error); + +namespace { +struct grpc_composite_call_credentials_metadata_context { + grpc_composite_call_credentials_metadata_context( + grpc_composite_call_credentials* composite_creds, + grpc_polling_entity* pollent, grpc_auth_metadata_context auth_md_context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata) + : composite_creds(composite_creds), + pollent(pollent), + auth_md_context(auth_md_context), + md_array(md_array), + on_request_metadata(on_request_metadata) { + GRPC_CLOSURE_INIT(&internal_on_request_metadata, composite_call_metadata_cb, + this, grpc_schedule_on_exec_ctx); + } + grpc_composite_call_credentials* composite_creds; - size_t creds_index = 0; + size_t creds_index = 0; grpc_polling_entity* pollent; grpc_auth_metadata_context auth_md_context; grpc_credentials_mdelem_array* md_array; grpc_closure* on_request_metadata; grpc_closure internal_on_request_metadata; -}; -} // namespace +}; +} // namespace static void composite_call_metadata_cb(void* arg, grpc_error* error) { grpc_composite_call_credentials_metadata_context* ctx = static_cast<grpc_composite_call_credentials_metadata_context*>(arg); if (error == GRPC_ERROR_NONE) { - const grpc_composite_call_credentials::CallCredentialsList& inner = - ctx->composite_creds->inner(); + const grpc_composite_call_credentials::CallCredentialsList& inner = + ctx->composite_creds->inner(); /* See if we need to get some more metadata. */ - if (ctx->creds_index < inner.size()) { - if (inner[ctx->creds_index++]->get_request_metadata( - ctx->pollent, ctx->auth_md_context, ctx->md_array, + if (ctx->creds_index < inner.size()) { + if (inner[ctx->creds_index++]->get_request_metadata( + ctx->pollent, ctx->auth_md_context, ctx->md_array, &ctx->internal_on_request_metadata, &error)) { // Synchronous response, so call ourselves recursively. composite_call_metadata_cb(arg, error); @@ -88,18 +88,18 @@ static void composite_call_metadata_cb(void* arg, grpc_error* error) { delete ctx; } -bool grpc_composite_call_credentials::get_request_metadata( - grpc_polling_entity* pollent, grpc_auth_metadata_context auth_md_context, +bool grpc_composite_call_credentials::get_request_metadata( + grpc_polling_entity* pollent, grpc_auth_metadata_context auth_md_context, grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, grpc_error** error) { grpc_composite_call_credentials_metadata_context* ctx; ctx = new grpc_composite_call_credentials_metadata_context( - this, pollent, auth_md_context, md_array, on_request_metadata); + this, pollent, auth_md_context, md_array, on_request_metadata); bool synchronous = true; - const CallCredentialsList& inner = ctx->composite_creds->inner(); - while (ctx->creds_index < inner.size()) { - if (inner[ctx->creds_index++]->get_request_metadata( - ctx->pollent, ctx->auth_md_context, ctx->md_array, + const CallCredentialsList& inner = ctx->composite_creds->inner(); + while (ctx->creds_index < inner.size()) { + if (inner[ctx->creds_index++]->get_request_metadata( + ctx->pollent, ctx->auth_md_context, ctx->md_array, &ctx->internal_on_request_metadata, error)) { if (*error != GRPC_ERROR_NONE) break; } else { @@ -111,10 +111,10 @@ bool grpc_composite_call_credentials::get_request_metadata( return synchronous; } -void grpc_composite_call_credentials::cancel_get_request_metadata( - grpc_credentials_mdelem_array* md_array, grpc_error* error) { - for (size_t i = 0; i < inner_.size(); ++i) { - inner_[i]->cancel_get_request_metadata(md_array, GRPC_ERROR_REF(error)); +void grpc_composite_call_credentials::cancel_get_request_metadata( + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + for (size_t i = 0; i < inner_.size(); ++i) { + inner_[i]->cancel_get_request_metadata(md_array, GRPC_ERROR_REF(error)); } GRPC_ERROR_UNREF(error); } @@ -128,41 +128,41 @@ TString grpc_composite_call_credentials::debug_string() { "}"); } -static size_t get_creds_array_size(const grpc_call_credentials* creds, - bool is_composite) { - return is_composite - ? static_cast<const grpc_composite_call_credentials*>(creds) - ->inner() - .size() - : 1; -} - -void grpc_composite_call_credentials::push_to_inner( - grpc_core::RefCountedPtr<grpc_call_credentials> creds, bool is_composite) { - if (!is_composite) { - inner_.push_back(std::move(creds)); - return; - } - auto composite_creds = - static_cast<grpc_composite_call_credentials*>(creds.get()); - for (size_t i = 0; i < composite_creds->inner().size(); ++i) { - inner_.push_back(std::move(composite_creds->inner_[i])); +static size_t get_creds_array_size(const grpc_call_credentials* creds, + bool is_composite) { + return is_composite + ? static_cast<const grpc_composite_call_credentials*>(creds) + ->inner() + .size() + : 1; +} + +void grpc_composite_call_credentials::push_to_inner( + grpc_core::RefCountedPtr<grpc_call_credentials> creds, bool is_composite) { + if (!is_composite) { + inner_.push_back(std::move(creds)); + return; } + auto composite_creds = + static_cast<grpc_composite_call_credentials*>(creds.get()); + for (size_t i = 0; i < composite_creds->inner().size(); ++i) { + inner_.push_back(std::move(composite_creds->inner_[i])); + } } -grpc_composite_call_credentials::grpc_composite_call_credentials( - grpc_core::RefCountedPtr<grpc_call_credentials> creds1, - grpc_core::RefCountedPtr<grpc_call_credentials> creds2) - : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) { - const bool creds1_is_composite = - strcmp(creds1->type(), GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0; - const bool creds2_is_composite = - strcmp(creds2->type(), GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0; - const size_t size = get_creds_array_size(creds1.get(), creds1_is_composite) + - get_creds_array_size(creds2.get(), creds2_is_composite); - inner_.reserve(size); - push_to_inner(std::move(creds1), creds1_is_composite); - push_to_inner(std::move(creds2), creds2_is_composite); +grpc_composite_call_credentials::grpc_composite_call_credentials( + grpc_core::RefCountedPtr<grpc_call_credentials> creds1, + grpc_core::RefCountedPtr<grpc_call_credentials> creds2) + : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) { + const bool creds1_is_composite = + strcmp(creds1->type(), GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0; + const bool creds2_is_composite = + strcmp(creds2->type(), GRPC_CALL_CREDENTIALS_TYPE_COMPOSITE) == 0; + const size_t size = get_creds_array_size(creds1.get(), creds1_is_composite) + + get_creds_array_size(creds2.get(), creds2_is_composite); + inner_.reserve(size); + push_to_inner(std::move(creds1), creds1_is_composite); + push_to_inner(std::move(creds2), creds2_is_composite); min_security_level_ = GRPC_SECURITY_NONE; for (size_t i = 0; i < inner_.size(); ++i) { if (static_cast<int>(min_security_level_) < @@ -170,16 +170,16 @@ grpc_composite_call_credentials::grpc_composite_call_credentials( min_security_level_ = inner_[i]->min_security_level(); } } -} - -static grpc_core::RefCountedPtr<grpc_call_credentials> -composite_call_credentials_create( - grpc_core::RefCountedPtr<grpc_call_credentials> creds1, - grpc_core::RefCountedPtr<grpc_call_credentials> creds2) { - return grpc_core::MakeRefCounted<grpc_composite_call_credentials>( - std::move(creds1), std::move(creds2)); -} - +} + +static grpc_core::RefCountedPtr<grpc_call_credentials> +composite_call_credentials_create( + grpc_core::RefCountedPtr<grpc_call_credentials> creds1, + grpc_core::RefCountedPtr<grpc_call_credentials> creds2) { + return grpc_core::MakeRefCounted<grpc_composite_call_credentials>( + std::move(creds1), std::move(creds2)); +} + grpc_call_credentials* grpc_composite_call_credentials_create( grpc_call_credentials* creds1, grpc_call_credentials* creds2, void* reserved) { @@ -191,27 +191,27 @@ grpc_call_credentials* grpc_composite_call_credentials_create( GPR_ASSERT(creds1 != nullptr); GPR_ASSERT(creds2 != nullptr); - return composite_call_credentials_create(creds1->Ref(), creds2->Ref()) - .release(); + return composite_call_credentials_create(creds1->Ref(), creds2->Ref()) + .release(); } /* -- Composite channel credentials. -- */ -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_composite_channel_credentials::create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_composite_channel_credentials::create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, const char* target, const grpc_channel_args* args, - grpc_channel_args** new_args) { - GPR_ASSERT(inner_creds_ != nullptr && call_creds_ != nullptr); + grpc_channel_args** new_args) { + GPR_ASSERT(inner_creds_ != nullptr && call_creds_ != nullptr); /* If we are passed a call_creds, create a call composite to pass it downstream. */ if (call_creds != nullptr) { - return inner_creds_->create_security_connector( - composite_call_credentials_create(call_creds_, std::move(call_creds)), - target, args, new_args); + return inner_creds_->create_security_connector( + composite_call_credentials_create(call_creds_, std::move(call_creds)), + target, args, new_args); } else { - return inner_creds_->create_security_connector(call_creds_, target, args, - new_args); + return inner_creds_->create_security_connector(call_creds_, target, args, + new_args); } } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h index 5bebb9bd5a..8c4c21ada6 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/composite/composite_credentials.h @@ -25,82 +25,82 @@ #include "y_absl/container/inlined_vector.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/credentials/credentials.h" -/* -- Composite channel credentials. -- */ - -class grpc_composite_channel_credentials : public grpc_channel_credentials { - public: - grpc_composite_channel_credentials( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds) - : grpc_channel_credentials(channel_creds->type()), - inner_creds_(std::move(channel_creds)), - call_creds_(std::move(call_creds)) {} - - ~grpc_composite_channel_credentials() override = default; - - grpc_core::RefCountedPtr<grpc_channel_credentials> - duplicate_without_call_credentials() override { - return inner_creds_; - } - - grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, - const char* target, const grpc_channel_args* args, - grpc_channel_args** new_args) override; - - grpc_channel_args* update_arguments(grpc_channel_args* args) override { - return inner_creds_->update_arguments(args); - } - - const grpc_channel_credentials* inner_creds() const { - return inner_creds_.get(); - } - const grpc_call_credentials* call_creds() const { return call_creds_.get(); } - grpc_call_credentials* mutable_call_creds() { return call_creds_.get(); } - - private: - grpc_core::RefCountedPtr<grpc_channel_credentials> inner_creds_; - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds_; -}; - +/* -- Composite channel credentials. -- */ + +class grpc_composite_channel_credentials : public grpc_channel_credentials { + public: + grpc_composite_channel_credentials( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds) + : grpc_channel_credentials(channel_creds->type()), + inner_creds_(std::move(channel_creds)), + call_creds_(std::move(call_creds)) {} + + ~grpc_composite_channel_credentials() override = default; + + grpc_core::RefCountedPtr<grpc_channel_credentials> + duplicate_without_call_credentials() override { + return inner_creds_; + } + + grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, + const char* target, const grpc_channel_args* args, + grpc_channel_args** new_args) override; + + grpc_channel_args* update_arguments(grpc_channel_args* args) override { + return inner_creds_->update_arguments(args); + } + + const grpc_channel_credentials* inner_creds() const { + return inner_creds_.get(); + } + const grpc_call_credentials* call_creds() const { return call_creds_.get(); } + grpc_call_credentials* mutable_call_creds() { return call_creds_.get(); } + + private: + grpc_core::RefCountedPtr<grpc_channel_credentials> inner_creds_; + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds_; +}; + /* -- Composite call credentials. -- */ -class grpc_composite_call_credentials : public grpc_call_credentials { - public: - using CallCredentialsList = +class grpc_composite_call_credentials : public grpc_call_credentials { + public: + using CallCredentialsList = y_absl::InlinedVector<grpc_core::RefCountedPtr<grpc_call_credentials>, 2>; - grpc_composite_call_credentials( - grpc_core::RefCountedPtr<grpc_call_credentials> creds1, - grpc_core::RefCountedPtr<grpc_call_credentials> creds2); - ~grpc_composite_call_credentials() override = default; - - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; - + grpc_composite_call_credentials( + grpc_core::RefCountedPtr<grpc_call_credentials> creds1, + grpc_core::RefCountedPtr<grpc_call_credentials> creds2); + ~grpc_composite_call_credentials() override = default; + + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; + grpc_security_level min_security_level() const override { return min_security_level_; } - const CallCredentialsList& inner() const { return inner_; } + const CallCredentialsList& inner() const { return inner_; } TString debug_string() override; - - private: - void push_to_inner(grpc_core::RefCountedPtr<grpc_call_credentials> creds, - bool is_composite); + + private: + void push_to_inner(grpc_core::RefCountedPtr<grpc_call_credentials> creds, + bool is_composite); grpc_security_level min_security_level_; - CallCredentialsList inner_; -}; - + CallCredentialsList inner_; +}; + #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_COMPOSITE_COMPOSITE_CREDENTIALS_H \ */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc index 90452d68d6..f83eba0e52 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.cc @@ -42,21 +42,21 @@ void grpc_channel_credentials_release(grpc_channel_credentials* creds) { GRPC_API_TRACE("grpc_channel_credentials_release(creds=%p)", 1, (creds)); grpc_core::ExecCtx exec_ctx; - if (creds) creds->Unref(); + if (creds) creds->Unref(); } void grpc_call_credentials_release(grpc_call_credentials* creds) { GRPC_API_TRACE("grpc_call_credentials_release(creds=%p)", 1, (creds)); grpc_core::ExecCtx exec_ctx; - if (creds) creds->Unref(); + if (creds) creds->Unref(); } static void credentials_pointer_arg_destroy(void* p) { - static_cast<grpc_channel_credentials*>(p)->Unref(); + static_cast<grpc_channel_credentials*>(p)->Unref(); } static void* credentials_pointer_arg_copy(void* p) { - return static_cast<grpc_channel_credentials*>(p)->Ref().release(); + return static_cast<grpc_channel_credentials*>(p)->Ref().release(); } static int credentials_pointer_cmp(void* a, void* b) { return GPR_ICMP(a, b); } @@ -98,32 +98,32 @@ grpc_channel_credentials* grpc_channel_credentials_find_in_args( void grpc_server_credentials_release(grpc_server_credentials* creds) { GRPC_API_TRACE("grpc_server_credentials_release(creds=%p)", 1, (creds)); grpc_core::ExecCtx exec_ctx; - if (creds) creds->Unref(); + if (creds) creds->Unref(); } -void grpc_server_credentials::set_auth_metadata_processor( - const grpc_auth_metadata_processor& processor) { +void grpc_server_credentials::set_auth_metadata_processor( + const grpc_auth_metadata_processor& processor) { GRPC_API_TRACE( "grpc_server_credentials_set_auth_metadata_processor(" "creds=%p, " "processor=grpc_auth_metadata_processor { process: %p, state: %p })", - 3, (this, (void*)(intptr_t)processor.process, processor.state)); - DestroyProcessor(); - processor_ = processor; -} - -void grpc_server_credentials_set_auth_metadata_processor( - grpc_server_credentials* creds, grpc_auth_metadata_processor processor) { - GPR_DEBUG_ASSERT(creds != nullptr); - creds->set_auth_metadata_processor(processor); + 3, (this, (void*)(intptr_t)processor.process, processor.state)); + DestroyProcessor(); + processor_ = processor; } +void grpc_server_credentials_set_auth_metadata_processor( + grpc_server_credentials* creds, grpc_auth_metadata_processor processor) { + GPR_DEBUG_ASSERT(creds != nullptr); + creds->set_auth_metadata_processor(processor); +} + static void server_credentials_pointer_arg_destroy(void* p) { - static_cast<grpc_server_credentials*>(p)->Unref(); + static_cast<grpc_server_credentials*>(p)->Unref(); } static void* server_credentials_pointer_arg_copy(void* p) { - return static_cast<grpc_server_credentials*>(p)->Ref().release(); + return static_cast<grpc_server_credentials*>(p)->Ref().release(); } static int server_credentials_pointer_cmp(void* a, void* b) { diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h index 15a85cbd0b..9a77d7685f 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/credentials.h @@ -30,7 +30,7 @@ #include <grpc/support/sync.h> #include "src/core/lib/transport/metadata_batch.h" -#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/http/httpcli.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/iomgr/polling_entity.h" @@ -50,7 +50,7 @@ typedef enum { #define GRPC_CHANNEL_CREDENTIALS_TYPE_SSL "Ssl" #define GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY \ "FakeTransportSecurity" -#define GRPC_CHANNEL_CREDENTIALS_TYPE_GOOGLE_DEFAULT "GoogleDefault" +#define GRPC_CHANNEL_CREDENTIALS_TYPE_GOOGLE_DEFAULT "GoogleDefault" #define GRPC_CALL_CREDENTIALS_TYPE_OAUTH2 "Oauth2" #define GRPC_CALL_CREDENTIALS_TYPE_JWT "Jwt" @@ -64,7 +64,7 @@ typedef enum { #define GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS 60 -#define GRPC_COMPUTE_ENGINE_METADATA_HOST "metadata.google.internal." +#define GRPC_COMPUTE_ENGINE_METADATA_HOST "metadata.google.internal." #define GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH \ "/computeMetadata/v1/instance/service-accounts/default/token" @@ -95,47 +95,47 @@ void grpc_override_well_known_credentials_path_getter( #define GRPC_ARG_CHANNEL_CREDENTIALS "grpc.channel_credentials" -// This type is forward declared as a C struct and we cannot define it as a -// class. Otherwise, compiler will complain about type mismatch due to -// -Wmismatched-tags. -struct grpc_channel_credentials - : grpc_core::RefCounted<grpc_channel_credentials> { - public: - explicit grpc_channel_credentials(const char* type) : type_(type) {} - virtual ~grpc_channel_credentials() = default; - - // Creates a security connector for the channel. May also create new channel - // args for the channel to be used in place of the passed in const args if - // returned non NULL. In that case the caller is responsible for destroying - // new_args after channel creation. - virtual grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, +// This type is forward declared as a C struct and we cannot define it as a +// class. Otherwise, compiler will complain about type mismatch due to +// -Wmismatched-tags. +struct grpc_channel_credentials + : grpc_core::RefCounted<grpc_channel_credentials> { + public: + explicit grpc_channel_credentials(const char* type) : type_(type) {} + virtual ~grpc_channel_credentials() = default; + + // Creates a security connector for the channel. May also create new channel + // args for the channel to be used in place of the passed in const args if + // returned non NULL. In that case the caller is responsible for destroying + // new_args after channel creation. + virtual grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, const char* target, const grpc_channel_args* args, grpc_channel_args** new_args) = 0; - // Creates a version of the channel credentials without any attached call - // credentials. This can be used in order to open a channel to a non-trusted - // gRPC load balancer. - virtual grpc_core::RefCountedPtr<grpc_channel_credentials> - duplicate_without_call_credentials() { - // By default we just increment the refcount. - return Ref(); - } - - // Allows credentials to optionally modify a parent channel's args. - // By default, leave channel args as is. The callee takes ownership - // of the passed-in channel args, and the caller takes ownership - // of the returned channel args. - virtual grpc_channel_args* update_arguments(grpc_channel_args* args) { - return args; - } - - const char* type() const { return type_; } - - private: - const char* type_; -}; + // Creates a version of the channel credentials without any attached call + // credentials. This can be used in order to open a channel to a non-trusted + // gRPC load balancer. + virtual grpc_core::RefCountedPtr<grpc_channel_credentials> + duplicate_without_call_credentials() { + // By default we just increment the refcount. + return Ref(); + } + + // Allows credentials to optionally modify a parent channel's args. + // By default, leave channel args as is. The callee takes ownership + // of the passed-in channel args, and the caller takes ownership + // of the returned channel args. + virtual grpc_channel_args* update_arguments(grpc_channel_args* args) { + return args; + } + + const char* type() const { return type_; } + + private: + const char* type_; +}; /* Util to encapsulate the channel credentials in a channel arg. */ grpc_arg grpc_channel_credentials_to_arg(grpc_channel_credentials* credentials); @@ -151,8 +151,8 @@ grpc_channel_credentials* grpc_channel_credentials_find_in_args( /* --- grpc_credentials_mdelem_array. --- */ struct grpc_credentials_mdelem_array { - grpc_mdelem* md = nullptr; - size_t size = 0; + grpc_mdelem* md = nullptr; + size_t size = 0; }; /// Takes a new ref to \a md. void grpc_credentials_mdelem_array_add(grpc_credentials_mdelem_array* list, @@ -166,33 +166,33 @@ void grpc_credentials_mdelem_array_destroy(grpc_credentials_mdelem_array* list); /* --- grpc_call_credentials. --- */ -// This type is forward declared as a C struct and we cannot define it as a -// class. Otherwise, compiler will complain about type mismatch due to -// -Wmismatched-tags. -struct grpc_call_credentials - : public grpc_core::RefCounted<grpc_call_credentials> { - public: +// This type is forward declared as a C struct and we cannot define it as a +// class. Otherwise, compiler will complain about type mismatch due to +// -Wmismatched-tags. +struct grpc_call_credentials + : public grpc_core::RefCounted<grpc_call_credentials> { + public: explicit grpc_call_credentials( const char* type, grpc_security_level min_security_level = GRPC_PRIVACY_AND_INTEGRITY) : type_(type), min_security_level_(min_security_level) {} - virtual ~grpc_call_credentials() = default; + virtual ~grpc_call_credentials() = default; - // Returns true if completed synchronously, in which case \a error will - // be set to indicate the result. Otherwise, \a on_request_metadata will - // be invoked asynchronously when complete. \a md_array will be populated - // with the resulting metadata once complete. - virtual bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, + // Returns true if completed synchronously, in which case \a error will + // be set to indicate the result. Otherwise, \a on_request_metadata will + // be invoked asynchronously when complete. \a md_array will be populated + // with the resulting metadata once complete. + virtual bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, grpc_error** error) = 0; - // Cancels a pending asynchronous operation started by - // grpc_call_credentials_get_request_metadata() with the corresponding - // value of \a md_array. - virtual void cancel_get_request_metadata( + // Cancels a pending asynchronous operation started by + // grpc_call_credentials_get_request_metadata() with the corresponding + // value of \a md_array. + virtual void cancel_get_request_metadata( grpc_credentials_mdelem_array* md_array, grpc_error* error) = 0; virtual grpc_security_level min_security_level() const { @@ -203,13 +203,13 @@ struct grpc_call_credentials return "grpc_call_credentials did not provide debug string"; } - const char* type() const { return type_; } + const char* type() const { return type_; } - private: - const char* type_; + private: + const char* type_; const grpc_security_level min_security_level_; -}; - +}; + /* Metadata-only credentials with the specified key and value where asynchronicity can be simulated for testing. */ grpc_call_credentials* grpc_md_only_test_credentials_create( @@ -217,39 +217,39 @@ grpc_call_credentials* grpc_md_only_test_credentials_create( /* --- grpc_server_credentials. --- */ -// This type is forward declared as a C struct and we cannot define it as a -// class. Otherwise, compiler will complain about type mismatch due to -// -Wmismatched-tags. -struct grpc_server_credentials - : public grpc_core::RefCounted<grpc_server_credentials> { - public: - explicit grpc_server_credentials(const char* type) : type_(type) {} +// This type is forward declared as a C struct and we cannot define it as a +// class. Otherwise, compiler will complain about type mismatch due to +// -Wmismatched-tags. +struct grpc_server_credentials + : public grpc_core::RefCounted<grpc_server_credentials> { + public: + explicit grpc_server_credentials(const char* type) : type_(type) {} - virtual ~grpc_server_credentials() { DestroyProcessor(); } + virtual ~grpc_server_credentials() { DestroyProcessor(); } - virtual grpc_core::RefCountedPtr<grpc_server_security_connector> + virtual grpc_core::RefCountedPtr<grpc_server_security_connector> create_security_connector() = 0; - const char* type() const { return type_; } - - const grpc_auth_metadata_processor& auth_metadata_processor() const { - return processor_; - } - void set_auth_metadata_processor( - const grpc_auth_metadata_processor& processor); - - private: - void DestroyProcessor() { - if (processor_.destroy != nullptr && processor_.state != nullptr) { - processor_.destroy(processor_.state); - } - } - - const char* type_; - grpc_auth_metadata_processor processor_ = - grpc_auth_metadata_processor(); // Zero-initialize the C struct. -}; - + const char* type() const { return type_; } + + const grpc_auth_metadata_processor& auth_metadata_processor() const { + return processor_; + } + void set_auth_metadata_processor( + const grpc_auth_metadata_processor& processor); + + private: + void DestroyProcessor() { + if (processor_.destroy != nullptr && processor_.state != nullptr) { + processor_.destroy(processor_.state); + } + } + + const char* type_; + grpc_auth_metadata_processor processor_ = + grpc_auth_metadata_processor(); // Zero-initialize the C struct. +}; + #define GRPC_SERVER_CREDENTIALS_ARG "grpc.server_credentials" grpc_arg grpc_server_credentials_to_arg(grpc_server_credentials* c); @@ -259,27 +259,27 @@ grpc_server_credentials* grpc_find_server_credentials_in_args( /* -- Credentials Metadata Request. -- */ -struct grpc_credentials_metadata_request { - explicit grpc_credentials_metadata_request( - grpc_core::RefCountedPtr<grpc_call_credentials> creds) - : creds(std::move(creds)) {} - ~grpc_credentials_metadata_request() { - grpc_http_response_destroy(&response); - } - - grpc_core::RefCountedPtr<grpc_call_credentials> creds; +struct grpc_credentials_metadata_request { + explicit grpc_credentials_metadata_request( + grpc_core::RefCountedPtr<grpc_call_credentials> creds) + : creds(std::move(creds)) {} + ~grpc_credentials_metadata_request() { + grpc_http_response_destroy(&response); + } + + grpc_core::RefCountedPtr<grpc_call_credentials> creds; grpc_http_response response; -}; +}; -inline grpc_credentials_metadata_request* -grpc_credentials_metadata_request_create( - grpc_core::RefCountedPtr<grpc_call_credentials> creds) { +inline grpc_credentials_metadata_request* +grpc_credentials_metadata_request_create( + grpc_core::RefCountedPtr<grpc_call_credentials> creds) { return new grpc_credentials_metadata_request(std::move(creds)); -} +} -inline void grpc_credentials_metadata_request_destroy( - grpc_credentials_metadata_request* r) { +inline void grpc_credentials_metadata_request_destroy( + grpc_credentials_metadata_request* r) { delete r; -} +} #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_CREDENTIALS_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc index 8fd0493ee4..8144510aef 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.cc @@ -29,48 +29,48 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/executor.h" -#include "src/core/lib/security/security_connector/fake/fake_security_connector.h" +#include "src/core/lib/security/security_connector/fake/fake_security_connector.h" /* -- Fake transport security credentials. -- */ -namespace { -class grpc_fake_channel_credentials final : public grpc_channel_credentials { - public: - grpc_fake_channel_credentials() - : grpc_channel_credentials( - GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY) {} - ~grpc_fake_channel_credentials() override = default; - - grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, - const char* target, const grpc_channel_args* args, +namespace { +class grpc_fake_channel_credentials final : public grpc_channel_credentials { + public: + grpc_fake_channel_credentials() + : grpc_channel_credentials( + GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY) {} + ~grpc_fake_channel_credentials() override = default; + + grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, + const char* target, const grpc_channel_args* args, grpc_channel_args** /*new_args*/) override { - return grpc_fake_channel_security_connector_create( - this->Ref(), std::move(call_creds), target, args); - } -}; - -class grpc_fake_server_credentials final : public grpc_server_credentials { - public: - grpc_fake_server_credentials() - : grpc_server_credentials( - GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY) {} - ~grpc_fake_server_credentials() override = default; - - grpc_core::RefCountedPtr<grpc_server_security_connector> - create_security_connector() override { - return grpc_fake_server_security_connector_create(this->Ref()); - } -}; -} // namespace - -grpc_channel_credentials* grpc_fake_transport_security_credentials_create() { + return grpc_fake_channel_security_connector_create( + this->Ref(), std::move(call_creds), target, args); + } +}; + +class grpc_fake_server_credentials final : public grpc_server_credentials { + public: + grpc_fake_server_credentials() + : grpc_server_credentials( + GRPC_CHANNEL_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY) {} + ~grpc_fake_server_credentials() override = default; + + grpc_core::RefCountedPtr<grpc_server_security_connector> + create_security_connector() override { + return grpc_fake_server_security_connector_create(this->Ref()); + } +}; +} // namespace + +grpc_channel_credentials* grpc_fake_transport_security_credentials_create() { return new grpc_fake_channel_credentials(); } -grpc_server_credentials* -grpc_fake_transport_security_server_credentials_create() { +grpc_server_credentials* +grpc_fake_transport_security_server_credentials_create() { return new grpc_fake_server_credentials(); } @@ -88,12 +88,12 @@ const char* grpc_fake_transport_get_expected_targets( /* -- Metadata-only test credentials. -- */ -bool grpc_md_only_test_credentials::get_request_metadata( +bool grpc_md_only_test_credentials::get_request_metadata( grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/, - grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, grpc_error** /*error*/) { - grpc_credentials_mdelem_array_add(md_array, md_); - if (is_async_) { + grpc_credentials_mdelem_array_add(md_array, md_); + if (is_async_) { grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_request_metadata, GRPC_ERROR_NONE); return false; @@ -101,7 +101,7 @@ bool grpc_md_only_test_credentials::get_request_metadata( return true; } -void grpc_md_only_test_credentials::cancel_get_request_metadata( +void grpc_md_only_test_credentials::cancel_get_request_metadata( grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) { GRPC_ERROR_UNREF(error); } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h index 27f3a28451..2937d50135 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/fake/fake_credentials.h @@ -57,31 +57,31 @@ const char* grpc_fake_transport_get_expected_targets( /* -- Metadata-only Test credentials. -- */ -class grpc_md_only_test_credentials : public grpc_call_credentials { - public: - grpc_md_only_test_credentials(const char* md_key, const char* md_value, - bool is_async) +class grpc_md_only_test_credentials : public grpc_call_credentials { + public: + grpc_md_only_test_credentials(const char* md_key, const char* md_value, + bool is_async) : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2, GRPC_SECURITY_NONE), - md_(grpc_mdelem_from_slices(grpc_slice_from_copied_string(md_key), - grpc_slice_from_copied_string(md_value))), - is_async_(is_async) {} - ~grpc_md_only_test_credentials() override { GRPC_MDELEM_UNREF(md_); } - - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; - + md_(grpc_mdelem_from_slices(grpc_slice_from_copied_string(md_key), + grpc_slice_from_copied_string(md_value))), + is_async_(is_async) {} + ~grpc_md_only_test_credentials() override { GRPC_MDELEM_UNREF(md_); } + + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; + TString debug_string() override { return "MD only Test Credentials"; }; - private: - grpc_mdelem md_; - bool is_async_; -}; - + private: + grpc_mdelem md_; + bool is_async_; +}; + #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_FAKE_FAKE_CREDENTIALS_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc index 8f3ca009a5..7be5998e2b 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.cc @@ -26,17 +26,17 @@ #include <grpc/support/log.h> #include <grpc/support/sync.h> -#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h" -#include "src/core/lib/channel/channel_args.h" +#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h" +#include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/string.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/http/httpcli.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/iomgr/polling_entity.h" -#include "src/core/lib/security/credentials/alts/alts_credentials.h" -#include "src/core/lib/security/credentials/alts/check_gcp_environment.h" +#include "src/core/lib/security/credentials/alts/alts_credentials.h" +#include "src/core/lib/security/credentials/alts/check_gcp_environment.h" #include "src/core/lib/security/credentials/google_default/google_default_credentials.h" #include "src/core/lib/security/credentials/jwt/jwt_credentials.h" #include "src/core/lib/security/credentials/oauth2/oauth2_credentials.h" @@ -48,24 +48,24 @@ using grpc_core::Json; /* -- Constants. -- */ -#define GRPC_COMPUTE_ENGINE_DETECTION_HOST "metadata.google.internal." +#define GRPC_COMPUTE_ENGINE_DETECTION_HOST "metadata.google.internal." #define GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR \ "Failed to create Google credentials" /* -- Default credentials. -- */ -/* A sticky bit that will be set only if the result of metadata server detection - * is positive. We do not set the bit if the result is negative. Because it - * means the detection is done via network test that is unreliable and the - * unreliable result should not be referred by successive calls. */ -static int g_metadata_server_available = 0; +/* A sticky bit that will be set only if the result of metadata server detection + * is positive. We do not set the bit if the result is negative. Because it + * means the detection is done via network test that is unreliable and the + * unreliable result should not be referred by successive calls. */ +static int g_metadata_server_available = 0; static gpr_mu g_state_mu; -/* Protect a metadata_server_detector instance that can be modified by more than - * one gRPC threads */ +/* Protect a metadata_server_detector instance that can be modified by more than + * one gRPC threads */ static gpr_mu* g_polling_mu; static gpr_once g_once = GPR_ONCE_INIT; -static grpc_core::internal::grpc_gce_tenancy_checker g_gce_tenancy_checker = - grpc_alts_is_running_on_gcp; +static grpc_core::internal::grpc_gce_tenancy_checker g_gce_tenancy_checker = + grpc_alts_is_running_on_gcp; static void init_default_credentials(void) { gpr_mu_init(&g_state_mu); } @@ -75,64 +75,64 @@ struct metadata_server_detector { int success; grpc_http_response response; }; -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_google_default_channel_credentials::create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, - const char* target, const grpc_channel_args* args, - grpc_channel_args** new_args) { - bool is_grpclb_load_balancer = grpc_channel_arg_get_bool( - grpc_channel_args_find(args, GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER), - false); - bool is_backend_from_grpclb_load_balancer = grpc_channel_arg_get_bool( - grpc_channel_args_find( - args, GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER), - false); - bool use_alts = - is_grpclb_load_balancer || is_backend_from_grpclb_load_balancer; - /* Return failure if ALTS is selected but not running on GCE. */ +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_google_default_channel_credentials::create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, + const char* target, const grpc_channel_args* args, + grpc_channel_args** new_args) { + bool is_grpclb_load_balancer = grpc_channel_arg_get_bool( + grpc_channel_args_find(args, GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER), + false); + bool is_backend_from_grpclb_load_balancer = grpc_channel_arg_get_bool( + grpc_channel_args_find( + args, GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER), + false); + bool use_alts = + is_grpclb_load_balancer || is_backend_from_grpclb_load_balancer; + /* Return failure if ALTS is selected but not running on GCE. */ if (use_alts && alts_creds_ == nullptr) { - gpr_log(GPR_ERROR, "ALTS is selected, but not running on GCE."); - return nullptr; - } - - grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = - use_alts ? alts_creds_->create_security_connector(call_creds, target, - args, new_args) - : ssl_creds_->create_security_connector(call_creds, target, args, - new_args); - /* grpclb-specific channel args are removed from the channel args set - * to ensure backends and fallback adresses will have the same set of channel - * args. By doing that, it guarantees the connections to backends will not be - * torn down and re-connected when switching in and out of fallback mode. - */ - if (use_alts) { - static const char* args_to_remove[] = { - GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER, - GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER, - }; - *new_args = grpc_channel_args_copy_and_add_and_remove( - args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), nullptr, 0); - } - return sc; -} - -grpc_channel_args* grpc_google_default_channel_credentials::update_arguments( - grpc_channel_args* args) { - grpc_channel_args* updated = args; - if (grpc_channel_args_find(args, GRPC_ARG_DNS_ENABLE_SRV_QUERIES) == - nullptr) { - grpc_arg new_srv_arg = grpc_channel_arg_integer_create( - const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true); - updated = grpc_channel_args_copy_and_add(args, &new_srv_arg, 1); - grpc_channel_args_destroy(args); - } - return updated; -} - -static void on_metadata_server_detection_http_response(void* user_data, - grpc_error* error) { - metadata_server_detector* detector = - static_cast<metadata_server_detector*>(user_data); + gpr_log(GPR_ERROR, "ALTS is selected, but not running on GCE."); + return nullptr; + } + + grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = + use_alts ? alts_creds_->create_security_connector(call_creds, target, + args, new_args) + : ssl_creds_->create_security_connector(call_creds, target, args, + new_args); + /* grpclb-specific channel args are removed from the channel args set + * to ensure backends and fallback adresses will have the same set of channel + * args. By doing that, it guarantees the connections to backends will not be + * torn down and re-connected when switching in and out of fallback mode. + */ + if (use_alts) { + static const char* args_to_remove[] = { + GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER, + GRPC_ARG_ADDRESS_IS_BACKEND_FROM_GRPCLB_LOAD_BALANCER, + }; + *new_args = grpc_channel_args_copy_and_add_and_remove( + args, args_to_remove, GPR_ARRAY_SIZE(args_to_remove), nullptr, 0); + } + return sc; +} + +grpc_channel_args* grpc_google_default_channel_credentials::update_arguments( + grpc_channel_args* args) { + grpc_channel_args* updated = args; + if (grpc_channel_args_find(args, GRPC_ARG_DNS_ENABLE_SRV_QUERIES) == + nullptr) { + grpc_arg new_srv_arg = grpc_channel_arg_integer_create( + const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true); + updated = grpc_channel_args_copy_and_add(args, &new_srv_arg, 1); + grpc_channel_args_destroy(args); + } + return updated; +} + +static void on_metadata_server_detection_http_response(void* user_data, + grpc_error* error) { + metadata_server_detector* detector = + static_cast<metadata_server_detector*>(user_data); if (error == GRPC_ERROR_NONE && detector->response.status == 200 && detector->response.hdr_count > 0) { /* Internet providers can return a generic response to all requests, so @@ -160,8 +160,8 @@ static void destroy_pollset(void* p, grpc_error* /*e*/) { grpc_pollset_destroy(static_cast<grpc_pollset*>(p)); } -static int is_metadata_server_reachable() { - metadata_server_detector detector; +static int is_metadata_server_reachable() { + metadata_server_detector detector; grpc_httpcli_request request; grpc_httpcli_context context; grpc_closure destroy_closure; @@ -183,13 +183,13 @@ static int is_metadata_server_reachable() { grpc_httpcli_get( &context, &detector.pollent, resource_quota, &request, grpc_core::ExecCtx::Get()->Now() + max_detection_delay, - GRPC_CLOSURE_CREATE(on_metadata_server_detection_http_response, &detector, + GRPC_CLOSURE_CREATE(on_metadata_server_detection_http_response, &detector, grpc_schedule_on_exec_ctx), &detector.response); grpc_resource_quota_unref_internal(resource_quota); grpc_core::ExecCtx::Get()->Flush(); /* Block until we get the response. This is not ideal but this should only be - called once for the lifetime of the process by the default credentials. */ + called once for the lifetime of the process by the default credentials. */ gpr_mu_lock(g_polling_mu); while (!detector.is_done) { grpc_pollset_worker* worker = nullptr; @@ -221,7 +221,7 @@ static grpc_error* create_default_creds_from_path( grpc_core::RefCountedPtr<grpc_call_credentials>* creds) { grpc_auth_json_key key; grpc_auth_refresh_token token; - grpc_core::RefCountedPtr<grpc_call_credentials> result; + grpc_core::RefCountedPtr<grpc_call_credentials> result; grpc_slice creds_data = grpc_empty_slice(); grpc_error* error = GRPC_ERROR_NONE; Json json; @@ -278,18 +278,18 @@ static void update_tenancy() { gpr_once_init(&g_once, init_default_credentials); grpc_core::MutexLock lock(&g_state_mu); - /* Try a platform-provided hint for GCE. */ - if (!g_metadata_server_available) { + /* Try a platform-provided hint for GCE. */ + if (!g_metadata_server_available) { g_metadata_server_available = g_gce_tenancy_checker(); - } - /* TODO: Add a platform-provided hint for GAE. */ - - /* Do a network test for metadata server. */ - if (!g_metadata_server_available) { - g_metadata_server_available = is_metadata_server_reachable(); - } + } + /* TODO: Add a platform-provided hint for GAE. */ + + /* Do a network test for metadata server. */ + if (!g_metadata_server_available) { + g_metadata_server_available = is_metadata_server_reachable(); + } } - + static bool metadata_server_available() { grpc_core::MutexLock lock(&g_state_mu); return static_cast<bool>(g_metadata_server_available); @@ -318,9 +318,9 @@ static grpc_core::RefCountedPtr<grpc_call_credentials> make_default_call_creds( update_tenancy(); if (metadata_server_available()) { - call_creds = grpc_core::RefCountedPtr<grpc_call_credentials>( - grpc_google_compute_engine_credentials_create(nullptr)); - if (call_creds == nullptr) { + call_creds = grpc_core::RefCountedPtr<grpc_call_credentials>( + grpc_google_compute_engine_credentials_create(nullptr)); + if (call_creds == nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( GRPC_GOOGLE_CREDENTIAL_CREATION_ERROR); *error = grpc_error_add_child( @@ -346,49 +346,49 @@ grpc_channel_credentials* grpc_google_default_credentials_create( call_creds = make_default_call_creds(&error); } - if (call_creds != nullptr) { - /* Create google default credentials. */ - grpc_channel_credentials* ssl_creds = - grpc_ssl_credentials_create(nullptr, nullptr, nullptr, nullptr); - GPR_ASSERT(ssl_creds != nullptr); - grpc_alts_credentials_options* options = - grpc_alts_credentials_client_options_create(); - grpc_channel_credentials* alts_creds = - grpc_alts_credentials_create(options); - grpc_alts_credentials_options_destroy(options); - auto creds = - grpc_core::MakeRefCounted<grpc_google_default_channel_credentials>( + if (call_creds != nullptr) { + /* Create google default credentials. */ + grpc_channel_credentials* ssl_creds = + grpc_ssl_credentials_create(nullptr, nullptr, nullptr, nullptr); + GPR_ASSERT(ssl_creds != nullptr); + grpc_alts_credentials_options* options = + grpc_alts_credentials_client_options_create(); + grpc_channel_credentials* alts_creds = + grpc_alts_credentials_create(options); + grpc_alts_credentials_options_destroy(options); + auto creds = + grpc_core::MakeRefCounted<grpc_google_default_channel_credentials>( grpc_core::RefCountedPtr<grpc_channel_credentials>(alts_creds), grpc_core::RefCountedPtr<grpc_channel_credentials>(ssl_creds)); - result = grpc_composite_channel_credentials_create( - creds.get(), call_creds.get(), nullptr); - GPR_ASSERT(result != nullptr); + result = grpc_composite_channel_credentials_create( + creds.get(), call_creds.get(), nullptr); + GPR_ASSERT(result != nullptr); } else { - gpr_log(GPR_ERROR, "Could not create google default credentials: %s", - grpc_error_string(error)); + gpr_log(GPR_ERROR, "Could not create google default credentials: %s", + grpc_error_string(error)); } - GRPC_ERROR_UNREF(error); + GRPC_ERROR_UNREF(error); return result; } -namespace grpc_core { -namespace internal { - -void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker) { - g_gce_tenancy_checker = checker; -} - +namespace grpc_core { +namespace internal { + +void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker) { + g_gce_tenancy_checker = checker; +} + void grpc_flush_cached_google_default_credentials(void) { grpc_core::ExecCtx exec_ctx; gpr_once_init(&g_once, init_default_credentials); gpr_mu_lock(&g_state_mu); - g_metadata_server_available = 0; + g_metadata_server_available = 0; gpr_mu_unlock(&g_state_mu); } -} // namespace internal -} // namespace grpc_core - +} // namespace internal +} // namespace grpc_core + /* -- Well known credentials path. -- */ static grpc_well_known_credentials_path_getter creds_path_getter = nullptr; diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h index 8a945da31e..fe0aedb92a 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/google_default/google_default_credentials.h @@ -21,7 +21,7 @@ #include <grpc/support/port_platform.h> -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/credentials/credentials.h" #define GRPC_GOOGLE_CLOUD_SDK_CONFIG_DIRECTORY "gcloud" @@ -40,48 +40,48 @@ "/" GRPC_GOOGLE_WELL_KNOWN_CREDENTIALS_FILE #endif -class grpc_google_default_channel_credentials - : public grpc_channel_credentials { - public: - grpc_google_default_channel_credentials( - grpc_core::RefCountedPtr<grpc_channel_credentials> alts_creds, - grpc_core::RefCountedPtr<grpc_channel_credentials> ssl_creds) - : grpc_channel_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_GOOGLE_DEFAULT), - alts_creds_(std::move(alts_creds)), - ssl_creds_(std::move(ssl_creds)) {} - - ~grpc_google_default_channel_credentials() override = default; - - grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, - const char* target, const grpc_channel_args* args, - grpc_channel_args** new_args) override; - - grpc_channel_args* update_arguments(grpc_channel_args* args) override; - - const grpc_channel_credentials* alts_creds() const { - return alts_creds_.get(); - } - const grpc_channel_credentials* ssl_creds() const { return ssl_creds_.get(); } - - private: - grpc_core::RefCountedPtr<grpc_channel_credentials> alts_creds_; - grpc_core::RefCountedPtr<grpc_channel_credentials> ssl_creds_; -}; - -namespace grpc_core { -namespace internal { - -typedef bool (*grpc_gce_tenancy_checker)(void); - -void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker); - -// TEST-ONLY. Reset the internal global state. +class grpc_google_default_channel_credentials + : public grpc_channel_credentials { + public: + grpc_google_default_channel_credentials( + grpc_core::RefCountedPtr<grpc_channel_credentials> alts_creds, + grpc_core::RefCountedPtr<grpc_channel_credentials> ssl_creds) + : grpc_channel_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_GOOGLE_DEFAULT), + alts_creds_(std::move(alts_creds)), + ssl_creds_(std::move(ssl_creds)) {} + + ~grpc_google_default_channel_credentials() override = default; + + grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, + const char* target, const grpc_channel_args* args, + grpc_channel_args** new_args) override; + + grpc_channel_args* update_arguments(grpc_channel_args* args) override; + + const grpc_channel_credentials* alts_creds() const { + return alts_creds_.get(); + } + const grpc_channel_credentials* ssl_creds() const { return ssl_creds_.get(); } + + private: + grpc_core::RefCountedPtr<grpc_channel_credentials> alts_creds_; + grpc_core::RefCountedPtr<grpc_channel_credentials> ssl_creds_; +}; + +namespace grpc_core { +namespace internal { + +typedef bool (*grpc_gce_tenancy_checker)(void); + +void set_gce_tenancy_checker_for_testing(grpc_gce_tenancy_checker checker); + +// TEST-ONLY. Reset the internal global state. void grpc_flush_cached_google_default_credentials(void); -} // namespace internal -} // namespace grpc_core - +} // namespace internal +} // namespace grpc_core + #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_GOOGLE_DEFAULT_GOOGLE_DEFAULT_CREDENTIALS_H \ */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc index a03e4970b8..c48eef0183 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.cc @@ -29,40 +29,40 @@ #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/surface/api_trace.h" -grpc_google_iam_credentials::~grpc_google_iam_credentials() { - grpc_credentials_mdelem_array_destroy(&md_array_); +grpc_google_iam_credentials::~grpc_google_iam_credentials() { + grpc_credentials_mdelem_array_destroy(&md_array_); } -bool grpc_google_iam_credentials::get_request_metadata( +bool grpc_google_iam_credentials::get_request_metadata( grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/, grpc_credentials_mdelem_array* md_array, grpc_closure* /*on_request_metadata*/, grpc_error** /*error*/) { - grpc_credentials_mdelem_array_append(md_array, &md_array_); + grpc_credentials_mdelem_array_append(md_array, &md_array_); return true; } -void grpc_google_iam_credentials::cancel_get_request_metadata( +void grpc_google_iam_credentials::cancel_get_request_metadata( grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) { GRPC_ERROR_UNREF(error); } -grpc_google_iam_credentials::grpc_google_iam_credentials( - const char* token, const char* authority_selector) +grpc_google_iam_credentials::grpc_google_iam_credentials( + const char* token, const char* authority_selector) : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_IAM), debug_string_(y_absl::StrFormat( "GoogleIAMCredentials{Token:%s,AuthoritySelector:%s}", token != nullptr ? "present" : "absent", authority_selector)) { - grpc_mdelem md = grpc_mdelem_from_slices( - grpc_slice_from_static_string(GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY), - grpc_slice_from_copied_string(token)); - grpc_credentials_mdelem_array_add(&md_array_, md); - GRPC_MDELEM_UNREF(md); - md = grpc_mdelem_from_slices( - grpc_slice_from_static_string(GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY), - grpc_slice_from_copied_string(authority_selector)); - grpc_credentials_mdelem_array_add(&md_array_, md); - GRPC_MDELEM_UNREF(md); -} + grpc_mdelem md = grpc_mdelem_from_slices( + grpc_slice_from_static_string(GRPC_IAM_AUTHORIZATION_TOKEN_METADATA_KEY), + grpc_slice_from_copied_string(token)); + grpc_credentials_mdelem_array_add(&md_array_, md); + GRPC_MDELEM_UNREF(md); + md = grpc_mdelem_from_slices( + grpc_slice_from_static_string(GRPC_IAM_AUTHORITY_SELECTOR_METADATA_KEY), + grpc_slice_from_copied_string(authority_selector)); + grpc_credentials_mdelem_array_add(&md_array_, md); + GRPC_MDELEM_UNREF(md); +} grpc_call_credentials* grpc_google_iam_credentials_create( const char* token, const char* authority_selector, void* reserved) { @@ -74,7 +74,7 @@ grpc_call_credentials* grpc_google_iam_credentials_create( GPR_ASSERT(reserved == nullptr); GPR_ASSERT(token != nullptr); GPR_ASSERT(authority_selector != nullptr); - return grpc_core::MakeRefCounted<grpc_google_iam_credentials>( - token, authority_selector) - .release(); + return grpc_core::MakeRefCounted<grpc_google_iam_credentials>( + token, authority_selector) + .release(); } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h index 76b6acfa28..ebd40853ce 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/iam/iam_credentials.h @@ -25,25 +25,25 @@ #include "src/core/lib/security/credentials/credentials.h" -class grpc_google_iam_credentials : public grpc_call_credentials { - public: - grpc_google_iam_credentials(const char* token, - const char* authority_selector); - ~grpc_google_iam_credentials() override; - - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; +class grpc_google_iam_credentials : public grpc_call_credentials { + public: + grpc_google_iam_credentials(const char* token, + const char* authority_selector); + ~grpc_google_iam_credentials() override; + + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; TString debug_string() override { return debug_string_; } - - private: - grpc_credentials_mdelem_array md_array_; + + private: + grpc_credentials_mdelem_array md_array_; const TString debug_string_; -}; - +}; + #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_IAM_IAM_CREDENTIALS_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc index d5555c3aa1..6fc60e5093 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.cc @@ -27,8 +27,8 @@ #include "y_absl/strings/str_cat.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/api_trace.h" @@ -39,24 +39,24 @@ using grpc_core::Json; -void grpc_service_account_jwt_access_credentials::reset_cache() { - GRPC_MDELEM_UNREF(cached_.jwt_md); - cached_.jwt_md = GRPC_MDNULL; - if (cached_.service_url != nullptr) { - gpr_free(cached_.service_url); - cached_.service_url = nullptr; +void grpc_service_account_jwt_access_credentials::reset_cache() { + GRPC_MDELEM_UNREF(cached_.jwt_md); + cached_.jwt_md = GRPC_MDNULL; + if (cached_.service_url != nullptr) { + gpr_free(cached_.service_url); + cached_.service_url = nullptr; } - cached_.jwt_expiration = gpr_inf_past(GPR_CLOCK_REALTIME); + cached_.jwt_expiration = gpr_inf_past(GPR_CLOCK_REALTIME); } -grpc_service_account_jwt_access_credentials:: - ~grpc_service_account_jwt_access_credentials() { - grpc_auth_json_key_destruct(&key_); - reset_cache(); - gpr_mu_destroy(&cache_mu_); +grpc_service_account_jwt_access_credentials:: + ~grpc_service_account_jwt_access_credentials() { + grpc_auth_json_key_destruct(&key_); + reset_cache(); + gpr_mu_destroy(&cache_mu_); } -bool grpc_service_account_jwt_access_credentials::get_request_metadata( +bool grpc_service_account_jwt_access_credentials::get_request_metadata( grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context context, grpc_credentials_mdelem_array* md_array, grpc_closure* /*on_request_metadata*/, grpc_error** error) { @@ -66,37 +66,37 @@ bool grpc_service_account_jwt_access_credentials::get_request_metadata( /* See if we can return a cached jwt. */ grpc_mdelem jwt_md = GRPC_MDNULL; { - gpr_mu_lock(&cache_mu_); - if (cached_.service_url != nullptr && - strcmp(cached_.service_url, context.service_url) == 0 && - !GRPC_MDISNULL(cached_.jwt_md) && - (gpr_time_cmp( - gpr_time_sub(cached_.jwt_expiration, gpr_now(GPR_CLOCK_REALTIME)), - refresh_threshold) > 0)) { - jwt_md = GRPC_MDELEM_REF(cached_.jwt_md); + gpr_mu_lock(&cache_mu_); + if (cached_.service_url != nullptr && + strcmp(cached_.service_url, context.service_url) == 0 && + !GRPC_MDISNULL(cached_.jwt_md) && + (gpr_time_cmp( + gpr_time_sub(cached_.jwt_expiration, gpr_now(GPR_CLOCK_REALTIME)), + refresh_threshold) > 0)) { + jwt_md = GRPC_MDELEM_REF(cached_.jwt_md); } - gpr_mu_unlock(&cache_mu_); + gpr_mu_unlock(&cache_mu_); } if (GRPC_MDISNULL(jwt_md)) { char* jwt = nullptr; /* Generate a new jwt. */ - gpr_mu_lock(&cache_mu_); - reset_cache(); - jwt = grpc_jwt_encode_and_sign(&key_, context.service_url, jwt_lifetime_, - nullptr); + gpr_mu_lock(&cache_mu_); + reset_cache(); + jwt = grpc_jwt_encode_and_sign(&key_, context.service_url, jwt_lifetime_, + nullptr); if (jwt != nullptr) { TString md_value = y_absl::StrCat("Bearer ", jwt); gpr_free(jwt); - cached_.jwt_expiration = - gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_); - cached_.service_url = gpr_strdup(context.service_url); - cached_.jwt_md = grpc_mdelem_from_slices( + cached_.jwt_expiration = + gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), jwt_lifetime_); + cached_.service_url = gpr_strdup(context.service_url); + cached_.jwt_md = grpc_mdelem_from_slices( grpc_slice_from_static_string(GRPC_AUTHORIZATION_METADATA_KEY), grpc_slice_from_cpp_string(std::move(md_value))); - jwt_md = GRPC_MDELEM_REF(cached_.jwt_md); + jwt_md = GRPC_MDELEM_REF(cached_.jwt_md); } - gpr_mu_unlock(&cache_mu_); + gpr_mu_unlock(&cache_mu_); } if (!GRPC_MDISNULL(jwt_md)) { @@ -108,15 +108,15 @@ bool grpc_service_account_jwt_access_credentials::get_request_metadata( return true; } -void grpc_service_account_jwt_access_credentials::cancel_get_request_metadata( +void grpc_service_account_jwt_access_credentials::cancel_get_request_metadata( grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) { GRPC_ERROR_UNREF(error); } -grpc_service_account_jwt_access_credentials:: - grpc_service_account_jwt_access_credentials(grpc_auth_json_key key, - gpr_timespec token_lifetime) - : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_JWT), key_(key) { +grpc_service_account_jwt_access_credentials:: + grpc_service_account_jwt_access_credentials(grpc_auth_json_key key, + gpr_timespec token_lifetime) + : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_JWT), key_(key) { gpr_timespec max_token_lifetime = grpc_max_auth_token_lifetime(); if (gpr_time_cmp(token_lifetime, max_token_lifetime) > 0) { gpr_log(GPR_INFO, @@ -124,22 +124,22 @@ grpc_service_account_jwt_access_credentials:: static_cast<int>(max_token_lifetime.tv_sec)); token_lifetime = grpc_max_auth_token_lifetime(); } - jwt_lifetime_ = token_lifetime; - gpr_mu_init(&cache_mu_); - reset_cache(); -} - -grpc_core::RefCountedPtr<grpc_call_credentials> -grpc_service_account_jwt_access_credentials_create_from_auth_json_key( - grpc_auth_json_key key, gpr_timespec token_lifetime) { - if (!grpc_auth_json_key_is_valid(&key)) { - gpr_log(GPR_ERROR, "Invalid input for jwt credentials creation"); - return nullptr; - } - return grpc_core::MakeRefCounted<grpc_service_account_jwt_access_credentials>( - key, token_lifetime); + jwt_lifetime_ = token_lifetime; + gpr_mu_init(&cache_mu_); + reset_cache(); } +grpc_core::RefCountedPtr<grpc_call_credentials> +grpc_service_account_jwt_access_credentials_create_from_auth_json_key( + grpc_auth_json_key key, gpr_timespec token_lifetime) { + if (!grpc_auth_json_key_is_valid(&key)) { + gpr_log(GPR_ERROR, "Invalid input for jwt credentials creation"); + return nullptr; + } + return grpc_core::MakeRefCounted<grpc_service_account_jwt_access_credentials>( + key, token_lifetime); +} + static char* redact_private_key(const char* json_key) { grpc_error* error = GRPC_ERROR_NONE; Json json = Json::Parse(json_key, &error); @@ -167,9 +167,9 @@ grpc_call_credentials* grpc_service_account_jwt_access_credentials_create( gpr_free(clean_json); } GPR_ASSERT(reserved == nullptr); - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; - return grpc_service_account_jwt_access_credentials_create_from_auth_json_key( - grpc_auth_json_key_create_from_string(json_key), token_lifetime) - .release(); + return grpc_service_account_jwt_access_credentials_create_from_auth_json_key( + grpc_auth_json_key_create_from_string(json_key), token_lifetime) + .release(); } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h index 9b60deacb5..0dd945b1d4 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_credentials.h @@ -30,50 +30,50 @@ #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/credentials/jwt/json_token.h" -class grpc_service_account_jwt_access_credentials - : public grpc_call_credentials { - public: - grpc_service_account_jwt_access_credentials(grpc_auth_json_key key, - gpr_timespec token_lifetime); - ~grpc_service_account_jwt_access_credentials() override; - - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; - - const gpr_timespec& jwt_lifetime() const { return jwt_lifetime_; } - const grpc_auth_json_key& key() const { return key_; } +class grpc_service_account_jwt_access_credentials + : public grpc_call_credentials { + public: + grpc_service_account_jwt_access_credentials(grpc_auth_json_key key, + gpr_timespec token_lifetime); + ~grpc_service_account_jwt_access_credentials() override; + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; + + const gpr_timespec& jwt_lifetime() const { return jwt_lifetime_; } + const grpc_auth_json_key& key() const { return key_; } + TString debug_string() override { return y_absl::StrFormat("JWTAccessCredentials{ExpirationTime:%s}", y_absl::FormatTime(y_absl::FromUnixMicros( gpr_timespec_to_micros(jwt_lifetime_)))); }; - private: - void reset_cache(); - + private: + void reset_cache(); + // Have a simple cache for now with just 1 entry. We could have a map based on // the service_url for a more sophisticated one. - gpr_mu cache_mu_; + gpr_mu cache_mu_; struct { - grpc_mdelem jwt_md = GRPC_MDNULL; - char* service_url = nullptr; + grpc_mdelem jwt_md = GRPC_MDNULL; + char* service_url = nullptr; gpr_timespec jwt_expiration; - } cached_; + } cached_; - grpc_auth_json_key key_; - gpr_timespec jwt_lifetime_; -}; + grpc_auth_json_key key_; + gpr_timespec jwt_lifetime_; +}; // Private constructor for jwt credentials from an already parsed json key. // Takes ownership of the key. -grpc_core::RefCountedPtr<grpc_call_credentials> +grpc_core::RefCountedPtr<grpc_call_credentials> grpc_service_account_jwt_access_credentials_create_from_auth_json_key( grpc_auth_json_key key, gpr_timespec token_lifetime); diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc index 0c9e118826..69280bd9db 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/jwt/jwt_verifier.cc @@ -29,9 +29,9 @@ #include <grpc/support/sync.h> extern "C" { -#include <openssl/bn.h> +#include <openssl/bn.h> #include <openssl/pem.h> -#include <openssl/rsa.h> +#include <openssl/rsa.h> } #include "src/core/lib/gpr/string.h" @@ -352,7 +352,7 @@ static verifier_cb_ctx* verifier_cb_ctx_create( grpc_jwt_claims* claims, const char* audience, const grpc_slice& signature, const char* signed_jwt, size_t signed_jwt_len, void* user_data, grpc_jwt_verification_done_cb cb) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; verifier_cb_ctx* ctx = static_cast<verifier_cb_ctx*>(gpr_zalloc(sizeof(verifier_cb_ctx))); diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc index 966a887baf..44279d5ac0 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.cc @@ -1,64 +1,64 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/credentials/local/local_credentials.h" - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/security/security_connector/local/local_security_connector.h" - -#define GRPC_CREDENTIALS_TYPE_LOCAL "Local" - -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_local_credentials::create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target_name, const grpc_channel_args* args, +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/credentials/local/local_credentials.h" + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/security/security_connector/local/local_security_connector.h" + +#define GRPC_CREDENTIALS_TYPE_LOCAL "Local" + +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_local_credentials::create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target_name, const grpc_channel_args* args, grpc_channel_args** /*new_args*/) { - return grpc_local_channel_security_connector_create( - this->Ref(), std::move(request_metadata_creds), args, target_name); -} - -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_local_server_credentials::create_security_connector() { - return grpc_local_server_security_connector_create(this->Ref()); -} - -grpc_local_credentials::grpc_local_credentials( - grpc_local_connect_type connect_type) - : grpc_channel_credentials(GRPC_CREDENTIALS_TYPE_LOCAL), - connect_type_(connect_type) {} - -grpc_channel_credentials* grpc_local_credentials_create( - grpc_local_connect_type connect_type) { + return grpc_local_channel_security_connector_create( + this->Ref(), std::move(request_metadata_creds), args, target_name); +} + +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_local_server_credentials::create_security_connector() { + return grpc_local_server_security_connector_create(this->Ref()); +} + +grpc_local_credentials::grpc_local_credentials( + grpc_local_connect_type connect_type) + : grpc_channel_credentials(GRPC_CREDENTIALS_TYPE_LOCAL), + connect_type_(connect_type) {} + +grpc_channel_credentials* grpc_local_credentials_create( + grpc_local_connect_type connect_type) { return new grpc_local_credentials(connect_type); -} - -grpc_local_server_credentials::grpc_local_server_credentials( - grpc_local_connect_type connect_type) - : grpc_server_credentials(GRPC_CREDENTIALS_TYPE_LOCAL), - connect_type_(connect_type) {} - -grpc_server_credentials* grpc_local_server_credentials_create( - grpc_local_connect_type connect_type) { +} + +grpc_local_server_credentials::grpc_local_server_credentials( + grpc_local_connect_type connect_type) + : grpc_server_credentials(GRPC_CREDENTIALS_TYPE_LOCAL), + connect_type_(connect_type) {} + +grpc_server_credentials* grpc_local_server_credentials_create( + grpc_local_connect_type connect_type) { return new grpc_local_server_credentials(connect_type); -} +} diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.h index 60a8a4f64c..bc9d816aa7 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/local/local_credentials.h @@ -1,61 +1,61 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H -#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc_security.h> - -#include "src/core/lib/security/credentials/credentials.h" - -/* Main class for grpc local channel credential. */ -class grpc_local_credentials final : public grpc_channel_credentials { - public: - explicit grpc_local_credentials(grpc_local_connect_type connect_type); - ~grpc_local_credentials() override = default; - - grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target_name, const grpc_channel_args* args, - grpc_channel_args** new_args) override; - - grpc_local_connect_type connect_type() const { return connect_type_; } - - private: - grpc_local_connect_type connect_type_; -}; - -/* Main class for grpc local server credential. */ -class grpc_local_server_credentials final : public grpc_server_credentials { - public: - explicit grpc_local_server_credentials(grpc_local_connect_type connect_type); - ~grpc_local_server_credentials() override = default; - - grpc_core::RefCountedPtr<grpc_server_security_connector> - create_security_connector() override; - - grpc_local_connect_type connect_type() const { return connect_type_; } - - private: - grpc_local_connect_type connect_type_; -}; - -#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H +#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc_security.h> + +#include "src/core/lib/security/credentials/credentials.h" + +/* Main class for grpc local channel credential. */ +class grpc_local_credentials final : public grpc_channel_credentials { + public: + explicit grpc_local_credentials(grpc_local_connect_type connect_type); + ~grpc_local_credentials() override = default; + + grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target_name, const grpc_channel_args* args, + grpc_channel_args** new_args) override; + + grpc_local_connect_type connect_type() const { return connect_type_; } + + private: + grpc_local_connect_type connect_type_; +}; + +/* Main class for grpc local server credential. */ +class grpc_local_server_credentials final : public grpc_server_credentials { + public: + explicit grpc_local_server_credentials(grpc_local_connect_type connect_type); + ~grpc_local_server_credentials() override = default; + + grpc_core::RefCountedPtr<grpc_server_security_connector> + create_security_connector() override; + + grpc_local_connect_type connect_type() const { return connect_type_; } + + private: + grpc_local_connect_type connect_type_; +}; + +#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_LOCAL_LOCAL_CREDENTIALS_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc index 552ee37cfc..7cc313b157 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.cc @@ -36,7 +36,7 @@ #include <grpc/support/string_util.h> #include "src/core/lib/gpr/string.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/error.h" #include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/security/util/json_util.h" @@ -124,12 +124,12 @@ void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token) { // Oauth2 Token Fetcher credentials. // -grpc_oauth2_token_fetcher_credentials:: - ~grpc_oauth2_token_fetcher_credentials() { - GRPC_MDELEM_UNREF(access_token_md_); - gpr_mu_destroy(&mu_); - grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&pollent_)); - grpc_httpcli_context_destroy(&httpcli_context_); +grpc_oauth2_token_fetcher_credentials:: + ~grpc_oauth2_token_fetcher_credentials() { + GRPC_MDELEM_UNREF(access_token_md_); + gpr_mu_destroy(&mu_); + grpc_pollset_set_destroy(grpc_polling_entity_pollset_set(&pollent_)); + grpc_httpcli_context_destroy(&httpcli_context_); } grpc_credentials_status @@ -226,12 +226,12 @@ static void on_oauth2_token_fetcher_http_response(void* user_data, grpc_credentials_metadata_request* r = static_cast<grpc_credentials_metadata_request*>(user_data); grpc_oauth2_token_fetcher_credentials* c = - reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(r->creds.get()); - c->on_http_response(r, error); -} - -void grpc_oauth2_token_fetcher_credentials::on_http_response( - grpc_credentials_metadata_request* r, grpc_error* error) { + reinterpret_cast<grpc_oauth2_token_fetcher_credentials*>(r->creds.get()); + c->on_http_response(r, error); +} + +void grpc_oauth2_token_fetcher_credentials::on_http_response( + grpc_credentials_metadata_request* r, grpc_error* error) { grpc_mdelem access_token_md = GRPC_MDNULL; grpc_millis token_lifetime = 0; grpc_credentials_status status = @@ -240,17 +240,17 @@ void grpc_oauth2_token_fetcher_credentials::on_http_response( &r->response, &access_token_md, &token_lifetime) : GRPC_CREDENTIALS_ERROR; // Update cache and grab list of pending requests. - gpr_mu_lock(&mu_); - token_fetch_pending_ = false; - access_token_md_ = GRPC_MDELEM_REF(access_token_md); - token_expiration_ = - status == GRPC_CREDENTIALS_OK - ? gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), - gpr_time_from_millis(token_lifetime, GPR_TIMESPAN)) - : gpr_inf_past(GPR_CLOCK_MONOTONIC); - grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_; - pending_requests_ = nullptr; - gpr_mu_unlock(&mu_); + gpr_mu_lock(&mu_); + token_fetch_pending_ = false; + access_token_md_ = GRPC_MDELEM_REF(access_token_md); + token_expiration_ = + status == GRPC_CREDENTIALS_OK + ? gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), + gpr_time_from_millis(token_lifetime, GPR_TIMESPAN)) + : gpr_inf_past(GPR_CLOCK_MONOTONIC); + grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_; + pending_requests_ = nullptr; + gpr_mu_unlock(&mu_); // Invoke callbacks for all pending requests. while (pending_request != nullptr) { grpc_error* new_error = GRPC_ERROR_NONE; @@ -259,45 +259,45 @@ void grpc_oauth2_token_fetcher_credentials::on_http_response( access_token_md); } else { new_error = GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Error occurred when fetching oauth2 token.", &error, 1); + "Error occurred when fetching oauth2 token.", &error, 1); } grpc_core::ExecCtx::Run(DEBUG_LOCATION, pending_request->on_request_metadata, new_error); grpc_polling_entity_del_from_pollset_set( - pending_request->pollent, grpc_polling_entity_pollset_set(&pollent_)); + pending_request->pollent, grpc_polling_entity_pollset_set(&pollent_)); grpc_oauth2_pending_get_request_metadata* prev = pending_request; pending_request = pending_request->next; gpr_free(prev); } GRPC_MDELEM_UNREF(access_token_md); - Unref(); + Unref(); grpc_credentials_metadata_request_destroy(r); } -bool grpc_oauth2_token_fetcher_credentials::get_request_metadata( +bool grpc_oauth2_token_fetcher_credentials::get_request_metadata( grpc_polling_entity* pollent, grpc_auth_metadata_context /*context*/, - grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, grpc_error** /*error*/) { // Check if we can use the cached token. grpc_millis refresh_threshold = GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS * GPR_MS_PER_SEC; grpc_mdelem cached_access_token_md = GRPC_MDNULL; - gpr_mu_lock(&mu_); - if (!GRPC_MDISNULL(access_token_md_) && - gpr_time_cmp( - gpr_time_sub(token_expiration_, gpr_now(GPR_CLOCK_MONOTONIC)), - gpr_time_from_seconds(GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, - GPR_TIMESPAN)) > 0) { - cached_access_token_md = GRPC_MDELEM_REF(access_token_md_); + gpr_mu_lock(&mu_); + if (!GRPC_MDISNULL(access_token_md_) && + gpr_time_cmp( + gpr_time_sub(token_expiration_, gpr_now(GPR_CLOCK_MONOTONIC)), + gpr_time_from_seconds(GRPC_SECURE_TOKEN_REFRESH_THRESHOLD_SECS, + GPR_TIMESPAN)) > 0) { + cached_access_token_md = GRPC_MDELEM_REF(access_token_md_); } if (!GRPC_MDISNULL(cached_access_token_md)) { - gpr_mu_unlock(&mu_); + gpr_mu_unlock(&mu_); grpc_credentials_mdelem_array_add(md_array, cached_access_token_md); GRPC_MDELEM_UNREF(cached_access_token_md); return true; } // Couldn't get the token from the cache. - // Add request to pending_requests_ and start a new fetch if needed. + // Add request to pending_requests_ and start a new fetch if needed. grpc_oauth2_pending_get_request_metadata* pending_request = static_cast<grpc_oauth2_pending_get_request_metadata*>( gpr_malloc(sizeof(*pending_request))); @@ -305,37 +305,37 @@ bool grpc_oauth2_token_fetcher_credentials::get_request_metadata( pending_request->on_request_metadata = on_request_metadata; pending_request->pollent = pollent; grpc_polling_entity_add_to_pollset_set( - pollent, grpc_polling_entity_pollset_set(&pollent_)); - pending_request->next = pending_requests_; - pending_requests_ = pending_request; + pollent, grpc_polling_entity_pollset_set(&pollent_)); + pending_request->next = pending_requests_; + pending_requests_ = pending_request; bool start_fetch = false; - if (!token_fetch_pending_) { - token_fetch_pending_ = true; + if (!token_fetch_pending_) { + token_fetch_pending_ = true; start_fetch = true; } - gpr_mu_unlock(&mu_); + gpr_mu_unlock(&mu_); if (start_fetch) { - Ref().release(); - fetch_oauth2(grpc_credentials_metadata_request_create(this->Ref()), - &httpcli_context_, &pollent_, - on_oauth2_token_fetcher_http_response, - grpc_core::ExecCtx::Get()->Now() + refresh_threshold); + Ref().release(); + fetch_oauth2(grpc_credentials_metadata_request_create(this->Ref()), + &httpcli_context_, &pollent_, + on_oauth2_token_fetcher_http_response, + grpc_core::ExecCtx::Get()->Now() + refresh_threshold); } return false; } -void grpc_oauth2_token_fetcher_credentials::cancel_get_request_metadata( - grpc_credentials_mdelem_array* md_array, grpc_error* error) { - gpr_mu_lock(&mu_); +void grpc_oauth2_token_fetcher_credentials::cancel_get_request_metadata( + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + gpr_mu_lock(&mu_); grpc_oauth2_pending_get_request_metadata* prev = nullptr; - grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_; + grpc_oauth2_pending_get_request_metadata* pending_request = pending_requests_; while (pending_request != nullptr) { if (pending_request->md_array == md_array) { // Remove matching pending request from the list. if (prev != nullptr) { prev->next = pending_request->next; } else { - pending_requests_ = pending_request->next; + pending_requests_ = pending_request->next; } // Invoke the callback immediately with an error. grpc_core::ExecCtx::Run(DEBUG_LOCATION, @@ -347,17 +347,17 @@ void grpc_oauth2_token_fetcher_credentials::cancel_get_request_metadata( prev = pending_request; pending_request = pending_request->next; } - gpr_mu_unlock(&mu_); + gpr_mu_unlock(&mu_); GRPC_ERROR_UNREF(error); } -grpc_oauth2_token_fetcher_credentials::grpc_oauth2_token_fetcher_credentials() - : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2), - token_expiration_(gpr_inf_past(GPR_CLOCK_MONOTONIC)), - pollent_(grpc_polling_entity_create_from_pollset_set( - grpc_pollset_set_create())) { - gpr_mu_init(&mu_); - grpc_httpcli_context_init(&httpcli_context_); +grpc_oauth2_token_fetcher_credentials::grpc_oauth2_token_fetcher_credentials() + : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2), + token_expiration_(gpr_inf_past(GPR_CLOCK_MONOTONIC)), + pollent_(grpc_polling_entity_create_from_pollset_set( + grpc_pollset_set_create())) { + gpr_mu_init(&mu_); + grpc_httpcli_context_init(&httpcli_context_); } TString grpc_oauth2_token_fetcher_credentials::debug_string() { @@ -368,39 +368,39 @@ TString grpc_oauth2_token_fetcher_credentials::debug_string() { // Google Compute Engine credentials. // -namespace { +namespace { -class grpc_compute_engine_token_fetcher_credentials - : public grpc_oauth2_token_fetcher_credentials { - public: - grpc_compute_engine_token_fetcher_credentials() = default; - ~grpc_compute_engine_token_fetcher_credentials() override = default; +class grpc_compute_engine_token_fetcher_credentials + : public grpc_oauth2_token_fetcher_credentials { + public: + grpc_compute_engine_token_fetcher_credentials() = default; + ~grpc_compute_engine_token_fetcher_credentials() override = default; - protected: - void fetch_oauth2(grpc_credentials_metadata_request* metadata_req, - grpc_httpcli_context* http_context, - grpc_polling_entity* pollent, - grpc_iomgr_cb_func response_cb, - grpc_millis deadline) override { + protected: + void fetch_oauth2(grpc_credentials_metadata_request* metadata_req, + grpc_httpcli_context* http_context, + grpc_polling_entity* pollent, + grpc_iomgr_cb_func response_cb, + grpc_millis deadline) override { grpc_http_header header = {const_cast<char*>("Metadata-Flavor"), const_cast<char*>("Google")}; - grpc_httpcli_request request; - memset(&request, 0, sizeof(grpc_httpcli_request)); - request.host = (char*)GRPC_COMPUTE_ENGINE_METADATA_HOST; - request.http.path = (char*)GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH; - request.http.hdr_count = 1; - request.http.hdrs = &header; - /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host - channel. This would allow us to cancel an authentication query when under - extreme memory pressure. */ - grpc_resource_quota* resource_quota = - grpc_resource_quota_create("oauth2_credentials"); - grpc_httpcli_get(http_context, pollent, resource_quota, &request, deadline, + grpc_httpcli_request request; + memset(&request, 0, sizeof(grpc_httpcli_request)); + request.host = (char*)GRPC_COMPUTE_ENGINE_METADATA_HOST; + request.http.path = (char*)GRPC_COMPUTE_ENGINE_METADATA_TOKEN_PATH; + request.http.hdr_count = 1; + request.http.hdrs = &header; + /* TODO(ctiller): Carry the resource_quota in ctx and share it with the host + channel. This would allow us to cancel an authentication query when under + extreme memory pressure. */ + grpc_resource_quota* resource_quota = + grpc_resource_quota_create("oauth2_credentials"); + grpc_httpcli_get(http_context, pollent, resource_quota, &request, deadline, GRPC_CLOSURE_INIT(&http_get_cb_closure_, response_cb, metadata_req, grpc_schedule_on_exec_ctx), - &metadata_req->response); - grpc_resource_quota_unref_internal(resource_quota); - } + &metadata_req->response); + grpc_resource_quota_unref_internal(resource_quota); + } TString debug_string() override { return y_absl::StrFormat( @@ -410,30 +410,30 @@ class grpc_compute_engine_token_fetcher_credentials private: grpc_closure http_get_cb_closure_; -}; - -} // namespace - +}; + +} // namespace + grpc_call_credentials* grpc_google_compute_engine_credentials_create( void* reserved) { GRPC_API_TRACE("grpc_compute_engine_credentials_create(reserved=%p)", 1, (reserved)); GPR_ASSERT(reserved == nullptr); - return grpc_core::MakeRefCounted< - grpc_compute_engine_token_fetcher_credentials>() - .release(); + return grpc_core::MakeRefCounted< + grpc_compute_engine_token_fetcher_credentials>() + .release(); } // // Google Refresh Token credentials. // -grpc_google_refresh_token_credentials:: - ~grpc_google_refresh_token_credentials() { - grpc_auth_refresh_token_destruct(&refresh_token_); +grpc_google_refresh_token_credentials:: + ~grpc_google_refresh_token_credentials() { + grpc_auth_refresh_token_destruct(&refresh_token_); } -void grpc_google_refresh_token_credentials::fetch_oauth2( +void grpc_google_refresh_token_credentials::fetch_oauth2( grpc_credentials_metadata_request* metadata_req, grpc_httpcli_context* httpcli_context, grpc_polling_entity* pollent, grpc_iomgr_cb_func response_cb, grpc_millis deadline) { @@ -463,19 +463,19 @@ void grpc_google_refresh_token_credentials::fetch_oauth2( grpc_resource_quota_unref_internal(resource_quota); } -grpc_google_refresh_token_credentials::grpc_google_refresh_token_credentials( - grpc_auth_refresh_token refresh_token) - : refresh_token_(refresh_token) {} - -grpc_core::RefCountedPtr<grpc_call_credentials> +grpc_google_refresh_token_credentials::grpc_google_refresh_token_credentials( + grpc_auth_refresh_token refresh_token) + : refresh_token_(refresh_token) {} + +grpc_core::RefCountedPtr<grpc_call_credentials> grpc_refresh_token_credentials_create_from_auth_refresh_token( grpc_auth_refresh_token refresh_token) { if (!grpc_auth_refresh_token_is_valid(&refresh_token)) { gpr_log(GPR_ERROR, "Invalid input for refresh token credentials creation"); return nullptr; } - return grpc_core::MakeRefCounted<grpc_google_refresh_token_credentials>( - refresh_token); + return grpc_core::MakeRefCounted<grpc_google_refresh_token_credentials>( + refresh_token); } TString grpc_google_refresh_token_credentials::debug_string() { @@ -506,8 +506,8 @@ grpc_call_credentials* grpc_google_refresh_token_credentials_create( create_loggable_refresh_token(&token).c_str(), reserved); } GPR_ASSERT(reserved == nullptr); - return grpc_refresh_token_credentials_create_from_auth_refresh_token(token) - .release(); + return grpc_refresh_token_credentials_create_from_auth_refresh_token(token) + .release(); } // @@ -718,31 +718,31 @@ grpc_call_credentials* grpc_sts_credentials_create( // Oauth2 Access Token credentials. // -grpc_access_token_credentials::~grpc_access_token_credentials() { - GRPC_MDELEM_UNREF(access_token_md_); +grpc_access_token_credentials::~grpc_access_token_credentials() { + GRPC_MDELEM_UNREF(access_token_md_); } -bool grpc_access_token_credentials::get_request_metadata( +bool grpc_access_token_credentials::get_request_metadata( grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context /*context*/, grpc_credentials_mdelem_array* md_array, grpc_closure* /*on_request_metadata*/, grpc_error** /*error*/) { - grpc_credentials_mdelem_array_add(md_array, access_token_md_); + grpc_credentials_mdelem_array_add(md_array, access_token_md_); return true; } -void grpc_access_token_credentials::cancel_get_request_metadata( +void grpc_access_token_credentials::cancel_get_request_metadata( grpc_credentials_mdelem_array* /*md_array*/, grpc_error* error) { GRPC_ERROR_UNREF(error); } -grpc_access_token_credentials::grpc_access_token_credentials( - const char* access_token) - : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) { - grpc_core::ExecCtx exec_ctx; - access_token_md_ = grpc_mdelem_from_slices( +grpc_access_token_credentials::grpc_access_token_credentials( + const char* access_token) + : grpc_call_credentials(GRPC_CALL_CREDENTIALS_TYPE_OAUTH2) { + grpc_core::ExecCtx exec_ctx; + access_token_md_ = grpc_mdelem_from_slices( grpc_core::ExternallyManagedSlice(GRPC_AUTHORIZATION_METADATA_KEY), grpc_slice_from_cpp_string(y_absl::StrCat("Bearer ", access_token))); -} +} TString grpc_access_token_credentials::debug_string() { bool access_token_present = !GRPC_MDISNULL(access_token_md_); @@ -757,6 +757,6 @@ grpc_call_credentials* grpc_access_token_credentials_create( "reserved=%p)", 1, (reserved)); GPR_ASSERT(reserved == nullptr); - return grpc_core::MakeRefCounted<grpc_access_token_credentials>(access_token) - .release(); + return grpc_core::MakeRefCounted<grpc_access_token_credentials>(access_token) + .release(); } diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h index fd886405cf..2384bce408 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/oauth2/oauth2_credentials.h @@ -62,95 +62,95 @@ void grpc_auth_refresh_token_destruct(grpc_auth_refresh_token* refresh_token); // This object is a base for credentials that need to acquire an oauth2 token // from an http service. -struct grpc_oauth2_pending_get_request_metadata { +struct grpc_oauth2_pending_get_request_metadata { grpc_credentials_mdelem_array* md_array; grpc_closure* on_request_metadata; grpc_polling_entity* pollent; struct grpc_oauth2_pending_get_request_metadata* next; -}; - -class grpc_oauth2_token_fetcher_credentials : public grpc_call_credentials { - public: - grpc_oauth2_token_fetcher_credentials(); - ~grpc_oauth2_token_fetcher_credentials() override; - - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; - - void on_http_response(grpc_credentials_metadata_request* r, - grpc_error* error); +}; + +class grpc_oauth2_token_fetcher_credentials : public grpc_call_credentials { + public: + grpc_oauth2_token_fetcher_credentials(); + ~grpc_oauth2_token_fetcher_credentials() override; + + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; + + void on_http_response(grpc_credentials_metadata_request* r, + grpc_error* error); TString debug_string() override; - - protected: - virtual void fetch_oauth2(grpc_credentials_metadata_request* req, - grpc_httpcli_context* httpcli_context, - grpc_polling_entity* pollent, grpc_iomgr_cb_func cb, + + protected: + virtual void fetch_oauth2(grpc_credentials_metadata_request* req, + grpc_httpcli_context* httpcli_context, + grpc_polling_entity* pollent, grpc_iomgr_cb_func cb, grpc_millis deadline) = 0; - - private: - gpr_mu mu_; - grpc_mdelem access_token_md_ = GRPC_MDNULL; - gpr_timespec token_expiration_; - bool token_fetch_pending_ = false; - grpc_oauth2_pending_get_request_metadata* pending_requests_ = nullptr; - grpc_httpcli_context httpcli_context_; - grpc_polling_entity pollent_; -}; - + + private: + gpr_mu mu_; + grpc_mdelem access_token_md_ = GRPC_MDNULL; + gpr_timespec token_expiration_; + bool token_fetch_pending_ = false; + grpc_oauth2_pending_get_request_metadata* pending_requests_ = nullptr; + grpc_httpcli_context httpcli_context_; + grpc_polling_entity pollent_; +}; + // Google refresh token credentials. -class grpc_google_refresh_token_credentials final - : public grpc_oauth2_token_fetcher_credentials { - public: - grpc_google_refresh_token_credentials(grpc_auth_refresh_token refresh_token); - ~grpc_google_refresh_token_credentials() override; - - const grpc_auth_refresh_token& refresh_token() const { - return refresh_token_; - } - +class grpc_google_refresh_token_credentials final + : public grpc_oauth2_token_fetcher_credentials { + public: + grpc_google_refresh_token_credentials(grpc_auth_refresh_token refresh_token); + ~grpc_google_refresh_token_credentials() override; + + const grpc_auth_refresh_token& refresh_token() const { + return refresh_token_; + } + TString debug_string() override; - protected: - void fetch_oauth2(grpc_credentials_metadata_request* req, - grpc_httpcli_context* httpcli_context, - grpc_polling_entity* pollent, grpc_iomgr_cb_func cb, - grpc_millis deadline) override; - - private: - grpc_auth_refresh_token refresh_token_; + protected: + void fetch_oauth2(grpc_credentials_metadata_request* req, + grpc_httpcli_context* httpcli_context, + grpc_polling_entity* pollent, grpc_iomgr_cb_func cb, + grpc_millis deadline) override; + + private: + grpc_auth_refresh_token refresh_token_; grpc_closure http_post_cb_closure_; -}; - +}; + // Access token credentials. -class grpc_access_token_credentials final : public grpc_call_credentials { - public: - grpc_access_token_credentials(const char* access_token); - ~grpc_access_token_credentials() override; - - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; - +class grpc_access_token_credentials final : public grpc_call_credentials { + public: + grpc_access_token_credentials(const char* access_token); + ~grpc_access_token_credentials() override; + + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; + TString debug_string() override; - private: - grpc_mdelem access_token_md_; -}; - + private: + grpc_mdelem access_token_md_; +}; + // Private constructor for refresh token credentials from an already parsed // refresh token. Takes ownership of the refresh token. -grpc_core::RefCountedPtr<grpc_call_credentials> +grpc_core::RefCountedPtr<grpc_call_credentials> grpc_refresh_token_credentials_create_from_auth_refresh_token( grpc_auth_refresh_token token); diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc index 40d8fec6e4..8e60b5e567 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.cc @@ -36,10 +36,10 @@ grpc_core::TraceFlag grpc_plugin_credentials_trace(false, "plugin_credentials"); -grpc_plugin_credentials::~grpc_plugin_credentials() { - gpr_mu_destroy(&mu_); - if (plugin_.state != nullptr && plugin_.destroy != nullptr) { - plugin_.destroy(plugin_.state); +grpc_plugin_credentials::~grpc_plugin_credentials() { + gpr_mu_destroy(&mu_); + if (plugin_.state != nullptr && plugin_.destroy != nullptr) { + plugin_.destroy(plugin_.state); } } @@ -56,10 +56,10 @@ TString grpc_plugin_credentials::debug_string() { return debug_str; } -void grpc_plugin_credentials::pending_request_remove_locked( - pending_request* pending_request) { +void grpc_plugin_credentials::pending_request_remove_locked( + pending_request* pending_request) { if (pending_request->prev == nullptr) { - pending_requests_ = pending_request->next; + pending_requests_ = pending_request->next; } else { pending_request->prev->next = pending_request->next; } @@ -73,17 +73,17 @@ void grpc_plugin_credentials::pending_request_remove_locked( // cancelled out from under us. // When this returns, r->cancelled indicates whether the request was // cancelled before completion. -void grpc_plugin_credentials::pending_request_complete(pending_request* r) { - GPR_DEBUG_ASSERT(r->creds == this); - gpr_mu_lock(&mu_); - if (!r->cancelled) pending_request_remove_locked(r); - gpr_mu_unlock(&mu_); +void grpc_plugin_credentials::pending_request_complete(pending_request* r) { + GPR_DEBUG_ASSERT(r->creds == this); + gpr_mu_lock(&mu_); + if (!r->cancelled) pending_request_remove_locked(r); + gpr_mu_unlock(&mu_); // Ref to credentials not needed anymore. - Unref(); + Unref(); } static grpc_error* process_plugin_result( - grpc_plugin_credentials::pending_request* r, const grpc_metadata* md, + grpc_plugin_credentials::pending_request* r, const grpc_metadata* md, size_t num_md, grpc_status_code status, const char* error_details) { grpc_error* error = GRPC_ERROR_NONE; if (status != GRPC_STATUS_OK) { @@ -112,7 +112,7 @@ static grpc_error* process_plugin_result( } else { for (size_t i = 0; i < num_md; ++i) { grpc_mdelem mdelem = - grpc_mdelem_create(md[i].key, md[i].value, nullptr); + grpc_mdelem_create(md[i].key, md[i].value, nullptr); grpc_credentials_mdelem_array_add(r->md_array, mdelem); GRPC_MDELEM_UNREF(mdelem); } @@ -127,11 +127,11 @@ static void plugin_md_request_metadata_ready(void* request, grpc_status_code status, const char* error_details) { /* called from application code */ - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx(GRPC_EXEC_CTX_FLAG_IS_FINISHED | GRPC_EXEC_CTX_FLAG_THREAD_RESOURCE_LOOP); - grpc_plugin_credentials::pending_request* r = - static_cast<grpc_plugin_credentials::pending_request*>(request); + grpc_plugin_credentials::pending_request* r = + static_cast<grpc_plugin_credentials::pending_request*>(request); if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin returned " @@ -139,7 +139,7 @@ static void plugin_md_request_metadata_ready(void* request, r->creds, r); } // Remove request from pending list if not previously cancelled. - r->creds->pending_request_complete(r); + r->creds->pending_request_complete(r); // If it has not been cancelled, process it. if (!r->cancelled) { grpc_error* error = @@ -154,59 +154,59 @@ static void plugin_md_request_metadata_ready(void* request, gpr_free(r); } -bool grpc_plugin_credentials::get_request_metadata( +bool grpc_plugin_credentials::get_request_metadata( grpc_polling_entity* /*pollent*/, grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, - grpc_error** error) { + grpc_credentials_mdelem_array* md_array, grpc_closure* on_request_metadata, + grpc_error** error) { bool retval = true; // Synchronous return. - if (plugin_.get_metadata != nullptr) { + if (plugin_.get_metadata != nullptr) { // Create pending_request object. - pending_request* request = - static_cast<pending_request*>(gpr_zalloc(sizeof(*request))); - request->creds = this; - request->md_array = md_array; - request->on_request_metadata = on_request_metadata; + pending_request* request = + static_cast<pending_request*>(gpr_zalloc(sizeof(*request))); + request->creds = this; + request->md_array = md_array; + request->on_request_metadata = on_request_metadata; // Add it to the pending list. - gpr_mu_lock(&mu_); - if (pending_requests_ != nullptr) { - pending_requests_->prev = request; + gpr_mu_lock(&mu_); + if (pending_requests_ != nullptr) { + pending_requests_->prev = request; } - request->next = pending_requests_; - pending_requests_ = request; - gpr_mu_unlock(&mu_); + request->next = pending_requests_; + pending_requests_ = request; + gpr_mu_unlock(&mu_); // Invoke the plugin. The callback holds a ref to us. if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: invoking plugin", - this, request); + this, request); } - Ref().release(); + Ref().release(); grpc_metadata creds_md[GRPC_METADATA_CREDENTIALS_PLUGIN_SYNC_MAX]; size_t num_creds_md = 0; grpc_status_code status = GRPC_STATUS_OK; const char* error_details = nullptr; - if (!plugin_.get_metadata( - plugin_.state, context, plugin_md_request_metadata_ready, request, - creds_md, &num_creds_md, &status, &error_details)) { + if (!plugin_.get_metadata( + plugin_.state, context, plugin_md_request_metadata_ready, request, + creds_md, &num_creds_md, &status, &error_details)) { if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin will return " "asynchronously", - this, request); + this, request); } return false; // Asynchronous return. } // Returned synchronously. // Remove request from pending list if not previously cancelled. - request->creds->pending_request_complete(request); + request->creds->pending_request_complete(request); // If the request was cancelled, the error will have been returned // asynchronously by plugin_cancel_get_request_metadata(), so return // false. Otherwise, process the result. - if (request->cancelled) { + if (request->cancelled) { if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) { gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p was cancelled, error " "will be returned asynchronously", - this, request); + this, request); } retval = false; } else { @@ -214,10 +214,10 @@ bool grpc_plugin_credentials::get_request_metadata( gpr_log(GPR_INFO, "plugin_credentials[%p]: request %p: plugin returned " "synchronously", - this, request); + this, request); } - *error = process_plugin_result(request, creds_md, num_creds_md, status, - error_details); + *error = process_plugin_result(request, creds_md, num_creds_md, status, + error_details); } // Clean up. for (size_t i = 0; i < num_creds_md; ++i) { @@ -225,39 +225,39 @@ bool grpc_plugin_credentials::get_request_metadata( grpc_slice_unref_internal(creds_md[i].value); } gpr_free((void*)error_details); - gpr_free(request); + gpr_free(request); } return retval; } -void grpc_plugin_credentials::cancel_get_request_metadata( - grpc_credentials_mdelem_array* md_array, grpc_error* error) { - gpr_mu_lock(&mu_); - for (pending_request* pending_request = pending_requests_; +void grpc_plugin_credentials::cancel_get_request_metadata( + grpc_credentials_mdelem_array* md_array, grpc_error* error) { + gpr_mu_lock(&mu_); + for (pending_request* pending_request = pending_requests_; pending_request != nullptr; pending_request = pending_request->next) { if (pending_request->md_array == md_array) { if (GRPC_TRACE_FLAG_ENABLED(grpc_plugin_credentials_trace)) { - gpr_log(GPR_INFO, "plugin_credentials[%p]: cancelling request %p", this, + gpr_log(GPR_INFO, "plugin_credentials[%p]: cancelling request %p", this, pending_request); } pending_request->cancelled = true; grpc_core::ExecCtx::Run(DEBUG_LOCATION, pending_request->on_request_metadata, GRPC_ERROR_REF(error)); - pending_request_remove_locked(pending_request); + pending_request_remove_locked(pending_request); break; } } - gpr_mu_unlock(&mu_); + gpr_mu_unlock(&mu_); GRPC_ERROR_UNREF(error); } -grpc_plugin_credentials::grpc_plugin_credentials( +grpc_plugin_credentials::grpc_plugin_credentials( grpc_metadata_credentials_plugin plugin, grpc_security_level min_security_level) : grpc_call_credentials(plugin.type, min_security_level), plugin_(plugin) { - gpr_mu_init(&mu_); -} + gpr_mu_init(&mu_); +} grpc_call_credentials* grpc_metadata_credentials_create_from_plugin( grpc_metadata_credentials_plugin plugin, diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h index 78bca05fb9..79f881477b 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/plugin/plugin_credentials.h @@ -25,48 +25,48 @@ extern grpc_core::TraceFlag grpc_plugin_credentials_trace; -// This type is forward declared as a C struct and we cannot define it as a -// class. Otherwise, compiler will complain about type mismatch due to -// -Wmismatched-tags. -struct grpc_plugin_credentials final : public grpc_call_credentials { - public: - struct pending_request { - bool cancelled; - struct grpc_plugin_credentials* creds; - grpc_credentials_mdelem_array* md_array; - grpc_closure* on_request_metadata; - struct pending_request* prev; - struct pending_request* next; - }; +// This type is forward declared as a C struct and we cannot define it as a +// class. Otherwise, compiler will complain about type mismatch due to +// -Wmismatched-tags. +struct grpc_plugin_credentials final : public grpc_call_credentials { + public: + struct pending_request { + bool cancelled; + struct grpc_plugin_credentials* creds; + grpc_credentials_mdelem_array* md_array; + grpc_closure* on_request_metadata; + struct pending_request* prev; + struct pending_request* next; + }; explicit grpc_plugin_credentials(grpc_metadata_credentials_plugin plugin, grpc_security_level min_security_level); - ~grpc_plugin_credentials() override; + ~grpc_plugin_credentials() override; - bool get_request_metadata(grpc_polling_entity* pollent, - grpc_auth_metadata_context context, - grpc_credentials_mdelem_array* md_array, - grpc_closure* on_request_metadata, - grpc_error** error) override; - - void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, - grpc_error* error) override; - - // Checks if the request has been cancelled. - // If not, removes it from the pending list, so that it cannot be - // cancelled out from under us. - // When this returns, r->cancelled indicates whether the request was - // cancelled before completion. - void pending_request_complete(pending_request* r); + bool get_request_metadata(grpc_polling_entity* pollent, + grpc_auth_metadata_context context, + grpc_credentials_mdelem_array* md_array, + grpc_closure* on_request_metadata, + grpc_error** error) override; + void cancel_get_request_metadata(grpc_credentials_mdelem_array* md_array, + grpc_error* error) override; + + // Checks if the request has been cancelled. + // If not, removes it from the pending list, so that it cannot be + // cancelled out from under us. + // When this returns, r->cancelled indicates whether the request was + // cancelled before completion. + void pending_request_complete(pending_request* r); + TString debug_string() override; - private: - void pending_request_remove_locked(pending_request* pending_request); - - grpc_metadata_credentials_plugin plugin_; - gpr_mu mu_; - pending_request* pending_requests_ = nullptr; -}; - + private: + void pending_request_remove_locked(pending_request* pending_request); + + grpc_metadata_credentials_plugin plugin_; + gpr_mu mu_; + pending_request* pending_requests_ = nullptr; +}; + #endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_PLUGIN_PLUGIN_CREDENTIALS_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc index 3bb7790f5c..51fff873c2 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.cc @@ -44,27 +44,27 @@ void grpc_tsi_ssl_pem_key_cert_pairs_destroy(tsi_ssl_pem_key_cert_pair* kp, gpr_free(kp); } -grpc_ssl_credentials::grpc_ssl_credentials( - const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, +grpc_ssl_credentials::grpc_ssl_credentials( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const grpc_ssl_verify_peer_options* verify_options) - : grpc_channel_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) { - build_config(pem_root_certs, pem_key_cert_pair, verify_options); -} - -grpc_ssl_credentials::~grpc_ssl_credentials() { - gpr_free(config_.pem_root_certs); - grpc_tsi_ssl_pem_key_cert_pairs_destroy(config_.pem_key_cert_pair, 1); - if (config_.verify_options.verify_peer_destruct != nullptr) { - config_.verify_options.verify_peer_destruct( - config_.verify_options.verify_peer_callback_userdata); - } + : grpc_channel_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) { + build_config(pem_root_certs, pem_key_cert_pair, verify_options); } -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_ssl_credentials::create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, +grpc_ssl_credentials::~grpc_ssl_credentials() { + gpr_free(config_.pem_root_certs); + grpc_tsi_ssl_pem_key_cert_pairs_destroy(config_.pem_key_cert_pair, 1); + if (config_.verify_options.verify_peer_destruct != nullptr) { + config_.verify_options.verify_peer_destruct( + config_.verify_options.verify_peer_callback_userdata); + } +} + +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_ssl_credentials::create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, const char* target, const grpc_channel_args* args, - grpc_channel_args** new_args) { + grpc_channel_args** new_args) { const char* overridden_target_name = nullptr; tsi_ssl_session_cache* ssl_session_cache = nullptr; for (size_t i = 0; args && i < args->num_args; i++) { @@ -79,42 +79,42 @@ grpc_ssl_credentials::create_security_connector( static_cast<tsi_ssl_session_cache*>(arg->value.pointer.p); } } - grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = - grpc_ssl_channel_security_connector_create( - this->Ref(), std::move(call_creds), &config_, target, - overridden_target_name, ssl_session_cache); - if (sc == nullptr) { - return sc; + grpc_core::RefCountedPtr<grpc_channel_security_connector> sc = + grpc_ssl_channel_security_connector_create( + this->Ref(), std::move(call_creds), &config_, target, + overridden_target_name, ssl_session_cache); + if (sc == nullptr) { + return sc; } grpc_arg new_arg = grpc_channel_arg_string_create( (char*)GRPC_ARG_HTTP2_SCHEME, (char*)"https"); *new_args = grpc_channel_args_copy_and_add(args, &new_arg, 1); - return sc; + return sc; } -void grpc_ssl_credentials::build_config( - const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, +void grpc_ssl_credentials::build_config( + const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const grpc_ssl_verify_peer_options* verify_options) { - config_.pem_root_certs = gpr_strdup(pem_root_certs); + config_.pem_root_certs = gpr_strdup(pem_root_certs); if (pem_key_cert_pair != nullptr) { GPR_ASSERT(pem_key_cert_pair->private_key != nullptr); GPR_ASSERT(pem_key_cert_pair->cert_chain != nullptr); - config_.pem_key_cert_pair = static_cast<tsi_ssl_pem_key_cert_pair*>( + config_.pem_key_cert_pair = static_cast<tsi_ssl_pem_key_cert_pair*>( gpr_zalloc(sizeof(tsi_ssl_pem_key_cert_pair))); - config_.pem_key_cert_pair->cert_chain = + config_.pem_key_cert_pair->cert_chain = gpr_strdup(pem_key_cert_pair->cert_chain); - config_.pem_key_cert_pair->private_key = + config_.pem_key_cert_pair->private_key = gpr_strdup(pem_key_cert_pair->private_key); - } else { - config_.pem_key_cert_pair = nullptr; - } - if (verify_options != nullptr) { - memcpy(&config_.verify_options, verify_options, - sizeof(verify_peer_options)); - } else { - // Otherwise set all options to default values - memset(&config_.verify_options, 0, sizeof(verify_peer_options)); + } else { + config_.pem_key_cert_pair = nullptr; } + if (verify_options != nullptr) { + memcpy(&config_.verify_options, verify_options, + sizeof(verify_peer_options)); + } else { + // Otherwise set all options to default values + memset(&config_.verify_options, 0, sizeof(verify_peer_options)); + } } void grpc_ssl_credentials::set_min_tls_version( @@ -131,15 +131,15 @@ void grpc_ssl_credentials::set_max_tls_version( * once all of its call sites are migrated to grpc_ssl_credentials_create_ex. */ grpc_channel_credentials* grpc_ssl_credentials_create( const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, - const verify_peer_options* verify_options, void* reserved) { + const verify_peer_options* verify_options, void* reserved) { GRPC_API_TRACE( "grpc_ssl_credentials_create(pem_root_certs=%s, " "pem_key_cert_pair=%p, " - "verify_options=%p, " + "verify_options=%p, " "reserved=%p)", - 4, (pem_root_certs, pem_key_cert_pair, verify_options, reserved)); + 4, (pem_root_certs, pem_key_cert_pair, verify_options, reserved)); GPR_ASSERT(reserved == nullptr); - + return new grpc_ssl_credentials( pem_root_certs, pem_key_cert_pair, reinterpret_cast<const grpc_ssl_verify_peer_options*>(verify_options)); @@ -170,29 +170,29 @@ struct grpc_ssl_server_credentials_options { grpc_ssl_server_certificate_config_fetcher* certificate_config_fetcher; }; -grpc_ssl_server_credentials::grpc_ssl_server_credentials( - const grpc_ssl_server_credentials_options& options) - : grpc_server_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) { - if (options.certificate_config_fetcher != nullptr) { - config_.client_certificate_request = options.client_certificate_request; - certificate_config_fetcher_ = *options.certificate_config_fetcher; - } else { - build_config(options.certificate_config->pem_root_certs, - options.certificate_config->pem_key_cert_pairs, - options.certificate_config->num_key_cert_pairs, - options.client_certificate_request); - } +grpc_ssl_server_credentials::grpc_ssl_server_credentials( + const grpc_ssl_server_credentials_options& options) + : grpc_server_credentials(GRPC_CHANNEL_CREDENTIALS_TYPE_SSL) { + if (options.certificate_config_fetcher != nullptr) { + config_.client_certificate_request = options.client_certificate_request; + certificate_config_fetcher_ = *options.certificate_config_fetcher; + } else { + build_config(options.certificate_config->pem_root_certs, + options.certificate_config->pem_key_cert_pairs, + options.certificate_config->num_key_cert_pairs, + options.client_certificate_request); + } } -grpc_ssl_server_credentials::~grpc_ssl_server_credentials() { - grpc_tsi_ssl_pem_key_cert_pairs_destroy(config_.pem_key_cert_pairs, - config_.num_key_cert_pairs); - gpr_free(config_.pem_root_certs); -} -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_ssl_server_credentials::create_security_connector() { - return grpc_ssl_server_security_connector_create(this->Ref()); +grpc_ssl_server_credentials::~grpc_ssl_server_credentials() { + grpc_tsi_ssl_pem_key_cert_pairs_destroy(config_.pem_key_cert_pairs, + config_.num_key_cert_pairs); + gpr_free(config_.pem_root_certs); } +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_ssl_server_credentials::create_security_connector() { + return grpc_ssl_server_security_connector_create(this->Ref()); +} tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs( const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, @@ -212,15 +212,15 @@ tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs( return tsi_pairs; } -void grpc_ssl_server_credentials::build_config( +void grpc_ssl_server_credentials::build_config( const char* pem_root_certs, grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, - grpc_ssl_client_certificate_request_type client_certificate_request) { - config_.client_certificate_request = client_certificate_request; - config_.pem_root_certs = gpr_strdup(pem_root_certs); - config_.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs( + grpc_ssl_client_certificate_request_type client_certificate_request) { + config_.client_certificate_request = client_certificate_request; + config_.pem_root_certs = gpr_strdup(pem_root_certs); + config_.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs( pem_key_cert_pairs, num_key_cert_pairs); - config_.num_key_cert_pairs = num_key_cert_pairs; + config_.num_key_cert_pairs = num_key_cert_pairs; } void grpc_ssl_server_credentials::set_min_tls_version( @@ -240,7 +240,7 @@ grpc_ssl_server_certificate_config* grpc_ssl_server_certificate_config_create( grpc_ssl_server_certificate_config* config = static_cast<grpc_ssl_server_certificate_config*>( gpr_zalloc(sizeof(grpc_ssl_server_certificate_config))); - config->pem_root_certs = gpr_strdup(pem_root_certs); + config->pem_root_certs = gpr_strdup(pem_root_certs); if (num_key_cert_pairs > 0) { GPR_ASSERT(pem_key_cert_pairs != nullptr); config->pem_key_cert_pairs = static_cast<grpc_ssl_pem_key_cert_pair*>( diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h index 4c90813f8d..d911958304 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/ssl/ssl_credentials.h @@ -22,83 +22,83 @@ #include "src/core/lib/security/credentials/credentials.h" -#include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h" +#include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h" -class grpc_ssl_credentials : public grpc_channel_credentials { - public: - grpc_ssl_credentials(const char* pem_root_certs, - grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, +class grpc_ssl_credentials : public grpc_channel_credentials { + public: + grpc_ssl_credentials(const char* pem_root_certs, + grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const grpc_ssl_verify_peer_options* verify_options); - - ~grpc_ssl_credentials() override; - - grpc_core::RefCountedPtr<grpc_channel_security_connector> - create_security_connector( - grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, - const char* target, const grpc_channel_args* args, - grpc_channel_args** new_args) override; - + + ~grpc_ssl_credentials() override; + + grpc_core::RefCountedPtr<grpc_channel_security_connector> + create_security_connector( + grpc_core::RefCountedPtr<grpc_call_credentials> call_creds, + const char* target, const grpc_channel_args* args, + grpc_channel_args** new_args) override; + // TODO(mattstev): Plumb to wrapped languages. Until then, setting the TLS // version should be done for testing purposes only. void set_min_tls_version(grpc_tls_version min_tls_version); void set_max_tls_version(grpc_tls_version max_tls_version); - private: - void build_config(const char* pem_root_certs, - grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, + private: + void build_config(const char* pem_root_certs, + grpc_ssl_pem_key_cert_pair* pem_key_cert_pair, const grpc_ssl_verify_peer_options* verify_options); - - grpc_ssl_config config_; -}; - + + grpc_ssl_config config_; +}; + struct grpc_ssl_server_certificate_config { - grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs = nullptr; - size_t num_key_cert_pairs = 0; - char* pem_root_certs = nullptr; + grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs = nullptr; + size_t num_key_cert_pairs = 0; + char* pem_root_certs = nullptr; }; -struct grpc_ssl_server_certificate_config_fetcher { - grpc_ssl_server_certificate_config_callback cb = nullptr; +struct grpc_ssl_server_certificate_config_fetcher { + grpc_ssl_server_certificate_config_callback cb = nullptr; void* user_data; -}; - -class grpc_ssl_server_credentials final : public grpc_server_credentials { - public: - grpc_ssl_server_credentials( - const grpc_ssl_server_credentials_options& options); - ~grpc_ssl_server_credentials() override; - - grpc_core::RefCountedPtr<grpc_server_security_connector> - create_security_connector() override; - - bool has_cert_config_fetcher() const { - return certificate_config_fetcher_.cb != nullptr; - } - - grpc_ssl_certificate_config_reload_status FetchCertConfig( - grpc_ssl_server_certificate_config** config) { - GPR_DEBUG_ASSERT(has_cert_config_fetcher()); - return certificate_config_fetcher_.cb(certificate_config_fetcher_.user_data, - config); - } - +}; + +class grpc_ssl_server_credentials final : public grpc_server_credentials { + public: + grpc_ssl_server_credentials( + const grpc_ssl_server_credentials_options& options); + ~grpc_ssl_server_credentials() override; + + grpc_core::RefCountedPtr<grpc_server_security_connector> + create_security_connector() override; + + bool has_cert_config_fetcher() const { + return certificate_config_fetcher_.cb != nullptr; + } + + grpc_ssl_certificate_config_reload_status FetchCertConfig( + grpc_ssl_server_certificate_config** config) { + GPR_DEBUG_ASSERT(has_cert_config_fetcher()); + return certificate_config_fetcher_.cb(certificate_config_fetcher_.user_data, + config); + } + // TODO(mattstev): Plumb to wrapped languages. Until then, setting the TLS // version should be done for testing purposes only. void set_min_tls_version(grpc_tls_version min_tls_version); void set_max_tls_version(grpc_tls_version max_tls_version); - const grpc_ssl_server_config& config() const { return config_; } - - private: - void build_config( - const char* pem_root_certs, - grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, - grpc_ssl_client_certificate_request_type client_certificate_request); - - grpc_ssl_server_config config_; - grpc_ssl_server_certificate_config_fetcher certificate_config_fetcher_; -}; - + const grpc_ssl_server_config& config() const { return config_; } + + private: + void build_config( + const char* pem_root_certs, + grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs, + grpc_ssl_client_certificate_request_type client_certificate_request); + + grpc_ssl_server_config config_; + grpc_ssl_server_certificate_config_fetcher certificate_config_fetcher_; +}; + tsi_ssl_pem_key_cert_pair* grpc_convert_grpc_to_tsi_cert_pairs( const grpc_ssl_pem_key_cert_pair* pem_key_cert_pairs, size_t num_key_cert_pairs); diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc index 906a2f0209..01a77e696b 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc +++ b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc @@ -1,34 +1,34 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h" - -#include <stdlib.h> -#include <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -/** -- gRPC TLS key materials config API implementation. -- **/ -void grpc_tls_key_materials_config::set_key_materials( +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h" + +#include <stdlib.h> +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +/** -- gRPC TLS key materials config API implementation. -- **/ +void grpc_tls_key_materials_config::set_key_materials( const char* pem_root_certs, const grpc_ssl_pem_key_cert_pair** pem_key_cert_pairs, size_t num_key_cert_pairs) { @@ -42,8 +42,8 @@ void grpc_tls_key_materials_config::set_key_materials( cert_pair_list.emplace_back(grpc_core::PemKeyCertPair(current_pair)); } pem_key_cert_pair_list_ = std::move(cert_pair_list); -} - +} + void grpc_tls_key_materials_config::set_key_materials( const char* pem_root_certs, const PemKeyCertPairList& pem_key_cert_pair_list) { @@ -53,63 +53,63 @@ void grpc_tls_key_materials_config::set_key_materials( pem_key_cert_pair_list_ = std::move(dup_list); } -/** -- gRPC TLS credential reload config API implementation. -- **/ -grpc_tls_credential_reload_config::grpc_tls_credential_reload_config( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_credential_reload_arg* arg), - void (*cancel)(void* config_user_data, grpc_tls_credential_reload_arg* arg), - void (*destruct)(void* config_user_data)) - : config_user_data_(const_cast<void*>(config_user_data)), - schedule_(schedule), - cancel_(cancel), - destruct_(destruct) {} - -grpc_tls_credential_reload_config::~grpc_tls_credential_reload_config() { - if (destruct_ != nullptr) { - destruct_((void*)config_user_data_); - } -} - -/** -- gRPC TLS server authorization check API implementation. -- **/ -grpc_tls_server_authorization_check_config:: - grpc_tls_server_authorization_check_config( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*cancel)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*destruct)(void* config_user_data)) - : config_user_data_(const_cast<void*>(config_user_data)), - schedule_(schedule), - cancel_(cancel), - destruct_(destruct) {} - -grpc_tls_server_authorization_check_config:: - ~grpc_tls_server_authorization_check_config() { - if (destruct_ != nullptr) { - destruct_((void*)config_user_data_); - } -} - -/** -- Wrapper APIs declared in grpc_security.h -- **/ -grpc_tls_credentials_options* grpc_tls_credentials_options_create() { +/** -- gRPC TLS credential reload config API implementation. -- **/ +grpc_tls_credential_reload_config::grpc_tls_credential_reload_config( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_credential_reload_arg* arg), + void (*cancel)(void* config_user_data, grpc_tls_credential_reload_arg* arg), + void (*destruct)(void* config_user_data)) + : config_user_data_(const_cast<void*>(config_user_data)), + schedule_(schedule), + cancel_(cancel), + destruct_(destruct) {} + +grpc_tls_credential_reload_config::~grpc_tls_credential_reload_config() { + if (destruct_ != nullptr) { + destruct_((void*)config_user_data_); + } +} + +/** -- gRPC TLS server authorization check API implementation. -- **/ +grpc_tls_server_authorization_check_config:: + grpc_tls_server_authorization_check_config( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*cancel)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*destruct)(void* config_user_data)) + : config_user_data_(const_cast<void*>(config_user_data)), + schedule_(schedule), + cancel_(cancel), + destruct_(destruct) {} + +grpc_tls_server_authorization_check_config:: + ~grpc_tls_server_authorization_check_config() { + if (destruct_ != nullptr) { + destruct_((void*)config_user_data_); + } +} + +/** -- Wrapper APIs declared in grpc_security.h -- **/ +grpc_tls_credentials_options* grpc_tls_credentials_options_create() { return new grpc_tls_credentials_options(); -} - -int grpc_tls_credentials_options_set_cert_request_type( - grpc_tls_credentials_options* options, - grpc_ssl_client_certificate_request_type type) { - if (options == nullptr) { - gpr_log(GPR_ERROR, - "Invalid nullptr arguments to " - "grpc_tls_credentials_options_set_cert_request_type()"); - return 0; - } - options->set_cert_request_type(type); - return 1; -} - +} + +int grpc_tls_credentials_options_set_cert_request_type( + grpc_tls_credentials_options* options, + grpc_ssl_client_certificate_request_type type) { + if (options == nullptr) { + gpr_log(GPR_ERROR, + "Invalid nullptr arguments to " + "grpc_tls_credentials_options_set_cert_request_type()"); + return 0; + } + options->set_cert_request_type(type); + return 1; +} + int grpc_tls_credentials_options_set_server_verification_option( grpc_tls_credentials_options* options, grpc_tls_server_verification_option server_verification_option) { @@ -130,63 +130,63 @@ int grpc_tls_credentials_options_set_server_verification_option( return 1; } -int grpc_tls_credentials_options_set_key_materials_config( - grpc_tls_credentials_options* options, - grpc_tls_key_materials_config* config) { - if (options == nullptr || config == nullptr) { - gpr_log(GPR_ERROR, - "Invalid nullptr arguments to " - "grpc_tls_credentials_options_set_key_materials_config()"); - return 0; - } - options->set_key_materials_config(config->Ref()); - return 1; -} - -int grpc_tls_credentials_options_set_credential_reload_config( - grpc_tls_credentials_options* options, - grpc_tls_credential_reload_config* config) { - if (options == nullptr || config == nullptr) { - gpr_log(GPR_ERROR, - "Invalid nullptr arguments to " - "grpc_tls_credentials_options_set_credential_reload_config()"); - return 0; - } - options->set_credential_reload_config(config->Ref()); - return 1; -} - -int grpc_tls_credentials_options_set_server_authorization_check_config( - grpc_tls_credentials_options* options, - grpc_tls_server_authorization_check_config* config) { - if (options == nullptr || config == nullptr) { - gpr_log( - GPR_ERROR, - "Invalid nullptr arguments to " - "grpc_tls_credentials_options_set_server_authorization_check_config()"); - return 0; - } - options->set_server_authorization_check_config(config->Ref()); - return 1; -} - -grpc_tls_key_materials_config* grpc_tls_key_materials_config_create() { +int grpc_tls_credentials_options_set_key_materials_config( + grpc_tls_credentials_options* options, + grpc_tls_key_materials_config* config) { + if (options == nullptr || config == nullptr) { + gpr_log(GPR_ERROR, + "Invalid nullptr arguments to " + "grpc_tls_credentials_options_set_key_materials_config()"); + return 0; + } + options->set_key_materials_config(config->Ref()); + return 1; +} + +int grpc_tls_credentials_options_set_credential_reload_config( + grpc_tls_credentials_options* options, + grpc_tls_credential_reload_config* config) { + if (options == nullptr || config == nullptr) { + gpr_log(GPR_ERROR, + "Invalid nullptr arguments to " + "grpc_tls_credentials_options_set_credential_reload_config()"); + return 0; + } + options->set_credential_reload_config(config->Ref()); + return 1; +} + +int grpc_tls_credentials_options_set_server_authorization_check_config( + grpc_tls_credentials_options* options, + grpc_tls_server_authorization_check_config* config) { + if (options == nullptr || config == nullptr) { + gpr_log( + GPR_ERROR, + "Invalid nullptr arguments to " + "grpc_tls_credentials_options_set_server_authorization_check_config()"); + return 0; + } + options->set_server_authorization_check_config(config->Ref()); + return 1; +} + +grpc_tls_key_materials_config* grpc_tls_key_materials_config_create() { return new grpc_tls_key_materials_config(); -} - -int grpc_tls_key_materials_config_set_key_materials( - grpc_tls_key_materials_config* config, const char* root_certs, - const grpc_ssl_pem_key_cert_pair** key_cert_pairs, size_t num) { - if (config == nullptr || key_cert_pairs == nullptr || num == 0) { - gpr_log(GPR_ERROR, - "Invalid arguments to " - "grpc_tls_key_materials_config_set_key_materials()"); - return 0; - } +} + +int grpc_tls_key_materials_config_set_key_materials( + grpc_tls_key_materials_config* config, const char* root_certs, + const grpc_ssl_pem_key_cert_pair** key_cert_pairs, size_t num) { + if (config == nullptr || key_cert_pairs == nullptr || num == 0) { + gpr_log(GPR_ERROR, + "Invalid arguments to " + "grpc_tls_key_materials_config_set_key_materials()"); + return 0; + } config->set_key_materials(root_certs, key_cert_pairs, num); - return 1; -} - + return 1; +} + int grpc_tls_key_materials_config_set_version( grpc_tls_key_materials_config* config, int version) { if (config == nullptr) { @@ -210,36 +210,36 @@ int grpc_tls_key_materials_config_get_version( return config->version(); } -grpc_tls_credential_reload_config* grpc_tls_credential_reload_config_create( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_credential_reload_arg* arg), - void (*cancel)(void* config_user_data, grpc_tls_credential_reload_arg* arg), - void (*destruct)(void* config_user_data)) { - if (schedule == nullptr) { - gpr_log( - GPR_ERROR, - "Schedule API is nullptr in creating TLS credential reload config."); - return nullptr; - } +grpc_tls_credential_reload_config* grpc_tls_credential_reload_config_create( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_credential_reload_arg* arg), + void (*cancel)(void* config_user_data, grpc_tls_credential_reload_arg* arg), + void (*destruct)(void* config_user_data)) { + if (schedule == nullptr) { + gpr_log( + GPR_ERROR, + "Schedule API is nullptr in creating TLS credential reload config."); + return nullptr; + } return new grpc_tls_credential_reload_config(config_user_data, schedule, cancel, destruct); -} - -grpc_tls_server_authorization_check_config* -grpc_tls_server_authorization_check_config_create( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*cancel)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*destruct)(void* config_user_data)) { - if (schedule == nullptr) { - gpr_log(GPR_ERROR, - "Schedule API is nullptr in creating TLS server authorization " - "check config."); - return nullptr; - } +} + +grpc_tls_server_authorization_check_config* +grpc_tls_server_authorization_check_config_create( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*cancel)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*destruct)(void* config_user_data)) { + if (schedule == nullptr) { + gpr_log(GPR_ERROR, + "Schedule API is nullptr in creating TLS server authorization " + "check config."); + return nullptr; + } return new grpc_tls_server_authorization_check_config( - config_user_data, schedule, cancel, destruct); -} + config_user_data, schedule, cancel, destruct); +} diff --git a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h index 59411d4169..aa3f9d0a8d 100644 --- a/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h +++ b/contrib/libs/grpc/src/core/lib/security/credentials/tls/grpc_tls_credentials_options.h @@ -1,33 +1,33 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H -#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc_security.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H +#define GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc_security.h> + #include "y_absl/container/inlined_vector.h" -#include "src/core/lib/gprpp/ref_counted.h" -#include "src/core/lib/security/security_connector/ssl_utils.h" - +#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/security/security_connector/ssl_utils.h" + struct grpc_tls_error_details : public grpc_core::RefCounted<grpc_tls_error_details> { public: @@ -41,20 +41,20 @@ struct grpc_tls_error_details TString error_details_; }; -/** TLS key materials config. **/ -struct grpc_tls_key_materials_config - : public grpc_core::RefCounted<grpc_tls_key_materials_config> { - public: +/** TLS key materials config. **/ +struct grpc_tls_key_materials_config + : public grpc_core::RefCounted<grpc_tls_key_materials_config> { + public: typedef y_absl::InlinedVector<grpc_core::PemKeyCertPair, 1> PemKeyCertPairList; - - /** Getters for member fields. **/ - const char* pem_root_certs() const { return pem_root_certs_.get(); } - const PemKeyCertPairList& pem_key_cert_pair_list() const { - return pem_key_cert_pair_list_; - } + + /** Getters for member fields. **/ + const char* pem_root_certs() const { return pem_root_certs_.get(); } + const PemKeyCertPairList& pem_key_cert_pair_list() const { + return pem_key_cert_pair_list_; + } int version() const { return version_; } - - /** Setters for member fields. **/ + + /** Setters for member fields. **/ // TODO(ZhenLian): Remove this function void set_pem_root_certs(grpc_core::UniquePtr<char> pem_root_certs) { pem_root_certs_ = std::move(pem_root_certs); @@ -78,30 +78,30 @@ struct grpc_tls_key_materials_config void set_key_materials(const char* pem_root_certs, const PemKeyCertPairList& pem_key_cert_pair_list); void set_version(int version) { version_ = version; } - - private: + + private: int version_ = 0; - PemKeyCertPairList pem_key_cert_pair_list_; - grpc_core::UniquePtr<char> pem_root_certs_; -}; - -/** TLS credential reload config. **/ -struct grpc_tls_credential_reload_config - : public grpc_core::RefCounted<grpc_tls_credential_reload_config> { - public: - grpc_tls_credential_reload_config( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_credential_reload_arg* arg), - void (*cancel)(void* config_user_data, - grpc_tls_credential_reload_arg* arg), - void (*destruct)(void* config_user_data)); - ~grpc_tls_credential_reload_config(); - + PemKeyCertPairList pem_key_cert_pair_list_; + grpc_core::UniquePtr<char> pem_root_certs_; +}; + +/** TLS credential reload config. **/ +struct grpc_tls_credential_reload_config + : public grpc_core::RefCounted<grpc_tls_credential_reload_config> { + public: + grpc_tls_credential_reload_config( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_credential_reload_arg* arg), + void (*cancel)(void* config_user_data, + grpc_tls_credential_reload_arg* arg), + void (*destruct)(void* config_user_data)); + ~grpc_tls_credential_reload_config(); + void* context() const { return context_; } void set_context(void* context) { context_ = context; } - int Schedule(grpc_tls_credential_reload_arg* arg) const { + int Schedule(grpc_tls_credential_reload_arg* arg) const { if (schedule_ == nullptr) { gpr_log(GPR_ERROR, "schedule API is nullptr"); if (arg != nullptr) { @@ -114,70 +114,70 @@ struct grpc_tls_credential_reload_config if (arg != nullptr) { arg->config = const_cast<grpc_tls_credential_reload_config*>(this); } - return schedule_(config_user_data_, arg); - } - void Cancel(grpc_tls_credential_reload_arg* arg) const { - if (cancel_ == nullptr) { - gpr_log(GPR_ERROR, "cancel API is nullptr."); + return schedule_(config_user_data_, arg); + } + void Cancel(grpc_tls_credential_reload_arg* arg) const { + if (cancel_ == nullptr) { + gpr_log(GPR_ERROR, "cancel API is nullptr."); if (arg != nullptr) { arg->status = GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL; arg->error_details->set_error_details( "cancel API in credential reload config is nullptr"); } - return; - } + return; + } if (arg != nullptr) { arg->config = const_cast<grpc_tls_credential_reload_config*>(this); } - cancel_(config_user_data_, arg); - } - - private: + cancel_(config_user_data_, arg); + } + + private: /** This is a pointer to the wrapped language implementation of * grpc_tls_credential_reload_config. It is necessary to implement the C * schedule and cancel functions, given the schedule or cancel function in a * wrapped language. **/ void* context_ = nullptr; - /** config-specific, read-only user data that works for all channels created - with a credential using the config. */ - void* config_user_data_; - /** callback function for invoking credential reload API. The implementation - of this method has to be non-blocking, but can be performed synchronously - or asynchronously. - If processing occurs synchronously, it populates \a arg->key_materials, \a - arg->status, and \a arg->error_details and returns zero. - If processing occurs asynchronously, it returns a non-zero value. - Application then invokes \a arg->cb when processing is completed. Note that - \a arg->cb cannot be invoked before \a schedule returns. - */ - int (*schedule_)(void* config_user_data, grpc_tls_credential_reload_arg* arg); - /** callback function for cancelling a credential reload request scheduled via - an asynchronous \a schedule. \a arg is used to pinpoint an exact reloading - request to be cancelled, and the operation may not have any effect if the - request has already been processed. */ - void (*cancel_)(void* config_user_data, grpc_tls_credential_reload_arg* arg); - /** callback function for cleaning up any data associated with credential - reload config. */ - void (*destruct_)(void* config_user_data); -}; - -/** TLS server authorization check config. **/ -struct grpc_tls_server_authorization_check_config - : public grpc_core::RefCounted<grpc_tls_server_authorization_check_config> { - public: - grpc_tls_server_authorization_check_config( - const void* config_user_data, - int (*schedule)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*cancel)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg), - void (*destruct)(void* config_user_data)); - ~grpc_tls_server_authorization_check_config(); - + /** config-specific, read-only user data that works for all channels created + with a credential using the config. */ + void* config_user_data_; + /** callback function for invoking credential reload API. The implementation + of this method has to be non-blocking, but can be performed synchronously + or asynchronously. + If processing occurs synchronously, it populates \a arg->key_materials, \a + arg->status, and \a arg->error_details and returns zero. + If processing occurs asynchronously, it returns a non-zero value. + Application then invokes \a arg->cb when processing is completed. Note that + \a arg->cb cannot be invoked before \a schedule returns. + */ + int (*schedule_)(void* config_user_data, grpc_tls_credential_reload_arg* arg); + /** callback function for cancelling a credential reload request scheduled via + an asynchronous \a schedule. \a arg is used to pinpoint an exact reloading + request to be cancelled, and the operation may not have any effect if the + request has already been processed. */ + void (*cancel_)(void* config_user_data, grpc_tls_credential_reload_arg* arg); + /** callback function for cleaning up any data associated with credential + reload config. */ + void (*destruct_)(void* config_user_data); +}; + +/** TLS server authorization check config. **/ +struct grpc_tls_server_authorization_check_config + : public grpc_core::RefCounted<grpc_tls_server_authorization_check_config> { + public: + grpc_tls_server_authorization_check_config( + const void* config_user_data, + int (*schedule)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*cancel)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg), + void (*destruct)(void* config_user_data)); + ~grpc_tls_server_authorization_check_config(); + void* context() const { return context_; } void set_context(void* context) { context_ = context; } - int Schedule(grpc_tls_server_authorization_check_arg* arg) const { + int Schedule(grpc_tls_server_authorization_check_arg* arg) const { if (schedule_ == nullptr) { gpr_log(GPR_ERROR, "schedule API is nullptr"); if (arg != nullptr) { @@ -191,97 +191,97 @@ struct grpc_tls_server_authorization_check_config arg->config = const_cast<grpc_tls_server_authorization_check_config*>(this); } - return schedule_(config_user_data_, arg); - } - void Cancel(grpc_tls_server_authorization_check_arg* arg) const { - if (cancel_ == nullptr) { - gpr_log(GPR_ERROR, "cancel API is nullptr."); + return schedule_(config_user_data_, arg); + } + void Cancel(grpc_tls_server_authorization_check_arg* arg) const { + if (cancel_ == nullptr) { + gpr_log(GPR_ERROR, "cancel API is nullptr."); if (arg != nullptr) { arg->status = GRPC_STATUS_NOT_FOUND; arg->error_details->set_error_details( "schedule API in server authorization check config is nullptr"); } - return; - } + return; + } if (arg != nullptr) { arg->config = const_cast<grpc_tls_server_authorization_check_config*>(this); } - cancel_(config_user_data_, arg); - } - - private: + cancel_(config_user_data_, arg); + } + + private: /** This is a pointer to the wrapped language implementation of * grpc_tls_server_authorization_check_config. It is necessary to implement * the C schedule and cancel functions, given the schedule or cancel function * in a wrapped language. **/ void* context_ = nullptr; - /** config-specific, read-only user data that works for all channels created - with a Credential using the config. */ - void* config_user_data_; - - /** callback function for invoking server authorization check. The - implementation of this method has to be non-blocking, but can be performed - synchronously or asynchronously. - If processing occurs synchronously, it populates \a arg->result, \a - arg->status, and \a arg->error_details, and returns zero. - If processing occurs asynchronously, it returns a non-zero value. - Application then invokes \a arg->cb when processing is completed. Note that - \a arg->cb cannot be invoked before \a schedule() returns. - */ - int (*schedule_)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg); - - /** callback function for canceling a server authorization check request. */ - void (*cancel_)(void* config_user_data, - grpc_tls_server_authorization_check_arg* arg); - - /** callback function for cleaning up any data associated with server - authorization check config. */ - void (*destruct_)(void* config_user_data); -}; - -/* TLS credentials options. */ -struct grpc_tls_credentials_options - : public grpc_core::RefCounted<grpc_tls_credentials_options> { - public: - ~grpc_tls_credentials_options() { - if (key_materials_config_.get() != nullptr) { - key_materials_config_.get()->Unref(); - } - if (credential_reload_config_.get() != nullptr) { - credential_reload_config_.get()->Unref(); - } - if (server_authorization_check_config_.get() != nullptr) { - server_authorization_check_config_.get()->Unref(); - } - } - - /* Getters for member fields. */ - grpc_ssl_client_certificate_request_type cert_request_type() const { - return cert_request_type_; - } + /** config-specific, read-only user data that works for all channels created + with a Credential using the config. */ + void* config_user_data_; + + /** callback function for invoking server authorization check. The + implementation of this method has to be non-blocking, but can be performed + synchronously or asynchronously. + If processing occurs synchronously, it populates \a arg->result, \a + arg->status, and \a arg->error_details, and returns zero. + If processing occurs asynchronously, it returns a non-zero value. + Application then invokes \a arg->cb when processing is completed. Note that + \a arg->cb cannot be invoked before \a schedule() returns. + */ + int (*schedule_)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg); + + /** callback function for canceling a server authorization check request. */ + void (*cancel_)(void* config_user_data, + grpc_tls_server_authorization_check_arg* arg); + + /** callback function for cleaning up any data associated with server + authorization check config. */ + void (*destruct_)(void* config_user_data); +}; + +/* TLS credentials options. */ +struct grpc_tls_credentials_options + : public grpc_core::RefCounted<grpc_tls_credentials_options> { + public: + ~grpc_tls_credentials_options() { + if (key_materials_config_.get() != nullptr) { + key_materials_config_.get()->Unref(); + } + if (credential_reload_config_.get() != nullptr) { + credential_reload_config_.get()->Unref(); + } + if (server_authorization_check_config_.get() != nullptr) { + server_authorization_check_config_.get()->Unref(); + } + } + + /* Getters for member fields. */ + grpc_ssl_client_certificate_request_type cert_request_type() const { + return cert_request_type_; + } grpc_tls_server_verification_option server_verification_option() const { return server_verification_option_; } grpc_tls_version min_tls_version() const { return min_tls_version_; } grpc_tls_version max_tls_version() const { return max_tls_version_; } grpc_tls_key_materials_config* key_materials_config() const { - return key_materials_config_.get(); - } + return key_materials_config_.get(); + } grpc_tls_credential_reload_config* credential_reload_config() const { - return credential_reload_config_.get(); - } + return credential_reload_config_.get(); + } grpc_tls_server_authorization_check_config* - server_authorization_check_config() const { - return server_authorization_check_config_.get(); - } - - /* Setters for member fields. */ - void set_cert_request_type( - const grpc_ssl_client_certificate_request_type type) { - cert_request_type_ = type; - } + server_authorization_check_config() const { + return server_authorization_check_config_.get(); + } + + /* Setters for member fields. */ + void set_cert_request_type( + const grpc_ssl_client_certificate_request_type type) { + cert_request_type_ = type; + } void set_server_verification_option( const grpc_tls_server_verification_option server_verification_option) { server_verification_option_ = server_verification_option; @@ -292,32 +292,32 @@ struct grpc_tls_credentials_options void set_max_tls_version(grpc_tls_version max_tls_version) { max_tls_version_ = max_tls_version; } - void set_key_materials_config( - grpc_core::RefCountedPtr<grpc_tls_key_materials_config> config) { - key_materials_config_ = std::move(config); - } - void set_credential_reload_config( - grpc_core::RefCountedPtr<grpc_tls_credential_reload_config> config) { - credential_reload_config_ = std::move(config); - } - void set_server_authorization_check_config( - grpc_core::RefCountedPtr<grpc_tls_server_authorization_check_config> - config) { - server_authorization_check_config_ = std::move(config); - } - - private: - grpc_ssl_client_certificate_request_type cert_request_type_; + void set_key_materials_config( + grpc_core::RefCountedPtr<grpc_tls_key_materials_config> config) { + key_materials_config_ = std::move(config); + } + void set_credential_reload_config( + grpc_core::RefCountedPtr<grpc_tls_credential_reload_config> config) { + credential_reload_config_ = std::move(config); + } + void set_server_authorization_check_config( + grpc_core::RefCountedPtr<grpc_tls_server_authorization_check_config> + config) { + server_authorization_check_config_ = std::move(config); + } + + private: + grpc_ssl_client_certificate_request_type cert_request_type_; grpc_tls_server_verification_option server_verification_option_ = GRPC_TLS_SERVER_VERIFICATION; grpc_tls_version min_tls_version_ = grpc_tls_version::TLS1_2; grpc_tls_version max_tls_version_ = grpc_tls_version::TLS1_3; - grpc_core::RefCountedPtr<grpc_tls_key_materials_config> key_materials_config_; - grpc_core::RefCountedPtr<grpc_tls_credential_reload_config> - credential_reload_config_; - grpc_core::RefCountedPtr<grpc_tls_server_authorization_check_config> - server_authorization_check_config_; -}; - -#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H \ - */ + grpc_core::RefCountedPtr<grpc_tls_key_materials_config> key_materials_config_; + grpc_core::RefCountedPtr<grpc_tls_credential_reload_config> + credential_reload_config_; + grpc_core::RefCountedPtr<grpc_tls_server_authorization_check_config> + server_authorization_check_config_; +}; + +#endif /* GRPC_CORE_LIB_SECURITY_CREDENTIALS_TLS_GRPC_TLS_CREDENTIALS_OPTIONS_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc index d0b532ae18..c2d56bc2ea 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.cc @@ -1,87 +1,87 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/security_connector/alts/alts_security_connector.h" - -#include <stdbool.h> -#include <string.h> - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/security/credentials/alts/alts_credentials.h" -#include "src/core/lib/security/transport/security_handshaker.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/transport/transport.h" -#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h" -#include "src/core/tsi/transport_security.h" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/security_connector/alts/alts_security_connector.h" + +#include <stdbool.h> +#include <string.h> + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/security/credentials/alts/alts_credentials.h" +#include "src/core/lib/security/transport/security_handshaker.h" +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/transport/transport.h" +#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h" +#include "src/core/tsi/transport_security.h" + void grpc_alts_set_rpc_protocol_versions( - grpc_gcp_rpc_protocol_versions* rpc_versions) { - grpc_gcp_rpc_protocol_versions_set_max(rpc_versions, - GRPC_PROTOCOL_VERSION_MAX_MAJOR, - GRPC_PROTOCOL_VERSION_MAX_MINOR); - grpc_gcp_rpc_protocol_versions_set_min(rpc_versions, - GRPC_PROTOCOL_VERSION_MIN_MAJOR, - GRPC_PROTOCOL_VERSION_MIN_MINOR); -} - + grpc_gcp_rpc_protocol_versions* rpc_versions) { + grpc_gcp_rpc_protocol_versions_set_max(rpc_versions, + GRPC_PROTOCOL_VERSION_MAX_MAJOR, + GRPC_PROTOCOL_VERSION_MAX_MINOR); + grpc_gcp_rpc_protocol_versions_set_min(rpc_versions, + GRPC_PROTOCOL_VERSION_MIN_MAJOR, + GRPC_PROTOCOL_VERSION_MIN_MINOR); +} + namespace { -void alts_check_peer(tsi_peer peer, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) { - *auth_context = - grpc_core::internal::grpc_alts_auth_context_from_tsi_peer(&peer); - tsi_peer_destruct(&peer); - grpc_error* error = - *auth_context != nullptr - ? GRPC_ERROR_NONE - : GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Could not get ALTS auth context from TSI peer"); +void alts_check_peer(tsi_peer peer, + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) { + *auth_context = + grpc_core::internal::grpc_alts_auth_context_from_tsi_peer(&peer); + tsi_peer_destruct(&peer); + grpc_error* error = + *auth_context != nullptr + ? GRPC_ERROR_NONE + : GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Could not get ALTS auth context from TSI peer"); grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); -} - -class grpc_alts_channel_security_connector final - : public grpc_channel_security_connector { - public: - grpc_alts_channel_security_connector( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target_name) +} + +class grpc_alts_channel_security_connector final + : public grpc_channel_security_connector { + public: + grpc_alts_channel_security_connector( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target_name) : grpc_channel_security_connector(GRPC_ALTS_URL_SCHEME, - std::move(channel_creds), - std::move(request_metadata_creds)), + std::move(channel_creds), + std::move(request_metadata_creds)), target_name_(gpr_strdup(target_name)) {} - - ~grpc_alts_channel_security_connector() override { gpr_free(target_name_); } - - void add_handshakers( + + ~grpc_alts_channel_security_connector() override { gpr_free(target_name_); } + + void add_handshakers( const grpc_channel_args* args, grpc_pollset_set* interested_parties, - grpc_core::HandshakeManager* handshake_manager) override { - tsi_handshaker* handshaker = nullptr; - const grpc_alts_credentials* creds = - static_cast<const grpc_alts_credentials*>(channel_creds()); + grpc_core::HandshakeManager* handshake_manager) override { + tsi_handshaker* handshaker = nullptr; + const grpc_alts_credentials* creds = + static_cast<const grpc_alts_credentials*>(channel_creds()); size_t user_specified_max_frame_size = 0; const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_TSI_MAX_FRAME_SIZE); @@ -93,60 +93,60 @@ class grpc_alts_channel_security_connector final creds->options(), target_name_, creds->handshaker_service_url(), true, interested_parties, &handshaker, user_specified_max_frame_size) == TSI_OK); - handshake_manager->Add( + handshake_manager->Add( grpc_core::SecurityHandshakerCreate(handshaker, this, args)); - } - + } + void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { - alts_check_peer(peer, auth_context, on_peer_checked); - } - - int cmp(const grpc_security_connector* other_sc) const override { - auto* other = - reinterpret_cast<const grpc_alts_channel_security_connector*>(other_sc); - int c = channel_security_connector_cmp(other); - if (c != 0) return c; - return strcmp(target_name_, other->target_name_); - } - + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { + alts_check_peer(peer, auth_context, on_peer_checked); + } + + int cmp(const grpc_security_connector* other_sc) const override { + auto* other = + reinterpret_cast<const grpc_alts_channel_security_connector*>(other_sc); + int c = channel_security_connector_cmp(other); + if (c != 0) return c; + return strcmp(target_name_, other->target_name_); + } + bool check_call_host(y_absl::string_view host, grpc_auth_context* /*auth_context*/, grpc_closure* /*on_call_host_checked*/, - grpc_error** error) override { + grpc_error** error) override { if (host.empty() || host != target_name_) { - *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "ALTS call host does not match target name"); - } - return true; - } - + *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "ALTS call host does not match target name"); + } + return true; + } + void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/, - grpc_error* error) override { - GRPC_ERROR_UNREF(error); - } - - private: - char* target_name_; -}; - -class grpc_alts_server_security_connector final - : public grpc_server_security_connector { - public: - grpc_alts_server_security_connector( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) + grpc_error* error) override { + GRPC_ERROR_UNREF(error); + } + + private: + char* target_name_; +}; + +class grpc_alts_server_security_connector final + : public grpc_server_security_connector { + public: + grpc_alts_server_security_connector( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) : grpc_server_security_connector(GRPC_ALTS_URL_SCHEME, std::move(server_creds)) {} - ~grpc_alts_server_security_connector() override = default; - - void add_handshakers( + ~grpc_alts_server_security_connector() override = default; + + void add_handshakers( const grpc_channel_args* args, grpc_pollset_set* interested_parties, - grpc_core::HandshakeManager* handshake_manager) override { - tsi_handshaker* handshaker = nullptr; - const grpc_alts_server_credentials* creds = - static_cast<const grpc_alts_server_credentials*>(server_creds()); + grpc_core::HandshakeManager* handshake_manager) override { + tsi_handshaker* handshaker = nullptr; + const grpc_alts_server_credentials* creds = + static_cast<const grpc_alts_server_credentials*>(server_creds()); size_t user_specified_max_frame_size = 0; const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_TSI_MAX_FRAME_SIZE); @@ -154,45 +154,45 @@ class grpc_alts_server_security_connector final user_specified_max_frame_size = grpc_channel_arg_get_integer( arg, {0, 0, std::numeric_limits<int>::max()}); } - GPR_ASSERT(alts_tsi_handshaker_create( - creds->options(), nullptr, creds->handshaker_service_url(), + GPR_ASSERT(alts_tsi_handshaker_create( + creds->options(), nullptr, creds->handshaker_service_url(), false, interested_parties, &handshaker, user_specified_max_frame_size) == TSI_OK); - handshake_manager->Add( + handshake_manager->Add( grpc_core::SecurityHandshakerCreate(handshaker, this, args)); - } - + } + void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { - alts_check_peer(peer, auth_context, on_peer_checked); - } - - int cmp(const grpc_security_connector* other) const override { - return server_security_connector_cmp( - static_cast<const grpc_server_security_connector*>(other)); - } -}; -} // namespace - -namespace grpc_core { -namespace internal { -grpc_core::RefCountedPtr<grpc_auth_context> -grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) { - if (peer == nullptr) { - gpr_log(GPR_ERROR, - "Invalid arguments to grpc_alts_auth_context_from_tsi_peer()"); - return nullptr; - } - /* Validate certificate type. */ - const tsi_peer_property* cert_type_prop = - tsi_peer_get_property_by_name(peer, TSI_CERTIFICATE_TYPE_PEER_PROPERTY); - if (cert_type_prop == nullptr || - strncmp(cert_type_prop->value.data, TSI_ALTS_CERTIFICATE_TYPE, - cert_type_prop->value.length) != 0) { - gpr_log(GPR_ERROR, "Invalid or missing certificate type property."); - return nullptr; - } + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { + alts_check_peer(peer, auth_context, on_peer_checked); + } + + int cmp(const grpc_security_connector* other) const override { + return server_security_connector_cmp( + static_cast<const grpc_server_security_connector*>(other)); + } +}; +} // namespace + +namespace grpc_core { +namespace internal { +grpc_core::RefCountedPtr<grpc_auth_context> +grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) { + if (peer == nullptr) { + gpr_log(GPR_ERROR, + "Invalid arguments to grpc_alts_auth_context_from_tsi_peer()"); + return nullptr; + } + /* Validate certificate type. */ + const tsi_peer_property* cert_type_prop = + tsi_peer_get_property_by_name(peer, TSI_CERTIFICATE_TYPE_PEER_PROPERTY); + if (cert_type_prop == nullptr || + strncmp(cert_type_prop->value.data, TSI_ALTS_CERTIFICATE_TYPE, + cert_type_prop->value.length) != 0) { + gpr_log(GPR_ERROR, "Invalid or missing certificate type property."); + return nullptr; + } /* Check if security level exists. */ const tsi_peer_property* security_level_prop = tsi_peer_get_property_by_name(peer, TSI_SECURITY_LEVEL_PEER_PROPERTY); @@ -200,31 +200,31 @@ grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) { gpr_log(GPR_ERROR, "Missing security level property."); return nullptr; } - /* Validate RPC protocol versions. */ - const tsi_peer_property* rpc_versions_prop = - tsi_peer_get_property_by_name(peer, TSI_ALTS_RPC_VERSIONS); - if (rpc_versions_prop == nullptr) { - gpr_log(GPR_ERROR, "Missing rpc protocol versions property."); - return nullptr; - } - grpc_gcp_rpc_protocol_versions local_versions, peer_versions; + /* Validate RPC protocol versions. */ + const tsi_peer_property* rpc_versions_prop = + tsi_peer_get_property_by_name(peer, TSI_ALTS_RPC_VERSIONS); + if (rpc_versions_prop == nullptr) { + gpr_log(GPR_ERROR, "Missing rpc protocol versions property."); + return nullptr; + } + grpc_gcp_rpc_protocol_versions local_versions, peer_versions; grpc_alts_set_rpc_protocol_versions(&local_versions); - grpc_slice slice = grpc_slice_from_copied_buffer( - rpc_versions_prop->value.data, rpc_versions_prop->value.length); - bool decode_result = - grpc_gcp_rpc_protocol_versions_decode(slice, &peer_versions); - grpc_slice_unref_internal(slice); - if (!decode_result) { - gpr_log(GPR_ERROR, "Invalid peer rpc protocol versions."); - return nullptr; - } - /* TODO: Pass highest common rpc protocol version to grpc caller. */ - bool check_result = grpc_gcp_rpc_protocol_versions_check( - &local_versions, &peer_versions, nullptr); - if (!check_result) { - gpr_log(GPR_ERROR, "Mismatch of local and peer rpc protocol versions."); - return nullptr; - } + grpc_slice slice = grpc_slice_from_copied_buffer( + rpc_versions_prop->value.data, rpc_versions_prop->value.length); + bool decode_result = + grpc_gcp_rpc_protocol_versions_decode(slice, &peer_versions); + grpc_slice_unref_internal(slice); + if (!decode_result) { + gpr_log(GPR_ERROR, "Invalid peer rpc protocol versions."); + return nullptr; + } + /* TODO: Pass highest common rpc protocol version to grpc caller. */ + bool check_result = grpc_gcp_rpc_protocol_versions_check( + &local_versions, &peer_versions, nullptr); + if (!check_result) { + gpr_log(GPR_ERROR, "Mismatch of local and peer rpc protocol versions."); + return nullptr; + } /* Validate ALTS Context. */ const tsi_peer_property* alts_context_prop = tsi_peer_get_property_by_name(peer, TSI_ALTS_CONTEXT); @@ -232,22 +232,22 @@ grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) { gpr_log(GPR_ERROR, "Missing alts context property."); return nullptr; } - /* Create auth context. */ - auto ctx = grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); - grpc_auth_context_add_cstring_property( - ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, - GRPC_ALTS_TRANSPORT_SECURITY_TYPE); - size_t i = 0; - for (i = 0; i < peer->property_count; i++) { - const tsi_peer_property* tsi_prop = &peer->properties[i]; - /* Add service account to auth context. */ - if (strcmp(tsi_prop->name, TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY) == 0) { - grpc_auth_context_add_property( - ctx.get(), TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY, - tsi_prop->value.data, tsi_prop->value.length); - GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( - ctx.get(), TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY) == 1); - } + /* Create auth context. */ + auto ctx = grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); + grpc_auth_context_add_cstring_property( + ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, + GRPC_ALTS_TRANSPORT_SECURITY_TYPE); + size_t i = 0; + for (i = 0; i < peer->property_count; i++) { + const tsi_peer_property* tsi_prop = &peer->properties[i]; + /* Add service account to auth context. */ + if (strcmp(tsi_prop->name, TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY) == 0) { + grpc_auth_context_add_property( + ctx.get(), TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY, + tsi_prop->value.data, tsi_prop->value.length); + GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( + ctx.get(), TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY) == 1); + } /* Add alts context to auth context. */ if (strcmp(tsi_prop->name, TSI_ALTS_CONTEXT) == 0) { grpc_auth_context_add_property(ctx.get(), TSI_ALTS_CONTEXT, @@ -260,42 +260,42 @@ grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer) { ctx.get(), GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME, tsi_prop->value.data, tsi_prop->value.length); } - } - if (!grpc_auth_context_peer_is_authenticated(ctx.get())) { - gpr_log(GPR_ERROR, "Invalid unauthenticated peer."); - ctx.reset(DEBUG_LOCATION, "test"); - return nullptr; - } - return ctx; -} - -} // namespace internal -} // namespace grpc_core - -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_alts_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target_name) { - if (channel_creds == nullptr || target_name == nullptr) { - gpr_log( - GPR_ERROR, - "Invalid arguments to grpc_alts_channel_security_connector_create()"); - return nullptr; - } - return grpc_core::MakeRefCounted<grpc_alts_channel_security_connector>( - std::move(channel_creds), std::move(request_metadata_creds), target_name); -} - -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_alts_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) { - if (server_creds == nullptr) { - gpr_log( - GPR_ERROR, - "Invalid arguments to grpc_alts_server_security_connector_create()"); - return nullptr; - } - return grpc_core::MakeRefCounted<grpc_alts_server_security_connector>( - std::move(server_creds)); -} + } + if (!grpc_auth_context_peer_is_authenticated(ctx.get())) { + gpr_log(GPR_ERROR, "Invalid unauthenticated peer."); + ctx.reset(DEBUG_LOCATION, "test"); + return nullptr; + } + return ctx; +} + +} // namespace internal +} // namespace grpc_core + +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_alts_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target_name) { + if (channel_creds == nullptr || target_name == nullptr) { + gpr_log( + GPR_ERROR, + "Invalid arguments to grpc_alts_channel_security_connector_create()"); + return nullptr; + } + return grpc_core::MakeRefCounted<grpc_alts_channel_security_connector>( + std::move(channel_creds), std::move(request_metadata_creds), target_name); +} + +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_alts_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) { + if (server_creds == nullptr) { + gpr_log( + GPR_ERROR, + "Invalid arguments to grpc_alts_server_security_connector_create()"); + return nullptr; + } + return grpc_core::MakeRefCounted<grpc_alts_server_security_connector>( + std::move(server_creds)); +} diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h index 10c3fe9364..2be8849321 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/alts/alts_security_connector.h @@ -1,76 +1,76 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/context/security_context.h" -#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h" - -#define GRPC_ALTS_TRANSPORT_SECURITY_TYPE "alts" +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/context/security_context.h" +#include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h" + +#define GRPC_ALTS_TRANSPORT_SECURITY_TYPE "alts" #define GRPC_ALTS_URL_SCHEME "https" - -/** - * This method creates an ALTS channel security connector. - * - * - channel_creds: channel credential instance. - * - request_metadata_creds: credential object which will be sent with each - * request. This parameter can be nullptr. - * - target_name: the name of the endpoint that the channel is connecting to. - * - sc: address of ALTS channel security connector instance to be returned from - * the method. - * - * It returns nullptr on failure. - */ -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_alts_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target_name); - -/** - * This method creates an ALTS server security connector. - * - * - server_creds: server credential instance. - * - sc: address of ALTS server security connector instance to be returned from - * the method. - * - * It returns nullptr on failure. - */ -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_alts_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); - + +/** + * This method creates an ALTS channel security connector. + * + * - channel_creds: channel credential instance. + * - request_metadata_creds: credential object which will be sent with each + * request. This parameter can be nullptr. + * - target_name: the name of the endpoint that the channel is connecting to. + * - sc: address of ALTS channel security connector instance to be returned from + * the method. + * + * It returns nullptr on failure. + */ +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_alts_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target_name); + +/** + * This method creates an ALTS server security connector. + * + * - server_creds: server credential instance. + * - sc: address of ALTS server security connector instance to be returned from + * the method. + * + * It returns nullptr on failure. + */ +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_alts_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); + /* Initializes rpc_versions. */ void grpc_alts_set_rpc_protocol_versions( grpc_gcp_rpc_protocol_versions* rpc_versions); -namespace grpc_core { -namespace internal { - -/* Exposed only for testing. */ -grpc_core::RefCountedPtr<grpc_auth_context> -grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer); - -} // namespace internal -} // namespace grpc_core - -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H \ - */ +namespace grpc_core { +namespace internal { + +/* Exposed only for testing. */ +grpc_core::RefCountedPtr<grpc_auth_context> +grpc_alts_auth_context_from_tsi_peer(const tsi_peer* peer); + +} // namespace internal +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_ALTS_ALTS_SECURITY_CONNECTOR_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc index efbf6d231c..a9b50ac6c1 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.cc @@ -1,107 +1,107 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/security_connector/fake/fake_security_connector.h" - -#include <stdbool.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/security_connector/fake/fake_security_connector.h" + +#include <stdbool.h> + #include "y_absl/strings/str_cat.h" -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.h" -#include "src/core/ext/transport/chttp2/alpn/alpn.h" +#include "src/core/ext/transport/chttp2/alpn/alpn.h" #include "src/core/ext/xds/xds_channel_args.h" -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/channel/handshaker.h" -#include "src/core/lib/gpr/string.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/channel/handshaker.h" +#include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/host_port.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/security/context/security_context.h" -#include "src/core/lib/security/credentials/credentials.h" -#include "src/core/lib/security/credentials/fake/fake_credentials.h" -#include "src/core/lib/security/transport/security_handshaker.h" -#include "src/core/tsi/fake_transport_security.h" - -namespace { -class grpc_fake_channel_security_connector final - : public grpc_channel_security_connector { - public: - grpc_fake_channel_security_connector( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target, const grpc_channel_args* args) - : grpc_channel_security_connector(GRPC_FAKE_SECURITY_URL_SCHEME, - std::move(channel_creds), - std::move(request_metadata_creds)), - target_(gpr_strdup(target)), - expected_targets_( - gpr_strdup(grpc_fake_transport_get_expected_targets(args))), +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/security/context/security_context.h" +#include "src/core/lib/security/credentials/credentials.h" +#include "src/core/lib/security/credentials/fake/fake_credentials.h" +#include "src/core/lib/security/transport/security_handshaker.h" +#include "src/core/tsi/fake_transport_security.h" + +namespace { +class grpc_fake_channel_security_connector final + : public grpc_channel_security_connector { + public: + grpc_fake_channel_security_connector( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target, const grpc_channel_args* args) + : grpc_channel_security_connector(GRPC_FAKE_SECURITY_URL_SCHEME, + std::move(channel_creds), + std::move(request_metadata_creds)), + target_(gpr_strdup(target)), + expected_targets_( + gpr_strdup(grpc_fake_transport_get_expected_targets(args))), is_lb_channel_(grpc_channel_args_find( args, GRPC_ARG_ADDRESS_IS_GRPCLB_LOAD_BALANCER) != nullptr) { - const grpc_arg* target_name_override_arg = - grpc_channel_args_find(args, GRPC_SSL_TARGET_NAME_OVERRIDE_ARG); - if (target_name_override_arg != nullptr) { - target_name_override_ = - gpr_strdup(grpc_channel_arg_get_string(target_name_override_arg)); - } else { - target_name_override_ = nullptr; - } - } - - ~grpc_fake_channel_security_connector() override { - gpr_free(target_); - gpr_free(expected_targets_); - if (target_name_override_ != nullptr) gpr_free(target_name_override_); - } - - void check_peer(tsi_peer peer, grpc_endpoint* ep, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override; - - int cmp(const grpc_security_connector* other_sc) const override { - auto* other = - reinterpret_cast<const grpc_fake_channel_security_connector*>(other_sc); - int c = channel_security_connector_cmp(other); - if (c != 0) return c; - c = strcmp(target_, other->target_); - if (c != 0) return c; - if (expected_targets_ == nullptr || other->expected_targets_ == nullptr) { - c = GPR_ICMP(expected_targets_, other->expected_targets_); - } else { - c = strcmp(expected_targets_, other->expected_targets_); - } - if (c != 0) return c; - return GPR_ICMP(is_lb_channel_, other->is_lb_channel_); - } - + const grpc_arg* target_name_override_arg = + grpc_channel_args_find(args, GRPC_SSL_TARGET_NAME_OVERRIDE_ARG); + if (target_name_override_arg != nullptr) { + target_name_override_ = + gpr_strdup(grpc_channel_arg_get_string(target_name_override_arg)); + } else { + target_name_override_ = nullptr; + } + } + + ~grpc_fake_channel_security_connector() override { + gpr_free(target_); + gpr_free(expected_targets_); + if (target_name_override_ != nullptr) gpr_free(target_name_override_); + } + + void check_peer(tsi_peer peer, grpc_endpoint* ep, + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override; + + int cmp(const grpc_security_connector* other_sc) const override { + auto* other = + reinterpret_cast<const grpc_fake_channel_security_connector*>(other_sc); + int c = channel_security_connector_cmp(other); + if (c != 0) return c; + c = strcmp(target_, other->target_); + if (c != 0) return c; + if (expected_targets_ == nullptr || other->expected_targets_ == nullptr) { + c = GPR_ICMP(expected_targets_, other->expected_targets_); + } else { + c = strcmp(expected_targets_, other->expected_targets_); + } + if (c != 0) return c; + return GPR_ICMP(is_lb_channel_, other->is_lb_channel_); + } + void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_mgr) override { - handshake_mgr->Add(grpc_core::SecurityHandshakerCreate( + grpc_core::HandshakeManager* handshake_mgr) override { + handshake_mgr->Add(grpc_core::SecurityHandshakerCreate( tsi_create_fake_handshaker(/*is_client=*/true), this, args)); - } - + } + bool check_call_host(y_absl::string_view host, grpc_auth_context* /*auth_context*/, grpc_closure* /*on_call_host_checked*/, @@ -113,129 +113,129 @@ class grpc_fake_channel_security_connector final grpc_core::SplitHostPort(host, &authority_hostname, &authority_ignored_port); grpc_core::SplitHostPort(target_, &target_hostname, &target_ignored_port); - if (target_name_override_ != nullptr) { + if (target_name_override_ != nullptr) { y_absl::string_view fake_security_target_name_override_hostname; y_absl::string_view fake_security_target_name_override_ignored_port; grpc_core::SplitHostPort( target_name_override_, &fake_security_target_name_override_hostname, &fake_security_target_name_override_ignored_port); if (authority_hostname != fake_security_target_name_override_hostname) { - gpr_log(GPR_ERROR, - "Authority (host) '%s' != Fake Security Target override '%s'", + gpr_log(GPR_ERROR, + "Authority (host) '%s' != Fake Security Target override '%s'", host.data(), fake_security_target_name_override_hostname.data()); - abort(); - } + abort(); + } } else if (authority_hostname != target_hostname) { gpr_log(GPR_ERROR, "Authority (host) '%s' != Target '%s'", host.data(), target_); - abort(); - } - return true; - } - + abort(); + } + return true; + } + void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/, - grpc_error* error) override { - GRPC_ERROR_UNREF(error); - } - - char* target() const { return target_; } - char* expected_targets() const { return expected_targets_; } - bool is_lb_channel() const { return is_lb_channel_; } - char* target_name_override() const { return target_name_override_; } - - private: + grpc_error* error) override { + GRPC_ERROR_UNREF(error); + } + + char* target() const { return target_; } + char* expected_targets() const { return expected_targets_; } + bool is_lb_channel() const { return is_lb_channel_; } + char* target_name_override() const { return target_name_override_; } + + private: bool fake_check_target(const char* target, const char* set_str) const { - GPR_ASSERT(target != nullptr); - char** set = nullptr; - size_t set_size = 0; - gpr_string_split(set_str, ",", &set, &set_size); - bool found = false; - for (size_t i = 0; i < set_size; ++i) { - if (set[i] != nullptr && strcmp(target, set[i]) == 0) found = true; - } - for (size_t i = 0; i < set_size; ++i) { - gpr_free(set[i]); - } - gpr_free(set); - return found; - } - - void fake_secure_name_check() const { - if (expected_targets_ == nullptr) return; - char** lbs_and_backends = nullptr; - size_t lbs_and_backends_size = 0; - bool success = false; - gpr_string_split(expected_targets_, ";", &lbs_and_backends, - &lbs_and_backends_size); - if (lbs_and_backends_size > 2 || lbs_and_backends_size == 0) { - gpr_log(GPR_ERROR, "Invalid expected targets arg value: '%s'", - expected_targets_); - goto done; - } - if (is_lb_channel_) { - if (lbs_and_backends_size != 2) { - gpr_log(GPR_ERROR, - "Invalid expected targets arg value: '%s'. Expectations for LB " - "channels must be of the form 'be1,be2,be3,...;lb1,lb2,...", - expected_targets_); - goto done; - } + GPR_ASSERT(target != nullptr); + char** set = nullptr; + size_t set_size = 0; + gpr_string_split(set_str, ",", &set, &set_size); + bool found = false; + for (size_t i = 0; i < set_size; ++i) { + if (set[i] != nullptr && strcmp(target, set[i]) == 0) found = true; + } + for (size_t i = 0; i < set_size; ++i) { + gpr_free(set[i]); + } + gpr_free(set); + return found; + } + + void fake_secure_name_check() const { + if (expected_targets_ == nullptr) return; + char** lbs_and_backends = nullptr; + size_t lbs_and_backends_size = 0; + bool success = false; + gpr_string_split(expected_targets_, ";", &lbs_and_backends, + &lbs_and_backends_size); + if (lbs_and_backends_size > 2 || lbs_and_backends_size == 0) { + gpr_log(GPR_ERROR, "Invalid expected targets arg value: '%s'", + expected_targets_); + goto done; + } + if (is_lb_channel_) { + if (lbs_and_backends_size != 2) { + gpr_log(GPR_ERROR, + "Invalid expected targets arg value: '%s'. Expectations for LB " + "channels must be of the form 'be1,be2,be3,...;lb1,lb2,...", + expected_targets_); + goto done; + } if (!fake_check_target(target_, lbs_and_backends[1])) { - gpr_log(GPR_ERROR, "LB target '%s' not found in expected set '%s'", - target_, lbs_and_backends[1]); - goto done; - } - success = true; - } else { + gpr_log(GPR_ERROR, "LB target '%s' not found in expected set '%s'", + target_, lbs_and_backends[1]); + goto done; + } + success = true; + } else { if (!fake_check_target(target_, lbs_and_backends[0])) { - gpr_log(GPR_ERROR, "Backend target '%s' not found in expected set '%s'", - target_, lbs_and_backends[0]); - goto done; - } - success = true; - } - done: - for (size_t i = 0; i < lbs_and_backends_size; ++i) { - gpr_free(lbs_and_backends[i]); - } - gpr_free(lbs_and_backends); - if (!success) abort(); - } - - char* target_; - char* expected_targets_; - bool is_lb_channel_; - char* target_name_override_; -}; - -static void fake_check_peer( + gpr_log(GPR_ERROR, "Backend target '%s' not found in expected set '%s'", + target_, lbs_and_backends[0]); + goto done; + } + success = true; + } + done: + for (size_t i = 0; i < lbs_and_backends_size; ++i) { + gpr_free(lbs_and_backends[i]); + } + gpr_free(lbs_and_backends); + if (!success) abort(); + } + + char* target_; + char* expected_targets_; + bool is_lb_channel_; + char* target_name_override_; +}; + +static void fake_check_peer( grpc_security_connector* /*sc*/, tsi_peer peer, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) { - const char* prop_name; - grpc_error* error = GRPC_ERROR_NONE; - *auth_context = nullptr; + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) { + const char* prop_name; + grpc_error* error = GRPC_ERROR_NONE; + *auth_context = nullptr; if (peer.property_count != 2) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Fake peers should only have 2 properties."); - goto end; - } - prop_name = peer.properties[0].name; - if (prop_name == nullptr || - strcmp(prop_name, TSI_CERTIFICATE_TYPE_PEER_PROPERTY)) { + goto end; + } + prop_name = peer.properties[0].name; + if (prop_name == nullptr || + strcmp(prop_name, TSI_CERTIFICATE_TYPE_PEER_PROPERTY)) { error = GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("Unexpected property in fake peer: ", prop_name == nullptr ? "<EMPTY>" : prop_name) .c_str()); - goto end; - } - if (strncmp(peer.properties[0].value.data, TSI_FAKE_CERTIFICATE_TYPE, - peer.properties[0].value.length)) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Invalid value for cert type property."); - goto end; - } + goto end; + } + if (strncmp(peer.properties[0].value.data, TSI_FAKE_CERTIFICATE_TYPE, + peer.properties[0].value.length)) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Invalid value for cert type property."); + goto end; + } prop_name = peer.properties[1].name; if (prop_name == nullptr || strcmp(prop_name, TSI_SECURITY_LEVEL_PEER_PROPERTY) != 0) { @@ -252,68 +252,68 @@ static void fake_check_peer( goto end; } - *auth_context = grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); - grpc_auth_context_add_cstring_property( - auth_context->get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, - GRPC_FAKE_TRANSPORT_SECURITY_TYPE); + *auth_context = grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); + grpc_auth_context_add_cstring_property( + auth_context->get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, + GRPC_FAKE_TRANSPORT_SECURITY_TYPE); grpc_auth_context_add_cstring_property( auth_context->get(), GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME, TSI_FAKE_SECURITY_LEVEL); -end: +end: grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); - tsi_peer_destruct(&peer); -} - -void grpc_fake_channel_security_connector::check_peer( + tsi_peer_destruct(&peer); +} + +void grpc_fake_channel_security_connector::check_peer( tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) { - fake_check_peer(this, peer, auth_context, on_peer_checked); - fake_secure_name_check(); -} - -class grpc_fake_server_security_connector - : public grpc_server_security_connector { - public: - grpc_fake_server_security_connector( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) - : grpc_server_security_connector(GRPC_FAKE_SECURITY_URL_SCHEME, - std::move(server_creds)) {} - ~grpc_fake_server_security_connector() override = default; - + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) { + fake_check_peer(this, peer, auth_context, on_peer_checked); + fake_secure_name_check(); +} + +class grpc_fake_server_security_connector + : public grpc_server_security_connector { + public: + grpc_fake_server_security_connector( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) + : grpc_server_security_connector(GRPC_FAKE_SECURITY_URL_SCHEME, + std::move(server_creds)) {} + ~grpc_fake_server_security_connector() override = default; + void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { - fake_check_peer(this, peer, auth_context, on_peer_checked); - } - + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { + fake_check_peer(this, peer, auth_context, on_peer_checked); + } + void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_mgr) override { - handshake_mgr->Add(grpc_core::SecurityHandshakerCreate( + grpc_core::HandshakeManager* handshake_mgr) override { + handshake_mgr->Add(grpc_core::SecurityHandshakerCreate( tsi_create_fake_handshaker(/*=is_client*/ false), this, args)); - } - - int cmp(const grpc_security_connector* other) const override { - return server_security_connector_cmp( - static_cast<const grpc_server_security_connector*>(other)); - } -}; -} // namespace - -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_fake_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target, const grpc_channel_args* args) { - return grpc_core::MakeRefCounted<grpc_fake_channel_security_connector>( - std::move(channel_creds), std::move(request_metadata_creds), target, - args); -} - -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_fake_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) { - return grpc_core::MakeRefCounted<grpc_fake_server_security_connector>( - std::move(server_creds)); -} + } + + int cmp(const grpc_security_connector* other) const override { + return server_security_connector_cmp( + static_cast<const grpc_server_security_connector*>(other)); + } +}; +} // namespace + +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_fake_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target, const grpc_channel_args* args) { + return grpc_core::MakeRefCounted<grpc_fake_channel_security_connector>( + std::move(channel_creds), std::move(request_metadata_creds), target, + args); +} + +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_fake_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) { + return grpc_core::MakeRefCounted<grpc_fake_server_security_connector>( + std::move(server_creds)); +} diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.h index 344a2349a4..c862112870 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/fake/fake_security_connector.h @@ -1,45 +1,45 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc_security.h> - -#include "src/core/lib/channel/handshaker.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/security/security_connector/security_connector.h" - -#define GRPC_FAKE_SECURITY_URL_SCHEME "http+fake_security" - -/* Creates a fake connector that emulates real channel security. */ -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_fake_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target, const grpc_channel_args* args); - -/* Creates a fake connector that emulates real server security. */ -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_fake_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); - -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H \ - */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc_security.h> + +#include "src/core/lib/channel/handshaker.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/security/security_connector/security_connector.h" + +#define GRPC_FAKE_SECURITY_URL_SCHEME "http+fake_security" + +/* Creates a fake connector that emulates real channel security. */ +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_fake_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target, const grpc_channel_args* args); + +/* Creates a fake connector that emulates real server security. */ +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_fake_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); + +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_FAKE_FAKE_SECURITY_CONNECTOR_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots.h b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots.h index 5fdec15498..3e36c142f2 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots.h @@ -1,29 +1,29 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_H - -namespace grpc_core { - -// Returns a slice containing roots from the OS trust store -grpc_slice LoadSystemRootCerts(); - -} // namespace grpc_core - -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_H + +namespace grpc_core { + +// Returns a slice containing roots from the OS trust store +grpc_slice LoadSystemRootCerts(); + +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_fallback.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_fallback.cc index f04d0ed225..88e64b1f75 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_fallback.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_fallback.cc @@ -1,32 +1,32 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include <grpc/slice_buffer.h> -#include "src/core/lib/security/security_connector/load_system_roots.h" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include <grpc/slice_buffer.h> +#include "src/core/lib/security/security_connector/load_system_roots.h" + #if !defined(GPR_LINUX) && !defined(GPR_ANDROID) - -namespace grpc_core { - -grpc_slice LoadSystemRootCerts() { return grpc_empty_slice(); } - -} // namespace grpc_core - + +namespace grpc_core { + +grpc_slice LoadSystemRootCerts() { return grpc_empty_slice(); } + +} // namespace grpc_core + #endif /* !(GPR_LINUX || GPR_ANDROID) */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc index c0b6d5d727..bb39ff09ba 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.cc @@ -1,171 +1,171 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include <grpc/slice_buffer.h> -#include "src/core/lib/security/security_connector/load_system_roots_linux.h" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include <grpc/slice_buffer.h> +#include "src/core/lib/security/security_connector/load_system_roots_linux.h" + #if defined(GPR_LINUX) || defined(GPR_ANDROID) - -#include "src/core/lib/security/security_connector/load_system_roots.h" - -#include <dirent.h> -#include <fcntl.h> -#include <stdbool.h> -#include <string.h> -#include <sys/param.h> -#include <sys/stat.h> -#include <sys/types.h> -#include <unistd.h> - + +#include "src/core/lib/security/security_connector/load_system_roots.h" + +#include <dirent.h> +#include <fcntl.h> +#include <stdbool.h> +#include <string.h> +#include <sys/param.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> + #include "y_absl/container/inlined_vector.h" -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/gpr/useful.h" +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/gpr/useful.h" #include "src/core/lib/gprpp/global_config.h" -#include "src/core/lib/iomgr/load_file.h" - +#include "src/core/lib/iomgr/load_file.h" + GPR_GLOBAL_CONFIG_DEFINE_STRING(grpc_system_ssl_roots_dir, "", "Custom directory to SSL Roots"); -namespace grpc_core { -namespace { - -const char* kLinuxCertFiles[] = { - "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", - "/etc/ssl/ca-bundle.pem", "/etc/pki/tls/cacert.pem", - "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"}; -const char* kLinuxCertDirectories[] = { - "/etc/ssl/certs", "/system/etc/security/cacerts", "/usr/local/share/certs", - "/etc/pki/tls/certs", "/etc/openssl/certs"}; - -grpc_slice GetSystemRootCerts() { - grpc_slice valid_bundle_slice = grpc_empty_slice(); - size_t num_cert_files_ = GPR_ARRAY_SIZE(kLinuxCertFiles); - for (size_t i = 0; i < num_cert_files_; i++) { - grpc_error* error = - grpc_load_file(kLinuxCertFiles[i], 1, &valid_bundle_slice); - if (error == GRPC_ERROR_NONE) { - return valid_bundle_slice; +namespace grpc_core { +namespace { + +const char* kLinuxCertFiles[] = { + "/etc/ssl/certs/ca-certificates.crt", "/etc/pki/tls/certs/ca-bundle.crt", + "/etc/ssl/ca-bundle.pem", "/etc/pki/tls/cacert.pem", + "/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"}; +const char* kLinuxCertDirectories[] = { + "/etc/ssl/certs", "/system/etc/security/cacerts", "/usr/local/share/certs", + "/etc/pki/tls/certs", "/etc/openssl/certs"}; + +grpc_slice GetSystemRootCerts() { + grpc_slice valid_bundle_slice = grpc_empty_slice(); + size_t num_cert_files_ = GPR_ARRAY_SIZE(kLinuxCertFiles); + for (size_t i = 0; i < num_cert_files_; i++) { + grpc_error* error = + grpc_load_file(kLinuxCertFiles[i], 1, &valid_bundle_slice); + if (error == GRPC_ERROR_NONE) { + return valid_bundle_slice; } else { GRPC_ERROR_UNREF(error); - } - } - return grpc_empty_slice(); -} - -} // namespace - -void GetAbsoluteFilePath(const char* valid_file_dir, - const char* file_entry_name, char* path_buffer) { - if (valid_file_dir != nullptr && file_entry_name != nullptr) { - int path_len = snprintf(path_buffer, MAXPATHLEN, "%s/%s", valid_file_dir, - file_entry_name); - if (path_len == 0) { - gpr_log(GPR_ERROR, "failed to get absolute path for file: %s", - file_entry_name); - } - } -} - -grpc_slice CreateRootCertsBundle(const char* certs_directory) { - grpc_slice bundle_slice = grpc_empty_slice(); - if (certs_directory == nullptr) { - return bundle_slice; - } - DIR* ca_directory = opendir(certs_directory); - if (ca_directory == nullptr) { - return bundle_slice; - } - struct FileData { - char path[MAXPATHLEN]; - off_t size; - }; + } + } + return grpc_empty_slice(); +} + +} // namespace + +void GetAbsoluteFilePath(const char* valid_file_dir, + const char* file_entry_name, char* path_buffer) { + if (valid_file_dir != nullptr && file_entry_name != nullptr) { + int path_len = snprintf(path_buffer, MAXPATHLEN, "%s/%s", valid_file_dir, + file_entry_name); + if (path_len == 0) { + gpr_log(GPR_ERROR, "failed to get absolute path for file: %s", + file_entry_name); + } + } +} + +grpc_slice CreateRootCertsBundle(const char* certs_directory) { + grpc_slice bundle_slice = grpc_empty_slice(); + if (certs_directory == nullptr) { + return bundle_slice; + } + DIR* ca_directory = opendir(certs_directory); + if (ca_directory == nullptr) { + return bundle_slice; + } + struct FileData { + char path[MAXPATHLEN]; + off_t size; + }; y_absl::InlinedVector<FileData, 2> roots_filenames; - size_t total_bundle_size = 0; - struct dirent* directory_entry; - while ((directory_entry = readdir(ca_directory)) != nullptr) { - struct stat dir_entry_stat; - const char* file_entry_name = directory_entry->d_name; - FileData file_data; - GetAbsoluteFilePath(certs_directory, file_entry_name, file_data.path); - int stat_return = stat(file_data.path, &dir_entry_stat); - if (stat_return == -1 || !S_ISREG(dir_entry_stat.st_mode)) { - // no subdirectories. - if (stat_return == -1) { - gpr_log(GPR_ERROR, "failed to get status for file: %s", file_data.path); - } - continue; - } - file_data.size = dir_entry_stat.st_size; - total_bundle_size += file_data.size; - roots_filenames.push_back(file_data); - } - closedir(ca_directory); - char* bundle_string = static_cast<char*>(gpr_zalloc(total_bundle_size + 1)); - size_t bytes_read = 0; - for (size_t i = 0; i < roots_filenames.size(); i++) { - int file_descriptor = open(roots_filenames[i].path, O_RDONLY); - if (file_descriptor != -1) { - // Read file into bundle. - size_t cert_file_size = roots_filenames[i].size; - int read_ret = - read(file_descriptor, bundle_string + bytes_read, cert_file_size); - if (read_ret != -1) { - bytes_read += read_ret; - } else { - gpr_log(GPR_ERROR, "failed to read file: %s", roots_filenames[i].path); - } - } - } - bundle_slice = grpc_slice_new(bundle_string, bytes_read, gpr_free); - return bundle_slice; -} - -grpc_slice LoadSystemRootCerts() { - grpc_slice result = grpc_empty_slice(); - // Prioritize user-specified custom directory if flag is set. + size_t total_bundle_size = 0; + struct dirent* directory_entry; + while ((directory_entry = readdir(ca_directory)) != nullptr) { + struct stat dir_entry_stat; + const char* file_entry_name = directory_entry->d_name; + FileData file_data; + GetAbsoluteFilePath(certs_directory, file_entry_name, file_data.path); + int stat_return = stat(file_data.path, &dir_entry_stat); + if (stat_return == -1 || !S_ISREG(dir_entry_stat.st_mode)) { + // no subdirectories. + if (stat_return == -1) { + gpr_log(GPR_ERROR, "failed to get status for file: %s", file_data.path); + } + continue; + } + file_data.size = dir_entry_stat.st_size; + total_bundle_size += file_data.size; + roots_filenames.push_back(file_data); + } + closedir(ca_directory); + char* bundle_string = static_cast<char*>(gpr_zalloc(total_bundle_size + 1)); + size_t bytes_read = 0; + for (size_t i = 0; i < roots_filenames.size(); i++) { + int file_descriptor = open(roots_filenames[i].path, O_RDONLY); + if (file_descriptor != -1) { + // Read file into bundle. + size_t cert_file_size = roots_filenames[i].size; + int read_ret = + read(file_descriptor, bundle_string + bytes_read, cert_file_size); + if (read_ret != -1) { + bytes_read += read_ret; + } else { + gpr_log(GPR_ERROR, "failed to read file: %s", roots_filenames[i].path); + } + } + } + bundle_slice = grpc_slice_new(bundle_string, bytes_read, gpr_free); + return bundle_slice; +} + +grpc_slice LoadSystemRootCerts() { + grpc_slice result = grpc_empty_slice(); + // Prioritize user-specified custom directory if flag is set. grpc_core::UniquePtr<char> custom_dir = GPR_GLOBAL_CONFIG_GET(grpc_system_ssl_roots_dir); if (strlen(custom_dir.get()) > 0) { result = CreateRootCertsBundle(custom_dir.get()); - } - // If the custom directory is empty/invalid/not specified, fallback to - // distribution-specific directory. - if (GRPC_SLICE_IS_EMPTY(result)) { - result = GetSystemRootCerts(); - } - if (GRPC_SLICE_IS_EMPTY(result)) { - for (size_t i = 0; i < GPR_ARRAY_SIZE(kLinuxCertDirectories); i++) { - result = CreateRootCertsBundle(kLinuxCertDirectories[i]); - if (!GRPC_SLICE_IS_EMPTY(result)) { - break; - } - } - } - return result; -} - -} // namespace grpc_core - + } + // If the custom directory is empty/invalid/not specified, fallback to + // distribution-specific directory. + if (GRPC_SLICE_IS_EMPTY(result)) { + result = GetSystemRootCerts(); + } + if (GRPC_SLICE_IS_EMPTY(result)) { + for (size_t i = 0; i < GPR_ARRAY_SIZE(kLinuxCertDirectories); i++) { + result = CreateRootCertsBundle(kLinuxCertDirectories[i]); + if (!GRPC_SLICE_IS_EMPTY(result)) { + break; + } + } + } + return result; +} + +} // namespace grpc_core + #endif /* GPR_LINUX || GPR_ANDROID */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.h b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.h index 12617df492..b5d8876268 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/load_system_roots_linux.h @@ -1,44 +1,44 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_LINUX_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_LINUX_H - -#include <grpc/support/port_platform.h> - -#ifdef GPR_LINUX - -namespace grpc_core { - -// Creates a bundle slice containing the contents of all certificate files in -// a directory. -// Returns such slice. -// Exposed for testing purposes only. -grpc_slice CreateRootCertsBundle(const char* certs_directory); - -// Gets the absolute file path needed to load a certificate file. -// Populates path_buffer, which must be of size MAXPATHLEN. -// Exposed for testing purposes only. -void GetAbsoluteFilePath(const char* valid_file_dir, - const char* file_entry_name, char* path_buffer); - -} // namespace grpc_core - -#endif /* GPR_LINUX */ -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_LINUX_H \ - */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_LINUX_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_LINUX_H + +#include <grpc/support/port_platform.h> + +#ifdef GPR_LINUX + +namespace grpc_core { + +// Creates a bundle slice containing the contents of all certificate files in +// a directory. +// Returns such slice. +// Exposed for testing purposes only. +grpc_slice CreateRootCertsBundle(const char* certs_directory); + +// Gets the absolute file path needed to load a certificate file. +// Populates path_buffer, which must be of size MAXPATHLEN. +// Exposed for testing purposes only. +void GetAbsoluteFilePath(const char* valid_file_dir, + const char* file_entry_name, char* path_buffer); + +} // namespace grpc_core + +#endif /* GPR_LINUX */ +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOAD_SYSTEM_ROOTS_LINUX_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc index 8f622d4c22..b94bef0e27 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.cc @@ -1,61 +1,61 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/security_connector/local/local_security_connector.h" - -#include <stdbool.h> -#include <string.h> - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -#include "src/core/ext/filters/client_channel/client_channel.h" -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/iomgr/pollset.h" -#include "src/core/lib/iomgr/resolve_address.h" -#include "src/core/lib/iomgr/sockaddr.h" -#include "src/core/lib/iomgr/sockaddr_utils.h" -#include "src/core/lib/iomgr/socket_utils.h" -#include "src/core/lib/iomgr/unix_sockets_posix.h" -#include "src/core/lib/security/credentials/local/local_credentials.h" -#include "src/core/lib/security/transport/security_handshaker.h" -#include "src/core/tsi/local_transport_security.h" - -#define GRPC_UDS_URI_PATTERN "unix:" -#define GRPC_LOCAL_TRANSPORT_SECURITY_TYPE "local" - -namespace { - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/security_connector/local/local_security_connector.h" + +#include <stdbool.h> +#include <string.h> + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +#include "src/core/ext/filters/client_channel/client_channel.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/iomgr/pollset.h" +#include "src/core/lib/iomgr/resolve_address.h" +#include "src/core/lib/iomgr/sockaddr.h" +#include "src/core/lib/iomgr/sockaddr_utils.h" +#include "src/core/lib/iomgr/socket_utils.h" +#include "src/core/lib/iomgr/unix_sockets_posix.h" +#include "src/core/lib/security/credentials/local/local_credentials.h" +#include "src/core/lib/security/transport/security_handshaker.h" +#include "src/core/tsi/local_transport_security.h" + +#define GRPC_UDS_URI_PATTERN "unix:" +#define GRPC_LOCAL_TRANSPORT_SECURITY_TYPE "local" + +namespace { + grpc_core::RefCountedPtr<grpc_auth_context> local_auth_context_create( const tsi_peer* peer) { - /* Create auth context. */ - grpc_core::RefCountedPtr<grpc_auth_context> ctx = - grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); - grpc_auth_context_add_cstring_property( - ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, - GRPC_LOCAL_TRANSPORT_SECURITY_TYPE); - GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( - ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME) == 1); + /* Create auth context. */ + grpc_core::RefCountedPtr<grpc_auth_context> ctx = + grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); + grpc_auth_context_add_cstring_property( + ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, + GRPC_LOCAL_TRANSPORT_SECURITY_TYPE); + GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( + ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME) == 1); GPR_ASSERT(peer->property_count == 1); const tsi_peer_property* prop = &peer->properties[0]; GPR_ASSERT(prop != nullptr); @@ -63,53 +63,53 @@ grpc_core::RefCountedPtr<grpc_auth_context> local_auth_context_create( grpc_auth_context_add_property(ctx.get(), GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME, prop->value.data, prop->value.length); - return ctx; -} - + return ctx; +} + void local_check_peer(tsi_peer peer, grpc_endpoint* ep, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked, - grpc_local_connect_type type) { - int fd = grpc_endpoint_get_fd(ep); - grpc_resolved_address resolved_addr; - memset(&resolved_addr, 0, sizeof(resolved_addr)); - resolved_addr.len = GRPC_MAX_SOCKADDR_SIZE; - bool is_endpoint_local = false; - if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(resolved_addr.addr), - &resolved_addr.len) == 0) { - grpc_resolved_address addr_normalized; - grpc_resolved_address* addr = - grpc_sockaddr_is_v4mapped(&resolved_addr, &addr_normalized) - ? &addr_normalized - : &resolved_addr; - grpc_sockaddr* sock_addr = reinterpret_cast<grpc_sockaddr*>(&addr->addr); - // UDS - if (type == UDS && grpc_is_unix_socket(addr)) { - is_endpoint_local = true; - // IPV4 - } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET) { - const grpc_sockaddr_in* addr4 = - reinterpret_cast<const grpc_sockaddr_in*>(sock_addr); - if (grpc_htonl(addr4->sin_addr.s_addr) == INADDR_LOOPBACK) { - is_endpoint_local = true; - } - // IPv6 - } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET6) { - const grpc_sockaddr_in6* addr6 = - reinterpret_cast<const grpc_sockaddr_in6*>(addr); - if (memcmp(&addr6->sin6_addr, &in6addr_loopback, - sizeof(in6addr_loopback)) == 0) { - is_endpoint_local = true; - } - } - } - grpc_error* error = GRPC_ERROR_NONE; - if (!is_endpoint_local) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Endpoint is neither UDS or TCP loopback address."); + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked, + grpc_local_connect_type type) { + int fd = grpc_endpoint_get_fd(ep); + grpc_resolved_address resolved_addr; + memset(&resolved_addr, 0, sizeof(resolved_addr)); + resolved_addr.len = GRPC_MAX_SOCKADDR_SIZE; + bool is_endpoint_local = false; + if (getsockname(fd, reinterpret_cast<grpc_sockaddr*>(resolved_addr.addr), + &resolved_addr.len) == 0) { + grpc_resolved_address addr_normalized; + grpc_resolved_address* addr = + grpc_sockaddr_is_v4mapped(&resolved_addr, &addr_normalized) + ? &addr_normalized + : &resolved_addr; + grpc_sockaddr* sock_addr = reinterpret_cast<grpc_sockaddr*>(&addr->addr); + // UDS + if (type == UDS && grpc_is_unix_socket(addr)) { + is_endpoint_local = true; + // IPV4 + } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET) { + const grpc_sockaddr_in* addr4 = + reinterpret_cast<const grpc_sockaddr_in*>(sock_addr); + if (grpc_htonl(addr4->sin_addr.s_addr) == INADDR_LOOPBACK) { + is_endpoint_local = true; + } + // IPv6 + } else if (type == LOCAL_TCP && sock_addr->sa_family == GRPC_AF_INET6) { + const grpc_sockaddr_in6* addr6 = + reinterpret_cast<const grpc_sockaddr_in6*>(addr); + if (memcmp(&addr6->sin6_addr, &in6addr_loopback, + sizeof(in6addr_loopback)) == 0) { + is_endpoint_local = true; + } + } + } + grpc_error* error = GRPC_ERROR_NONE; + if (!is_endpoint_local) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Endpoint is neither UDS or TCP loopback address."); grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); - return; - } + return; + } // Add TSI_SECURITY_LEVEL_PEER_PROPERTY type peer property. size_t new_property_count = peer.property_count + 1; tsi_peer_property* new_properties = static_cast<tsi_peer_property*>( @@ -127,155 +127,155 @@ void local_check_peer(tsi_peer peer, grpc_endpoint* ep, &peer.properties[peer.property_count]); if (result != TSI_OK) return; peer.property_count++; - /* Create an auth context which is necessary to pass the santiy check in - * {client, server}_auth_filter that verifies if the peer's auth context is - * obtained during handshakes. The auth context is only checked for its - * existence and not actually used. - */ + /* Create an auth context which is necessary to pass the santiy check in + * {client, server}_auth_filter that verifies if the peer's auth context is + * obtained during handshakes. The auth context is only checked for its + * existence and not actually used. + */ *auth_context = local_auth_context_create(&peer); tsi_peer_destruct(&peer); - error = *auth_context != nullptr ? GRPC_ERROR_NONE - : GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Could not create local auth context"); + error = *auth_context != nullptr ? GRPC_ERROR_NONE + : GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Could not create local auth context"); grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); -} - -class grpc_local_channel_security_connector final - : public grpc_channel_security_connector { - public: - grpc_local_channel_security_connector( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const char* target_name) - : grpc_channel_security_connector(nullptr, std::move(channel_creds), - std::move(request_metadata_creds)), - target_name_(gpr_strdup(target_name)) {} - - ~grpc_local_channel_security_connector() override { gpr_free(target_name_); } - - void add_handshakers( +} + +class grpc_local_channel_security_connector final + : public grpc_channel_security_connector { + public: + grpc_local_channel_security_connector( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const char* target_name) + : grpc_channel_security_connector(nullptr, std::move(channel_creds), + std::move(request_metadata_creds)), + target_name_(gpr_strdup(target_name)) {} + + ~grpc_local_channel_security_connector() override { gpr_free(target_name_); } + + void add_handshakers( const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_manager) override { - tsi_handshaker* handshaker = nullptr; - GPR_ASSERT(local_tsi_handshaker_create(true /* is_client */, &handshaker) == - TSI_OK); - handshake_manager->Add( + grpc_core::HandshakeManager* handshake_manager) override { + tsi_handshaker* handshaker = nullptr; + GPR_ASSERT(local_tsi_handshaker_create(true /* is_client */, &handshaker) == + TSI_OK); + handshake_manager->Add( grpc_core::SecurityHandshakerCreate(handshaker, this, args)); - } - - int cmp(const grpc_security_connector* other_sc) const override { - auto* other = - reinterpret_cast<const grpc_local_channel_security_connector*>( - other_sc); - int c = channel_security_connector_cmp(other); - if (c != 0) return c; - return strcmp(target_name_, other->target_name_); - } - - void check_peer(tsi_peer peer, grpc_endpoint* ep, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { - grpc_local_credentials* creds = - reinterpret_cast<grpc_local_credentials*>(mutable_channel_creds()); + } + + int cmp(const grpc_security_connector* other_sc) const override { + auto* other = + reinterpret_cast<const grpc_local_channel_security_connector*>( + other_sc); + int c = channel_security_connector_cmp(other); + if (c != 0) return c; + return strcmp(target_name_, other->target_name_); + } + + void check_peer(tsi_peer peer, grpc_endpoint* ep, + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { + grpc_local_credentials* creds = + reinterpret_cast<grpc_local_credentials*>(mutable_channel_creds()); local_check_peer(peer, ep, auth_context, on_peer_checked, - creds->connect_type()); - } - + creds->connect_type()); + } + bool check_call_host(y_absl::string_view host, grpc_auth_context* /*auth_context*/, grpc_closure* /*on_call_host_checked*/, - grpc_error** error) override { + grpc_error** error) override { if (host.empty() || host != target_name_) { - *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "local call host does not match target name"); - } - return true; - } - + *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "local call host does not match target name"); + } + return true; + } + void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/, - grpc_error* error) override { - GRPC_ERROR_UNREF(error); - } - - const char* target_name() const { return target_name_; } - - private: - char* target_name_; -}; - -class grpc_local_server_security_connector final - : public grpc_server_security_connector { - public: - grpc_local_server_security_connector( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) - : grpc_server_security_connector(nullptr, std::move(server_creds)) {} - ~grpc_local_server_security_connector() override = default; - - void add_handshakers( + grpc_error* error) override { + GRPC_ERROR_UNREF(error); + } + + const char* target_name() const { return target_name_; } + + private: + char* target_name_; +}; + +class grpc_local_server_security_connector final + : public grpc_server_security_connector { + public: + grpc_local_server_security_connector( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) + : grpc_server_security_connector(nullptr, std::move(server_creds)) {} + ~grpc_local_server_security_connector() override = default; + + void add_handshakers( const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_manager) override { - tsi_handshaker* handshaker = nullptr; - GPR_ASSERT(local_tsi_handshaker_create(false /* is_client */, - &handshaker) == TSI_OK); - handshake_manager->Add( + grpc_core::HandshakeManager* handshake_manager) override { + tsi_handshaker* handshaker = nullptr; + GPR_ASSERT(local_tsi_handshaker_create(false /* is_client */, + &handshaker) == TSI_OK); + handshake_manager->Add( grpc_core::SecurityHandshakerCreate(handshaker, this, args)); - } - - void check_peer(tsi_peer peer, grpc_endpoint* ep, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { - grpc_local_server_credentials* creds = - static_cast<grpc_local_server_credentials*>(mutable_server_creds()); + } + + void check_peer(tsi_peer peer, grpc_endpoint* ep, + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { + grpc_local_server_credentials* creds = + static_cast<grpc_local_server_credentials*>(mutable_server_creds()); local_check_peer(peer, ep, auth_context, on_peer_checked, - creds->connect_type()); - } - - int cmp(const grpc_security_connector* other) const override { - return server_security_connector_cmp( - static_cast<const grpc_server_security_connector*>(other)); - } -}; -} // namespace - -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_local_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const grpc_channel_args* args, const char* target_name) { - if (channel_creds == nullptr || target_name == nullptr) { - gpr_log( - GPR_ERROR, - "Invalid arguments to grpc_local_channel_security_connector_create()"); - return nullptr; - } - // Perform sanity check on UDS address. For TCP local connection, the check - // will be done during check_peer procedure. - grpc_local_credentials* creds = - static_cast<grpc_local_credentials*>(channel_creds.get()); - const grpc_arg* server_uri_arg = - grpc_channel_args_find(args, GRPC_ARG_SERVER_URI); - const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg); - if (creds->connect_type() == UDS && - strncmp(GRPC_UDS_URI_PATTERN, server_uri_str, - strlen(GRPC_UDS_URI_PATTERN)) != 0) { - gpr_log(GPR_ERROR, - "Invalid UDS target name to " - "grpc_local_channel_security_connector_create()"); - return nullptr; - } - return grpc_core::MakeRefCounted<grpc_local_channel_security_connector>( - channel_creds, request_metadata_creds, target_name); -} - -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_local_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) { - if (server_creds == nullptr) { - gpr_log( - GPR_ERROR, - "Invalid arguments to grpc_local_server_security_connector_create()"); - return nullptr; - } - return grpc_core::MakeRefCounted<grpc_local_server_security_connector>( - std::move(server_creds)); -} + creds->connect_type()); + } + + int cmp(const grpc_security_connector* other) const override { + return server_security_connector_cmp( + static_cast<const grpc_server_security_connector*>(other)); + } +}; +} // namespace + +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_local_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const grpc_channel_args* args, const char* target_name) { + if (channel_creds == nullptr || target_name == nullptr) { + gpr_log( + GPR_ERROR, + "Invalid arguments to grpc_local_channel_security_connector_create()"); + return nullptr; + } + // Perform sanity check on UDS address. For TCP local connection, the check + // will be done during check_peer procedure. + grpc_local_credentials* creds = + static_cast<grpc_local_credentials*>(channel_creds.get()); + const grpc_arg* server_uri_arg = + grpc_channel_args_find(args, GRPC_ARG_SERVER_URI); + const char* server_uri_str = grpc_channel_arg_get_string(server_uri_arg); + if (creds->connect_type() == UDS && + strncmp(GRPC_UDS_URI_PATTERN, server_uri_str, + strlen(GRPC_UDS_URI_PATTERN)) != 0) { + gpr_log(GPR_ERROR, + "Invalid UDS target name to " + "grpc_local_channel_security_connector_create()"); + return nullptr; + } + return grpc_core::MakeRefCounted<grpc_local_channel_security_connector>( + channel_creds, request_metadata_creds, target_name); +} + +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_local_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) { + if (server_creds == nullptr) { + gpr_log( + GPR_ERROR, + "Invalid arguments to grpc_local_server_security_connector_create()"); + return nullptr; + } + return grpc_core::MakeRefCounted<grpc_local_server_security_connector>( + std::move(server_creds)); +} diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.h index 6eee0ca9a6..7ad8455a77 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/local/local_security_connector.h @@ -1,59 +1,59 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/context/security_context.h" - -/** - * This method creates a local channel security connector. - * - * - channel_creds: channel credential instance. - * - request_metadata_creds: credential object which will be sent with each - * request. This parameter can be nullptr. - * - target_name: the name of the endpoint that the channel is connecting to. - * - args: channel args passed from the caller. - * - sc: address of local channel security connector instance to be returned - * from the method. - * - * It returns nullptr on failure. - */ -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_local_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const grpc_channel_args* args, const char* target_name); - -/** - * This method creates a local server security connector. - * - * - server_creds: server credential instance. - * - sc: address of local server security connector instance to be returned from - * the method. - * - * It returns nullptr on failure. - */ -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_local_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); - -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H \ - */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/context/security_context.h" + +/** + * This method creates a local channel security connector. + * + * - channel_creds: channel credential instance. + * - request_metadata_creds: credential object which will be sent with each + * request. This parameter can be nullptr. + * - target_name: the name of the endpoint that the channel is connecting to. + * - args: channel args passed from the caller. + * - sc: address of local channel security connector instance to be returned + * from the method. + * + * It returns nullptr on failure. + */ +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_local_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const grpc_channel_args* args, const char* target_name); + +/** + * This method creates a local server security connector. + * + * - server_creds: server credential instance. + * - sc: address of local server security connector instance to be returned from + * the method. + * + * It returns nullptr on failure. + */ +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_local_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); + +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_LOCAL_LOCAL_SECURITY_CONNECTOR_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc index 0400ad6fb8..84ca0ebb33 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.cc @@ -33,71 +33,71 @@ #include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/credentials/credentials.h" -#include "src/core/lib/security/security_connector/load_system_roots.h" -#include "src/core/lib/security/security_connector/security_connector.h" +#include "src/core/lib/security/security_connector/load_system_roots.h" +#include "src/core/lib/security/security_connector/security_connector.h" #include "src/core/lib/security/transport/security_handshaker.h" grpc_core::DebugOnlyTraceFlag grpc_trace_security_connector_refcount( false, "security_connector_refcount"); -grpc_server_security_connector::grpc_server_security_connector( - const char* url_scheme, - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) - : grpc_security_connector(url_scheme), - server_creds_(std::move(server_creds)) {} +grpc_server_security_connector::grpc_server_security_connector( + const char* url_scheme, + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) + : grpc_security_connector(url_scheme), + server_creds_(std::move(server_creds)) {} grpc_server_security_connector::~grpc_server_security_connector() = default; -grpc_channel_security_connector::grpc_channel_security_connector( - const char* url_scheme, - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds) - : grpc_security_connector(url_scheme), - channel_creds_(std::move(channel_creds)), - request_metadata_creds_(std::move(request_metadata_creds)) {} +grpc_channel_security_connector::grpc_channel_security_connector( + const char* url_scheme, + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds) + : grpc_security_connector(url_scheme), + channel_creds_(std::move(channel_creds)), + request_metadata_creds_(std::move(request_metadata_creds)) {} -grpc_channel_security_connector::~grpc_channel_security_connector() {} +grpc_channel_security_connector::~grpc_channel_security_connector() {} -int grpc_security_connector_cmp(const grpc_security_connector* sc, - const grpc_security_connector* other) { +int grpc_security_connector_cmp(const grpc_security_connector* sc, + const grpc_security_connector* other) { if (sc == nullptr || other == nullptr) return GPR_ICMP(sc, other); - return sc->cmp(other); + return sc->cmp(other); } -int grpc_channel_security_connector::channel_security_connector_cmp( - const grpc_channel_security_connector* other) const { - const grpc_channel_security_connector* other_sc = - static_cast<const grpc_channel_security_connector*>(other); - GPR_ASSERT(channel_creds() != nullptr); - GPR_ASSERT(other_sc->channel_creds() != nullptr); - int c = GPR_ICMP(channel_creds(), other_sc->channel_creds()); +int grpc_channel_security_connector::channel_security_connector_cmp( + const grpc_channel_security_connector* other) const { + const grpc_channel_security_connector* other_sc = + static_cast<const grpc_channel_security_connector*>(other); + GPR_ASSERT(channel_creds() != nullptr); + GPR_ASSERT(other_sc->channel_creds() != nullptr); + int c = GPR_ICMP(channel_creds(), other_sc->channel_creds()); if (c != 0) return c; - return GPR_ICMP(request_metadata_creds(), other_sc->request_metadata_creds()); + return GPR_ICMP(request_metadata_creds(), other_sc->request_metadata_creds()); } -int grpc_server_security_connector::server_security_connector_cmp( - const grpc_server_security_connector* other) const { - const grpc_server_security_connector* other_sc = - static_cast<const grpc_server_security_connector*>(other); - GPR_ASSERT(server_creds() != nullptr); - GPR_ASSERT(other_sc->server_creds() != nullptr); - return GPR_ICMP(server_creds(), other_sc->server_creds()); +int grpc_server_security_connector::server_security_connector_cmp( + const grpc_server_security_connector* other) const { + const grpc_server_security_connector* other_sc = + static_cast<const grpc_server_security_connector*>(other); + GPR_ASSERT(server_creds() != nullptr); + GPR_ASSERT(other_sc->server_creds() != nullptr); + return GPR_ICMP(server_creds(), other_sc->server_creds()); } static void connector_arg_destroy(void* p) { - static_cast<grpc_security_connector*>(p)->Unref(DEBUG_LOCATION, - "connector_arg_destroy"); + static_cast<grpc_security_connector*>(p)->Unref(DEBUG_LOCATION, + "connector_arg_destroy"); } static void* connector_arg_copy(void* p) { - return static_cast<grpc_security_connector*>(p) - ->Ref(DEBUG_LOCATION, "connector_arg_copy") - .release(); + return static_cast<grpc_security_connector*>(p) + ->Ref(DEBUG_LOCATION, "connector_arg_copy") + .release(); } static int connector_cmp(void* a, void* b) { - return static_cast<grpc_security_connector*>(a)->cmp( - static_cast<grpc_security_connector*>(b)); + return static_cast<grpc_security_connector*>(a)->cmp( + static_cast<grpc_security_connector*>(b)); } static const grpc_arg_pointer_vtable connector_arg_vtable = { diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h index 74d04600b2..8e9896bc8e 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/security_connector.h @@ -26,9 +26,9 @@ #include <grpc/grpc_security.h> #include "src/core/lib/channel/handshaker.h" -#include "src/core/lib/gprpp/ref_counted.h" +#include "src/core/lib/gprpp/ref_counted.h" #include "src/core/lib/iomgr/endpoint.h" -#include "src/core/lib/iomgr/pollset.h" +#include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/tcp_server.h" #include "src/core/tsi/ssl_transport_security.h" #include "src/core/tsi/transport_security_interface.h" @@ -44,31 +44,31 @@ typedef enum { GRPC_SECURITY_OK = 0, GRPC_SECURITY_ERROR } grpc_security_status; #define GRPC_ARG_SECURITY_CONNECTOR "grpc.security_connector" -class grpc_security_connector - : public grpc_core::RefCounted<grpc_security_connector> { - public: - explicit grpc_security_connector(const char* url_scheme) - : grpc_core::RefCounted<grpc_security_connector>( - &grpc_trace_security_connector_refcount), - url_scheme_(url_scheme) {} - virtual ~grpc_security_connector() = default; - - /* Check the peer. Callee takes ownership of the peer object. - When done, sets *auth_context and invokes on_peer_checked. */ - virtual void check_peer( - tsi_peer peer, grpc_endpoint* ep, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, +class grpc_security_connector + : public grpc_core::RefCounted<grpc_security_connector> { + public: + explicit grpc_security_connector(const char* url_scheme) + : grpc_core::RefCounted<grpc_security_connector>( + &grpc_trace_security_connector_refcount), + url_scheme_(url_scheme) {} + virtual ~grpc_security_connector() = default; + + /* Check the peer. Callee takes ownership of the peer object. + When done, sets *auth_context and invokes on_peer_checked. */ + virtual void check_peer( + tsi_peer peer, grpc_endpoint* ep, + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, grpc_closure* on_peer_checked) = 0; - /* Compares two security connectors. */ + /* Compares two security connectors. */ virtual int cmp(const grpc_security_connector* other) const = 0; - const char* url_scheme() const { return url_scheme_; } - - private: - const char* url_scheme_; -}; + const char* url_scheme() const { return url_scheme_; } + private: + const char* url_scheme_; +}; + /* Util to encapsulate the connector in a channel arg. */ grpc_arg grpc_security_connector_to_arg(grpc_security_connector* sc); @@ -84,93 +84,93 @@ grpc_security_connector* grpc_security_connector_find_in_args( A channel security connector object represents a way to configure the underlying transport security mechanism on the client side. */ -class grpc_channel_security_connector : public grpc_security_connector { - public: - grpc_channel_security_connector( - const char* url_scheme, - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, +class grpc_channel_security_connector : public grpc_security_connector { + public: + grpc_channel_security_connector( + const char* url_scheme, + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds /*, grpc_channel_args* channel_args = nullptr*/); - ~grpc_channel_security_connector() override; + ~grpc_channel_security_connector() override; - /// Checks that the host that will be set for a call is acceptable. - /// Returns true if completed synchronously, in which case \a error will - /// be set to indicate the result. Otherwise, \a on_call_host_checked - /// will be invoked when complete. + /// Checks that the host that will be set for a call is acceptable. + /// Returns true if completed synchronously, in which case \a error will + /// be set to indicate the result. Otherwise, \a on_call_host_checked + /// will be invoked when complete. virtual bool check_call_host(y_absl::string_view host, - grpc_auth_context* auth_context, - grpc_closure* on_call_host_checked, + grpc_auth_context* auth_context, + grpc_closure* on_call_host_checked, grpc_error** error) = 0; /// Cancels a pending asynchronous call to - /// grpc_channel_security_connector_check_call_host() with - /// \a on_call_host_checked as its callback. - virtual void cancel_check_call_host(grpc_closure* on_call_host_checked, + /// grpc_channel_security_connector_check_call_host() with + /// \a on_call_host_checked as its callback. + virtual void cancel_check_call_host(grpc_closure* on_call_host_checked, grpc_error* error) = 0; - /// Registers handshakers with \a handshake_mgr. + /// Registers handshakers with \a handshake_mgr. virtual void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* interested_parties, grpc_core::HandshakeManager* handshake_mgr) = 0; - const grpc_channel_credentials* channel_creds() const { - return channel_creds_.get(); - } - grpc_channel_credentials* mutable_channel_creds() { - return channel_creds_.get(); - } - const grpc_call_credentials* request_metadata_creds() const { - return request_metadata_creds_.get(); - } - grpc_call_credentials* mutable_request_metadata_creds() { - return request_metadata_creds_.get(); - } - - protected: - // Helper methods to be used in subclasses. - int channel_security_connector_cmp( - const grpc_channel_security_connector* other) const; + const grpc_channel_credentials* channel_creds() const { + return channel_creds_.get(); + } + grpc_channel_credentials* mutable_channel_creds() { + return channel_creds_.get(); + } + const grpc_call_credentials* request_metadata_creds() const { + return request_metadata_creds_.get(); + } + grpc_call_credentials* mutable_request_metadata_creds() { + return request_metadata_creds_.get(); + } + + protected: + // Helper methods to be used in subclasses. + int channel_security_connector_cmp( + const grpc_channel_security_connector* other) const; // grpc_channel_args* channel_args() const { return channel_args_.get(); } //// Should be called as soon as the channel args are not needed to reduce //// memory usage. // void clear_channel_arg() { channel_args_.reset(); } - private: - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds_; - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds_; + private: + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds_; + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds_; std::unique_ptr<grpc_channel_args> channel_args_; -}; +}; /* --- server_security_connector object. --- A server security connector object represents a way to configure the underlying transport security mechanism on the server side. */ -class grpc_server_security_connector : public grpc_security_connector { - public: - grpc_server_security_connector( - const char* url_scheme, - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); +class grpc_server_security_connector : public grpc_security_connector { + public: + grpc_server_security_connector( + const char* url_scheme, + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds); ~grpc_server_security_connector() override; virtual void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* interested_parties, grpc_core::HandshakeManager* handshake_mgr) = 0; - const grpc_server_credentials* server_creds() const { - return server_creds_.get(); - } - grpc_server_credentials* mutable_server_creds() { - return server_creds_.get(); - } + const grpc_server_credentials* server_creds() const { + return server_creds_.get(); + } + grpc_server_credentials* mutable_server_creds() { + return server_creds_.get(); + } protected: - // Helper methods to be used in subclasses. - int server_security_connector_cmp( - const grpc_server_security_connector* other) const; + // Helper methods to be used in subclasses. + int server_security_connector_cmp( + const grpc_server_security_connector* other) const; private: - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds_; + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds_; }; #endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SECURITY_CONNECTOR_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc index b5e78ddbbb..8e331c8771 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.cc @@ -1,243 +1,243 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h" - -#include <stdbool.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/security_connector/ssl/ssl_security_connector.h" + +#include <stdbool.h> + #include "y_absl/strings/str_cat.h" #include "y_absl/strings/str_format.h" #include "y_absl/strings/string_view.h" -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "src/core/ext/transport/chttp2/alpn/alpn.h" -#include "src/core/lib/channel/handshaker.h" -#include "src/core/lib/gpr/string.h" +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/ext/transport/chttp2/alpn/alpn.h" +#include "src/core/lib/channel/handshaker.h" +#include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/host_port.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/security/context/security_context.h" -#include "src/core/lib/security/credentials/credentials.h" -#include "src/core/lib/security/credentials/ssl/ssl_credentials.h" -#include "src/core/lib/security/security_connector/load_system_roots.h" -#include "src/core/lib/security/security_connector/ssl_utils.h" -#include "src/core/lib/security/transport/security_handshaker.h" -#include "src/core/tsi/ssl_transport_security.h" -#include "src/core/tsi/transport_security.h" - -namespace { -grpc_error* ssl_check_peer( - const char* peer_name, const tsi_peer* peer, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context) { +#include "src/core/lib/security/context/security_context.h" +#include "src/core/lib/security/credentials/credentials.h" +#include "src/core/lib/security/credentials/ssl/ssl_credentials.h" +#include "src/core/lib/security/security_connector/load_system_roots.h" +#include "src/core/lib/security/security_connector/ssl_utils.h" +#include "src/core/lib/security/transport/security_handshaker.h" +#include "src/core/tsi/ssl_transport_security.h" +#include "src/core/tsi/transport_security.h" + +namespace { +grpc_error* ssl_check_peer( + const char* peer_name, const tsi_peer* peer, + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context) { grpc_error* error = grpc_ssl_check_alpn(peer); if (error != GRPC_ERROR_NONE) { return error; - } - /* Check the peer name if specified. */ - if (peer_name != nullptr && !grpc_ssl_host_matches_name(peer, peer_name)) { + } + /* Check the peer name if specified. */ + if (peer_name != nullptr && !grpc_ssl_host_matches_name(peer, peer_name)) { return GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("Peer name ", peer_name, " is not in peer certificate") .c_str()); - } + } *auth_context = grpc_ssl_peer_to_auth_context(peer, GRPC_SSL_TRANSPORT_SECURITY_TYPE); - return GRPC_ERROR_NONE; -} - -class grpc_ssl_channel_security_connector final - : public grpc_channel_security_connector { - public: - grpc_ssl_channel_security_connector( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const grpc_ssl_config* config, const char* target_name, - const char* overridden_target_name) - : grpc_channel_security_connector(GRPC_SSL_URL_SCHEME, - std::move(channel_creds), - std::move(request_metadata_creds)), + return GRPC_ERROR_NONE; +} + +class grpc_ssl_channel_security_connector final + : public grpc_channel_security_connector { + public: + grpc_ssl_channel_security_connector( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const grpc_ssl_config* config, const char* target_name, + const char* overridden_target_name) + : grpc_channel_security_connector(GRPC_SSL_URL_SCHEME, + std::move(channel_creds), + std::move(request_metadata_creds)), overridden_target_name_( overridden_target_name == nullptr ? "" : overridden_target_name), - verify_options_(&config->verify_options) { + verify_options_(&config->verify_options) { y_absl::string_view host; y_absl::string_view port; grpc_core::SplitHostPort(target_name, &host, &port); target_name_ = TString(host); - } - - ~grpc_ssl_channel_security_connector() override { - tsi_ssl_client_handshaker_factory_unref(client_handshaker_factory_); - } - - grpc_security_status InitializeHandshakerFactory( - const grpc_ssl_config* config, const char* pem_root_certs, - const tsi_ssl_root_certs_store* root_store, - tsi_ssl_session_cache* ssl_session_cache) { - bool has_key_cert_pair = - config->pem_key_cert_pair != nullptr && - config->pem_key_cert_pair->private_key != nullptr && - config->pem_key_cert_pair->cert_chain != nullptr; - tsi_ssl_client_handshaker_options options; - GPR_DEBUG_ASSERT(pem_root_certs != nullptr); - options.pem_root_certs = pem_root_certs; - options.root_store = root_store; - options.alpn_protocols = - grpc_fill_alpn_protocol_strings(&options.num_alpn_protocols); - if (has_key_cert_pair) { - options.pem_key_cert_pair = config->pem_key_cert_pair; - } - options.cipher_suites = grpc_get_ssl_cipher_suites(); - options.session_cache = ssl_session_cache; + } + + ~grpc_ssl_channel_security_connector() override { + tsi_ssl_client_handshaker_factory_unref(client_handshaker_factory_); + } + + grpc_security_status InitializeHandshakerFactory( + const grpc_ssl_config* config, const char* pem_root_certs, + const tsi_ssl_root_certs_store* root_store, + tsi_ssl_session_cache* ssl_session_cache) { + bool has_key_cert_pair = + config->pem_key_cert_pair != nullptr && + config->pem_key_cert_pair->private_key != nullptr && + config->pem_key_cert_pair->cert_chain != nullptr; + tsi_ssl_client_handshaker_options options; + GPR_DEBUG_ASSERT(pem_root_certs != nullptr); + options.pem_root_certs = pem_root_certs; + options.root_store = root_store; + options.alpn_protocols = + grpc_fill_alpn_protocol_strings(&options.num_alpn_protocols); + if (has_key_cert_pair) { + options.pem_key_cert_pair = config->pem_key_cert_pair; + } + options.cipher_suites = grpc_get_ssl_cipher_suites(); + options.session_cache = ssl_session_cache; options.min_tls_version = grpc_get_tsi_tls_version(config->min_tls_version); options.max_tls_version = grpc_get_tsi_tls_version(config->max_tls_version); - const tsi_result result = - tsi_create_ssl_client_handshaker_factory_with_options( - &options, &client_handshaker_factory_); - gpr_free((void*)options.alpn_protocols); - if (result != TSI_OK) { - gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", - tsi_result_to_string(result)); - return GRPC_SECURITY_ERROR; - } - return GRPC_SECURITY_OK; - } - + const tsi_result result = + tsi_create_ssl_client_handshaker_factory_with_options( + &options, &client_handshaker_factory_); + gpr_free((void*)options.alpn_protocols); + if (result != TSI_OK) { + gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", + tsi_result_to_string(result)); + return GRPC_SECURITY_ERROR; + } + return GRPC_SECURITY_OK; + } + void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_mgr) override { - // Instantiate TSI handshaker. - tsi_handshaker* tsi_hs = nullptr; - tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( - client_handshaker_factory_, + grpc_core::HandshakeManager* handshake_mgr) override { + // Instantiate TSI handshaker. + tsi_handshaker* tsi_hs = nullptr; + tsi_result result = tsi_ssl_client_handshaker_factory_create_handshaker( + client_handshaker_factory_, overridden_target_name_.empty() ? target_name_.c_str() : overridden_target_name_.c_str(), - &tsi_hs); - if (result != TSI_OK) { - gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", - tsi_result_to_string(result)); - return; - } - // Create handshakers. + &tsi_hs); + if (result != TSI_OK) { + gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", + tsi_result_to_string(result)); + return; + } + // Create handshakers. handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args)); - } - + } + void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { const char* target_name = overridden_target_name_.empty() ? target_name_.c_str() : overridden_target_name_.c_str(); - grpc_error* error = ssl_check_peer(target_name, &peer, auth_context); - if (error == GRPC_ERROR_NONE && - verify_options_->verify_peer_callback != nullptr) { - const tsi_peer_property* p = - tsi_peer_get_property_by_name(&peer, TSI_X509_PEM_CERT_PROPERTY); - if (p == nullptr) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Cannot check peer: missing pem cert property."); - } else { - char* peer_pem = static_cast<char*>(gpr_malloc(p->value.length + 1)); - memcpy(peer_pem, p->value.data, p->value.length); - peer_pem[p->value.length] = '\0'; - int callback_status = verify_options_->verify_peer_callback( - target_name, peer_pem, - verify_options_->verify_peer_callback_userdata); - gpr_free(peer_pem); - if (callback_status) { + grpc_error* error = ssl_check_peer(target_name, &peer, auth_context); + if (error == GRPC_ERROR_NONE && + verify_options_->verify_peer_callback != nullptr) { + const tsi_peer_property* p = + tsi_peer_get_property_by_name(&peer, TSI_X509_PEM_CERT_PROPERTY); + if (p == nullptr) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Cannot check peer: missing pem cert property."); + } else { + char* peer_pem = static_cast<char*>(gpr_malloc(p->value.length + 1)); + memcpy(peer_pem, p->value.data, p->value.length); + peer_pem[p->value.length] = '\0'; + int callback_status = verify_options_->verify_peer_callback( + target_name, peer_pem, + verify_options_->verify_peer_callback_userdata); + gpr_free(peer_pem); + if (callback_status) { error = GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrFormat("Verify peer callback returned a failure (%d)", callback_status) .c_str()); - } - } - } + } + } + } grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); - tsi_peer_destruct(&peer); - } - - int cmp(const grpc_security_connector* other_sc) const override { - auto* other = - reinterpret_cast<const grpc_ssl_channel_security_connector*>(other_sc); - int c = channel_security_connector_cmp(other); - if (c != 0) return c; + tsi_peer_destruct(&peer); + } + + int cmp(const grpc_security_connector* other_sc) const override { + auto* other = + reinterpret_cast<const grpc_ssl_channel_security_connector*>(other_sc); + int c = channel_security_connector_cmp(other); + if (c != 0) return c; c = target_name_.compare(other->target_name_); - if (c != 0) return c; + if (c != 0) return c; return overridden_target_name_.compare(other->overridden_target_name_); - } - + } + bool check_call_host(y_absl::string_view host, grpc_auth_context* auth_context, grpc_closure* /*on_call_host_checked*/, - grpc_error** error) override { + grpc_error** error) override { return grpc_ssl_check_call_host(host, target_name_.c_str(), overridden_target_name_.c_str(), auth_context, error); - } - + } + void cancel_check_call_host(grpc_closure* /*on_call_host_checked*/, - grpc_error* error) override { - GRPC_ERROR_UNREF(error); - } - - private: - tsi_ssl_client_handshaker_factory* client_handshaker_factory_; + grpc_error* error) override { + GRPC_ERROR_UNREF(error); + } + + private: + tsi_ssl_client_handshaker_factory* client_handshaker_factory_; TString target_name_; TString overridden_target_name_; - const verify_peer_options* verify_options_; -}; - -class grpc_ssl_server_security_connector - : public grpc_server_security_connector { - public: - grpc_ssl_server_security_connector( - grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) - : grpc_server_security_connector(GRPC_SSL_URL_SCHEME, - std::move(server_creds)) {} - - ~grpc_ssl_server_security_connector() override { - tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); - } - - bool has_cert_config_fetcher() const { - return static_cast<const grpc_ssl_server_credentials*>(server_creds()) - ->has_cert_config_fetcher(); - } - - const tsi_ssl_server_handshaker_factory* server_handshaker_factory() const { - return server_handshaker_factory_; - } - - grpc_security_status InitializeHandshakerFactory() { - if (has_cert_config_fetcher()) { - // Load initial credentials from certificate_config_fetcher: - if (!try_fetch_ssl_server_credentials()) { - gpr_log(GPR_ERROR, - "Failed loading SSL server credentials from fetcher."); - return GRPC_SECURITY_ERROR; - } - } else { - auto* server_credentials = - static_cast<const grpc_ssl_server_credentials*>(server_creds()); - size_t num_alpn_protocols = 0; - const char** alpn_protocol_strings = - grpc_fill_alpn_protocol_strings(&num_alpn_protocols); + const verify_peer_options* verify_options_; +}; + +class grpc_ssl_server_security_connector + : public grpc_server_security_connector { + public: + grpc_ssl_server_security_connector( + grpc_core::RefCountedPtr<grpc_server_credentials> server_creds) + : grpc_server_security_connector(GRPC_SSL_URL_SCHEME, + std::move(server_creds)) {} + + ~grpc_ssl_server_security_connector() override { + tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); + } + + bool has_cert_config_fetcher() const { + return static_cast<const grpc_ssl_server_credentials*>(server_creds()) + ->has_cert_config_fetcher(); + } + + const tsi_ssl_server_handshaker_factory* server_handshaker_factory() const { + return server_handshaker_factory_; + } + + grpc_security_status InitializeHandshakerFactory() { + if (has_cert_config_fetcher()) { + // Load initial credentials from certificate_config_fetcher: + if (!try_fetch_ssl_server_credentials()) { + gpr_log(GPR_ERROR, + "Failed loading SSL server credentials from fetcher."); + return GRPC_SECURITY_ERROR; + } + } else { + auto* server_credentials = + static_cast<const grpc_ssl_server_credentials*>(server_creds()); + size_t num_alpn_protocols = 0; + const char** alpn_protocol_strings = + grpc_fill_alpn_protocol_strings(&num_alpn_protocols); tsi_ssl_server_handshaker_options options; options.pem_key_cert_pairs = server_credentials->config().pem_key_cert_pairs; @@ -246,7 +246,7 @@ class grpc_ssl_server_security_connector options.pem_client_root_certs = server_credentials->config().pem_root_certs; options.client_certificate_request = - grpc_get_tsi_client_certificate_request_type( + grpc_get_tsi_client_certificate_request_type( server_credentials->config().client_certificate_request); options.cipher_suites = grpc_get_ssl_cipher_suites(); options.alpn_protocols = alpn_protocol_strings; @@ -258,107 +258,107 @@ class grpc_ssl_server_security_connector const tsi_result result = tsi_create_ssl_server_handshaker_factory_with_options( &options, &server_handshaker_factory_); - gpr_free((void*)alpn_protocol_strings); - if (result != TSI_OK) { - gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", - tsi_result_to_string(result)); - return GRPC_SECURITY_ERROR; - } - } - return GRPC_SECURITY_OK; - } - + gpr_free((void*)alpn_protocol_strings); + if (result != TSI_OK) { + gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", + tsi_result_to_string(result)); + return GRPC_SECURITY_ERROR; + } + } + return GRPC_SECURITY_OK; + } + void add_handshakers(const grpc_channel_args* args, grpc_pollset_set* /*interested_parties*/, - grpc_core::HandshakeManager* handshake_mgr) override { - // Instantiate TSI handshaker. - try_fetch_ssl_server_credentials(); - tsi_handshaker* tsi_hs = nullptr; - tsi_result result = tsi_ssl_server_handshaker_factory_create_handshaker( - server_handshaker_factory_, &tsi_hs); - if (result != TSI_OK) { - gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", - tsi_result_to_string(result)); - return; - } - // Create handshakers. + grpc_core::HandshakeManager* handshake_mgr) override { + // Instantiate TSI handshaker. + try_fetch_ssl_server_credentials(); + tsi_handshaker* tsi_hs = nullptr; + tsi_result result = tsi_ssl_server_handshaker_factory_create_handshaker( + server_handshaker_factory_, &tsi_hs); + if (result != TSI_OK) { + gpr_log(GPR_ERROR, "Handshaker creation failed with error %s.", + tsi_result_to_string(result)); + return; + } + // Create handshakers. handshake_mgr->Add(grpc_core::SecurityHandshakerCreate(tsi_hs, this, args)); - } - + } + void check_peer(tsi_peer peer, grpc_endpoint* /*ep*/, - grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, - grpc_closure* on_peer_checked) override { - grpc_error* error = ssl_check_peer(nullptr, &peer, auth_context); - tsi_peer_destruct(&peer); + grpc_core::RefCountedPtr<grpc_auth_context>* auth_context, + grpc_closure* on_peer_checked) override { + grpc_error* error = ssl_check_peer(nullptr, &peer, auth_context); + tsi_peer_destruct(&peer); grpc_core::ExecCtx::Run(DEBUG_LOCATION, on_peer_checked, error); - } - - int cmp(const grpc_security_connector* other) const override { - return server_security_connector_cmp( - static_cast<const grpc_server_security_connector*>(other)); - } - - private: - /* Attempts to fetch the server certificate config if a callback is available. - * Current certificate config will continue to be used if the callback returns + } + + int cmp(const grpc_security_connector* other) const override { + return server_security_connector_cmp( + static_cast<const grpc_server_security_connector*>(other)); + } + + private: + /* Attempts to fetch the server certificate config if a callback is available. + * Current certificate config will continue to be used if the callback returns * an error. Returns true if new credentials were successfully loaded. */ - bool try_fetch_ssl_server_credentials() { - grpc_ssl_server_certificate_config* certificate_config = nullptr; - bool status; - if (!has_cert_config_fetcher()) return false; - + bool try_fetch_ssl_server_credentials() { + grpc_ssl_server_certificate_config* certificate_config = nullptr; + bool status; + if (!has_cert_config_fetcher()) return false; + grpc_core::MutexLock lock(&mu_); - grpc_ssl_server_credentials* server_creds = - static_cast<grpc_ssl_server_credentials*>(this->mutable_server_creds()); - grpc_ssl_certificate_config_reload_status cb_result = - server_creds->FetchCertConfig(&certificate_config); - if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED) { - gpr_log(GPR_DEBUG, "No change in SSL server credentials."); - status = false; - } else if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW) { - status = try_replace_server_handshaker_factory(certificate_config); - } else { - // Log error, continue using previously-loaded credentials. - gpr_log(GPR_ERROR, - "Failed fetching new server credentials, continuing to " - "use previously-loaded credentials."); - status = false; - } - - if (certificate_config != nullptr) { - grpc_ssl_server_certificate_config_destroy(certificate_config); - } - return status; - } - - /* Attempts to replace the server_handshaker_factory with a new factory using - * the provided grpc_ssl_server_certificate_config. Should new factory - * creation fail, the existing factory will not be replaced. Returns true on - * success (new factory created). */ - bool try_replace_server_handshaker_factory( - const grpc_ssl_server_certificate_config* config) { - if (config == nullptr) { - gpr_log(GPR_ERROR, - "Server certificate config callback returned invalid (NULL) " - "config."); - return false; - } - gpr_log(GPR_DEBUG, "Using new server certificate config (%p).", config); - - size_t num_alpn_protocols = 0; - const char** alpn_protocol_strings = - grpc_fill_alpn_protocol_strings(&num_alpn_protocols); - tsi_ssl_server_handshaker_factory* new_handshaker_factory = nullptr; - const grpc_ssl_server_credentials* server_creds = - static_cast<const grpc_ssl_server_credentials*>(this->server_creds()); - GPR_DEBUG_ASSERT(config->pem_root_certs != nullptr); + grpc_ssl_server_credentials* server_creds = + static_cast<grpc_ssl_server_credentials*>(this->mutable_server_creds()); + grpc_ssl_certificate_config_reload_status cb_result = + server_creds->FetchCertConfig(&certificate_config); + if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED) { + gpr_log(GPR_DEBUG, "No change in SSL server credentials."); + status = false; + } else if (cb_result == GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW) { + status = try_replace_server_handshaker_factory(certificate_config); + } else { + // Log error, continue using previously-loaded credentials. + gpr_log(GPR_ERROR, + "Failed fetching new server credentials, continuing to " + "use previously-loaded credentials."); + status = false; + } + + if (certificate_config != nullptr) { + grpc_ssl_server_certificate_config_destroy(certificate_config); + } + return status; + } + + /* Attempts to replace the server_handshaker_factory with a new factory using + * the provided grpc_ssl_server_certificate_config. Should new factory + * creation fail, the existing factory will not be replaced. Returns true on + * success (new factory created). */ + bool try_replace_server_handshaker_factory( + const grpc_ssl_server_certificate_config* config) { + if (config == nullptr) { + gpr_log(GPR_ERROR, + "Server certificate config callback returned invalid (NULL) " + "config."); + return false; + } + gpr_log(GPR_DEBUG, "Using new server certificate config (%p).", config); + + size_t num_alpn_protocols = 0; + const char** alpn_protocol_strings = + grpc_fill_alpn_protocol_strings(&num_alpn_protocols); + tsi_ssl_server_handshaker_factory* new_handshaker_factory = nullptr; + const grpc_ssl_server_credentials* server_creds = + static_cast<const grpc_ssl_server_credentials*>(this->server_creds()); + GPR_DEBUG_ASSERT(config->pem_root_certs != nullptr); tsi_ssl_server_handshaker_options options; options.pem_key_cert_pairs = grpc_convert_grpc_to_tsi_cert_pairs( config->pem_key_cert_pairs, config->num_key_cert_pairs); options.num_key_cert_pairs = config->num_key_cert_pairs; options.pem_client_root_certs = config->pem_root_certs; options.client_certificate_request = - grpc_get_tsi_client_certificate_request_type( + grpc_get_tsi_client_certificate_request_type( server_creds->config().client_certificate_request); options.cipher_suites = grpc_get_ssl_cipher_suites(); options.alpn_protocols = alpn_protocol_strings; @@ -368,79 +368,79 @@ class grpc_ssl_server_security_connector grpc_tsi_ssl_pem_key_cert_pairs_destroy( const_cast<tsi_ssl_pem_key_cert_pair*>(options.pem_key_cert_pairs), options.num_key_cert_pairs); - gpr_free((void*)alpn_protocol_strings); - - if (result != TSI_OK) { - gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", - tsi_result_to_string(result)); - return false; - } - set_server_handshaker_factory(new_handshaker_factory); - return true; - } - - void set_server_handshaker_factory( - tsi_ssl_server_handshaker_factory* new_factory) { - if (server_handshaker_factory_) { - tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); - } - server_handshaker_factory_ = new_factory; - } - + gpr_free((void*)alpn_protocol_strings); + + if (result != TSI_OK) { + gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.", + tsi_result_to_string(result)); + return false; + } + set_server_handshaker_factory(new_handshaker_factory); + return true; + } + + void set_server_handshaker_factory( + tsi_ssl_server_handshaker_factory* new_factory) { + if (server_handshaker_factory_) { + tsi_ssl_server_handshaker_factory_unref(server_handshaker_factory_); + } + server_handshaker_factory_ = new_factory; + } + grpc_core::Mutex mu_; - tsi_ssl_server_handshaker_factory* server_handshaker_factory_ = nullptr; -}; -} // namespace - -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_ssl_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const grpc_ssl_config* config, const char* target_name, - const char* overridden_target_name, - tsi_ssl_session_cache* ssl_session_cache) { - if (config == nullptr || target_name == nullptr) { - gpr_log(GPR_ERROR, "An ssl channel needs a config and a target name."); - return nullptr; - } - - const char* pem_root_certs; - const tsi_ssl_root_certs_store* root_store; - if (config->pem_root_certs == nullptr) { - // Use default root certificates. - pem_root_certs = grpc_core::DefaultSslRootStore::GetPemRootCerts(); - if (pem_root_certs == nullptr) { - gpr_log(GPR_ERROR, "Could not get default pem root certs."); - return nullptr; - } - root_store = grpc_core::DefaultSslRootStore::GetRootStore(); - } else { - pem_root_certs = config->pem_root_certs; - root_store = nullptr; - } - - grpc_core::RefCountedPtr<grpc_ssl_channel_security_connector> c = - grpc_core::MakeRefCounted<grpc_ssl_channel_security_connector>( - std::move(channel_creds), std::move(request_metadata_creds), config, - target_name, overridden_target_name); - const grpc_security_status result = c->InitializeHandshakerFactory( - config, pem_root_certs, root_store, ssl_session_cache); - if (result != GRPC_SECURITY_OK) { - return nullptr; - } - return c; -} - -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_ssl_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) { - GPR_ASSERT(server_credentials != nullptr); - grpc_core::RefCountedPtr<grpc_ssl_server_security_connector> c = - grpc_core::MakeRefCounted<grpc_ssl_server_security_connector>( - std::move(server_credentials)); - const grpc_security_status retval = c->InitializeHandshakerFactory(); - if (retval != GRPC_SECURITY_OK) { - return nullptr; - } - return c; -} + tsi_ssl_server_handshaker_factory* server_handshaker_factory_ = nullptr; +}; +} // namespace + +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_ssl_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const grpc_ssl_config* config, const char* target_name, + const char* overridden_target_name, + tsi_ssl_session_cache* ssl_session_cache) { + if (config == nullptr || target_name == nullptr) { + gpr_log(GPR_ERROR, "An ssl channel needs a config and a target name."); + return nullptr; + } + + const char* pem_root_certs; + const tsi_ssl_root_certs_store* root_store; + if (config->pem_root_certs == nullptr) { + // Use default root certificates. + pem_root_certs = grpc_core::DefaultSslRootStore::GetPemRootCerts(); + if (pem_root_certs == nullptr) { + gpr_log(GPR_ERROR, "Could not get default pem root certs."); + return nullptr; + } + root_store = grpc_core::DefaultSslRootStore::GetRootStore(); + } else { + pem_root_certs = config->pem_root_certs; + root_store = nullptr; + } + + grpc_core::RefCountedPtr<grpc_ssl_channel_security_connector> c = + grpc_core::MakeRefCounted<grpc_ssl_channel_security_connector>( + std::move(channel_creds), std::move(request_metadata_creds), config, + target_name, overridden_target_name); + const grpc_security_status result = c->InitializeHandshakerFactory( + config, pem_root_certs, root_store, ssl_session_cache); + if (result != GRPC_SECURITY_OK) { + return nullptr; + } + return c; +} + +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_ssl_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials) { + GPR_ASSERT(server_credentials != nullptr); + grpc_core::RefCountedPtr<grpc_ssl_server_security_connector> c = + grpc_core::MakeRefCounted<grpc_ssl_server_security_connector>( + std::move(server_credentials)); + const grpc_security_status retval = c->InitializeHandshakerFactory(); + if (retval != GRPC_SECURITY_OK) { + return nullptr; + } + return c; +} diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.h b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.h index 04c32bb2a8..c313a19955 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl/ssl_security_connector.h @@ -1,82 +1,82 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc_security.h> - -#include "src/core/lib/security/security_connector/security_connector.h" - -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/tsi/ssl_transport_security.h" -#include "src/core/tsi/transport_security_interface.h" - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc_security.h> + +#include "src/core/lib/security/security_connector/security_connector.h" + +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/tsi/ssl_transport_security.h" +#include "src/core/tsi/transport_security_interface.h" + struct grpc_ssl_config { - tsi_ssl_pem_key_cert_pair* pem_key_cert_pair; - char* pem_root_certs; - verify_peer_options verify_options; + tsi_ssl_pem_key_cert_pair* pem_key_cert_pair; + char* pem_root_certs; + verify_peer_options verify_options; grpc_tls_version min_tls_version = grpc_tls_version::TLS1_2; grpc_tls_version max_tls_version = grpc_tls_version::TLS1_3; }; -/* Creates an SSL channel_security_connector. - - request_metadata_creds is the credentials object which metadata - will be sent with each request. This parameter can be NULL. - - config is the SSL config to be used for the SSL channel establishment. - - is_client should be 0 for a server or a non-0 value for a client. - - secure_peer_name is the secure peer name that should be checked in - grpc_channel_security_connector_check_peer. This parameter may be NULL in - which case the peer name will not be checked. Note that if this parameter - is not NULL, then, pem_root_certs should not be NULL either. - - sc is a pointer on the connector to be created. - This function returns GRPC_SECURITY_OK in case of success or a - specific error code otherwise. -*/ -grpc_core::RefCountedPtr<grpc_channel_security_connector> -grpc_ssl_channel_security_connector_create( - grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, - grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, - const grpc_ssl_config* config, const char* target_name, - const char* overridden_target_name, - tsi_ssl_session_cache* ssl_session_cache); - -/* Config for ssl servers. */ +/* Creates an SSL channel_security_connector. + - request_metadata_creds is the credentials object which metadata + will be sent with each request. This parameter can be NULL. + - config is the SSL config to be used for the SSL channel establishment. + - is_client should be 0 for a server or a non-0 value for a client. + - secure_peer_name is the secure peer name that should be checked in + grpc_channel_security_connector_check_peer. This parameter may be NULL in + which case the peer name will not be checked. Note that if this parameter + is not NULL, then, pem_root_certs should not be NULL either. + - sc is a pointer on the connector to be created. + This function returns GRPC_SECURITY_OK in case of success or a + specific error code otherwise. +*/ +grpc_core::RefCountedPtr<grpc_channel_security_connector> +grpc_ssl_channel_security_connector_create( + grpc_core::RefCountedPtr<grpc_channel_credentials> channel_creds, + grpc_core::RefCountedPtr<grpc_call_credentials> request_metadata_creds, + const grpc_ssl_config* config, const char* target_name, + const char* overridden_target_name, + tsi_ssl_session_cache* ssl_session_cache); + +/* Config for ssl servers. */ struct grpc_ssl_server_config { - tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs = nullptr; - size_t num_key_cert_pairs = 0; - char* pem_root_certs = nullptr; - grpc_ssl_client_certificate_request_type client_certificate_request = - GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; + tsi_ssl_pem_key_cert_pair* pem_key_cert_pairs = nullptr; + size_t num_key_cert_pairs = 0; + char* pem_root_certs = nullptr; + grpc_ssl_client_certificate_request_type client_certificate_request = + GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE; grpc_tls_version min_tls_version = grpc_tls_version::TLS1_2; grpc_tls_version max_tls_version = grpc_tls_version::TLS1_3; }; -/* Creates an SSL server_security_connector. - - config is the SSL config to be used for the SSL channel establishment. - - sc is a pointer on the connector to be created. - This function returns GRPC_SECURITY_OK in case of success or a - specific error code otherwise. -*/ -grpc_core::RefCountedPtr<grpc_server_security_connector> -grpc_ssl_server_security_connector_create( - grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials); - -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H \ - */ +/* Creates an SSL server_security_connector. + - config is the SSL config to be used for the SSL channel establishment. + - sc is a pointer on the connector to be created. + This function returns GRPC_SECURITY_OK in case of success or a + specific error code otherwise. +*/ +grpc_core::RefCountedPtr<grpc_server_security_connector> +grpc_ssl_server_security_connector_create( + grpc_core::RefCountedPtr<grpc_server_credentials> server_credentials); + +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_SSL_SECURITY_CONNECTOR_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc index 6c83968f8e..f9d32e4a25 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.cc @@ -1,72 +1,72 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/security/security_connector/ssl_utils.h" - +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/security/security_connector/ssl_utils.h" + #include <vector> #include "y_absl/strings/str_cat.h" -#include <grpc/slice_buffer.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "src/core/ext/transport/chttp2/alpn/alpn.h" -#include "src/core/lib/channel/channel_args.h" -#include "src/core/lib/gpr/string.h" +#include <grpc/slice_buffer.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/ext/transport/chttp2/alpn/alpn.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/host_port.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/iomgr/load_file.h" -#include "src/core/lib/security/context/security_context.h" -#include "src/core/lib/security/security_connector/load_system_roots.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/iomgr/load_file.h" +#include "src/core/lib/security/context/security_context.h" +#include "src/core/lib/security/security_connector/load_system_roots.h" #include "src/core/lib/security/security_connector/ssl_utils_config.h" -#include "src/core/tsi/ssl_transport_security.h" - +#include "src/core/tsi/ssl_transport_security.h" + #include "load_arcadia_root_certs.h" -/* -- Constants. -- */ - -#ifndef INSTALL_PREFIX -static const char* installed_roots_path = "/usr/share/grpc/roots.pem"; -#else -static const char* installed_roots_path = - INSTALL_PREFIX "/share/grpc/roots.pem"; -#endif - -#ifndef TSI_OPENSSL_ALPN_SUPPORT -#define TSI_OPENSSL_ALPN_SUPPORT 1 -#endif - -/* -- Overridden default roots. -- */ - -static grpc_ssl_roots_override_callback ssl_roots_override_cb = nullptr; - -void grpc_set_ssl_roots_override_callback(grpc_ssl_roots_override_callback cb) { - ssl_roots_override_cb = cb; -} - -/* -- Cipher suites. -- */ - -static gpr_once cipher_suites_once = GPR_ONCE_INIT; -static const char* cipher_suites = nullptr; - +/* -- Constants. -- */ + +#ifndef INSTALL_PREFIX +static const char* installed_roots_path = "/usr/share/grpc/roots.pem"; +#else +static const char* installed_roots_path = + INSTALL_PREFIX "/share/grpc/roots.pem"; +#endif + +#ifndef TSI_OPENSSL_ALPN_SUPPORT +#define TSI_OPENSSL_ALPN_SUPPORT 1 +#endif + +/* -- Overridden default roots. -- */ + +static grpc_ssl_roots_override_callback ssl_roots_override_cb = nullptr; + +void grpc_set_ssl_roots_override_callback(grpc_ssl_roots_override_callback cb) { + ssl_roots_override_cb = cb; +} + +/* -- Cipher suites. -- */ + +static gpr_once cipher_suites_once = GPR_ONCE_INIT; +static const char* cipher_suites = nullptr; + // All cipher suites for default are compliant with HTTP2. GPR_GLOBAL_CONFIG_DEFINE_STRING( grpc_ssl_cipher_suites, @@ -79,19 +79,19 @@ GPR_GLOBAL_CONFIG_DEFINE_STRING( "ECDHE-RSA-AES256-GCM-SHA384", "A colon separated list of cipher suites to use with OpenSSL") -static void init_cipher_suites(void) { +static void init_cipher_suites(void) { grpc_core::UniquePtr<char> value = GPR_GLOBAL_CONFIG_GET(grpc_ssl_cipher_suites); cipher_suites = value.release(); -} - -/* --- Util --- */ - -const char* grpc_get_ssl_cipher_suites(void) { - gpr_once_init(&cipher_suites_once, init_cipher_suites); - return cipher_suites; -} - +} + +/* --- Util --- */ + +const char* grpc_get_ssl_cipher_suites(void) { + gpr_once_init(&cipher_suites_once, init_cipher_suites); + return cipher_suites; +} + grpc_security_level grpc_tsi_security_level_string_to_enum( const char* security_level) { if (strcmp(security_level, "TSI_INTEGRITY_ONLY") == 0) { @@ -116,30 +116,30 @@ bool grpc_check_security_level(grpc_security_level channel_level, return static_cast<int>(channel_level) >= static_cast<int>(call_cred_level); } -tsi_client_certificate_request_type -grpc_get_tsi_client_certificate_request_type( - grpc_ssl_client_certificate_request_type grpc_request_type) { - switch (grpc_request_type) { - case GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE: - return TSI_DONT_REQUEST_CLIENT_CERTIFICATE; - - case GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: - return TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY; - - case GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY: - return TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY; - - case GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: - return TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY; - - case GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY: - return TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY; - - default: - return TSI_DONT_REQUEST_CLIENT_CERTIFICATE; - } -} - +tsi_client_certificate_request_type +grpc_get_tsi_client_certificate_request_type( + grpc_ssl_client_certificate_request_type grpc_request_type) { + switch (grpc_request_type) { + case GRPC_SSL_DONT_REQUEST_CLIENT_CERTIFICATE: + return TSI_DONT_REQUEST_CLIENT_CERTIFICATE; + + case GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: + return TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY; + + case GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY: + return TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY; + + case GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: + return TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY; + + case GRPC_SSL_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY: + return TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY; + + default: + return TSI_DONT_REQUEST_CLIENT_CERTIFICATE; + } +} + tsi_tls_version grpc_get_tsi_tls_version(grpc_tls_version tls_version) { switch (tls_version) { case grpc_tls_version::TLS1_2: @@ -202,32 +202,32 @@ bool grpc_ssl_check_call_host(y_absl::string_view host, return true; } -const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols) { - GPR_ASSERT(num_alpn_protocols != nullptr); - *num_alpn_protocols = grpc_chttp2_num_alpn_versions(); - const char** alpn_protocol_strings = static_cast<const char**>( - gpr_malloc(sizeof(const char*) * (*num_alpn_protocols))); - for (size_t i = 0; i < *num_alpn_protocols; i++) { - alpn_protocol_strings[i] = grpc_chttp2_get_alpn_version_index(i); - } - return alpn_protocol_strings; -} - +const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols) { + GPR_ASSERT(num_alpn_protocols != nullptr); + *num_alpn_protocols = grpc_chttp2_num_alpn_versions(); + const char** alpn_protocol_strings = static_cast<const char**>( + gpr_malloc(sizeof(const char*) * (*num_alpn_protocols))); + for (size_t i = 0; i < *num_alpn_protocols; i++) { + alpn_protocol_strings[i] = grpc_chttp2_get_alpn_version_index(i); + } + return alpn_protocol_strings; +} + int grpc_ssl_host_matches_name(const tsi_peer* peer, y_absl::string_view peer_name) { y_absl::string_view allocated_name; y_absl::string_view ignored_port; grpc_core::SplitHostPort(peer_name, &allocated_name, &ignored_port); if (allocated_name.empty()) return 0; - - // IPv6 zone-id should not be included in comparisons. + + // IPv6 zone-id should not be included in comparisons. const size_t zone_id = allocated_name.find('%'); if (zone_id != y_absl::string_view::npos) { allocated_name.remove_suffix(allocated_name.size() - zone_id); } return tsi_ssl_peer_matches_name(peer, allocated_name); } - + int grpc_ssl_cmp_target_name(y_absl::string_view target_name, y_absl::string_view other_target_name, y_absl::string_view overridden_target_name, @@ -235,8 +235,8 @@ int grpc_ssl_cmp_target_name(y_absl::string_view target_name, int c = target_name.compare(other_target_name); if (c != 0) return c; return overridden_target_name.compare(other_overridden_target_name); -} - +} + static bool IsSpiffeId(y_absl::string_view uri) { // Return false without logging for a non-spiffe uri scheme. if (!y_absl::StartsWith(uri, "spiffe://")) { @@ -258,49 +258,49 @@ static bool IsSpiffeId(y_absl::string_view uri) { return true; } -grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context( +grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context( const tsi_peer* peer, const char* transport_security_type) { - size_t i; - const char* peer_identity_property_name = nullptr; - - /* The caller has checked the certificate type property. */ - GPR_ASSERT(peer->property_count >= 1); - grpc_core::RefCountedPtr<grpc_auth_context> ctx = - grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); - grpc_auth_context_add_cstring_property( - ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, + size_t i; + const char* peer_identity_property_name = nullptr; + + /* The caller has checked the certificate type property. */ + GPR_ASSERT(peer->property_count >= 1); + grpc_core::RefCountedPtr<grpc_auth_context> ctx = + grpc_core::MakeRefCounted<grpc_auth_context>(nullptr); + grpc_auth_context_add_cstring_property( + ctx.get(), GRPC_TRANSPORT_SECURITY_TYPE_PROPERTY_NAME, transport_security_type); const char* spiffe_data = nullptr; size_t spiffe_length = 0; int uri_count = 0; bool has_spiffe_id = false; - for (i = 0; i < peer->property_count; i++) { - const tsi_peer_property* prop = &peer->properties[i]; - if (prop->name == nullptr) continue; - if (strcmp(prop->name, TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) { - /* If there is no subject alt name, have the CN as the identity. */ - if (peer_identity_property_name == nullptr) { - peer_identity_property_name = GRPC_X509_CN_PROPERTY_NAME; - } - grpc_auth_context_add_property(ctx.get(), GRPC_X509_CN_PROPERTY_NAME, - prop->value.data, prop->value.length); - } else if (strcmp(prop->name, - TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) { - peer_identity_property_name = GRPC_X509_SAN_PROPERTY_NAME; - grpc_auth_context_add_property(ctx.get(), GRPC_X509_SAN_PROPERTY_NAME, - prop->value.data, prop->value.length); - } else if (strcmp(prop->name, TSI_X509_PEM_CERT_PROPERTY) == 0) { - grpc_auth_context_add_property(ctx.get(), - GRPC_X509_PEM_CERT_PROPERTY_NAME, - prop->value.data, prop->value.length); + for (i = 0; i < peer->property_count; i++) { + const tsi_peer_property* prop = &peer->properties[i]; + if (prop->name == nullptr) continue; + if (strcmp(prop->name, TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY) == 0) { + /* If there is no subject alt name, have the CN as the identity. */ + if (peer_identity_property_name == nullptr) { + peer_identity_property_name = GRPC_X509_CN_PROPERTY_NAME; + } + grpc_auth_context_add_property(ctx.get(), GRPC_X509_CN_PROPERTY_NAME, + prop->value.data, prop->value.length); + } else if (strcmp(prop->name, + TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY) == 0) { + peer_identity_property_name = GRPC_X509_SAN_PROPERTY_NAME; + grpc_auth_context_add_property(ctx.get(), GRPC_X509_SAN_PROPERTY_NAME, + prop->value.data, prop->value.length); + } else if (strcmp(prop->name, TSI_X509_PEM_CERT_PROPERTY) == 0) { + grpc_auth_context_add_property(ctx.get(), + GRPC_X509_PEM_CERT_PROPERTY_NAME, + prop->value.data, prop->value.length); } else if (strcmp(prop->name, TSI_X509_PEM_CERT_CHAIN_PROPERTY) == 0) { grpc_auth_context_add_property(ctx.get(), GRPC_X509_PEM_CERT_CHAIN_PROPERTY_NAME, prop->value.data, prop->value.length); - } else if (strcmp(prop->name, TSI_SSL_SESSION_REUSED_PEER_PROPERTY) == 0) { - grpc_auth_context_add_property(ctx.get(), - GRPC_SSL_SESSION_REUSED_PROPERTY, - prop->value.data, prop->value.length); + } else if (strcmp(prop->name, TSI_SSL_SESSION_REUSED_PEER_PROPERTY) == 0) { + grpc_auth_context_add_property(ctx.get(), + GRPC_SSL_SESSION_REUSED_PROPERTY, + prop->value.data, prop->value.length); } else if (strcmp(prop->name, TSI_SECURITY_LEVEL_PEER_PROPERTY) == 0) { grpc_auth_context_add_property( ctx.get(), GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME, @@ -313,12 +313,12 @@ grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context( spiffe_length = prop->value.length; has_spiffe_id = true; } - } - } - if (peer_identity_property_name != nullptr) { - GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( - ctx.get(), peer_identity_property_name) == 1); - } + } + } + if (peer_identity_property_name != nullptr) { + GPR_ASSERT(grpc_auth_context_set_peer_identity_property_name( + ctx.get(), peer_identity_property_name) == 1); + } // A valid SPIFFE certificate can only have exact one URI SAN field. if (has_spiffe_id) { if (uri_count == 1) { @@ -331,43 +331,43 @@ grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context( gpr_log(GPR_INFO, "Invalid SPIFFE ID: multiple URI SANs."); } } - return ctx; -} - -static void add_shallow_auth_property_to_peer(tsi_peer* peer, - const grpc_auth_property* prop, - const char* tsi_prop_name) { - tsi_peer_property* tsi_prop = &peer->properties[peer->property_count++]; - tsi_prop->name = const_cast<char*>(tsi_prop_name); - tsi_prop->value.data = prop->value; - tsi_prop->value.length = prop->value_length; -} - -tsi_peer grpc_shallow_peer_from_ssl_auth_context( - const grpc_auth_context* auth_context) { - size_t max_num_props = 0; - grpc_auth_property_iterator it; - const grpc_auth_property* prop; - tsi_peer peer; - memset(&peer, 0, sizeof(peer)); - - it = grpc_auth_context_property_iterator(auth_context); - while (grpc_auth_property_iterator_next(&it) != nullptr) max_num_props++; - - if (max_num_props > 0) { - peer.properties = static_cast<tsi_peer_property*>( - gpr_malloc(max_num_props * sizeof(tsi_peer_property))); - it = grpc_auth_context_property_iterator(auth_context); - while ((prop = grpc_auth_property_iterator_next(&it)) != nullptr) { - if (strcmp(prop->name, GRPC_X509_SAN_PROPERTY_NAME) == 0) { - add_shallow_auth_property_to_peer( - &peer, prop, TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY); - } else if (strcmp(prop->name, GRPC_X509_CN_PROPERTY_NAME) == 0) { - add_shallow_auth_property_to_peer( - &peer, prop, TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY); - } else if (strcmp(prop->name, GRPC_X509_PEM_CERT_PROPERTY_NAME) == 0) { - add_shallow_auth_property_to_peer(&peer, prop, - TSI_X509_PEM_CERT_PROPERTY); + return ctx; +} + +static void add_shallow_auth_property_to_peer(tsi_peer* peer, + const grpc_auth_property* prop, + const char* tsi_prop_name) { + tsi_peer_property* tsi_prop = &peer->properties[peer->property_count++]; + tsi_prop->name = const_cast<char*>(tsi_prop_name); + tsi_prop->value.data = prop->value; + tsi_prop->value.length = prop->value_length; +} + +tsi_peer grpc_shallow_peer_from_ssl_auth_context( + const grpc_auth_context* auth_context) { + size_t max_num_props = 0; + grpc_auth_property_iterator it; + const grpc_auth_property* prop; + tsi_peer peer; + memset(&peer, 0, sizeof(peer)); + + it = grpc_auth_context_property_iterator(auth_context); + while (grpc_auth_property_iterator_next(&it) != nullptr) max_num_props++; + + if (max_num_props > 0) { + peer.properties = static_cast<tsi_peer_property*>( + gpr_malloc(max_num_props * sizeof(tsi_peer_property))); + it = grpc_auth_context_property_iterator(auth_context); + while ((prop = grpc_auth_property_iterator_next(&it)) != nullptr) { + if (strcmp(prop->name, GRPC_X509_SAN_PROPERTY_NAME) == 0) { + add_shallow_auth_property_to_peer( + &peer, prop, TSI_X509_SUBJECT_ALTERNATIVE_NAME_PEER_PROPERTY); + } else if (strcmp(prop->name, GRPC_X509_CN_PROPERTY_NAME) == 0) { + add_shallow_auth_property_to_peer( + &peer, prop, TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY); + } else if (strcmp(prop->name, GRPC_X509_PEM_CERT_PROPERTY_NAME) == 0) { + add_shallow_auth_property_to_peer(&peer, prop, + TSI_X509_PEM_CERT_PROPERTY); } else if (strcmp(prop->name, GRPC_TRANSPORT_SECURITY_LEVEL_PROPERTY_NAME) == 0) { add_shallow_auth_property_to_peer(&peer, prop, @@ -379,16 +379,16 @@ tsi_peer grpc_shallow_peer_from_ssl_auth_context( } else if (strcmp(prop->name, GRPC_PEER_SPIFFE_ID_PROPERTY_NAME) == 0) { add_shallow_auth_property_to_peer(&peer, prop, TSI_X509_URI_PEER_PROPERTY); - } - } - } - return peer; -} - -void grpc_shallow_peer_destruct(tsi_peer* peer) { - if (peer->properties != nullptr) gpr_free(peer->properties); -} - + } + } + } + return peer; +} + +void grpc_shallow_peer_destruct(tsi_peer* peer) { + if (peer->properties != nullptr) gpr_free(peer->properties); +} + grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init( tsi_ssl_pem_key_cert_pair* pem_key_cert_pair, const char* pem_root_certs, bool skip_server_certificate_verification, tsi_tls_version min_tls_version, @@ -470,70 +470,70 @@ grpc_security_status grpc_ssl_tsi_server_handshaker_factory_init( return GRPC_SECURITY_OK; } -/* --- Ssl cache implementation. --- */ - -grpc_ssl_session_cache* grpc_ssl_session_cache_create_lru(size_t capacity) { - tsi_ssl_session_cache* cache = tsi_ssl_session_cache_create_lru(capacity); - return reinterpret_cast<grpc_ssl_session_cache*>(cache); -} - -void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache) { - tsi_ssl_session_cache* tsi_cache = - reinterpret_cast<tsi_ssl_session_cache*>(cache); - tsi_ssl_session_cache_unref(tsi_cache); -} - -static void* grpc_ssl_session_cache_arg_copy(void* p) { - tsi_ssl_session_cache* tsi_cache = - reinterpret_cast<tsi_ssl_session_cache*>(p); - // destroy call below will unref the pointer. - tsi_ssl_session_cache_ref(tsi_cache); - return p; -} - -static void grpc_ssl_session_cache_arg_destroy(void* p) { - tsi_ssl_session_cache* tsi_cache = - reinterpret_cast<tsi_ssl_session_cache*>(p); - tsi_ssl_session_cache_unref(tsi_cache); -} - -static int grpc_ssl_session_cache_arg_cmp(void* p, void* q) { - return GPR_ICMP(p, q); -} - -grpc_arg grpc_ssl_session_cache_create_channel_arg( - grpc_ssl_session_cache* cache) { - static const grpc_arg_pointer_vtable vtable = { - grpc_ssl_session_cache_arg_copy, - grpc_ssl_session_cache_arg_destroy, - grpc_ssl_session_cache_arg_cmp, - }; - return grpc_channel_arg_pointer_create( - const_cast<char*>(GRPC_SSL_SESSION_CACHE_ARG), cache, &vtable); -} - -/* --- Default SSL root store implementation. --- */ - -namespace grpc_core { - -tsi_ssl_root_certs_store* DefaultSslRootStore::default_root_store_; -grpc_slice DefaultSslRootStore::default_pem_root_certs_; - -const tsi_ssl_root_certs_store* DefaultSslRootStore::GetRootStore() { - InitRootStore(); - return default_root_store_; -} - -const char* DefaultSslRootStore::GetPemRootCerts() { - InitRootStore(); - return GRPC_SLICE_IS_EMPTY(default_pem_root_certs_) - ? nullptr - : reinterpret_cast<const char*> - GRPC_SLICE_START_PTR(default_pem_root_certs_); -} - -grpc_slice DefaultSslRootStore::ComputePemRootCerts() { - grpc_slice result = grpc_empty_slice(); +/* --- Ssl cache implementation. --- */ + +grpc_ssl_session_cache* grpc_ssl_session_cache_create_lru(size_t capacity) { + tsi_ssl_session_cache* cache = tsi_ssl_session_cache_create_lru(capacity); + return reinterpret_cast<grpc_ssl_session_cache*>(cache); +} + +void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache) { + tsi_ssl_session_cache* tsi_cache = + reinterpret_cast<tsi_ssl_session_cache*>(cache); + tsi_ssl_session_cache_unref(tsi_cache); +} + +static void* grpc_ssl_session_cache_arg_copy(void* p) { + tsi_ssl_session_cache* tsi_cache = + reinterpret_cast<tsi_ssl_session_cache*>(p); + // destroy call below will unref the pointer. + tsi_ssl_session_cache_ref(tsi_cache); + return p; +} + +static void grpc_ssl_session_cache_arg_destroy(void* p) { + tsi_ssl_session_cache* tsi_cache = + reinterpret_cast<tsi_ssl_session_cache*>(p); + tsi_ssl_session_cache_unref(tsi_cache); +} + +static int grpc_ssl_session_cache_arg_cmp(void* p, void* q) { + return GPR_ICMP(p, q); +} + +grpc_arg grpc_ssl_session_cache_create_channel_arg( + grpc_ssl_session_cache* cache) { + static const grpc_arg_pointer_vtable vtable = { + grpc_ssl_session_cache_arg_copy, + grpc_ssl_session_cache_arg_destroy, + grpc_ssl_session_cache_arg_cmp, + }; + return grpc_channel_arg_pointer_create( + const_cast<char*>(GRPC_SSL_SESSION_CACHE_ARG), cache, &vtable); +} + +/* --- Default SSL root store implementation. --- */ + +namespace grpc_core { + +tsi_ssl_root_certs_store* DefaultSslRootStore::default_root_store_; +grpc_slice DefaultSslRootStore::default_pem_root_certs_; + +const tsi_ssl_root_certs_store* DefaultSslRootStore::GetRootStore() { + InitRootStore(); + return default_root_store_; +} + +const char* DefaultSslRootStore::GetPemRootCerts() { + InitRootStore(); + return GRPC_SLICE_IS_EMPTY(default_pem_root_certs_) + ? nullptr + : reinterpret_cast<const char*> + GRPC_SLICE_START_PTR(default_pem_root_certs_); +} + +grpc_slice DefaultSslRootStore::ComputePemRootCerts() { + grpc_slice result = grpc_empty_slice(); const bool not_use_system_roots = GPR_GLOBAL_CONFIG_GET(grpc_not_use_system_ssl_roots); // First try to load the roots from the configuration. @@ -542,49 +542,49 @@ grpc_slice DefaultSslRootStore::ComputePemRootCerts() { if (strlen(default_root_certs_path.get()) > 0) { GRPC_LOG_IF_ERROR( "load_file", grpc_load_file(default_root_certs_path.get(), 1, &result)); - } - // Try overridden roots if needed. - grpc_ssl_roots_override_result ovrd_res = GRPC_SSL_ROOTS_OVERRIDE_FAIL; - if (GRPC_SLICE_IS_EMPTY(result) && ssl_roots_override_cb != nullptr) { - char* pem_root_certs = nullptr; - ovrd_res = ssl_roots_override_cb(&pem_root_certs); - if (ovrd_res == GRPC_SSL_ROOTS_OVERRIDE_OK) { - GPR_ASSERT(pem_root_certs != nullptr); - result = grpc_slice_from_copied_buffer( - pem_root_certs, - strlen(pem_root_certs) + 1); // nullptr terminator. - } - gpr_free(pem_root_certs); - } + } + // Try overridden roots if needed. + grpc_ssl_roots_override_result ovrd_res = GRPC_SSL_ROOTS_OVERRIDE_FAIL; + if (GRPC_SLICE_IS_EMPTY(result) && ssl_roots_override_cb != nullptr) { + char* pem_root_certs = nullptr; + ovrd_res = ssl_roots_override_cb(&pem_root_certs); + if (ovrd_res == GRPC_SSL_ROOTS_OVERRIDE_OK) { + GPR_ASSERT(pem_root_certs != nullptr); + result = grpc_slice_from_copied_buffer( + pem_root_certs, + strlen(pem_root_certs) + 1); // nullptr terminator. + } + gpr_free(pem_root_certs); + } // Load Arcadia certs. if (GRPC_SLICE_IS_EMPTY(result)) { result = LoadArcadiaRootCerts(); } - // Try loading roots from OS trust store if flag is enabled. - if (GRPC_SLICE_IS_EMPTY(result) && !not_use_system_roots) { - result = LoadSystemRootCerts(); - } - // Fallback to roots manually shipped with gRPC. - if (GRPC_SLICE_IS_EMPTY(result) && - ovrd_res != GRPC_SSL_ROOTS_OVERRIDE_FAIL_PERMANENTLY) { - GRPC_LOG_IF_ERROR("load_file", - grpc_load_file(installed_roots_path, 1, &result)); - } - return result; -} - -void DefaultSslRootStore::InitRootStore() { - static gpr_once once = GPR_ONCE_INIT; - gpr_once_init(&once, DefaultSslRootStore::InitRootStoreOnce); -} - -void DefaultSslRootStore::InitRootStoreOnce() { - default_pem_root_certs_ = ComputePemRootCerts(); - if (!GRPC_SLICE_IS_EMPTY(default_pem_root_certs_)) { - default_root_store_ = - tsi_ssl_root_certs_store_create(reinterpret_cast<const char*>( - GRPC_SLICE_START_PTR(default_pem_root_certs_))); - } -} - -} // namespace grpc_core + // Try loading roots from OS trust store if flag is enabled. + if (GRPC_SLICE_IS_EMPTY(result) && !not_use_system_roots) { + result = LoadSystemRootCerts(); + } + // Fallback to roots manually shipped with gRPC. + if (GRPC_SLICE_IS_EMPTY(result) && + ovrd_res != GRPC_SSL_ROOTS_OVERRIDE_FAIL_PERMANENTLY) { + GRPC_LOG_IF_ERROR("load_file", + grpc_load_file(installed_roots_path, 1, &result)); + } + return result; +} + +void DefaultSslRootStore::InitRootStore() { + static gpr_once once = GPR_ONCE_INIT; + gpr_once_init(&once, DefaultSslRootStore::InitRootStoreOnce); +} + +void DefaultSslRootStore::InitRootStoreOnce() { + default_pem_root_certs_ = ComputePemRootCerts(); + if (!GRPC_SLICE_IS_EMPTY(default_pem_root_certs_)) { + default_root_store_ = + tsi_ssl_root_certs_store_create(reinterpret_cast<const char*>( + GRPC_SLICE_START_PTR(default_pem_root_certs_))); + } +} + +} // namespace grpc_core diff --git a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h index 6141f8d9cb..c9278cdfd2 100644 --- a/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h +++ b/contrib/libs/grpc/src/core/lib/security/security_connector/ssl_utils.h @@ -1,48 +1,48 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H -#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H - -#include <grpc/support/port_platform.h> - -#include <stdbool.h> - +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H +#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H + +#include <grpc/support/port_platform.h> + +#include <stdbool.h> + #include "y_absl/strings/str_split.h" #include "y_absl/strings/string_view.h" -#include <grpc/grpc_security.h> -#include <grpc/slice_buffer.h> - +#include <grpc/grpc_security.h> +#include <grpc/slice_buffer.h> + #include "src/core/lib/gprpp/global_config.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/error.h" #include "src/core/lib/security/security_connector/security_connector.h" #include "src/core/lib/security/security_connector/ssl_utils_config.h" -#include "src/core/tsi/ssl_transport_security.h" +#include "src/core/tsi/ssl_transport_security.h" #include "src/core/tsi/transport_security.h" -#include "src/core/tsi/transport_security_interface.h" - +#include "src/core/tsi/transport_security_interface.h" + /* --- Util --- */ - -/* --- URL schemes. --- */ -#define GRPC_SSL_URL_SCHEME "https" - + +/* --- URL schemes. --- */ +#define GRPC_SSL_URL_SCHEME "https" + /* Check ALPN information returned from SSL handshakes. */ grpc_error* grpc_ssl_check_alpn(const tsi_peer* peer); @@ -60,15 +60,15 @@ bool grpc_ssl_check_call_host(y_absl::string_view host, y_absl::string_view overridden_target_name, grpc_auth_context* auth_context, grpc_error** error); -/* Return HTTP2-compliant cipher suites that gRPC accepts by default. */ -const char* grpc_get_ssl_cipher_suites(void); - -/* Map from grpc_ssl_client_certificate_request_type to - * tsi_client_certificate_request_type. */ -tsi_client_certificate_request_type -grpc_get_tsi_client_certificate_request_type( - grpc_ssl_client_certificate_request_type grpc_request_type); - +/* Return HTTP2-compliant cipher suites that gRPC accepts by default. */ +const char* grpc_get_ssl_cipher_suites(void); + +/* Map from grpc_ssl_client_certificate_request_type to + * tsi_client_certificate_request_type. */ +tsi_client_certificate_request_type +grpc_get_tsi_client_certificate_request_type( + grpc_ssl_client_certificate_request_type grpc_request_type); + /* Map tsi_security_level string to grpc_security_level enum. */ grpc_security_level grpc_tsi_security_level_string_to_enum( const char* security_level); @@ -83,9 +83,9 @@ const char* grpc_security_level_to_string(grpc_security_level security_level); bool grpc_check_security_level(grpc_security_level channel_level, grpc_security_level call_cred_level); -/* Return an array of strings containing alpn protocols. */ -const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols); - +/* Return an array of strings containing alpn protocols. */ +const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols); + /* Initialize TSI SSL server/client handshaker factory. */ grpc_security_status grpc_ssl_tsi_client_handshaker_factory_init( tsi_ssl_pem_key_cert_pair* key_cert_pair, const char* pem_root_certs, @@ -100,70 +100,70 @@ grpc_security_status grpc_ssl_tsi_server_handshaker_factory_init( tsi_tls_version min_tls_version, tsi_tls_version max_tls_version, tsi_ssl_server_handshaker_factory** handshaker_factory); -/* Exposed for testing only. */ -grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context( +/* Exposed for testing only. */ +grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context( const tsi_peer* peer, const char* transport_security_type); -tsi_peer grpc_shallow_peer_from_ssl_auth_context( - const grpc_auth_context* auth_context); -void grpc_shallow_peer_destruct(tsi_peer* peer); +tsi_peer grpc_shallow_peer_from_ssl_auth_context( + const grpc_auth_context* auth_context); +void grpc_shallow_peer_destruct(tsi_peer* peer); int grpc_ssl_host_matches_name(const tsi_peer* peer, y_absl::string_view peer_name); - -/* --- Default SSL Root Store. --- */ -namespace grpc_core { - -// The class implements default SSL root store. -class DefaultSslRootStore { - public: - // Gets the default SSL root store. Returns nullptr if not found. - static const tsi_ssl_root_certs_store* GetRootStore(); - - // Gets the default PEM root certificate. - static const char* GetPemRootCerts(); - - protected: - // Returns default PEM root certificates in nullptr terminated grpc_slice. - // This function is protected instead of private, so that it can be tested. - static grpc_slice ComputePemRootCerts(); - - private: - // Construct me not! - DefaultSslRootStore(); - - // Initialization of default SSL root store. - static void InitRootStore(); - - // One-time initialization of default SSL root store. - static void InitRootStoreOnce(); - - // SSL root store in tsi_ssl_root_certs_store object. - static tsi_ssl_root_certs_store* default_root_store_; - - // Default PEM root certificates. - static grpc_slice default_pem_root_certs_; -}; - -class PemKeyCertPair { - public: - // Construct from the C struct. We steal its members and then immediately - // free it. - explicit PemKeyCertPair(grpc_ssl_pem_key_cert_pair* pair) - : private_key_(const_cast<char*>(pair->private_key)), - cert_chain_(const_cast<char*>(pair->cert_chain)) { - gpr_free(pair); - } - - // Movable. - PemKeyCertPair(PemKeyCertPair&& other) { - private_key_ = std::move(other.private_key_); - cert_chain_ = std::move(other.cert_chain_); - } - PemKeyCertPair& operator=(PemKeyCertPair&& other) { - private_key_ = std::move(other.private_key_); - cert_chain_ = std::move(other.cert_chain_); - return *this; - } - + +/* --- Default SSL Root Store. --- */ +namespace grpc_core { + +// The class implements default SSL root store. +class DefaultSslRootStore { + public: + // Gets the default SSL root store. Returns nullptr if not found. + static const tsi_ssl_root_certs_store* GetRootStore(); + + // Gets the default PEM root certificate. + static const char* GetPemRootCerts(); + + protected: + // Returns default PEM root certificates in nullptr terminated grpc_slice. + // This function is protected instead of private, so that it can be tested. + static grpc_slice ComputePemRootCerts(); + + private: + // Construct me not! + DefaultSslRootStore(); + + // Initialization of default SSL root store. + static void InitRootStore(); + + // One-time initialization of default SSL root store. + static void InitRootStoreOnce(); + + // SSL root store in tsi_ssl_root_certs_store object. + static tsi_ssl_root_certs_store* default_root_store_; + + // Default PEM root certificates. + static grpc_slice default_pem_root_certs_; +}; + +class PemKeyCertPair { + public: + // Construct from the C struct. We steal its members and then immediately + // free it. + explicit PemKeyCertPair(grpc_ssl_pem_key_cert_pair* pair) + : private_key_(const_cast<char*>(pair->private_key)), + cert_chain_(const_cast<char*>(pair->cert_chain)) { + gpr_free(pair); + } + + // Movable. + PemKeyCertPair(PemKeyCertPair&& other) { + private_key_ = std::move(other.private_key_); + cert_chain_ = std::move(other.cert_chain_); + } + PemKeyCertPair& operator=(PemKeyCertPair&& other) { + private_key_ = std::move(other.private_key_); + cert_chain_ = std::move(other.cert_chain_); + return *this; + } + // Copyable. PemKeyCertPair(const PemKeyCertPair& other) : private_key_(gpr_strdup(other.private_key())), @@ -173,21 +173,21 @@ class PemKeyCertPair { cert_chain_ = grpc_core::UniquePtr<char>(gpr_strdup(other.cert_chain())); return *this; } - + bool operator==(const PemKeyCertPair& other) const { return std::strcmp(this->private_key(), other.private_key()) == 0 && std::strcmp(this->cert_chain(), other.cert_chain()) == 0; } - char* private_key() const { return private_key_.get(); } - char* cert_chain() const { return cert_chain_.get(); } - - private: - grpc_core::UniquePtr<char> private_key_; - grpc_core::UniquePtr<char> cert_chain_; -}; - -} // namespace grpc_core - -#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H \ - */ + char* private_key() const { return private_key_.get(); } + char* cert_chain() const { return cert_chain_.get(); } + + private: + grpc_core::UniquePtr<char> private_key_; + grpc_core::UniquePtr<char> cert_chain_; +}; + +} // namespace grpc_core + +#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H \ + */ diff --git a/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc b/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc index b1a9d3f938..13bcfe96c9 100644 --- a/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc +++ b/contrib/libs/grpc/src/core/lib/security/transport/client_auth_filter.cc @@ -36,7 +36,7 @@ #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/credentials/credentials.h" #include "src/core/lib/security/security_connector/security_connector.h" -#include "src/core/lib/security/security_connector/ssl_utils.h" +#include "src/core/lib/security/security_connector/ssl_utils.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/surface/call.h" @@ -64,7 +64,7 @@ struct channel_data { /* We can have a per-call credentials. */ struct call_data { - call_data(grpc_call_element* elem, const grpc_call_element_args& args) + call_data(grpc_call_element* elem, const grpc_call_element_args& args) : owning_call(args.call_stack), call_combiner(args.call_combiner) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); GPR_ASSERT(args.context != nullptr); @@ -81,34 +81,34 @@ struct call_data { sec_ctx->auth_context = chand->auth_context->Ref(DEBUG_LOCATION, "client_auth_filter"); } - - // This method is technically the dtor of this class. However, since - // `get_request_metadata_cancel_closure` can run in parallel to - // `destroy_call_elem`, we cannot call the dtor in them. Otherwise, - // fields will be accessed after calling dtor, and msan correctly complains - // that the memory is not initialized. - void destroy() { - grpc_credentials_mdelem_array_destroy(&md_array); - creds.reset(); - grpc_slice_unref_internal(host); - grpc_slice_unref_internal(method); - grpc_auth_metadata_context_reset(&auth_md_context); - } - + + // This method is technically the dtor of this class. However, since + // `get_request_metadata_cancel_closure` can run in parallel to + // `destroy_call_elem`, we cannot call the dtor in them. Otherwise, + // fields will be accessed after calling dtor, and msan correctly complains + // that the memory is not initialized. + void destroy() { + grpc_credentials_mdelem_array_destroy(&md_array); + creds.reset(); + grpc_slice_unref_internal(host); + grpc_slice_unref_internal(method); + grpc_auth_metadata_context_reset(&auth_md_context); + } + grpc_call_stack* owning_call; grpc_core::CallCombiner* call_combiner; - grpc_core::RefCountedPtr<grpc_call_credentials> creds; - grpc_slice host = grpc_empty_slice(); - grpc_slice method = grpc_empty_slice(); + grpc_core::RefCountedPtr<grpc_call_credentials> creds; + grpc_slice host = grpc_empty_slice(); + grpc_slice method = grpc_empty_slice(); /* pollset{_set} bound to this call; if we need to make external network requests, they should be done under a pollset added to this pollset_set so that work can progress when this call wants work to progress */ - grpc_polling_entity* pollent = nullptr; + grpc_polling_entity* pollent = nullptr; grpc_credentials_mdelem_array md_array; - grpc_linked_mdelem md_links[MAX_CREDENTIALS_METADATA_COUNT] = {}; - grpc_auth_metadata_context auth_md_context = - grpc_auth_metadata_context(); // Zero-initialize the C struct. + grpc_linked_mdelem md_links[MAX_CREDENTIALS_METADATA_COUNT] = {}; + grpc_auth_metadata_context auth_md_context = + grpc_auth_metadata_context(); // Zero-initialize the C struct. grpc_closure async_result_closure; grpc_closure check_call_host_cancel_closure; grpc_closure get_request_metadata_cancel_closure; @@ -124,11 +124,11 @@ void grpc_auth_metadata_context_copy(grpc_auth_metadata_context* from, const_cast<grpc_auth_context*>(to->channel_auth_context) ->Ref(DEBUG_LOCATION, "grpc_auth_metadata_context_copy") .release(); - } + } to->service_url = gpr_strdup(from->service_url); to->method_name = gpr_strdup(from->method_name); } - + void grpc_auth_metadata_context_reset( grpc_auth_metadata_context* auth_md_context) { if (auth_md_context->service_url != nullptr) { @@ -139,11 +139,11 @@ void grpc_auth_metadata_context_reset( gpr_free(const_cast<char*>(auth_md_context->method_name)); auth_md_context->method_name = nullptr; } - if (auth_md_context->channel_auth_context != nullptr) { - const_cast<grpc_auth_context*>(auth_md_context->channel_auth_context) - ->Unref(DEBUG_LOCATION, "grpc_auth_metadata_context"); - auth_md_context->channel_auth_context = nullptr; - } + if (auth_md_context->channel_auth_context != nullptr) { + const_cast<grpc_auth_context*>(auth_md_context->channel_auth_context) + ->Unref(DEBUG_LOCATION, "grpc_auth_metadata_context"); + auth_md_context->channel_auth_context = nullptr; + } } static void add_error(grpc_error** combined, grpc_error* error) { @@ -217,10 +217,10 @@ void grpc_auth_metadata_context_build( auth_md_context->service_url = service_url; auth_md_context->method_name = method_name; auth_md_context->channel_auth_context = - auth_context == nullptr - ? nullptr - : auth_context->Ref(DEBUG_LOCATION, "grpc_auth_metadata_context") - .release(); + auth_context == nullptr + ? nullptr + : auth_context->Ref(DEBUG_LOCATION, "grpc_auth_metadata_context") + .release(); gpr_free(service); gpr_free(host_and_port); } @@ -229,8 +229,8 @@ static void cancel_get_request_metadata(void* arg, grpc_error* error) { grpc_call_element* elem = static_cast<grpc_call_element*>(arg); call_data* calld = static_cast<call_data*>(elem->call_data); if (error != GRPC_ERROR_NONE) { - calld->creds->cancel_get_request_metadata(&calld->md_array, - GRPC_ERROR_REF(error)); + calld->creds->cancel_get_request_metadata(&calld->md_array, + GRPC_ERROR_REF(error)); } } @@ -242,7 +242,7 @@ static void send_security_metadata(grpc_call_element* elem, static_cast<grpc_client_security_context*>( batch->payload->context[GRPC_CONTEXT_SECURITY].value); grpc_call_credentials* channel_call_creds = - chand->security_connector->mutable_request_metadata_creds(); + chand->security_connector->mutable_request_metadata_creds(); int call_creds_has_md = (ctx != nullptr) && (ctx->creds != nullptr); if (channel_call_creds == nullptr && !call_creds_has_md) { @@ -252,9 +252,9 @@ static void send_security_metadata(grpc_call_element* elem, } if (channel_call_creds != nullptr && call_creds_has_md) { - calld->creds = grpc_core::RefCountedPtr<grpc_call_credentials>( - grpc_composite_call_credentials_create(channel_call_creds, - ctx->creds.get(), nullptr)); + calld->creds = grpc_core::RefCountedPtr<grpc_call_credentials>( + grpc_composite_call_credentials_create(channel_call_creds, + ctx->creds.get(), nullptr)); if (calld->creds == nullptr) { grpc_transport_stream_op_batch_finish_with_failure( batch, @@ -266,8 +266,8 @@ static void send_security_metadata(grpc_call_element* elem, return; } } else { - calld->creds = - call_creds_has_md ? ctx->creds->Ref() : channel_call_creds->Ref(); + calld->creds = + call_creds_has_md ? ctx->creds->Ref() : channel_call_creds->Ref(); } /* Check security level of call credential and channel, and do not send @@ -304,17 +304,17 @@ static void send_security_metadata(grpc_call_element* elem, } grpc_auth_metadata_context_build( - chand->security_connector->url_scheme(), calld->host, calld->method, - chand->auth_context.get(), &calld->auth_md_context); + chand->security_connector->url_scheme(), calld->host, calld->method, + chand->auth_context.get(), &calld->auth_md_context); GPR_ASSERT(calld->pollent != nullptr); GRPC_CALL_STACK_REF(calld->owning_call, "get_request_metadata"); GRPC_CLOSURE_INIT(&calld->async_result_closure, on_credentials_metadata, batch, grpc_schedule_on_exec_ctx); grpc_error* error = GRPC_ERROR_NONE; - if (calld->creds->get_request_metadata( - calld->pollent, calld->auth_md_context, &calld->md_array, - &calld->async_result_closure, &error)) { + if (calld->creds->get_request_metadata( + calld->pollent, calld->auth_md_context, &calld->md_array, + &calld->async_result_closure, &error)) { // Synchronous return; invoke on_credentials_metadata() directly. on_credentials_metadata(batch, error); GRPC_ERROR_UNREF(error); @@ -353,8 +353,8 @@ static void cancel_check_call_host(void* arg, grpc_error* error) { call_data* calld = static_cast<call_data*>(elem->call_data); channel_data* chand = static_cast<channel_data*>(elem->channel_data); if (error != GRPC_ERROR_NONE) { - chand->security_connector->cancel_check_call_host( - &calld->async_result_closure, GRPC_ERROR_REF(error)); + chand->security_connector->cancel_check_call_host( + &calld->async_result_closure, GRPC_ERROR_REF(error)); } } @@ -382,8 +382,8 @@ static void client_auth_start_transport_stream_op_batch( grpc_schedule_on_exec_ctx); y_absl::string_view call_host(grpc_core::StringViewFromSlice(calld->host)); grpc_error* error = GRPC_ERROR_NONE; - if (chand->security_connector->check_call_host( - call_host, chand->auth_context.get(), + if (chand->security_connector->check_call_host( + call_host, chand->auth_context.get(), &calld->async_result_closure, &error)) { // Synchronous return; invoke on_host_checked() directly. on_host_checked(batch, error); @@ -405,7 +405,7 @@ static void client_auth_start_transport_stream_op_batch( /* Constructor for call_data */ static grpc_error* client_auth_init_call_elem( grpc_call_element* elem, const grpc_call_element_args* args) { - new (elem->call_data) call_data(elem, *args); + new (elem->call_data) call_data(elem, *args); return GRPC_ERROR_NONE; } @@ -420,16 +420,16 @@ static void client_auth_destroy_call_elem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { call_data* calld = static_cast<call_data*>(elem->call_data); - calld->destroy(); + calld->destroy(); } /* Constructor for channel_data */ static grpc_error* client_auth_init_channel_elem( grpc_channel_element* elem, grpc_channel_element_args* args) { - /* The first and the last filters tend to be implemented differently to - handle the case that there's no 'next' filter to call on the up or down - path */ - GPR_ASSERT(!args->is_last); + /* The first and the last filters tend to be implemented differently to + handle the case that there's no 'next' filter to call on the up or down + path */ + GPR_ASSERT(!args->is_last); grpc_security_connector* sc = grpc_security_connector_find_in_args(args->channel_args); if (sc == nullptr) { @@ -442,15 +442,15 @@ static grpc_error* client_auth_init_channel_elem( return GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Auth context missing from client auth filter args"); } - new (elem->channel_data) channel_data( - static_cast<grpc_channel_security_connector*>(sc), auth_context); + new (elem->channel_data) channel_data( + static_cast<grpc_channel_security_connector*>(sc), auth_context); return GRPC_ERROR_NONE; } /* Destructor for channel data */ static void client_auth_destroy_channel_elem(grpc_channel_element* elem) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); - chand->~channel_data(); + chand->~channel_data(); } const grpc_channel_filter grpc_client_auth_filter = { diff --git a/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc b/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc index e79184fac1..7109deb541 100644 --- a/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc +++ b/contrib/libs/grpc/src/core/lib/security/transport/secure_endpoint.cc @@ -22,8 +22,8 @@ headers. Therefore, sockaddr.h must always be included first */ #include <grpc/support/port_platform.h> -#include <new> - +#include <new> + #include "src/core/lib/iomgr/sockaddr.h" #include <grpc/slice.h> @@ -33,7 +33,7 @@ #include <grpc/support/sync.h> #include "src/core/lib/debug/trace.h" #include "src/core/lib/gpr/string.h" -#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/gprpp/memory.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/security/transport/secure_endpoint.h" #include "src/core/lib/security/transport/tsi_error.h" @@ -43,64 +43,64 @@ #define STAGING_BUFFER_SIZE 8192 -static void on_read(void* user_data, grpc_error* error); - -namespace { -struct secure_endpoint { - secure_endpoint(const grpc_endpoint_vtable* vtable, - tsi_frame_protector* protector, - tsi_zero_copy_grpc_protector* zero_copy_protector, - grpc_endpoint* transport, grpc_slice* leftover_slices, - size_t leftover_nslices) - : wrapped_ep(transport), - protector(protector), - zero_copy_protector(zero_copy_protector) { - base.vtable = vtable; - gpr_mu_init(&protector_mu); - GRPC_CLOSURE_INIT(&on_read, ::on_read, this, grpc_schedule_on_exec_ctx); - grpc_slice_buffer_init(&source_buffer); - grpc_slice_buffer_init(&leftover_bytes); - for (size_t i = 0; i < leftover_nslices; i++) { - grpc_slice_buffer_add(&leftover_bytes, - grpc_slice_ref_internal(leftover_slices[i])); - } - grpc_slice_buffer_init(&output_buffer); - gpr_ref_init(&ref, 1); - } - - ~secure_endpoint() { - grpc_endpoint_destroy(wrapped_ep); - tsi_frame_protector_destroy(protector); - tsi_zero_copy_grpc_protector_destroy(zero_copy_protector); - grpc_slice_buffer_destroy_internal(&source_buffer); - grpc_slice_buffer_destroy_internal(&leftover_bytes); - grpc_slice_unref_internal(read_staging_buffer); - grpc_slice_unref_internal(write_staging_buffer); - grpc_slice_buffer_destroy_internal(&output_buffer); - gpr_mu_destroy(&protector_mu); - } - +static void on_read(void* user_data, grpc_error* error); + +namespace { +struct secure_endpoint { + secure_endpoint(const grpc_endpoint_vtable* vtable, + tsi_frame_protector* protector, + tsi_zero_copy_grpc_protector* zero_copy_protector, + grpc_endpoint* transport, grpc_slice* leftover_slices, + size_t leftover_nslices) + : wrapped_ep(transport), + protector(protector), + zero_copy_protector(zero_copy_protector) { + base.vtable = vtable; + gpr_mu_init(&protector_mu); + GRPC_CLOSURE_INIT(&on_read, ::on_read, this, grpc_schedule_on_exec_ctx); + grpc_slice_buffer_init(&source_buffer); + grpc_slice_buffer_init(&leftover_bytes); + for (size_t i = 0; i < leftover_nslices; i++) { + grpc_slice_buffer_add(&leftover_bytes, + grpc_slice_ref_internal(leftover_slices[i])); + } + grpc_slice_buffer_init(&output_buffer); + gpr_ref_init(&ref, 1); + } + + ~secure_endpoint() { + grpc_endpoint_destroy(wrapped_ep); + tsi_frame_protector_destroy(protector); + tsi_zero_copy_grpc_protector_destroy(zero_copy_protector); + grpc_slice_buffer_destroy_internal(&source_buffer); + grpc_slice_buffer_destroy_internal(&leftover_bytes); + grpc_slice_unref_internal(read_staging_buffer); + grpc_slice_unref_internal(write_staging_buffer); + grpc_slice_buffer_destroy_internal(&output_buffer); + gpr_mu_destroy(&protector_mu); + } + grpc_endpoint base; grpc_endpoint* wrapped_ep; struct tsi_frame_protector* protector; struct tsi_zero_copy_grpc_protector* zero_copy_protector; gpr_mu protector_mu; /* saved upper level callbacks and user_data. */ - grpc_closure* read_cb = nullptr; - grpc_closure* write_cb = nullptr; + grpc_closure* read_cb = nullptr; + grpc_closure* write_cb = nullptr; grpc_closure on_read; - grpc_slice_buffer* read_buffer = nullptr; + grpc_slice_buffer* read_buffer = nullptr; grpc_slice_buffer source_buffer; /* saved handshaker leftover data to unprotect. */ grpc_slice_buffer leftover_bytes; /* buffers for read and write */ - grpc_slice read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); - grpc_slice write_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); + grpc_slice read_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); + grpc_slice write_staging_buffer = GRPC_SLICE_MALLOC(STAGING_BUFFER_SIZE); grpc_slice_buffer output_buffer; gpr_refcount ref; -}; -} // namespace +}; +} // namespace grpc_core::TraceFlag grpc_trace_secure_endpoint(false, "secure_endpoint"); @@ -281,7 +281,7 @@ static void flush_write_staging_buffer(secure_endpoint* ep, uint8_t** cur, } static void endpoint_write(grpc_endpoint* secure_ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* arg) { + grpc_closure* cb, void* arg) { GPR_TIMER_SCOPE("secure_endpoint.endpoint_write", 0); unsigned i; @@ -370,7 +370,7 @@ static void endpoint_write(grpc_endpoint* secure_ep, grpc_slice_buffer* slices, return; } - grpc_endpoint_write(ep->wrapped_ep, &ep->output_buffer, cb, arg); + grpc_endpoint_write(ep->wrapped_ep, &ep->output_buffer, cb, arg); } static void endpoint_shutdown(grpc_endpoint* secure_ep, grpc_error* why) { @@ -422,11 +422,11 @@ static grpc_resource_user* endpoint_get_resource_user( return grpc_endpoint_get_resource_user(ep->wrapped_ep); } -static bool endpoint_can_track_err(grpc_endpoint* secure_ep) { - secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep); - return grpc_endpoint_can_track_err(ep->wrapped_ep); -} - +static bool endpoint_can_track_err(grpc_endpoint* secure_ep) { + secure_endpoint* ep = reinterpret_cast<secure_endpoint*>(secure_ep); + return grpc_endpoint_can_track_err(ep->wrapped_ep); +} + static const grpc_endpoint_vtable vtable = {endpoint_read, endpoint_write, endpoint_add_to_pollset, @@ -437,8 +437,8 @@ static const grpc_endpoint_vtable vtable = {endpoint_read, endpoint_get_resource_user, endpoint_get_peer, endpoint_get_local_address, - endpoint_get_fd, - endpoint_can_track_err}; + endpoint_get_fd, + endpoint_can_track_err}; grpc_endpoint* grpc_secure_endpoint_create( struct tsi_frame_protector* protector, diff --git a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc index 079b49c95a..d4a1baddd4 100644 --- a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc +++ b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.cc @@ -31,7 +31,7 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/channel/handshaker_registry.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/security/context/security_context.h" #include "src/core/lib/security/transport/secure_endpoint.h" #include "src/core/lib/security/transport/tsi_error.h" @@ -40,118 +40,118 @@ #define GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE 256 -namespace grpc_core { +namespace grpc_core { -namespace { - -class SecurityHandshaker : public Handshaker { - public: - SecurityHandshaker(tsi_handshaker* handshaker, +namespace { + +class SecurityHandshaker : public Handshaker { + public: + SecurityHandshaker(tsi_handshaker* handshaker, grpc_security_connector* connector, const grpc_channel_args* args); - ~SecurityHandshaker() override; - void Shutdown(grpc_error* why) override; - void DoHandshake(grpc_tcp_server_acceptor* acceptor, - grpc_closure* on_handshake_done, - HandshakerArgs* args) override; - const char* name() const override { return "security"; } - - private: - grpc_error* DoHandshakerNextLocked(const unsigned char* bytes_received, - size_t bytes_received_size); - - grpc_error* OnHandshakeNextDoneLocked( - tsi_result result, const unsigned char* bytes_to_send, - size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result); - void HandshakeFailedLocked(grpc_error* error); - void CleanupArgsForFailureLocked(); - - static void OnHandshakeDataReceivedFromPeerFn(void* arg, grpc_error* error); - static void OnHandshakeDataSentToPeerFn(void* arg, grpc_error* error); + ~SecurityHandshaker() override; + void Shutdown(grpc_error* why) override; + void DoHandshake(grpc_tcp_server_acceptor* acceptor, + grpc_closure* on_handshake_done, + HandshakerArgs* args) override; + const char* name() const override { return "security"; } + + private: + grpc_error* DoHandshakerNextLocked(const unsigned char* bytes_received, + size_t bytes_received_size); + + grpc_error* OnHandshakeNextDoneLocked( + tsi_result result, const unsigned char* bytes_to_send, + size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result); + void HandshakeFailedLocked(grpc_error* error); + void CleanupArgsForFailureLocked(); + + static void OnHandshakeDataReceivedFromPeerFn(void* arg, grpc_error* error); + static void OnHandshakeDataSentToPeerFn(void* arg, grpc_error* error); static void OnHandshakeDataReceivedFromPeerFnScheduler(void* arg, grpc_error* error); static void OnHandshakeDataSentToPeerFnScheduler(void* arg, grpc_error* error); - static void OnHandshakeNextDoneGrpcWrapper( - tsi_result result, void* user_data, const unsigned char* bytes_to_send, - size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result); - static void OnPeerCheckedFn(void* arg, grpc_error* error); - void OnPeerCheckedInner(grpc_error* error); - size_t MoveReadBufferIntoHandshakeBuffer(); - grpc_error* CheckPeerLocked(); - + static void OnHandshakeNextDoneGrpcWrapper( + tsi_result result, void* user_data, const unsigned char* bytes_to_send, + size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result); + static void OnPeerCheckedFn(void* arg, grpc_error* error); + void OnPeerCheckedInner(grpc_error* error); + size_t MoveReadBufferIntoHandshakeBuffer(); + grpc_error* CheckPeerLocked(); + // State set at creation time. - tsi_handshaker* handshaker_; - RefCountedPtr<grpc_security_connector> connector_; + tsi_handshaker* handshaker_; + RefCountedPtr<grpc_security_connector> connector_; - gpr_mu mu_; + gpr_mu mu_; - bool is_shutdown_ = false; + bool is_shutdown_ = false; // Endpoint and read buffer to destroy after a shutdown. - grpc_endpoint* endpoint_to_destroy_ = nullptr; - grpc_slice_buffer* read_buffer_to_destroy_ = nullptr; + grpc_endpoint* endpoint_to_destroy_ = nullptr; + grpc_slice_buffer* read_buffer_to_destroy_ = nullptr; // State saved while performing the handshake. - HandshakerArgs* args_ = nullptr; - grpc_closure* on_handshake_done_ = nullptr; - - size_t handshake_buffer_size_; - unsigned char* handshake_buffer_; - grpc_slice_buffer outgoing_; - grpc_closure on_handshake_data_sent_to_peer_; - grpc_closure on_handshake_data_received_from_peer_; - grpc_closure on_peer_checked_; - RefCountedPtr<grpc_auth_context> auth_context_; - tsi_handshaker_result* handshaker_result_ = nullptr; + HandshakerArgs* args_ = nullptr; + grpc_closure* on_handshake_done_ = nullptr; + + size_t handshake_buffer_size_; + unsigned char* handshake_buffer_; + grpc_slice_buffer outgoing_; + grpc_closure on_handshake_data_sent_to_peer_; + grpc_closure on_handshake_data_received_from_peer_; + grpc_closure on_peer_checked_; + RefCountedPtr<grpc_auth_context> auth_context_; + tsi_handshaker_result* handshaker_result_ = nullptr; size_t max_frame_size_ = 0; -}; +}; -SecurityHandshaker::SecurityHandshaker(tsi_handshaker* handshaker, +SecurityHandshaker::SecurityHandshaker(tsi_handshaker* handshaker, grpc_security_connector* connector, const grpc_channel_args* args) - : handshaker_(handshaker), - connector_(connector->Ref(DEBUG_LOCATION, "handshake")), - handshake_buffer_size_(GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE), - handshake_buffer_( - static_cast<uint8_t*>(gpr_malloc(handshake_buffer_size_))) { + : handshaker_(handshaker), + connector_(connector->Ref(DEBUG_LOCATION, "handshake")), + handshake_buffer_size_(GRPC_INITIAL_HANDSHAKE_BUFFER_SIZE), + handshake_buffer_( + static_cast<uint8_t*>(gpr_malloc(handshake_buffer_size_))) { const grpc_arg* arg = grpc_channel_args_find(args, GRPC_ARG_TSI_MAX_FRAME_SIZE); if (arg != nullptr && arg->type == GRPC_ARG_INTEGER) { max_frame_size_ = grpc_channel_arg_get_integer( arg, {0, 0, std::numeric_limits<int>::max()}); } - gpr_mu_init(&mu_); - grpc_slice_buffer_init(&outgoing_); - GRPC_CLOSURE_INIT(&on_peer_checked_, &SecurityHandshaker::OnPeerCheckedFn, - this, grpc_schedule_on_exec_ctx); -} - -SecurityHandshaker::~SecurityHandshaker() { - gpr_mu_destroy(&mu_); - tsi_handshaker_destroy(handshaker_); - tsi_handshaker_result_destroy(handshaker_result_); - if (endpoint_to_destroy_ != nullptr) { - grpc_endpoint_destroy(endpoint_to_destroy_); - } - if (read_buffer_to_destroy_ != nullptr) { - grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_); - gpr_free(read_buffer_to_destroy_); - } - gpr_free(handshake_buffer_); - grpc_slice_buffer_destroy_internal(&outgoing_); - auth_context_.reset(DEBUG_LOCATION, "handshake"); - connector_.reset(DEBUG_LOCATION, "handshake"); -} - -size_t SecurityHandshaker::MoveReadBufferIntoHandshakeBuffer() { - size_t bytes_in_read_buffer = args_->read_buffer->length; - if (handshake_buffer_size_ < bytes_in_read_buffer) { - handshake_buffer_ = static_cast<uint8_t*>( - gpr_realloc(handshake_buffer_, bytes_in_read_buffer)); - handshake_buffer_size_ = bytes_in_read_buffer; + gpr_mu_init(&mu_); + grpc_slice_buffer_init(&outgoing_); + GRPC_CLOSURE_INIT(&on_peer_checked_, &SecurityHandshaker::OnPeerCheckedFn, + this, grpc_schedule_on_exec_ctx); +} + +SecurityHandshaker::~SecurityHandshaker() { + gpr_mu_destroy(&mu_); + tsi_handshaker_destroy(handshaker_); + tsi_handshaker_result_destroy(handshaker_result_); + if (endpoint_to_destroy_ != nullptr) { + grpc_endpoint_destroy(endpoint_to_destroy_); } + if (read_buffer_to_destroy_ != nullptr) { + grpc_slice_buffer_destroy_internal(read_buffer_to_destroy_); + gpr_free(read_buffer_to_destroy_); + } + gpr_free(handshake_buffer_); + grpc_slice_buffer_destroy_internal(&outgoing_); + auth_context_.reset(DEBUG_LOCATION, "handshake"); + connector_.reset(DEBUG_LOCATION, "handshake"); +} + +size_t SecurityHandshaker::MoveReadBufferIntoHandshakeBuffer() { + size_t bytes_in_read_buffer = args_->read_buffer->length; + if (handshake_buffer_size_ < bytes_in_read_buffer) { + handshake_buffer_ = static_cast<uint8_t*>( + gpr_realloc(handshake_buffer_, bytes_in_read_buffer)); + handshake_buffer_size_ = bytes_in_read_buffer; + } size_t offset = 0; - while (args_->read_buffer->count > 0) { + while (args_->read_buffer->count > 0) { grpc_slice* next_slice = grpc_slice_buffer_peek_first(args_->read_buffer); memcpy(handshake_buffer_ + offset, GRPC_SLICE_START_PTR(*next_slice), GRPC_SLICE_LENGTH(*next_slice)); @@ -161,20 +161,20 @@ size_t SecurityHandshaker::MoveReadBufferIntoHandshakeBuffer() { return bytes_in_read_buffer; } -// Set args_ fields to NULL, saving the endpoint and read buffer for +// Set args_ fields to NULL, saving the endpoint and read buffer for // later destruction. -void SecurityHandshaker::CleanupArgsForFailureLocked() { - endpoint_to_destroy_ = args_->endpoint; - args_->endpoint = nullptr; - read_buffer_to_destroy_ = args_->read_buffer; - args_->read_buffer = nullptr; - grpc_channel_args_destroy(args_->args); - args_->args = nullptr; +void SecurityHandshaker::CleanupArgsForFailureLocked() { + endpoint_to_destroy_ = args_->endpoint; + args_->endpoint = nullptr; + read_buffer_to_destroy_ = args_->read_buffer; + args_->read_buffer = nullptr; + grpc_channel_args_destroy(args_->args); + args_->args = nullptr; } // If the handshake failed or we're shutting down, clean up and invoke the // callback with the error. -void SecurityHandshaker::HandshakeFailedLocked(grpc_error* error) { +void SecurityHandshaker::HandshakeFailedLocked(grpc_error* error) { if (error == GRPC_ERROR_NONE) { // If we were shut down after the handshake succeeded but before an // endpoint callback was invoked, we need to generate our own error. @@ -183,27 +183,27 @@ void SecurityHandshaker::HandshakeFailedLocked(grpc_error* error) { const char* msg = grpc_error_string(error); gpr_log(GPR_DEBUG, "Security handshake failed: %s", msg); - if (!is_shutdown_) { + if (!is_shutdown_) { tsi_handshaker_shutdown(handshaker_); // TODO(ctiller): It is currently necessary to shutdown endpoints // before destroying them, even if we know that there are no // pending read/write callbacks. This should be fixed, at which // point this can be removed. - grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(error)); + grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(error)); // Not shutting down, so the write failed. Clean up before // invoking the callback. - CleanupArgsForFailureLocked(); + CleanupArgsForFailureLocked(); // Set shutdown to true so that subsequent calls to // security_handshaker_shutdown() do nothing. - is_shutdown_ = true; + is_shutdown_ = true; } // Invoke callback. ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, error); } -void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) { - MutexLock lock(&mu_); - if (error != GRPC_ERROR_NONE || is_shutdown_) { +void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) { + MutexLock lock(&mu_); + if (error != GRPC_ERROR_NONE || is_shutdown_) { HandshakeFailedLocked(error); return; } @@ -217,7 +217,7 @@ void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) { GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Zero-copy frame protector creation failed"), result); - HandshakeFailedLocked(error); + HandshakeFailedLocked(error); return; } // Create frame protector if zero-copy frame protector is NULL. @@ -230,7 +230,7 @@ void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) { error = grpc_set_tsi_error_result(GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Frame protector creation failed"), result); - HandshakeFailedLocked(error); + HandshakeFailedLocked(error); return; } } @@ -238,56 +238,56 @@ void SecurityHandshaker::OnPeerCheckedInner(grpc_error* error) { const unsigned char* unused_bytes = nullptr; size_t unused_bytes_size = 0; result = tsi_handshaker_result_get_unused_bytes( - handshaker_result_, &unused_bytes, &unused_bytes_size); + handshaker_result_, &unused_bytes, &unused_bytes_size); // Create secure endpoint. if (unused_bytes_size > 0) { grpc_slice slice = grpc_slice_from_copied_buffer((char*)unused_bytes, unused_bytes_size); - args_->endpoint = grpc_secure_endpoint_create( - protector, zero_copy_protector, args_->endpoint, &slice, 1); + args_->endpoint = grpc_secure_endpoint_create( + protector, zero_copy_protector, args_->endpoint, &slice, 1); grpc_slice_unref_internal(slice); } else { - args_->endpoint = grpc_secure_endpoint_create( - protector, zero_copy_protector, args_->endpoint, nullptr, 0); + args_->endpoint = grpc_secure_endpoint_create( + protector, zero_copy_protector, args_->endpoint, nullptr, 0); } - tsi_handshaker_result_destroy(handshaker_result_); - handshaker_result_ = nullptr; + tsi_handshaker_result_destroy(handshaker_result_); + handshaker_result_ = nullptr; // Add auth context to channel args. - grpc_arg auth_context_arg = grpc_auth_context_to_arg(auth_context_.get()); - grpc_channel_args* tmp_args = args_->args; - args_->args = grpc_channel_args_copy_and_add(tmp_args, &auth_context_arg, 1); + grpc_arg auth_context_arg = grpc_auth_context_to_arg(auth_context_.get()); + grpc_channel_args* tmp_args = args_->args; + args_->args = grpc_channel_args_copy_and_add(tmp_args, &auth_context_arg, 1); grpc_channel_args_destroy(tmp_args); // Invoke callback. ExecCtx::Run(DEBUG_LOCATION, on_handshake_done_, GRPC_ERROR_NONE); // Set shutdown to true so that subsequent calls to // security_handshaker_shutdown() do nothing. - is_shutdown_ = true; + is_shutdown_ = true; } -void SecurityHandshaker::OnPeerCheckedFn(void* arg, grpc_error* error) { - RefCountedPtr<SecurityHandshaker>(static_cast<SecurityHandshaker*>(arg)) +void SecurityHandshaker::OnPeerCheckedFn(void* arg, grpc_error* error) { + RefCountedPtr<SecurityHandshaker>(static_cast<SecurityHandshaker*>(arg)) ->OnPeerCheckedInner(GRPC_ERROR_REF(error)); } -grpc_error* SecurityHandshaker::CheckPeerLocked() { +grpc_error* SecurityHandshaker::CheckPeerLocked() { tsi_peer peer; tsi_result result = - tsi_handshaker_result_extract_peer(handshaker_result_, &peer); + tsi_handshaker_result_extract_peer(handshaker_result_, &peer); if (result != TSI_OK) { return grpc_set_tsi_error_result( GRPC_ERROR_CREATE_FROM_STATIC_STRING("Peer extraction failed"), result); } - connector_->check_peer(peer, args_->endpoint, &auth_context_, - &on_peer_checked_); + connector_->check_peer(peer, args_->endpoint, &auth_context_, + &on_peer_checked_); return GRPC_ERROR_NONE; } -grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked( - tsi_result result, const unsigned char* bytes_to_send, - size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) { +grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked( + tsi_result result, const unsigned char* bytes_to_send, + size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) { grpc_error* error = GRPC_ERROR_NONE; // Handshaker was shutdown. - if (is_shutdown_) { + if (is_shutdown_) { return GRPC_ERROR_CREATE_FROM_STATIC_STRING("Handshaker shutdown"); } // Read more if we need to. @@ -308,15 +308,15 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked( } // Update handshaker result. if (handshaker_result != nullptr) { - GPR_ASSERT(handshaker_result_ == nullptr); - handshaker_result_ = handshaker_result; + GPR_ASSERT(handshaker_result_ == nullptr); + handshaker_result_ = handshaker_result; } if (bytes_to_send_size > 0) { // Send data to peer, if needed. grpc_slice to_send = grpc_slice_from_copied_buffer( reinterpret_cast<const char*>(bytes_to_send), bytes_to_send_size); - grpc_slice_buffer_reset_and_unref_internal(&outgoing_); - grpc_slice_buffer_add(&outgoing_, to_send); + grpc_slice_buffer_reset_and_unref_internal(&outgoing_); + grpc_slice_buffer_add(&outgoing_, to_send); grpc_endpoint_write( args_->endpoint, &outgoing_, GRPC_CLOSURE_INIT( @@ -335,35 +335,35 @@ grpc_error* SecurityHandshaker::OnHandshakeNextDoneLocked( /*urgent=*/true); } else { // Handshake has finished, check peer and so on. - error = CheckPeerLocked(); + error = CheckPeerLocked(); } return error; } -void SecurityHandshaker::OnHandshakeNextDoneGrpcWrapper( +void SecurityHandshaker::OnHandshakeNextDoneGrpcWrapper( tsi_result result, void* user_data, const unsigned char* bytes_to_send, size_t bytes_to_send_size, tsi_handshaker_result* handshaker_result) { - RefCountedPtr<SecurityHandshaker> h( - static_cast<SecurityHandshaker*>(user_data)); - MutexLock lock(&h->mu_); - grpc_error* error = h->OnHandshakeNextDoneLocked( - result, bytes_to_send, bytes_to_send_size, handshaker_result); + RefCountedPtr<SecurityHandshaker> h( + static_cast<SecurityHandshaker*>(user_data)); + MutexLock lock(&h->mu_); + grpc_error* error = h->OnHandshakeNextDoneLocked( + result, bytes_to_send, bytes_to_send_size, handshaker_result); if (error != GRPC_ERROR_NONE) { - h->HandshakeFailedLocked(error); + h->HandshakeFailedLocked(error); } else { - h.release(); // Avoid unref + h.release(); // Avoid unref } } -grpc_error* SecurityHandshaker::DoHandshakerNextLocked( - const unsigned char* bytes_received, size_t bytes_received_size) { +grpc_error* SecurityHandshaker::DoHandshakerNextLocked( + const unsigned char* bytes_received, size_t bytes_received_size) { // Invoke TSI handshaker. const unsigned char* bytes_to_send = nullptr; size_t bytes_to_send_size = 0; - tsi_handshaker_result* hs_result = nullptr; + tsi_handshaker_result* hs_result = nullptr; tsi_result result = tsi_handshaker_next( - handshaker_, bytes_received, bytes_received_size, &bytes_to_send, - &bytes_to_send_size, &hs_result, &OnHandshakeNextDoneGrpcWrapper, this); + handshaker_, bytes_received, bytes_received_size, &bytes_to_send, + &bytes_to_send_size, &hs_result, &OnHandshakeNextDoneGrpcWrapper, this); if (result == TSI_ASYNC) { // Handshaker operating asynchronously. Nothing else to do here; // callback will be invoked in a TSI thread. @@ -371,8 +371,8 @@ grpc_error* SecurityHandshaker::DoHandshakerNextLocked( } // Handshaker returned synchronously. Invoke callback directly in // this thread with our existing exec_ctx. - return OnHandshakeNextDoneLocked(result, bytes_to_send, bytes_to_send_size, - hs_result); + return OnHandshakeNextDoneLocked(result, bytes_to_send, bytes_to_send_size, + hs_result); } // This callback might be run inline while we are still holding on to the mutex, @@ -388,24 +388,24 @@ void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFnScheduler( GRPC_ERROR_REF(error)); } -void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn(void* arg, - grpc_error* error) { - RefCountedPtr<SecurityHandshaker> h(static_cast<SecurityHandshaker*>(arg)); - MutexLock lock(&h->mu_); - if (error != GRPC_ERROR_NONE || h->is_shutdown_) { - h->HandshakeFailedLocked(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Handshake read failed", &error, 1)); +void SecurityHandshaker::OnHandshakeDataReceivedFromPeerFn(void* arg, + grpc_error* error) { + RefCountedPtr<SecurityHandshaker> h(static_cast<SecurityHandshaker*>(arg)); + MutexLock lock(&h->mu_); + if (error != GRPC_ERROR_NONE || h->is_shutdown_) { + h->HandshakeFailedLocked(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + "Handshake read failed", &error, 1)); return; } // Copy all slices received. - size_t bytes_received_size = h->MoveReadBufferIntoHandshakeBuffer(); + size_t bytes_received_size = h->MoveReadBufferIntoHandshakeBuffer(); // Call TSI handshaker. - error = h->DoHandshakerNextLocked(h->handshake_buffer_, bytes_received_size); + error = h->DoHandshakerNextLocked(h->handshake_buffer_, bytes_received_size); if (error != GRPC_ERROR_NONE) { - h->HandshakeFailedLocked(error); + h->HandshakeFailedLocked(error); } else { - h.release(); // Avoid unref + h.release(); // Avoid unref } } @@ -422,17 +422,17 @@ void SecurityHandshaker::OnHandshakeDataSentToPeerFnScheduler( GRPC_ERROR_REF(error)); } -void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg, - grpc_error* error) { - RefCountedPtr<SecurityHandshaker> h(static_cast<SecurityHandshaker*>(arg)); - MutexLock lock(&h->mu_); - if (error != GRPC_ERROR_NONE || h->is_shutdown_) { - h->HandshakeFailedLocked(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Handshake write failed", &error, 1)); +void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg, + grpc_error* error) { + RefCountedPtr<SecurityHandshaker> h(static_cast<SecurityHandshaker*>(arg)); + MutexLock lock(&h->mu_); + if (error != GRPC_ERROR_NONE || h->is_shutdown_) { + h->HandshakeFailedLocked(GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + "Handshake write failed", &error, 1)); return; } // We may be done. - if (h->handshaker_result_ == nullptr) { + if (h->handshaker_result_ == nullptr) { grpc_endpoint_read( h->args_->endpoint, h->args_->read_buffer, GRPC_CLOSURE_INIT( @@ -441,134 +441,134 @@ void SecurityHandshaker::OnHandshakeDataSentToPeerFn(void* arg, h.get(), grpc_schedule_on_exec_ctx), /*urgent=*/true); } else { - error = h->CheckPeerLocked(); + error = h->CheckPeerLocked(); if (error != GRPC_ERROR_NONE) { - h->HandshakeFailedLocked(error); + h->HandshakeFailedLocked(error); return; } } - h.release(); // Avoid unref + h.release(); // Avoid unref } // // public handshaker API // -void SecurityHandshaker::Shutdown(grpc_error* why) { - MutexLock lock(&mu_); - if (!is_shutdown_) { - is_shutdown_ = true; - tsi_handshaker_shutdown(handshaker_); - grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why)); - CleanupArgsForFailureLocked(); +void SecurityHandshaker::Shutdown(grpc_error* why) { + MutexLock lock(&mu_); + if (!is_shutdown_) { + is_shutdown_ = true; + tsi_handshaker_shutdown(handshaker_); + grpc_endpoint_shutdown(args_->endpoint, GRPC_ERROR_REF(why)); + CleanupArgsForFailureLocked(); } GRPC_ERROR_UNREF(why); } void SecurityHandshaker::DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, - grpc_closure* on_handshake_done, - HandshakerArgs* args) { - auto ref = Ref(); - MutexLock lock(&mu_); - args_ = args; - on_handshake_done_ = on_handshake_done; - size_t bytes_received_size = MoveReadBufferIntoHandshakeBuffer(); + grpc_closure* on_handshake_done, + HandshakerArgs* args) { + auto ref = Ref(); + MutexLock lock(&mu_); + args_ = args; + on_handshake_done_ = on_handshake_done; + size_t bytes_received_size = MoveReadBufferIntoHandshakeBuffer(); grpc_error* error = - DoHandshakerNextLocked(handshake_buffer_, bytes_received_size); + DoHandshakerNextLocked(handshake_buffer_, bytes_received_size); if (error != GRPC_ERROR_NONE) { - HandshakeFailedLocked(error); - } else { - ref.release(); // Avoid unref + HandshakeFailedLocked(error); + } else { + ref.release(); // Avoid unref } } // -// FailHandshaker +// FailHandshaker // -class FailHandshaker : public Handshaker { - public: - const char* name() const override { return "security_fail"; } - void Shutdown(grpc_error* why) override { GRPC_ERROR_UNREF(why); } +class FailHandshaker : public Handshaker { + public: + const char* name() const override { return "security_fail"; } + void Shutdown(grpc_error* why) override { GRPC_ERROR_UNREF(why); } void DoHandshake(grpc_tcp_server_acceptor* /*acceptor*/, - grpc_closure* on_handshake_done, + grpc_closure* on_handshake_done, HandshakerArgs* /*args*/) override { ExecCtx::Run(DEBUG_LOCATION, on_handshake_done, GRPC_ERROR_CREATE_FROM_STATIC_STRING( "Failed to create security handshaker")); - } + } - private: - virtual ~FailHandshaker() = default; -}; + private: + virtual ~FailHandshaker() = default; +}; // // handshaker factories // -class ClientSecurityHandshakerFactory : public HandshakerFactory { - public: - void AddHandshakers(const grpc_channel_args* args, - grpc_pollset_set* interested_parties, - HandshakeManager* handshake_mgr) override { - auto* security_connector = - reinterpret_cast<grpc_channel_security_connector*>( - grpc_security_connector_find_in_args(args)); - if (security_connector) { +class ClientSecurityHandshakerFactory : public HandshakerFactory { + public: + void AddHandshakers(const grpc_channel_args* args, + grpc_pollset_set* interested_parties, + HandshakeManager* handshake_mgr) override { + auto* security_connector = + reinterpret_cast<grpc_channel_security_connector*>( + grpc_security_connector_find_in_args(args)); + if (security_connector) { security_connector->add_handshakers(args, interested_parties, handshake_mgr); - } - } - ~ClientSecurityHandshakerFactory() override = default; -}; - -class ServerSecurityHandshakerFactory : public HandshakerFactory { - public: - void AddHandshakers(const grpc_channel_args* args, - grpc_pollset_set* interested_parties, - HandshakeManager* handshake_mgr) override { - auto* security_connector = - reinterpret_cast<grpc_server_security_connector*>( - grpc_security_connector_find_in_args(args)); - if (security_connector) { + } + } + ~ClientSecurityHandshakerFactory() override = default; +}; + +class ServerSecurityHandshakerFactory : public HandshakerFactory { + public: + void AddHandshakers(const grpc_channel_args* args, + grpc_pollset_set* interested_parties, + HandshakeManager* handshake_mgr) override { + auto* security_connector = + reinterpret_cast<grpc_server_security_connector*>( + grpc_security_connector_find_in_args(args)); + if (security_connector) { security_connector->add_handshakers(args, interested_parties, handshake_mgr); - } - } - ~ServerSecurityHandshakerFactory() override = default; -}; + } + } + ~ServerSecurityHandshakerFactory() override = default; +}; -} // namespace +} // namespace // // exported functions // -RefCountedPtr<Handshaker> SecurityHandshakerCreate( +RefCountedPtr<Handshaker> SecurityHandshakerCreate( tsi_handshaker* handshaker, grpc_security_connector* connector, const grpc_channel_args* args) { // If no TSI handshaker was created, return a handshaker that always fails. // Otherwise, return a real security handshaker. if (handshaker == nullptr) { - return MakeRefCounted<FailHandshaker>(); + return MakeRefCounted<FailHandshaker>(); } else { return MakeRefCounted<SecurityHandshaker>(handshaker, connector, args); } } -void SecurityRegisterHandshakerFactories() { - HandshakerRegistry::RegisterHandshakerFactory( - false /* at_start */, HANDSHAKER_CLIENT, +void SecurityRegisterHandshakerFactories() { + HandshakerRegistry::RegisterHandshakerFactory( + false /* at_start */, HANDSHAKER_CLIENT, y_absl::make_unique<ClientSecurityHandshakerFactory>()); - HandshakerRegistry::RegisterHandshakerFactory( - false /* at_start */, HANDSHAKER_SERVER, + HandshakerRegistry::RegisterHandshakerFactory( + false /* at_start */, HANDSHAKER_SERVER, y_absl::make_unique<ServerSecurityHandshakerFactory>()); } - -} // namespace grpc_core - -grpc_handshaker* grpc_security_handshaker_create( + +} // namespace grpc_core + +grpc_handshaker* grpc_security_handshaker_create( tsi_handshaker* handshaker, grpc_security_connector* connector, const grpc_channel_args* args) { return SecurityHandshakerCreate(handshaker, connector, args).release(); -} +} diff --git a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h index a9e1fe83d4..bed8b4bfee 100644 --- a/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h +++ b/contrib/libs/grpc/src/core/lib/security/transport/security_handshaker.h @@ -24,22 +24,22 @@ #include "src/core/lib/channel/handshaker.h" #include "src/core/lib/security/security_connector/security_connector.h" -namespace grpc_core { - +namespace grpc_core { + /// Creates a security handshaker using \a handshaker. -RefCountedPtr<Handshaker> SecurityHandshakerCreate( +RefCountedPtr<Handshaker> SecurityHandshakerCreate( tsi_handshaker* handshaker, grpc_security_connector* connector, const grpc_channel_args* args); /// Registers security handshaker factories. -void SecurityRegisterHandshakerFactories(); - -} // namespace grpc_core +void SecurityRegisterHandshakerFactories(); -// TODO(arjunroy): This is transitional to account for the new handshaker API -// and will eventually be removed entirely. -grpc_handshaker* grpc_security_handshaker_create( +} // namespace grpc_core + +// TODO(arjunroy): This is transitional to account for the new handshaker API +// and will eventually be removed entirely. +grpc_handshaker* grpc_security_handshaker_create( tsi_handshaker* handshaker, grpc_security_connector* connector, const grpc_channel_args* args); - + #endif /* GRPC_CORE_LIB_SECURITY_TRANSPORT_SECURITY_HANDSHAKER_H */ diff --git a/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc b/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc index 6f83a179b4..90e843f011 100644 --- a/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc +++ b/contrib/libs/grpc/src/core/lib/security/transport/server_auth_filter.cc @@ -28,9 +28,9 @@ #include "src/core/lib/security/transport/auth_filters.h" #include "src/core/lib/slice/slice_internal.h" -static void recv_initial_metadata_ready(void* arg, grpc_error* error); -static void recv_trailing_metadata_ready(void* user_data, grpc_error* error); - +static void recv_initial_metadata_ready(void* arg, grpc_error* error); +static void recv_trailing_metadata_ready(void* user_data, grpc_error* error); + namespace { enum async_state { STATE_INIT = 0, @@ -38,57 +38,57 @@ enum async_state { STATE_CANCELLED, }; -struct channel_data { - channel_data(grpc_auth_context* auth_context, grpc_server_credentials* creds) - : auth_context(auth_context->Ref()), creds(creds->Ref()) {} - ~channel_data() { auth_context.reset(DEBUG_LOCATION, "server_auth_filter"); } - - grpc_core::RefCountedPtr<grpc_auth_context> auth_context; - grpc_core::RefCountedPtr<grpc_server_credentials> creds; -}; - +struct channel_data { + channel_data(grpc_auth_context* auth_context, grpc_server_credentials* creds) + : auth_context(auth_context->Ref()), creds(creds->Ref()) {} + ~channel_data() { auth_context.reset(DEBUG_LOCATION, "server_auth_filter"); } + + grpc_core::RefCountedPtr<grpc_auth_context> auth_context; + grpc_core::RefCountedPtr<grpc_server_credentials> creds; +}; + struct call_data { - call_data(grpc_call_element* elem, const grpc_call_element_args& args) - : call_combiner(args.call_combiner), owning_call(args.call_stack) { - GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, - ::recv_initial_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, - ::recv_trailing_metadata_ready, elem, - grpc_schedule_on_exec_ctx); - // Create server security context. Set its auth context from channel - // data and save it in the call context. - grpc_server_security_context* server_ctx = - grpc_server_security_context_create(args.arena); - channel_data* chand = static_cast<channel_data*>(elem->channel_data); - server_ctx->auth_context = - chand->auth_context->Ref(DEBUG_LOCATION, "server_auth_filter"); - if (args.context[GRPC_CONTEXT_SECURITY].value != nullptr) { - args.context[GRPC_CONTEXT_SECURITY].destroy( - args.context[GRPC_CONTEXT_SECURITY].value); - } - args.context[GRPC_CONTEXT_SECURITY].value = server_ctx; - args.context[GRPC_CONTEXT_SECURITY].destroy = - grpc_server_security_context_destroy; - } - - ~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); } - + call_data(grpc_call_element* elem, const grpc_call_element_args& args) + : call_combiner(args.call_combiner), owning_call(args.call_stack) { + GRPC_CLOSURE_INIT(&recv_initial_metadata_ready, + ::recv_initial_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + GRPC_CLOSURE_INIT(&recv_trailing_metadata_ready, + ::recv_trailing_metadata_ready, elem, + grpc_schedule_on_exec_ctx); + // Create server security context. Set its auth context from channel + // data and save it in the call context. + grpc_server_security_context* server_ctx = + grpc_server_security_context_create(args.arena); + channel_data* chand = static_cast<channel_data*>(elem->channel_data); + server_ctx->auth_context = + chand->auth_context->Ref(DEBUG_LOCATION, "server_auth_filter"); + if (args.context[GRPC_CONTEXT_SECURITY].value != nullptr) { + args.context[GRPC_CONTEXT_SECURITY].destroy( + args.context[GRPC_CONTEXT_SECURITY].value); + } + args.context[GRPC_CONTEXT_SECURITY].value = server_ctx; + args.context[GRPC_CONTEXT_SECURITY].destroy = + grpc_server_security_context_destroy; + } + + ~call_data() { GRPC_ERROR_UNREF(recv_initial_metadata_error); } + grpc_core::CallCombiner* call_combiner; grpc_call_stack* owning_call; grpc_transport_stream_op_batch* recv_initial_metadata_batch; grpc_closure* original_recv_initial_metadata_ready; grpc_closure recv_initial_metadata_ready; - grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE; - grpc_closure recv_trailing_metadata_ready; - grpc_closure* original_recv_trailing_metadata_ready; - grpc_error* recv_trailing_metadata_error; - bool seen_recv_trailing_metadata_ready = false; + grpc_error* recv_initial_metadata_error = GRPC_ERROR_NONE; + grpc_closure recv_trailing_metadata_ready; + grpc_closure* original_recv_trailing_metadata_ready; + grpc_error* recv_trailing_metadata_error; + bool seen_recv_trailing_metadata_ready = false; grpc_metadata_array md; const grpc_metadata* consumed_md; size_t num_consumed_md; grpc_closure cancel_closure; - gpr_atm state = STATE_INIT; // async_state + gpr_atm state = STATE_INIT; // async_state }; } // namespace @@ -150,15 +150,15 @@ static void on_md_processing_done_inner(grpc_call_element* elem, batch->payload->recv_initial_metadata.recv_initial_metadata, remove_consumed_md, elem, "Response metadata filtering error"); } - calld->recv_initial_metadata_error = GRPC_ERROR_REF(error); - grpc_closure* closure = calld->original_recv_initial_metadata_ready; - calld->original_recv_initial_metadata_ready = nullptr; - if (calld->seen_recv_trailing_metadata_ready) { - GRPC_CALL_COMBINER_START(calld->call_combiner, - &calld->recv_trailing_metadata_ready, - calld->recv_trailing_metadata_error, - "continue recv_trailing_metadata_ready"); - } + calld->recv_initial_metadata_error = GRPC_ERROR_REF(error); + grpc_closure* closure = calld->original_recv_initial_metadata_ready; + calld->original_recv_initial_metadata_ready = nullptr; + if (calld->seen_recv_trailing_metadata_ready) { + GRPC_CALL_COMBINER_START(calld->call_combiner, + &calld->recv_trailing_metadata_ready, + calld->recv_trailing_metadata_error, + "continue recv_trailing_metadata_ready"); + } grpc_core::ExecCtx::Run(DEBUG_LOCATION, closure, error); } @@ -169,7 +169,7 @@ static void on_md_processing_done( grpc_status_code status, const char* error_details) { grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); call_data* calld = static_cast<call_data*>(elem->call_data); - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; // If the call was not cancelled while we were in flight, process the result. if (gpr_atm_full_cas(&calld->state, static_cast<gpr_atm>(STATE_INIT), @@ -213,8 +213,8 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) { call_data* calld = static_cast<call_data*>(elem->call_data); grpc_transport_stream_op_batch* batch = calld->recv_initial_metadata_batch; if (error == GRPC_ERROR_NONE) { - if (chand->creds != nullptr && - chand->creds->auth_metadata_processor().process != nullptr) { + if (chand->creds != nullptr && + chand->creds->auth_metadata_processor().process != nullptr) { // We're calling out to the application, so we need to make sure // to drop the call combiner early if we get cancelled. GRPC_CLOSURE_INIT(&calld->cancel_closure, cancel_call, elem, @@ -223,41 +223,41 @@ static void recv_initial_metadata_ready(void* arg, grpc_error* error) { GRPC_CALL_STACK_REF(calld->owning_call, "server_auth_metadata"); calld->md = metadata_batch_to_md_array( batch->payload->recv_initial_metadata.recv_initial_metadata); - chand->creds->auth_metadata_processor().process( - chand->creds->auth_metadata_processor().state, - chand->auth_context.get(), calld->md.metadata, calld->md.count, - on_md_processing_done, elem); + chand->creds->auth_metadata_processor().process( + chand->creds->auth_metadata_processor().state, + chand->auth_context.get(), calld->md.metadata, calld->md.count, + on_md_processing_done, elem); return; } } - grpc_closure* closure = calld->original_recv_initial_metadata_ready; - calld->original_recv_initial_metadata_ready = nullptr; - if (calld->seen_recv_trailing_metadata_ready) { - GRPC_CALL_COMBINER_START(calld->call_combiner, - &calld->recv_trailing_metadata_ready, - calld->recv_trailing_metadata_error, - "continue recv_trailing_metadata_ready"); - } + grpc_closure* closure = calld->original_recv_initial_metadata_ready; + calld->original_recv_initial_metadata_ready = nullptr; + if (calld->seen_recv_trailing_metadata_ready) { + GRPC_CALL_COMBINER_START(calld->call_combiner, + &calld->recv_trailing_metadata_ready, + calld->recv_trailing_metadata_error, + "continue recv_trailing_metadata_ready"); + } grpc_core::Closure::Run(DEBUG_LOCATION, closure, GRPC_ERROR_REF(error)); } -static void recv_trailing_metadata_ready(void* user_data, grpc_error* err) { - grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); - call_data* calld = static_cast<call_data*>(elem->call_data); - if (calld->original_recv_initial_metadata_ready != nullptr) { - calld->recv_trailing_metadata_error = GRPC_ERROR_REF(err); - calld->seen_recv_trailing_metadata_ready = true; - GRPC_CALL_COMBINER_STOP(calld->call_combiner, - "deferring recv_trailing_metadata_ready until " - "after recv_initial_metadata_ready"); - return; - } - err = grpc_error_add_child( - GRPC_ERROR_REF(err), GRPC_ERROR_REF(calld->recv_initial_metadata_error)); +static void recv_trailing_metadata_ready(void* user_data, grpc_error* err) { + grpc_call_element* elem = static_cast<grpc_call_element*>(user_data); + call_data* calld = static_cast<call_data*>(elem->call_data); + if (calld->original_recv_initial_metadata_ready != nullptr) { + calld->recv_trailing_metadata_error = GRPC_ERROR_REF(err); + calld->seen_recv_trailing_metadata_ready = true; + GRPC_CALL_COMBINER_STOP(calld->call_combiner, + "deferring recv_trailing_metadata_ready until " + "after recv_initial_metadata_ready"); + return; + } + err = grpc_error_add_child( + GRPC_ERROR_REF(err), GRPC_ERROR_REF(calld->recv_initial_metadata_error)); grpc_core::Closure::Run(DEBUG_LOCATION, calld->original_recv_trailing_metadata_ready, err); -} - +} + static void server_auth_start_transport_stream_op_batch( grpc_call_element* elem, grpc_transport_stream_op_batch* batch) { call_data* calld = static_cast<call_data*>(elem->call_data); @@ -269,19 +269,19 @@ static void server_auth_start_transport_stream_op_batch( batch->payload->recv_initial_metadata.recv_initial_metadata_ready = &calld->recv_initial_metadata_ready; } - if (batch->recv_trailing_metadata) { - calld->original_recv_trailing_metadata_ready = - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &calld->recv_trailing_metadata_ready; - } + if (batch->recv_trailing_metadata) { + calld->original_recv_trailing_metadata_ready = + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready; + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &calld->recv_trailing_metadata_ready; + } grpc_call_next_op(elem, batch); } /* Constructor for call_data */ static grpc_error* server_auth_init_call_elem( grpc_call_element* elem, const grpc_call_element_args* args) { - new (elem->call_data) call_data(elem, *args); + new (elem->call_data) call_data(elem, *args); return GRPC_ERROR_NONE; } @@ -289,9 +289,9 @@ static grpc_error* server_auth_init_call_elem( static void server_auth_destroy_call_elem( grpc_call_element* elem, const grpc_call_final_info* /*final_info*/, grpc_closure* /*ignored*/) { - call_data* calld = static_cast<call_data*>(elem->call_data); - calld->~call_data(); -} + call_data* calld = static_cast<call_data*>(elem->call_data); + calld->~call_data(); +} /* Constructor for channel_data */ static grpc_error* server_auth_init_channel_elem( @@ -302,14 +302,14 @@ static grpc_error* server_auth_init_channel_elem( GPR_ASSERT(auth_context != nullptr); grpc_server_credentials* creds = grpc_find_server_credentials_in_args(args->channel_args); - new (elem->channel_data) channel_data(auth_context, creds); + new (elem->channel_data) channel_data(auth_context, creds); return GRPC_ERROR_NONE; } /* Destructor for channel data */ static void server_auth_destroy_channel_elem(grpc_channel_element* elem) { channel_data* chand = static_cast<channel_data*>(elem->channel_data); - chand->~channel_data(); + chand->~channel_data(); } const grpc_channel_filter grpc_server_auth_filter = { diff --git a/contrib/libs/grpc/src/core/lib/security/util/json_util.cc b/contrib/libs/grpc/src/core/lib/security/util/json_util.cc index 70ed064841..00601bf4bb 100644 --- a/contrib/libs/grpc/src/core/lib/security/util/json_util.cc +++ b/contrib/libs/grpc/src/core/lib/security/util/json_util.cc @@ -35,7 +35,7 @@ const char* grpc_json_get_string_property(const grpc_core::Json& json, if (error != nullptr) { *error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("JSON value is not an object"); - } + } return nullptr; } auto it = json.object_value().find(prop_name); diff --git a/contrib/libs/grpc/src/core/lib/slice/slice.cc b/contrib/libs/grpc/src/core/lib/slice/slice.cc index 838cf4ba49..b0a13a8c17 100644 --- a/contrib/libs/grpc/src/core/lib/slice/slice.cc +++ b/contrib/libs/grpc/src/core/lib/slice/slice.cc @@ -93,14 +93,14 @@ class NewSliceRefcount { } // namespace grpc_core -size_t grpc_slice_memory_usage(grpc_slice s) { +size_t grpc_slice_memory_usage(grpc_slice s) { if (s.refcount == nullptr || s.refcount == &grpc_core::kNoopRefcount) { - return 0; - } else { - return s.data.refcounted.length; - } -} - + return 0; + } else { + return s.data.refcounted.length; + } +} + grpc_slice grpc_slice_from_static_buffer(const void* s, size_t len) { return grpc_core::ExternallyManagedSlice(s, len); } diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc b/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc index 2d66694736..8a6dc318b8 100644 --- a/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc +++ b/contrib/libs/grpc/src/core/lib/slice/slice_buffer.cc @@ -349,26 +349,26 @@ void grpc_slice_buffer_trim_end(grpc_slice_buffer* sb, size_t n, size_t slice_len = GRPC_SLICE_LENGTH(slice); if (slice_len > n) { sb->slices[idx] = grpc_slice_split_head(&slice, slice_len - n); - if (garbage) { - grpc_slice_buffer_add_indexed(garbage, slice); - } else { - grpc_slice_unref_internal(slice); - } + if (garbage) { + grpc_slice_buffer_add_indexed(garbage, slice); + } else { + grpc_slice_unref_internal(slice); + } return; } else if (slice_len == n) { - if (garbage) { - grpc_slice_buffer_add_indexed(garbage, slice); - } else { - grpc_slice_unref_internal(slice); - } + if (garbage) { + grpc_slice_buffer_add_indexed(garbage, slice); + } else { + grpc_slice_unref_internal(slice); + } sb->count = idx; return; } else { - if (garbage) { - grpc_slice_buffer_add_indexed(garbage, slice); - } else { - grpc_slice_unref_internal(slice); - } + if (garbage) { + grpc_slice_buffer_add_indexed(garbage, slice); + } else { + grpc_slice_unref_internal(slice); + } n -= slice_len; sb->count = idx; } diff --git a/contrib/libs/grpc/src/core/lib/slice/slice_internal.h b/contrib/libs/grpc/src/core/lib/slice/slice_internal.h index 8a17b6e72e..b9a9e0400e 100644 --- a/contrib/libs/grpc/src/core/lib/slice/slice_internal.h +++ b/contrib/libs/grpc/src/core/lib/slice/slice_internal.h @@ -340,11 +340,11 @@ grpc_slice grpc_slice_from_moved_buffer(grpc_core::UniquePtr<char> p, grpc_slice grpc_slice_from_moved_string(grpc_core::UniquePtr<char> p); grpc_slice grpc_slice_from_cpp_string(TString str); -// Returns the memory used by this slice, not counting the slice structure -// itself. This means that inlined and slices from static strings will return -// 0. All other slices will return the size of the allocated chars. -size_t grpc_slice_memory_usage(grpc_slice s); - +// Returns the memory used by this slice, not counting the slice structure +// itself. This means that inlined and slices from static strings will return +// 0. All other slices will return the size of the allocated chars. +size_t grpc_slice_memory_usage(grpc_slice s); + grpc_core::UnmanagedMemorySlice grpc_slice_sub_no_ref( const grpc_core::UnmanagedMemorySlice& source, size_t begin, size_t end); diff --git a/contrib/libs/grpc/src/core/lib/surface/call.cc b/contrib/libs/grpc/src/core/lib/surface/call.cc index fe4c774c52..380df44b7d 100644 --- a/contrib/libs/grpc/src/core/lib/surface/call.cc +++ b/contrib/libs/grpc/src/core/lib/surface/call.cc @@ -39,7 +39,7 @@ #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/compression/algorithm_metadata.h" #include "src/core/lib/debug/stats.h" -#include "src/core/lib/gpr/alloc.h" +#include "src/core/lib/gpr/alloc.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/time_precise.h" #include "src/core/lib/gpr/useful.h" @@ -55,7 +55,7 @@ #include "src/core/lib/surface/call_test_only.h" #include "src/core/lib/surface/channel.h" #include "src/core/lib/surface/completion_queue.h" -#include "src/core/lib/surface/server.h" +#include "src/core/lib/surface/server.h" #include "src/core/lib/surface/validate_metadata.h" #include "src/core/lib/transport/error_utils.h" #include "src/core/lib/transport/metadata.h" @@ -78,14 +78,14 @@ #define MAX_SEND_EXTRA_METADATA_COUNT 3 -// Used to create arena for the first call. -#define ESTIMATED_MDELEM_COUNT 16 +// Used to create arena for the first call. +#define ESTIMATED_MDELEM_COUNT 16 -struct batch_control { +struct batch_control { batch_control() = default; - grpc_call* call = nullptr; - grpc_transport_stream_op_batch op; + grpc_call* call = nullptr; + grpc_transport_stream_op_batch op; /* Share memory for cq_completion and notify_tag as they are never needed simultaneously. Each byte used in this data structure count as six bytes per call, so any savings we can make are worthwhile, @@ -108,54 +108,54 @@ struct batch_control { grpc_closure start_batch; grpc_closure finish_batch; grpc_core::Atomic<intptr_t> steps_to_complete; - gpr_atm batch_error = reinterpret_cast<gpr_atm>(GRPC_ERROR_NONE); + gpr_atm batch_error = reinterpret_cast<gpr_atm>(GRPC_ERROR_NONE); void set_num_steps_to_complete(uintptr_t steps) { steps_to_complete.Store(steps, grpc_core::MemoryOrder::RELEASE); } bool completed_batch_step() { return steps_to_complete.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1; } -}; +}; -struct parent_call { - parent_call() { gpr_mu_init(&child_list_mu); } - ~parent_call() { gpr_mu_destroy(&child_list_mu); } +struct parent_call { + parent_call() { gpr_mu_init(&child_list_mu); } + ~parent_call() { gpr_mu_destroy(&child_list_mu); } gpr_mu child_list_mu; - grpc_call* first_child = nullptr; -}; + grpc_call* first_child = nullptr; +}; -struct child_call { - child_call(grpc_call* parent) : parent(parent) {} +struct child_call { + child_call(grpc_call* parent) : parent(parent) {} grpc_call* parent; /** siblings: children of the same parent form a list, and this list is protected under parent->mu */ - grpc_call* sibling_next = nullptr; - grpc_call* sibling_prev = nullptr; -}; + grpc_call* sibling_next = nullptr; + grpc_call* sibling_prev = nullptr; +}; #define RECV_NONE ((gpr_atm)0) #define RECV_INITIAL_METADATA_FIRST ((gpr_atm)1) struct grpc_call { grpc_call(grpc_core::Arena* arena, const grpc_call_create_args& args) - : arena(arena), - cq(args.cq), - channel(args.channel), - is_client(args.server_transport_data == nullptr), - stream_op_payload(context) { - for (int i = 0; i < 2; i++) { - for (int j = 0; j < 2; j++) { - metadata_batch[i][j].deadline = GRPC_MILLIS_INF_FUTURE; - } - } - } - - ~grpc_call() { - gpr_free(static_cast<void*>(const_cast<char*>(final_info.error_string))); - } - + : arena(arena), + cq(args.cq), + channel(args.channel), + is_client(args.server_transport_data == nullptr), + stream_op_payload(context) { + for (int i = 0; i < 2; i++) { + for (int j = 0; j < 2; j++) { + metadata_batch[i][j].deadline = GRPC_MILLIS_INF_FUTURE; + } + } + } + + ~grpc_call() { + gpr_free(static_cast<void*>(const_cast<char*>(final_info.error_string))); + } + grpc_core::RefCount ext_ref; grpc_core::Arena* arena; grpc_core::CallCombiner call_combiner; @@ -163,58 +163,58 @@ struct grpc_call { grpc_polling_entity pollent; grpc_channel* channel; gpr_cycle_counter start_time = gpr_get_cycle_counter(); - /* parent_call* */ gpr_atm parent_call_atm = 0; - child_call* child = nullptr; + /* parent_call* */ gpr_atm parent_call_atm = 0; + child_call* child = nullptr; /* client or server call */ bool is_client; /** has grpc_call_unref been called */ - bool destroy_called = false; + bool destroy_called = false; /** flag indicating that cancellation is inherited */ - bool cancellation_is_inherited = false; + bool cancellation_is_inherited = false; /** which ops are in-flight */ - bool sent_initial_metadata = false; - bool sending_message = false; - bool sent_final_op = false; - bool received_initial_metadata = false; - bool receiving_message = false; - bool requested_final_op = false; - gpr_atm any_ops_sent_atm = 0; - gpr_atm received_final_op_atm = 0; - - batch_control* active_batches[MAX_CONCURRENT_BATCHES] = {}; + bool sent_initial_metadata = false; + bool sending_message = false; + bool sent_final_op = false; + bool received_initial_metadata = false; + bool receiving_message = false; + bool requested_final_op = false; + gpr_atm any_ops_sent_atm = 0; + gpr_atm received_final_op_atm = 0; + + batch_control* active_batches[MAX_CONCURRENT_BATCHES] = {}; grpc_transport_stream_op_batch_payload stream_op_payload; /* first idx: is_receiving, second idx: is_trailing */ - grpc_metadata_batch metadata_batch[2][2] = {}; + grpc_metadata_batch metadata_batch[2][2] = {}; /* Buffered read metadata waiting to be returned to the application. Element 0 is initial metadata, element 1 is trailing metadata. */ - grpc_metadata_array* buffered_metadata[2] = {}; + grpc_metadata_array* buffered_metadata[2] = {}; grpc_metadata compression_md; // A char* indicating the peer name. - gpr_atm peer_string = 0; + gpr_atm peer_string = 0; /* Call data useful used for reporting. Only valid after the call has * completed */ grpc_call_final_info final_info; /* Compression algorithm for *incoming* data */ - grpc_message_compression_algorithm incoming_message_compression_algorithm = - GRPC_MESSAGE_COMPRESS_NONE; + grpc_message_compression_algorithm incoming_message_compression_algorithm = + GRPC_MESSAGE_COMPRESS_NONE; /* Stream compression algorithm for *incoming* data */ - grpc_stream_compression_algorithm incoming_stream_compression_algorithm = - GRPC_STREAM_COMPRESS_NONE; - /* Supported encodings (compression algorithms), a bitset. - * Always support no compression. */ - uint32_t encodings_accepted_by_peer = 1 << GRPC_MESSAGE_COMPRESS_NONE; + grpc_stream_compression_algorithm incoming_stream_compression_algorithm = + GRPC_STREAM_COMPRESS_NONE; + /* Supported encodings (compression algorithms), a bitset. + * Always support no compression. */ + uint32_t encodings_accepted_by_peer = 1 << GRPC_MESSAGE_COMPRESS_NONE; /* Supported stream encodings (stream compression algorithms), a bitset */ - uint32_t stream_encodings_accepted_by_peer = 0; + uint32_t stream_encodings_accepted_by_peer = 0; /* Contexts for various subsystems (security, tracing, ...). */ - grpc_call_context_element context[GRPC_CONTEXT_COUNT] = {}; + grpc_call_context_element context[GRPC_CONTEXT_COUNT] = {}; /* for the client, extra metadata is initial metadata; for the server, it's trailing metadata */ @@ -225,13 +225,13 @@ struct grpc_call { grpc_core::ManualConstructor<grpc_core::SliceBufferByteStream> sending_stream; grpc_core::OrphanablePtr<grpc_core::ByteStream> receiving_stream; - grpc_byte_buffer** receiving_buffer = nullptr; - grpc_slice receiving_slice = grpc_empty_slice(); + grpc_byte_buffer** receiving_buffer = nullptr; + grpc_slice receiving_slice = grpc_empty_slice(); grpc_closure receiving_slice_ready; grpc_closure receiving_stream_ready; grpc_closure receiving_initial_metadata_ready; - grpc_closure receiving_trailing_metadata_ready; - uint32_t test_only_last_message_flags = 0; + grpc_closure receiving_trailing_metadata_ready; + uint32_t test_only_last_message_flags = 0; // Status about operation of call bool sent_server_trailing_metadata = false; gpr_atm cancelled_with_error = 0; @@ -246,11 +246,11 @@ struct grpc_call { } client; struct { int* cancelled; - // backpointer to owning server if this is a server side call. + // backpointer to owning server if this is a server side call. grpc_core::Server* core_server; } server; } final_op; - gpr_atm status_error = 0; + gpr_atm status_error = 0; /* recv_state can contain one of the following values: RECV_NONE : : no initial metadata and messages received @@ -268,19 +268,19 @@ struct grpc_call { For 1, 4: See receiving_initial_metadata_ready() function For 2, 3: See receiving_stream_ready() function */ - gpr_atm recv_state = 0; + gpr_atm recv_state = 0; }; grpc_core::TraceFlag grpc_call_error_trace(false, "call_error"); grpc_core::TraceFlag grpc_compression_trace(false, "compression"); -#define CALL_STACK_FROM_CALL(call) \ - (grpc_call_stack*)((char*)(call) + \ - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call))) -#define CALL_FROM_CALL_STACK(call_stack) \ - (grpc_call*)(((char*)(call_stack)) - \ - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call))) - +#define CALL_STACK_FROM_CALL(call) \ + (grpc_call_stack*)((char*)(call) + \ + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call))) +#define CALL_FROM_CALL_STACK(call_stack) \ + (grpc_call*)(((char*)(call_stack)) - \ + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(grpc_call))) + #define CALL_ELEM_FROM_CALL(call, idx) \ grpc_call_stack_element(CALL_STACK_FROM_CALL(call), idx) #define CALL_FROM_TOP_ELEM(top_elem) \ @@ -288,13 +288,13 @@ grpc_core::TraceFlag grpc_compression_trace(false, "compression"); static void execute_batch(grpc_call* call, grpc_transport_stream_op_batch* op, grpc_closure* start_batch_closure); - -static void cancel_with_status(grpc_call* c, grpc_status_code status, + +static void cancel_with_status(grpc_call* c, grpc_status_code status, const char* description); -static void cancel_with_error(grpc_call* c, grpc_error* error); +static void cancel_with_error(grpc_call* c, grpc_error* error); static void destroy_call(void* call_stack, grpc_error* error); static void receiving_slice_ready(void* bctlp, grpc_error* error); -static void set_final_status(grpc_call* call, grpc_error* error); +static void set_final_status(grpc_call* call, grpc_error* error); static void process_data_after_md(batch_control* bctl); static void post_batch_completion(batch_control* bctl); @@ -315,7 +315,7 @@ static parent_call* get_or_create_parent_call(grpc_call* call) { p = call->arena->New<parent_call>(); if (!gpr_atm_rel_cas(&call->parent_call_atm, (gpr_atm) nullptr, (gpr_atm)p)) { - p->~parent_call(); + p->~parent_call(); p = (parent_call*)gpr_atm_acq_load(&call->parent_call_atm); } } @@ -326,17 +326,17 @@ static parent_call* get_parent_call(grpc_call* call) { return (parent_call*)gpr_atm_acq_load(&call->parent_call_atm); } -size_t grpc_call_get_initial_size_estimate() { - return sizeof(grpc_call) + sizeof(batch_control) * MAX_CONCURRENT_BATCHES + - sizeof(grpc_linked_mdelem) * ESTIMATED_MDELEM_COUNT; -} - +size_t grpc_call_get_initial_size_estimate() { + return sizeof(grpc_call) + sizeof(batch_control) * MAX_CONCURRENT_BATCHES + + sizeof(grpc_linked_mdelem) * ESTIMATED_MDELEM_COUNT; +} + grpc_error* grpc_call_create(const grpc_call_create_args* args, grpc_call** out_call) { GPR_TIMER_SCOPE("grpc_call_create", 0); - - GRPC_CHANNEL_INTERNAL_REF(args->channel, "call"); - + + GRPC_CHANNEL_INTERNAL_REF(args->channel, "call"); + grpc_core::Arena* arena; grpc_call* call; grpc_error* error = GRPC_ERROR_NONE; @@ -355,15 +355,15 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args, arena = arena_with_call.first; call = new (arena_with_call.second) grpc_call(arena, *args); *out_call = call; - grpc_slice path = grpc_empty_slice(); + grpc_slice path = grpc_empty_slice(); if (call->is_client) { - call->final_op.client.status_details = nullptr; - call->final_op.client.status = nullptr; - call->final_op.client.error_string = nullptr; + call->final_op.client.status_details = nullptr; + call->final_op.client.status = nullptr; + call->final_op.client.error_string = nullptr; GRPC_STATS_INC_CLIENT_CALLS_CREATED(); GPR_ASSERT(args->add_initial_metadata_count < MAX_SEND_EXTRA_METADATA_COUNT); - for (size_t i = 0; i < args->add_initial_metadata_count; i++) { + for (size_t i = 0; i < args->add_initial_metadata_count; i++) { call->send_extra_metadata[i].md = args->add_initial_metadata[i]; if (grpc_slice_eq_static_interned( GRPC_MDKEY(args->add_initial_metadata[i]), GRPC_MDSTR_PATH)) { @@ -374,13 +374,13 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args, call->send_extra_metadata_count = static_cast<int>(args->add_initial_metadata_count); } else { - GRPC_STATS_INC_SERVER_CALLS_CREATED(); - call->final_op.server.cancelled = nullptr; + GRPC_STATS_INC_SERVER_CALLS_CREATED(); + call->final_op.server.cancelled = nullptr; call->final_op.server.core_server = args->server; GPR_ASSERT(args->add_initial_metadata_count == 0); call->send_extra_metadata_count = 0; } - + grpc_millis send_deadline = args->send_deadline; bool immediately_cancel = false; @@ -448,12 +448,12 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args, } gpr_mu_unlock(&pc->child_list_mu); } - + if (error != GRPC_ERROR_NONE) { - cancel_with_error(call, GRPC_ERROR_REF(error)); + cancel_with_error(call, GRPC_ERROR_REF(error)); } if (immediately_cancel) { - cancel_with_error(call, GRPC_ERROR_CANCELLED); + cancel_with_error(call, GRPC_ERROR_CANCELLED); } if (args->cq != nullptr) { GPR_ASSERT(args->pollset_set_alternative == nullptr && @@ -472,20 +472,20 @@ grpc_error* grpc_call_create(const grpc_call_create_args* args, &call->pollent); } - if (call->is_client) { - grpc_core::channelz::ChannelNode* channelz_channel = - grpc_channel_get_channelz_node(call->channel); - if (channelz_channel != nullptr) { - channelz_channel->RecordCallStarted(); - } + if (call->is_client) { + grpc_core::channelz::ChannelNode* channelz_channel = + grpc_channel_get_channelz_node(call->channel); + if (channelz_channel != nullptr) { + channelz_channel->RecordCallStarted(); + } } else if (call->final_op.server.core_server != nullptr) { grpc_core::channelz::ServerNode* channelz_node = call->final_op.server.core_server->channelz_node(); if (channelz_node != nullptr) { channelz_node->RecordCallStarted(); - } - } - + } + } + grpc_slice_unref_internal(path); return error; @@ -524,7 +524,7 @@ static void release_call(void* call, grpc_error* /*error*/) { grpc_call* c = static_cast<grpc_call*>(call); grpc_channel* channel = c->channel; grpc_core::Arena* arena = c->arena; - c->~grpc_call(); + c->~grpc_call(); grpc_channel_update_call_size_estimate(channel, arena->Destroy()); GRPC_CHANNEL_INTERNAL_UNREF(channel, "call"); } @@ -541,7 +541,7 @@ static void destroy_call(void* call, grpc_error* /*error*/) { c->receiving_stream.reset(); parent_call* pc = get_parent_call(c); if (pc != nullptr) { - pc->~parent_call(); + pc->~parent_call(); } for (ii = 0; ii < c->send_extra_metadata_count; ii++) { GRPC_MDELEM_UNREF(c->send_extra_metadata[ii].md); @@ -555,12 +555,12 @@ static void destroy_call(void* call, grpc_error* /*error*/) { GRPC_CQ_INTERNAL_UNREF(c->cq, "bind"); } - grpc_error* status_error = - reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&c->status_error)); - grpc_error_get_status(status_error, c->send_deadline, - &c->final_info.final_status, nullptr, nullptr, - &(c->final_info.error_string)); - GRPC_ERROR_UNREF(status_error); + grpc_error* status_error = + reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&c->status_error)); + grpc_error_get_status(status_error, c->send_deadline, + &c->final_info.final_status, nullptr, nullptr, + &(c->final_info.error_string)); + GRPC_ERROR_UNREF(status_error); c->final_info.stats.latency = gpr_cycle_counter_sub(gpr_get_cycle_counter(), c->start_time); grpc_call_stack_destroy(CALL_STACK_FROM_CALL(c), &c->final_info, @@ -576,7 +576,7 @@ void grpc_call_unref(grpc_call* c) { GPR_TIMER_SCOPE("grpc_call_unref", 0); child_call* cc = c->child; - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE("grpc_call_unref(c=%p)", 1, (c)); @@ -601,16 +601,16 @@ void grpc_call_unref(grpc_call* c) { bool cancel = gpr_atm_acq_load(&c->any_ops_sent_atm) != 0 && gpr_atm_acq_load(&c->received_final_op_atm) == 0; if (cancel) { - cancel_with_error(c, GRPC_ERROR_CANCELLED); + cancel_with_error(c, GRPC_ERROR_CANCELLED); } else { // Unset the call combiner cancellation closure. This has the // effect of scheduling the previously set cancellation closure, if // any, so that it can release any internal references it may be - // holding to the call stack. Also flush the closures on exec_ctx so that - // filters that schedule cancel notification closures on exec_ctx do not - // need to take a ref of the call stack to guarantee closure liveness. + // holding to the call stack. Also flush the closures on exec_ctx so that + // filters that schedule cancel notification closures on exec_ctx do not + // need to take a ref of the call stack to guarantee closure liveness. c->call_combiner.SetNotifyOnCancel(nullptr); - grpc_core::ExecCtx::Get()->Flush(); + grpc_core::ExecCtx::Get()->Flush(); } GRPC_CALL_INTERNAL_UNREF(c, "destroy"); } @@ -618,9 +618,9 @@ void grpc_call_unref(grpc_call* c) { grpc_call_error grpc_call_cancel(grpc_call* call, void* reserved) { GRPC_API_TRACE("grpc_call_cancel(call=%p, reserved=%p)", 2, (call, reserved)); GPR_ASSERT(!reserved); - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; - cancel_with_error(call, GRPC_ERROR_CANCELLED); + cancel_with_error(call, GRPC_ERROR_CANCELLED); return GRPC_CALL_OK; } @@ -668,14 +668,14 @@ grpc_call_error grpc_call_cancel_with_status(grpc_call* c, grpc_status_code status, const char* description, void* reserved) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE( "grpc_call_cancel_with_status(" "c=%p, status=%d, description=%s, reserved=%p)", 4, (c, (int)status, description, reserved)); GPR_ASSERT(reserved == nullptr); - cancel_with_status(c, status, description); + cancel_with_status(c, status, description); return GRPC_CALL_OK; } @@ -694,11 +694,11 @@ static void done_termination(void* arg, grpc_error* /*error*/) { gpr_free(state); } -static void cancel_with_error(grpc_call* c, grpc_error* error) { +static void cancel_with_error(grpc_call* c, grpc_error* error) { if (!gpr_atm_rel_cas(&c->cancelled_with_error, 0, 1)) { - GRPC_ERROR_UNREF(error); - return; - } + GRPC_ERROR_UNREF(error); + return; + } GRPC_CALL_INTERNAL_REF(c, "termination"); // Inform the call combiner of the cancellation, so that it can cancel // any in-flight asynchronous actions that may be holding the call @@ -716,10 +716,10 @@ static void cancel_with_error(grpc_call* c, grpc_error* error) { execute_batch(c, op, &state->start_batch); } -void grpc_call_cancel_internal(grpc_call* call) { - cancel_with_error(call, GRPC_ERROR_CANCELLED); -} - +void grpc_call_cancel_internal(grpc_call* call) { + cancel_with_error(call, GRPC_ERROR_CANCELLED); +} + static grpc_error* error_from_status(grpc_status_code status, const char* description) { // copying 'description' is needed to ensure the grpc_call_cancel_with_status @@ -731,35 +731,35 @@ static grpc_error* error_from_status(grpc_status_code status, GRPC_ERROR_INT_GRPC_STATUS, status); } -static void cancel_with_status(grpc_call* c, grpc_status_code status, +static void cancel_with_status(grpc_call* c, grpc_status_code status, const char* description) { - cancel_with_error(c, error_from_status(status, description)); + cancel_with_error(c, error_from_status(status, description)); } -static void set_final_status(grpc_call* call, grpc_error* error) { +static void set_final_status(grpc_call* call, grpc_error* error) { if (GRPC_TRACE_FLAG_ENABLED(grpc_call_error_trace)) { - gpr_log(GPR_DEBUG, "set_final_status %s", call->is_client ? "CLI" : "SVR"); - gpr_log(GPR_DEBUG, "%s", grpc_error_string(error)); - } - if (call->is_client) { - grpc_error_get_status(error, call->send_deadline, - call->final_op.client.status, - call->final_op.client.status_details, nullptr, - call->final_op.client.error_string); - // explicitly take a ref - grpc_slice_ref_internal(*call->final_op.client.status_details); - gpr_atm_rel_store(&call->status_error, reinterpret_cast<gpr_atm>(error)); - grpc_core::channelz::ChannelNode* channelz_channel = - grpc_channel_get_channelz_node(call->channel); - if (channelz_channel != nullptr) { - if (*call->final_op.client.status != GRPC_STATUS_OK) { - channelz_channel->RecordCallFailed(); - } else { - channelz_channel->RecordCallSucceeded(); + gpr_log(GPR_DEBUG, "set_final_status %s", call->is_client ? "CLI" : "SVR"); + gpr_log(GPR_DEBUG, "%s", grpc_error_string(error)); + } + if (call->is_client) { + grpc_error_get_status(error, call->send_deadline, + call->final_op.client.status, + call->final_op.client.status_details, nullptr, + call->final_op.client.error_string); + // explicitly take a ref + grpc_slice_ref_internal(*call->final_op.client.status_details); + gpr_atm_rel_store(&call->status_error, reinterpret_cast<gpr_atm>(error)); + grpc_core::channelz::ChannelNode* channelz_channel = + grpc_channel_get_channelz_node(call->channel); + if (channelz_channel != nullptr) { + if (*call->final_op.client.status != GRPC_STATUS_OK) { + channelz_channel->RecordCallFailed(); + } else { + channelz_channel->RecordCallSucceeded(); } } - } else { - *call->final_op.server.cancelled = + } else { + *call->final_op.server.cancelled = error != GRPC_ERROR_NONE || !call->sent_server_trailing_metadata; grpc_core::channelz::ServerNode* channelz_node = call->final_op.server.core_server->channelz_node(); @@ -768,7 +768,7 @@ static void set_final_status(grpc_call* call, grpc_error* error) { reinterpret_cast<grpc_error*>( gpr_atm_acq_load(&call->status_error)) != GRPC_ERROR_NONE) { channelz_node->RecordCallFailed(); - } else { + } else { channelz_node->RecordCallSucceeded(); } } @@ -994,7 +994,7 @@ static grpc_stream_compression_algorithm decode_stream_compression( static void publish_app_metadata(grpc_call* call, grpc_metadata_batch* b, int is_trailing) { if (b->list.count == 0) return; - if (!call->is_client && is_trailing) return; + if (!call->is_client && is_trailing) return; if (is_trailing && call->buffered_metadata[1] == nullptr) return; GPR_TIMER_SCOPE("publish_app_metadata", 0); grpc_metadata_array* dest; @@ -1048,23 +1048,23 @@ static void recv_initial_filter(grpc_call* call, grpc_metadata_batch* b) { publish_app_metadata(call, b, false); } -static void recv_trailing_filter(void* args, grpc_metadata_batch* b, - grpc_error* batch_error) { +static void recv_trailing_filter(void* args, grpc_metadata_batch* b, + grpc_error* batch_error) { grpc_call* call = static_cast<grpc_call*>(args); - if (batch_error != GRPC_ERROR_NONE) { - set_final_status(call, batch_error); - } else if (b->idx.named.grpc_status != nullptr) { + if (batch_error != GRPC_ERROR_NONE) { + set_final_status(call, batch_error); + } else if (b->idx.named.grpc_status != nullptr) { grpc_status_code status_code = grpc_get_status_code_from_metadata(b->idx.named.grpc_status->md); - grpc_error* error = GRPC_ERROR_NONE; - if (status_code != GRPC_STATUS_OK) { + grpc_error* error = GRPC_ERROR_NONE; + if (status_code != GRPC_STATUS_OK) { char* peer = grpc_call_get_peer(call); error = grpc_error_set_int( GRPC_ERROR_CREATE_FROM_COPIED_STRING( y_absl::StrCat("Error received from peer ", peer).c_str()), GRPC_ERROR_INT_GRPC_STATUS, static_cast<intptr_t>(status_code)); gpr_free(peer); - } + } if (b->idx.named.grpc_message != nullptr) { error = grpc_error_set_str( error, GRPC_ERROR_STR_GRPC_MESSAGE, @@ -1074,24 +1074,24 @@ static void recv_trailing_filter(void* args, grpc_metadata_batch* b, error = grpc_error_set_str(error, GRPC_ERROR_STR_GRPC_MESSAGE, grpc_empty_slice()); } - set_final_status(call, GRPC_ERROR_REF(error)); + set_final_status(call, GRPC_ERROR_REF(error)); grpc_metadata_batch_remove(b, GRPC_BATCH_GRPC_STATUS); - GRPC_ERROR_UNREF(error); - } else if (!call->is_client) { - set_final_status(call, GRPC_ERROR_NONE); - } else { - gpr_log(GPR_DEBUG, - "Received trailing metadata with no error and no status"); - set_final_status( - call, grpc_error_set_int( - GRPC_ERROR_CREATE_FROM_STATIC_STRING("No status received"), - GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNKNOWN)); + GRPC_ERROR_UNREF(error); + } else if (!call->is_client) { + set_final_status(call, GRPC_ERROR_NONE); + } else { + gpr_log(GPR_DEBUG, + "Received trailing metadata with no error and no status"); + set_final_status( + call, grpc_error_set_int( + GRPC_ERROR_CREATE_FROM_STATIC_STRING("No status received"), + GRPC_ERROR_INT_GRPC_STATUS, GRPC_STATUS_UNKNOWN)); } publish_app_metadata(call, b, true); } grpc_core::Arena* grpc_call_get_arena(grpc_call* call) { return call->arena; } - + grpc_call_stack* grpc_call_get_call_stack(grpc_call* call) { return CALL_STACK_FROM_CALL(call); } @@ -1117,7 +1117,7 @@ static bool are_initial_metadata_flags_valid(uint32_t flags, bool is_client) { return !(flags & invalid_positions); } -static size_t batch_slot_for_op(grpc_op_type type) { +static size_t batch_slot_for_op(grpc_op_type type) { switch (type) { case GRPC_OP_SEND_INITIAL_METADATA: return 0; @@ -1137,21 +1137,21 @@ static size_t batch_slot_for_op(grpc_op_type type) { GPR_UNREACHABLE_CODE(return 123456789); } -static batch_control* reuse_or_allocate_batch_control(grpc_call* call, +static batch_control* reuse_or_allocate_batch_control(grpc_call* call, const grpc_op* ops) { - size_t slot_idx = batch_slot_for_op(ops[0].op); - batch_control** pslot = &call->active_batches[slot_idx]; - batch_control* bctl; - if (*pslot != nullptr) { - bctl = *pslot; - if (bctl->call != nullptr) { - return nullptr; - } - bctl->~batch_control(); - bctl->op = {}; - } else { + size_t slot_idx = batch_slot_for_op(ops[0].op); + batch_control** pslot = &call->active_batches[slot_idx]; + batch_control* bctl; + if (*pslot != nullptr) { + bctl = *pslot; + if (bctl->call != nullptr) { + return nullptr; + } + bctl->~batch_control(); + bctl->op = {}; + } else { bctl = call->arena->New<batch_control>(); - *pslot = bctl; + *pslot = bctl; } bctl->call = call; bctl->op.payload = &call->stream_op_payload; @@ -1166,18 +1166,18 @@ static void finish_batch_completion(void* user_data, GRPC_CALL_INTERNAL_UNREF(call, "completion"); } -static void reset_batch_errors(batch_control* bctl) { - GRPC_ERROR_UNREF( - reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error))); - gpr_atm_rel_store(&bctl->batch_error, - reinterpret_cast<gpr_atm>(GRPC_ERROR_NONE)); +static void reset_batch_errors(batch_control* bctl) { + GRPC_ERROR_UNREF( + reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error))); + gpr_atm_rel_store(&bctl->batch_error, + reinterpret_cast<gpr_atm>(GRPC_ERROR_NONE)); } static void post_batch_completion(batch_control* bctl) { grpc_call* next_child_call; grpc_call* call = bctl->call; - grpc_error* error = GRPC_ERROR_REF( - reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error))); + grpc_error* error = GRPC_ERROR_REF( + reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error))); if (bctl->op.send_initial_metadata) { grpc_metadata_batch_destroy( @@ -1209,7 +1209,7 @@ static void post_batch_completion(batch_control* bctl) { next_child_call = child->child->sibling_next; if (child->cancellation_is_inherited) { GRPC_CALL_INTERNAL_REF(child, "propagate_cancel"); - cancel_with_error(child, GRPC_ERROR_CANCELLED); + cancel_with_error(child, GRPC_ERROR_CANCELLED); GRPC_CALL_INTERNAL_UNREF(child, "propagate_cancel"); } child = next_child_call; @@ -1225,17 +1225,17 @@ static void post_batch_completion(batch_control* bctl) { grpc_byte_buffer_destroy(*call->receiving_buffer); *call->receiving_buffer = nullptr; } - reset_batch_errors(bctl); + reset_batch_errors(bctl); if (bctl->completion_data.notify_tag.is_closure) { - /* unrefs error */ + /* unrefs error */ bctl->call = nullptr; grpc_core::Closure::Run(DEBUG_LOCATION, (grpc_closure*)bctl->completion_data.notify_tag.tag, error); GRPC_CALL_INTERNAL_UNREF(call, "completion"); } else { - /* unrefs error */ + /* unrefs error */ grpc_cq_end_op(bctl->call->cq, bctl->completion_data.notify_tag.tag, error, finish_batch_completion, bctl, &bctl->completion_data.cq_completion); @@ -1345,12 +1345,12 @@ static void receiving_stream_ready(void* bctlp, grpc_error* error) { grpc_call* call = bctl->call; if (error != GRPC_ERROR_NONE) { call->receiving_stream.reset(); - if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) == - GRPC_ERROR_NONE) { - gpr_atm_rel_store(&bctl->batch_error, - reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error))); - } - cancel_with_error(call, GRPC_ERROR_REF(error)); + if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) == + GRPC_ERROR_NONE) { + gpr_atm_rel_store(&bctl->batch_error, + reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error))); + } + cancel_with_error(call, GRPC_ERROR_REF(error)); } /* If recv_state is RECV_NONE, we will save the batch_control * object with rel_cas, and will not use it after the cas. Its corresponding @@ -1476,13 +1476,13 @@ static void receiving_initial_metadata_ready(void* bctlp, grpc_error* error) { if (md->deadline != GRPC_MILLIS_INF_FUTURE && !call->is_client) { call->send_deadline = md->deadline; } - } else { - if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) == - GRPC_ERROR_NONE) { - gpr_atm_rel_store(&bctl->batch_error, - reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error))); - } - cancel_with_error(call, GRPC_ERROR_REF(error)); + } else { + if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) == + GRPC_ERROR_NONE) { + gpr_atm_rel_store(&bctl->batch_error, + reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error))); + } + cancel_with_error(call, GRPC_ERROR_REF(error)); } grpc_closure* saved_rsr_closure = nullptr; @@ -1517,28 +1517,28 @@ static void receiving_initial_metadata_ready(void* bctlp, grpc_error* error) { finish_batch_step(bctl); } -static void receiving_trailing_metadata_ready(void* bctlp, grpc_error* error) { - batch_control* bctl = static_cast<batch_control*>(bctlp); - grpc_call* call = bctl->call; - GRPC_CALL_COMBINER_STOP(&call->call_combiner, "recv_trailing_metadata_ready"); - grpc_metadata_batch* md = - &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */]; - recv_trailing_filter(call, md, GRPC_ERROR_REF(error)); - finish_batch_step(bctl); -} - +static void receiving_trailing_metadata_ready(void* bctlp, grpc_error* error) { + batch_control* bctl = static_cast<batch_control*>(bctlp); + grpc_call* call = bctl->call; + GRPC_CALL_COMBINER_STOP(&call->call_combiner, "recv_trailing_metadata_ready"); + grpc_metadata_batch* md = + &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */]; + recv_trailing_filter(call, md, GRPC_ERROR_REF(error)); + finish_batch_step(bctl); +} + static void finish_batch(void* bctlp, grpc_error* error) { batch_control* bctl = static_cast<batch_control*>(bctlp); grpc_call* call = bctl->call; GRPC_CALL_COMBINER_STOP(&call->call_combiner, "on_complete"); - if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) == - GRPC_ERROR_NONE) { - gpr_atm_rel_store(&bctl->batch_error, - reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error))); - } - if (error != GRPC_ERROR_NONE) { - cancel_with_error(call, GRPC_ERROR_REF(error)); - } + if (reinterpret_cast<grpc_error*>(gpr_atm_acq_load(&bctl->batch_error)) == + GRPC_ERROR_NONE) { + gpr_atm_rel_store(&bctl->batch_error, + reinterpret_cast<gpr_atm>(GRPC_ERROR_REF(error))); + } + if (error != GRPC_ERROR_NONE) { + cancel_with_error(call, GRPC_ERROR_REF(error)); + } finish_batch_step(bctl); } @@ -1554,8 +1554,8 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, size_t i; const grpc_op* op; batch_control* bctl; - bool has_send_ops = false; - int num_recv_ops = 0; + bool has_send_ops = false; + int num_recv_ops = 0; grpc_call_error error = GRPC_CALL_OK; grpc_transport_stream_op_batch* stream_op; grpc_transport_stream_op_batch_payload* stream_op_payload; @@ -1669,7 +1669,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, stream_op_payload->send_initial_metadata.peer_string = &call->peer_string; } - has_send_ops = true; + has_send_ops = true; break; } case GRPC_OP_SEND_MESSAGE: { @@ -1699,7 +1699,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, &op->data.send_message.send_message->data.raw.slice_buffer, flags); stream_op_payload->send_message.send_message.reset( call->sending_stream.get()); - has_send_ops = true; + has_send_ops = true; break; } case GRPC_OP_SEND_CLOSE_FROM_CLIENT: { @@ -1720,7 +1720,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, call->sent_final_op = true; stream_op_payload->send_trailing_metadata.send_trailing_metadata = &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */]; - has_send_ops = true; + has_send_ops = true; break; } case GRPC_OP_SEND_STATUS_FROM_SERVER: { @@ -1748,33 +1748,33 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, call->send_extra_metadata_count = 1; call->send_extra_metadata[0].md = grpc_get_reffed_status_elem( op->data.send_status_from_server.status); - grpc_error* status_error = - op->data.send_status_from_server.status == GRPC_STATUS_OK - ? GRPC_ERROR_NONE - : grpc_error_set_int( - GRPC_ERROR_CREATE_FROM_STATIC_STRING( - "Server returned error"), - GRPC_ERROR_INT_GRPC_STATUS, - static_cast<intptr_t>( - op->data.send_status_from_server.status)); - if (op->data.send_status_from_server.status_details != nullptr) { - call->send_extra_metadata[1].md = grpc_mdelem_from_slices( - GRPC_MDSTR_GRPC_MESSAGE, - grpc_slice_ref_internal( - *op->data.send_status_from_server.status_details)); - call->send_extra_metadata_count++; - if (status_error != GRPC_ERROR_NONE) { + grpc_error* status_error = + op->data.send_status_from_server.status == GRPC_STATUS_OK + ? GRPC_ERROR_NONE + : grpc_error_set_int( + GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Server returned error"), + GRPC_ERROR_INT_GRPC_STATUS, + static_cast<intptr_t>( + op->data.send_status_from_server.status)); + if (op->data.send_status_from_server.status_details != nullptr) { + call->send_extra_metadata[1].md = grpc_mdelem_from_slices( + GRPC_MDSTR_GRPC_MESSAGE, + grpc_slice_ref_internal( + *op->data.send_status_from_server.status_details)); + call->send_extra_metadata_count++; + if (status_error != GRPC_ERROR_NONE) { char* msg = grpc_slice_to_c_string( GRPC_MDVALUE(call->send_extra_metadata[1].md)); - status_error = - grpc_error_set_str(status_error, GRPC_ERROR_STR_GRPC_MESSAGE, + status_error = + grpc_error_set_str(status_error, GRPC_ERROR_STR_GRPC_MESSAGE, grpc_slice_from_copied_string(msg)); gpr_free(msg); } } - - gpr_atm_rel_store(&call->status_error, - reinterpret_cast<gpr_atm>(status_error)); + + gpr_atm_rel_store(&call->status_error, + reinterpret_cast<gpr_atm>(status_error)); if (!prepare_application_metadata( call, static_cast<int>( @@ -1792,7 +1792,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, &call->metadata_batch[0 /* is_receiving */][1 /* is_trailing */]; stream_op_payload->send_trailing_metadata.sent = &call->sent_server_trailing_metadata; - has_send_ops = true; + has_send_ops = true; break; } case GRPC_OP_RECV_INITIAL_METADATA: { @@ -1820,7 +1820,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, stream_op_payload->recv_initial_metadata.peer_string = &call->peer_string; } - ++num_recv_ops; + ++num_recv_ops; break; } case GRPC_OP_RECV_MESSAGE: { @@ -1842,7 +1842,7 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, grpc_schedule_on_exec_ctx); stream_op_payload->recv_message.recv_message_ready = &call->receiving_stream_ready; - ++num_recv_ops; + ++num_recv_ops; break; } case GRPC_OP_RECV_STATUS_ON_CLIENT: { @@ -1870,14 +1870,14 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, stream_op->recv_trailing_metadata = true; stream_op_payload->recv_trailing_metadata.recv_trailing_metadata = &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */]; - stream_op_payload->recv_trailing_metadata.collect_stats = + stream_op_payload->recv_trailing_metadata.collect_stats = &call->final_info.stats.transport_stream_stats; - GRPC_CLOSURE_INIT(&call->receiving_trailing_metadata_ready, - receiving_trailing_metadata_ready, bctl, - grpc_schedule_on_exec_ctx); - stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &call->receiving_trailing_metadata_ready; - ++num_recv_ops; + GRPC_CLOSURE_INIT(&call->receiving_trailing_metadata_ready, + receiving_trailing_metadata_ready, bctl, + grpc_schedule_on_exec_ctx); + stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &call->receiving_trailing_metadata_ready; + ++num_recv_ops; break; } case GRPC_OP_RECV_CLOSE_ON_SERVER: { @@ -1900,14 +1900,14 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, stream_op->recv_trailing_metadata = true; stream_op_payload->recv_trailing_metadata.recv_trailing_metadata = &call->metadata_batch[1 /* is_receiving */][1 /* is_trailing */]; - stream_op_payload->recv_trailing_metadata.collect_stats = + stream_op_payload->recv_trailing_metadata.collect_stats = &call->final_info.stats.transport_stream_stats; - GRPC_CLOSURE_INIT(&call->receiving_trailing_metadata_ready, - receiving_trailing_metadata_ready, bctl, - grpc_schedule_on_exec_ctx); - stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready = - &call->receiving_trailing_metadata_ready; - ++num_recv_ops; + GRPC_CLOSURE_INIT(&call->receiving_trailing_metadata_ready, + receiving_trailing_metadata_ready, bctl, + grpc_schedule_on_exec_ctx); + stream_op_payload->recv_trailing_metadata.recv_trailing_metadata_ready = + &call->receiving_trailing_metadata_ready; + ++num_recv_ops; break; } } @@ -1919,12 +1919,12 @@ static grpc_call_error call_start_batch(grpc_call* call, const grpc_op* ops, } bctl->set_num_steps_to_complete((has_send_ops ? 1 : 0) + num_recv_ops); - if (has_send_ops) { - GRPC_CLOSURE_INIT(&bctl->finish_batch, finish_batch, bctl, - grpc_schedule_on_exec_ctx); - stream_op->on_complete = &bctl->finish_batch; - } - + if (has_send_ops) { + GRPC_CLOSURE_INIT(&bctl->finish_batch, finish_batch, bctl, + grpc_schedule_on_exec_ctx); + stream_op->on_complete = &bctl->finish_batch; + } + gpr_atm_rel_store(&call->any_ops_sent_atm, 1); execute_batch(call, stream_op, &bctl->start_batch); @@ -1932,7 +1932,7 @@ done: return error; done_with_error: - /* reverse any mutations that occurred */ + /* reverse any mutations that occurred */ if (stream_op->send_initial_metadata) { call->sent_initial_metadata = false; grpc_metadata_batch_clear(&call->metadata_batch[0][0]); @@ -1969,8 +1969,8 @@ grpc_call_error grpc_call_start_batch(grpc_call* call, const grpc_op* ops, if (reserved != nullptr) { err = GRPC_CALL_ERROR; } else { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - grpc_core::ExecCtx exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ExecCtx exec_ctx; err = call_start_batch(call, ops, nops, tag, 0); } diff --git a/contrib/libs/grpc/src/core/lib/surface/call.h b/contrib/libs/grpc/src/core/lib/surface/call.h index 34d01db902..1ebd4ae72b 100644 --- a/contrib/libs/grpc/src/core/lib/surface/call.h +++ b/contrib/libs/grpc/src/core/lib/surface/call.h @@ -75,7 +75,7 @@ void grpc_call_internal_unref(grpc_call* call); #endif grpc_core::Arena* grpc_call_get_arena(grpc_call* call); - + grpc_call_stack* grpc_call_get_call_stack(grpc_call* call); grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call, @@ -83,10 +83,10 @@ grpc_call_error grpc_call_start_batch_and_execute(grpc_call* call, size_t nops, grpc_closure* closure); -/* gRPC core internal version of grpc_call_cancel that does not create - * exec_ctx. */ -void grpc_call_cancel_internal(grpc_call* call); - +/* gRPC core internal version of grpc_call_cancel that does not create + * exec_ctx. */ +void grpc_call_cancel_internal(grpc_call* call); + /* Given the top call_element, get the call object. */ grpc_call* grpc_call_from_top_element(grpc_call_element* surface_element); @@ -110,11 +110,11 @@ void* grpc_call_context_get(grpc_call* call, grpc_context_index elem); uint8_t grpc_call_is_client(grpc_call* call); -/* Get the estimated memory size for a call BESIDES the call stack. Combined - * with the size of the call stack, it helps estimate the arena size for the - * initial call. */ -size_t grpc_call_get_initial_size_estimate(); - +/* Get the estimated memory size for a call BESIDES the call stack. Combined + * with the size of the call stack, it helps estimate the arena size for the + * initial call. */ +size_t grpc_call_get_initial_size_estimate(); + /* Return an appropriate compression algorithm for the requested compression \a * level in the context of \a call. */ grpc_compression_algorithm grpc_call_compression_for_level( diff --git a/contrib/libs/grpc/src/core/lib/surface/channel.cc b/contrib/libs/grpc/src/core/lib/surface/channel.cc index 28df8e61ee..47e315762d 100644 --- a/contrib/libs/grpc/src/core/lib/surface/channel.cc +++ b/contrib/libs/grpc/src/core/lib/surface/channel.cc @@ -32,7 +32,7 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_trace.h" -#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channelz.h" #include "src/core/lib/channel/channelz_registry.h" #include "src/core/lib/debug/stats.h" #include "src/core/lib/gpr/string.h" @@ -40,7 +40,7 @@ #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/core/lib/iomgr/iomgr.h" -#include "src/core/lib/iomgr/resource_quota.h" +#include "src/core/lib/iomgr/resource_quota.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/api_trace.h" #include "src/core/lib/surface/call.h" @@ -62,8 +62,8 @@ grpc_channel* grpc_channel_create_with_builder( char* target = gpr_strdup(grpc_channel_stack_builder_get_target(builder)); grpc_channel_args* args = grpc_channel_args_copy( grpc_channel_stack_builder_get_channel_arguments(builder)); - grpc_resource_user* resource_user = - grpc_channel_stack_builder_get_resource_user(builder); + grpc_resource_user* resource_user = + grpc_channel_stack_builder_get_resource_user(builder); grpc_channel* channel; if (channel_stack_type == GRPC_SERVER_CHANNEL) { GRPC_STATS_INC_SERVER_CHANNELS_CREATED(); @@ -82,14 +82,14 @@ grpc_channel* grpc_channel_create_with_builder( return channel; } channel->target = target; - channel->resource_user = resource_user; + channel->resource_user = resource_user; channel->is_client = grpc_channel_stack_type_is_client(channel_stack_type); channel->registration_table.Init(); gpr_atm_no_barrier_store( &channel->call_size_estimate, - (gpr_atm)CHANNEL_STACK_FROM_CHANNEL(channel)->call_stack_size + - grpc_call_get_initial_size_estimate()); + (gpr_atm)CHANNEL_STACK_FROM_CHANNEL(channel)->call_stack_size + + grpc_call_get_initial_size_estimate()); grpc_compression_options_init(&channel->compression_options); for (size_t i = 0; i < args->num_args; i++) { @@ -218,8 +218,8 @@ void CreateChannelzNode(grpc_channel_stack_builder* builder) { grpc_channel* grpc_channel_create(const char* target, const grpc_channel_args* input_args, grpc_channel_stack_type channel_stack_type, - grpc_transport* optional_transport, - grpc_resource_user* resource_user) { + grpc_transport* optional_transport, + grpc_resource_user* resource_user) { // We need to make sure that grpc_shutdown() does not shut things down // until after the channel is destroyed. However, the channel may not // actually be destroyed by the time grpc_channel_destroy() returns, @@ -253,12 +253,12 @@ grpc_channel* grpc_channel_create(const char* target, grpc_channel_args_destroy(args); grpc_channel_stack_builder_set_target(builder, target); grpc_channel_stack_builder_set_transport(builder, optional_transport); - grpc_channel_stack_builder_set_resource_user(builder, resource_user); + grpc_channel_stack_builder_set_resource_user(builder, resource_user); if (!grpc_channel_init_create_stack(builder, channel_stack_type)) { grpc_channel_stack_builder_destroy(builder); - if (resource_user != nullptr) { - grpc_resource_user_free(resource_user, GRPC_RESOURCE_QUOTA_CHANNEL_SIZE); - } + if (resource_user != nullptr) { + grpc_resource_user_free(resource_user, GRPC_RESOURCE_QUOTA_CHANNEL_SIZE); + } grpc_shutdown(); // Since we won't call destroy_channel(). return nullptr; } @@ -267,12 +267,12 @@ grpc_channel* grpc_channel_create(const char* target, if (grpc_channel_stack_type_is_client(channel_stack_type)) { CreateChannelzNode(builder); } - grpc_channel* channel = - grpc_channel_create_with_builder(builder, channel_stack_type); + grpc_channel* channel = + grpc_channel_create_with_builder(builder, channel_stack_type); if (channel == nullptr) { grpc_shutdown(); // Since we won't call destroy_channel(). } - return channel; + return channel; } size_t grpc_channel_get_call_size_estimate(grpc_channel* channel) { @@ -324,18 +324,18 @@ void grpc_channel_get_info(grpc_channel* channel, elem->filter->get_channel_info(elem, channel_info); } -void grpc_channel_reset_connect_backoff(grpc_channel* channel) { +void grpc_channel_reset_connect_backoff(grpc_channel* channel) { grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - grpc_core::ExecCtx exec_ctx; - GRPC_API_TRACE("grpc_channel_reset_connect_backoff(channel=%p)", 1, - (channel)); - grpc_transport_op* op = grpc_make_transport_op(nullptr); - op->reset_connect_backoff = true; - grpc_channel_element* elem = - grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0); - elem->filter->start_transport_op(elem, op); -} - + grpc_core::ExecCtx exec_ctx; + GRPC_API_TRACE("grpc_channel_reset_connect_backoff(channel=%p)", 1, + (channel)); + grpc_transport_op* op = grpc_make_transport_op(nullptr); + op->reset_connect_backoff = true; + grpc_channel_element* elem = + grpc_channel_stack_element(CHANNEL_STACK_FROM_CHANNEL(channel), 0); + elem->filter->start_transport_op(elem, op); +} + static grpc_call* grpc_channel_create_call_internal( grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, grpc_completion_queue* cq, grpc_pollset_set* pollset_set_alternative, @@ -354,7 +354,7 @@ static grpc_call* grpc_channel_create_call_internal( grpc_call_create_args args; args.channel = channel; - args.server = nullptr; + args.server = nullptr; args.parent = parent_call; args.propagation_mask = propagation_mask; args.cq = cq; @@ -380,8 +380,8 @@ grpc_call* grpc_channel_create_call(grpc_channel* channel, grpc_core::ExecCtx exec_ctx; grpc_call* call = grpc_channel_create_call_internal( channel, parent_call, propagation_mask, cq, nullptr, - grpc_mdelem_create(GRPC_MDSTR_PATH, method, nullptr), - host != nullptr ? grpc_mdelem_create(GRPC_MDSTR_AUTHORITY, *host, nullptr) + grpc_mdelem_create(GRPC_MDSTR_PATH, method, nullptr), + host != nullptr ? grpc_mdelem_create(GRPC_MDSTR_AUTHORITY, *host, nullptr) : GRPC_MDNULL, grpc_timespec_to_millis_round_up(deadline)); @@ -390,13 +390,13 @@ grpc_call* grpc_channel_create_call(grpc_channel* channel, grpc_call* grpc_channel_create_pollset_set_call( grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, - grpc_pollset_set* pollset_set, const grpc_slice& method, - const grpc_slice* host, grpc_millis deadline, void* reserved) { + grpc_pollset_set* pollset_set, const grpc_slice& method, + const grpc_slice* host, grpc_millis deadline, void* reserved) { GPR_ASSERT(!reserved); return grpc_channel_create_call_internal( channel, parent_call, propagation_mask, nullptr, pollset_set, - grpc_mdelem_create(GRPC_MDSTR_PATH, method, nullptr), - host != nullptr ? grpc_mdelem_create(GRPC_MDSTR_AUTHORITY, *host, nullptr) + grpc_mdelem_create(GRPC_MDSTR_PATH, method, nullptr), + host != nullptr ? grpc_mdelem_create(GRPC_MDSTR_AUTHORITY, *host, nullptr) : GRPC_MDNULL, deadline); } @@ -495,16 +495,16 @@ static void destroy_channel(void* arg, grpc_error* /*error*/) { grpc_channel* channel = static_cast<grpc_channel*>(arg); if (channel->channelz_node != nullptr) { channel->channelz_node->AddTraceEvent( - grpc_core::channelz::ChannelTrace::Severity::Info, - grpc_slice_from_static_string("Channel destroyed")); + grpc_core::channelz::ChannelTrace::Severity::Info, + grpc_slice_from_static_string("Channel destroyed")); channel->channelz_node.reset(); - } + } grpc_channel_stack_destroy(CHANNEL_STACK_FROM_CHANNEL(channel)); channel->registration_table.Destroy(); - if (channel->resource_user != nullptr) { - grpc_resource_user_free(channel->resource_user, - GRPC_RESOURCE_QUOTA_CHANNEL_SIZE); - } + if (channel->resource_user != nullptr) { + grpc_resource_user_free(channel->resource_user, + GRPC_RESOURCE_QUOTA_CHANNEL_SIZE); + } gpr_free(channel->target); gpr_free(channel); // See comment in grpc_channel_create() for why we do this. diff --git a/contrib/libs/grpc/src/core/lib/surface/channel.h b/contrib/libs/grpc/src/core/lib/surface/channel.h index e49b9261f7..fea79921ed 100644 --- a/contrib/libs/grpc/src/core/lib/surface/channel.h +++ b/contrib/libs/grpc/src/core/lib/surface/channel.h @@ -25,7 +25,7 @@ #include "src/core/lib/channel/channel_stack.h" #include "src/core/lib/channel/channel_stack_builder.h" -#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channelz.h" #include "src/core/lib/gprpp/manual_constructor.h" #include "src/core/lib/surface/channel_stack_type.h" #include "src/core/lib/transport/metadata.h" @@ -33,8 +33,8 @@ grpc_channel* grpc_channel_create(const char* target, const grpc_channel_args* args, grpc_channel_stack_type channel_stack_type, - grpc_transport* optional_transport, - grpc_resource_user* resource_user = nullptr); + grpc_transport* optional_transport, + grpc_resource_user* resource_user = nullptr); /** The same as grpc_channel_destroy, but doesn't create an ExecCtx, and so * is safe to use from within core. */ @@ -54,15 +54,15 @@ grpc_channel* grpc_channel_create_with_builder( value of \a propagation_mask (see propagation_bits.h for possible values) */ grpc_call* grpc_channel_create_pollset_set_call( grpc_channel* channel, grpc_call* parent_call, uint32_t propagation_mask, - grpc_pollset_set* pollset_set, const grpc_slice& method, - const grpc_slice* host, grpc_millis deadline, void* reserved); + grpc_pollset_set* pollset_set, const grpc_slice& method, + const grpc_slice* host, grpc_millis deadline, void* reserved); /** Get a (borrowed) pointer to this channels underlying channel stack */ grpc_channel_stack* grpc_channel_get_channel_stack(grpc_channel* channel); -grpc_core::channelz::ChannelNode* grpc_channel_get_channelz_node( - grpc_channel* channel); - +grpc_core::channelz::ChannelNode* grpc_channel_get_channelz_node( + grpc_channel* channel); + size_t grpc_channel_get_call_size_estimate(grpc_channel* channel); void grpc_channel_update_call_size_estimate(grpc_channel* channel, size_t size); diff --git a/contrib/libs/grpc/src/core/lib/surface/channel_init.h b/contrib/libs/grpc/src/core/lib/surface/channel_init.h index d17a721606..37468314ac 100644 --- a/contrib/libs/grpc/src/core/lib/surface/channel_init.h +++ b/contrib/libs/grpc/src/core/lib/surface/channel_init.h @@ -45,11 +45,11 @@ void grpc_channel_init_init(void); /// registration order (in the case of a tie). /// Stages are registered against one of the pre-determined channel stack /// types. -/// If the channel stack type is GRPC_CLIENT_SUBCHANNEL, the caller should -/// ensure that subchannels with different filter lists will always have -/// different channel args. This requires setting a channel arg in case the -/// registration function relies on some condition other than channel args to -/// decide whether to add a filter or not. +/// If the channel stack type is GRPC_CLIENT_SUBCHANNEL, the caller should +/// ensure that subchannels with different filter lists will always have +/// different channel args. This requires setting a channel arg in case the +/// registration function relies on some condition other than channel args to +/// decide whether to add a filter or not. void grpc_channel_init_register_stage(grpc_channel_stack_type type, int priority, grpc_channel_init_stage stage_fn, diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc b/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc index 0f50906734..5a131c5016 100644 --- a/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc +++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue.cc @@ -86,7 +86,7 @@ typedef struct non_polling_worker { struct non_polling_poller { gpr_mu mu; - bool kicked_without_poller; + bool kicked_without_poller; non_polling_worker* root; grpc_closure* shutdown; }; @@ -108,10 +108,10 @@ grpc_error* non_polling_poller_work(grpc_pollset* pollset, grpc_millis deadline) { non_polling_poller* npp = reinterpret_cast<non_polling_poller*>(pollset); if (npp->shutdown) return GRPC_ERROR_NONE; - if (npp->kicked_without_poller) { - npp->kicked_without_poller = false; - return GRPC_ERROR_NONE; - } + if (npp->kicked_without_poller) { + npp->kicked_without_poller = false; + return GRPC_ERROR_NONE; + } non_polling_worker w; gpr_cv_init(&w.cv); if (worker != nullptr) *worker = reinterpret_cast<grpc_pollset_worker*>(&w); @@ -157,8 +157,8 @@ grpc_error* non_polling_poller_kick(grpc_pollset* pollset, w->kicked = true; gpr_cv_signal(&w->cv); } - } else { - p->kicked_without_poller = true; + } else { + p->kicked_without_poller = true; } return GRPC_ERROR_NONE; } @@ -196,8 +196,8 @@ const cq_poller_vtable g_poller_vtable_by_poller_type[] = { struct cq_vtable { grpc_cq_completion_type cq_completion_type; size_t data_size; - void (*init)(void* data, - grpc_experimental_completion_queue_functor* shutdown_callback); + void (*init)(void* data, + grpc_experimental_completion_queue_functor* shutdown_callback); void (*shutdown)(grpc_completion_queue* cq); void (*destroy)(void* data); bool (*begin_op)(grpc_completion_queue* cq, void* tag); @@ -321,19 +321,19 @@ struct cq_callback_data { #endif } - /** No actual completed events queue, unlike other types */ - + /** No actual completed events queue, unlike other types */ + /** Number of pending events (+1 if we're not shutdown). Initial count is dropped by grpc_completion_queue_shutdown. */ grpc_core::Atomic<intptr_t> pending_events{1}; - - /** 0 initially. 1 once we initiated shutdown */ + + /** 0 initially. 1 once we initiated shutdown */ bool shutdown_called = false; - - /** A callback that gets invoked when the CQ completes shutdown */ - grpc_experimental_completion_queue_functor* shutdown_callback; + + /** A callback that gets invoked when the CQ completes shutdown */ + grpc_experimental_completion_queue_functor* shutdown_callback; }; - + } // namespace /* Completion queue structure */ @@ -359,21 +359,21 @@ struct grpc_completion_queue { /* Forward declarations */ static void cq_finish_shutdown_next(grpc_completion_queue* cq); static void cq_finish_shutdown_pluck(grpc_completion_queue* cq); -static void cq_finish_shutdown_callback(grpc_completion_queue* cq); +static void cq_finish_shutdown_callback(grpc_completion_queue* cq); static void cq_shutdown_next(grpc_completion_queue* cq); static void cq_shutdown_pluck(grpc_completion_queue* cq); -static void cq_shutdown_callback(grpc_completion_queue* cq); +static void cq_shutdown_callback(grpc_completion_queue* cq); static bool cq_begin_op_for_next(grpc_completion_queue* cq, void* tag); static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* tag); -static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* tag); - -// A cq_end_op function is called when an operation on a given CQ with -// a given tag has completed. The storage argument is a reference to the -// space reserved for this completion as it is placed into the corresponding -// queue. The done argument is a callback that will be invoked when it is -// safe to free up that storage. The storage MUST NOT be freed until the -// done callback is invoked. +static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* tag); + +// A cq_end_op function is called when an operation on a given CQ with +// a given tag has completed. The storage argument is a reference to the +// space reserved for this completion as it is placed into the corresponding +// queue. The done argument is a callback that will be invoked when it is +// safe to free up that storage. The storage MUST NOT be freed until the +// done callback is invoked. static void cq_end_op_for_next( grpc_completion_queue* cq, void* tag, grpc_error* error, void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg, @@ -388,23 +388,23 @@ static void cq_end_op_for_callback( grpc_completion_queue* cq, void* tag, grpc_error* error, void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg, grpc_cq_completion* storage, bool internal); - + static grpc_event cq_next(grpc_completion_queue* cq, gpr_timespec deadline, void* reserved); static grpc_event cq_pluck(grpc_completion_queue* cq, void* tag, gpr_timespec deadline, void* reserved); -// Note that cq_init_next and cq_init_pluck do not use the shutdown_callback -static void cq_init_next( - void* data, grpc_experimental_completion_queue_functor* shutdown_callback); -static void cq_init_pluck( - void* data, grpc_experimental_completion_queue_functor* shutdown_callback); -static void cq_init_callback( - void* data, grpc_experimental_completion_queue_functor* shutdown_callback); +// Note that cq_init_next and cq_init_pluck do not use the shutdown_callback +static void cq_init_next( + void* data, grpc_experimental_completion_queue_functor* shutdown_callback); +static void cq_init_pluck( + void* data, grpc_experimental_completion_queue_functor* shutdown_callback); +static void cq_init_callback( + void* data, grpc_experimental_completion_queue_functor* shutdown_callback); static void cq_destroy_next(void* data); static void cq_destroy_pluck(void* data); -static void cq_destroy_callback(void* data); +static void cq_destroy_callback(void* data); /* Completion queue vtables based on the completion-type */ static const cq_vtable g_cq_vtable[] = { @@ -416,17 +416,17 @@ static const cq_vtable g_cq_vtable[] = { {GRPC_CQ_PLUCK, sizeof(cq_pluck_data), cq_init_pluck, cq_shutdown_pluck, cq_destroy_pluck, cq_begin_op_for_pluck, cq_end_op_for_pluck, nullptr, cq_pluck}, - /* GRPC_CQ_CALLBACK */ - {GRPC_CQ_CALLBACK, sizeof(cq_callback_data), cq_init_callback, - cq_shutdown_callback, cq_destroy_callback, cq_begin_op_for_callback, - cq_end_op_for_callback, nullptr, nullptr}, + /* GRPC_CQ_CALLBACK */ + {GRPC_CQ_CALLBACK, sizeof(cq_callback_data), cq_init_callback, + cq_shutdown_callback, cq_destroy_callback, cq_begin_op_for_callback, + cq_end_op_for_callback, nullptr, nullptr}, }; #define DATA_FROM_CQ(cq) ((void*)(cq + 1)) #define POLLSET_FROM_CQ(cq) \ ((grpc_pollset*)(cq->vtable->data_size + (char*)DATA_FROM_CQ(cq))) -grpc_core::TraceFlag grpc_cq_pluck_trace(false, "queue_pluck"); +grpc_core::TraceFlag grpc_cq_pluck_trace(false, "queue_pluck"); #define GRPC_SURFACE_TRACE_RETURNED_EVENT(cq, event) \ do { \ @@ -510,8 +510,8 @@ grpc_cq_completion* CqEventQueue::Pop() { } grpc_completion_queue* grpc_completion_queue_create_internal( - grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type, - grpc_experimental_completion_queue_functor* shutdown_callback) { + grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type, + grpc_experimental_completion_queue_functor* shutdown_callback) { GPR_TIMER_SCOPE("grpc_completion_queue_create_internal", 0); grpc_completion_queue* cq; @@ -539,45 +539,45 @@ grpc_completion_queue* grpc_completion_queue_create_internal( new (&cq->owning_refs) grpc_core::RefCount(2); poller_vtable->init(POLLSET_FROM_CQ(cq), &cq->mu); - vtable->init(DATA_FROM_CQ(cq), shutdown_callback); + vtable->init(DATA_FROM_CQ(cq), shutdown_callback); GRPC_CLOSURE_INIT(&cq->pollset_shutdown_done, on_pollset_shutdown_done, cq, grpc_schedule_on_exec_ctx); return cq; } -static void cq_init_next( +static void cq_init_next( void* data, grpc_experimental_completion_queue_functor* /*shutdown_callback*/) { new (data) cq_next_data(); } -static void cq_destroy_next(void* data) { - cq_next_data* cqd = static_cast<cq_next_data*>(data); +static void cq_destroy_next(void* data) { + cq_next_data* cqd = static_cast<cq_next_data*>(data); cqd->~cq_next_data(); } -static void cq_init_pluck( +static void cq_init_pluck( void* data, grpc_experimental_completion_queue_functor* /*shutdown_callback*/) { new (data) cq_pluck_data(); } -static void cq_destroy_pluck(void* data) { - cq_pluck_data* cqd = static_cast<cq_pluck_data*>(data); +static void cq_destroy_pluck(void* data) { + cq_pluck_data* cqd = static_cast<cq_pluck_data*>(data); cqd->~cq_pluck_data(); } -static void cq_init_callback( - void* data, grpc_experimental_completion_queue_functor* shutdown_callback) { +static void cq_init_callback( + void* data, grpc_experimental_completion_queue_functor* shutdown_callback) { new (data) cq_callback_data(shutdown_callback); } static void cq_destroy_callback(void* data) { - cq_callback_data* cqd = static_cast<cq_callback_data*>(data); + cq_callback_data* cqd = static_cast<cq_callback_data*>(data); cqd->~cq_callback_data(); -} - +} + grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cq) { return cq->vtable->cq_completion_type; } @@ -665,10 +665,10 @@ static bool cq_begin_op_for_pluck(grpc_completion_queue* cq, void* /*tag*/) { } static bool cq_begin_op_for_callback(grpc_completion_queue* cq, void* /*tag*/) { - cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); + cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); return cqd->pending_events.IncrementIfNonzero(); -} - +} + bool grpc_cq_begin_op(grpc_completion_queue* cq, void* tag) { #ifndef NDEBUG gpr_mu_lock(cq->mu); @@ -837,39 +837,39 @@ static void functor_callback(void* arg, grpc_error* error) { functor->functor_run(functor, error == GRPC_ERROR_NONE); } -/* Complete an event on a completion queue of type GRPC_CQ_CALLBACK */ -static void cq_end_op_for_callback( - grpc_completion_queue* cq, void* tag, grpc_error* error, - void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg, +/* Complete an event on a completion queue of type GRPC_CQ_CALLBACK */ +static void cq_end_op_for_callback( + grpc_completion_queue* cq, void* tag, grpc_error* error, + void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg, grpc_cq_completion* storage, bool internal) { - GPR_TIMER_SCOPE("cq_end_op_for_callback", 0); - - cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); - + GPR_TIMER_SCOPE("cq_end_op_for_callback", 0); + + cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); + if (GRPC_TRACE_FLAG_ENABLED(grpc_api_trace) || (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && error != GRPC_ERROR_NONE)) { - const char* errmsg = grpc_error_string(error); - GRPC_API_TRACE( - "cq_end_op_for_callback(cq=%p, tag=%p, error=%s, " - "done=%p, done_arg=%p, storage=%p)", - 6, (cq, tag, errmsg, done, done_arg, storage)); + const char* errmsg = grpc_error_string(error); + GRPC_API_TRACE( + "cq_end_op_for_callback(cq=%p, tag=%p, error=%s, " + "done=%p, done_arg=%p, storage=%p)", + 6, (cq, tag, errmsg, done, done_arg, storage)); if (GRPC_TRACE_FLAG_ENABLED(grpc_trace_operation_failures) && error != GRPC_ERROR_NONE) { - gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg); - } - } - - // The callback-based CQ isn't really a queue at all and thus has no need - // for reserved storage. Invoke the done callback right away to release it. - done(done_arg, storage); - - cq_check_tag(cq, tag, true); /* Used in debug builds only */ - + gpr_log(GPR_ERROR, "Operation failed: tag=%p, error=%s", tag, errmsg); + } + } + + // The callback-based CQ isn't really a queue at all and thus has no need + // for reserved storage. Invoke the done callback right away to release it. + done(done_arg, storage); + + cq_check_tag(cq, tag, true); /* Used in debug builds only */ + if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) { - cq_finish_shutdown_callback(cq); - } - + cq_finish_shutdown_callback(cq); + } + // If possible, schedule the callback onto an existing thread-local // ApplicationCallbackExecCtx, which is a work queue. This is possible for: // 1. The callback is internally-generated and there is an ACEC available @@ -885,13 +885,13 @@ static void cq_end_op_for_callback( GRPC_ERROR_UNREF(error); return; } - + // Schedule the callback on a closure if not internal or triggered // from a background poller thread. grpc_core::Executor::Run( GRPC_CLOSURE_CREATE(functor_callback, functor, nullptr), error); -} - +} + void grpc_cq_end_op(grpc_completion_queue* cq, void* tag, grpc_error* error, void (*done)(void* done_arg, grpc_cq_completion* storage), void* done_arg, grpc_cq_completion* storage, @@ -1360,13 +1360,13 @@ static void cq_shutdown_pluck(grpc_completion_queue* cq) { GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (pluck cq)"); } -static void cq_finish_shutdown_callback(grpc_completion_queue* cq) { - cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); - auto* callback = cqd->shutdown_callback; - - GPR_ASSERT(cqd->shutdown_called); - - cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done); +static void cq_finish_shutdown_callback(grpc_completion_queue* cq) { + cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); + auto* callback = cqd->shutdown_callback; + + GPR_ASSERT(cqd->shutdown_called); + + cq->poller_vtable->shutdown(POLLSET_FROM_CQ(cq), &cq->pollset_shutdown_done); if (grpc_iomgr_is_any_background_poller_thread()) { grpc_core::ApplicationCallbackExecCtx::Enqueue(callback, true); return; @@ -1377,39 +1377,39 @@ static void cq_finish_shutdown_callback(grpc_completion_queue* cq) { grpc_core::Executor::Run( GRPC_CLOSURE_CREATE(functor_callback, callback, nullptr), GRPC_ERROR_NONE); -} - -static void cq_shutdown_callback(grpc_completion_queue* cq) { - cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); - - /* Need an extra ref for cq here because: - * We call cq_finish_shutdown_callback() below, which calls pollset shutdown. - * Pollset shutdown decrements the cq ref count which can potentially destroy - * the cq (if that happens to be the last ref). - * Creating an extra ref here prevents the cq from getting destroyed while - * this function is still active */ - GRPC_CQ_INTERNAL_REF(cq, "shutting_down (callback cq)"); - gpr_mu_lock(cq->mu); - if (cqd->shutdown_called) { - gpr_mu_unlock(cq->mu); - GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)"); - return; - } - cqd->shutdown_called = true; +} + +static void cq_shutdown_callback(grpc_completion_queue* cq) { + cq_callback_data* cqd = static_cast<cq_callback_data*> DATA_FROM_CQ(cq); + + /* Need an extra ref for cq here because: + * We call cq_finish_shutdown_callback() below, which calls pollset shutdown. + * Pollset shutdown decrements the cq ref count which can potentially destroy + * the cq (if that happens to be the last ref). + * Creating an extra ref here prevents the cq from getting destroyed while + * this function is still active */ + GRPC_CQ_INTERNAL_REF(cq, "shutting_down (callback cq)"); + gpr_mu_lock(cq->mu); + if (cqd->shutdown_called) { + gpr_mu_unlock(cq->mu); + GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)"); + return; + } + cqd->shutdown_called = true; if (cqd->pending_events.FetchSub(1, grpc_core::MemoryOrder::ACQ_REL) == 1) { - gpr_mu_unlock(cq->mu); - cq_finish_shutdown_callback(cq); - } else { - gpr_mu_unlock(cq->mu); - } - GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)"); -} - + gpr_mu_unlock(cq->mu); + cq_finish_shutdown_callback(cq); + } else { + gpr_mu_unlock(cq->mu); + } + GRPC_CQ_INTERNAL_UNREF(cq, "shutting_down (callback cq)"); +} + /* Shutdown simply drops a ref that we reserved at creation time; if we drop to zero here, then enter shutdown mode and wake up any waiters */ void grpc_completion_queue_shutdown(grpc_completion_queue* cq) { GPR_TIMER_SCOPE("grpc_completion_queue_shutdown", 0); - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE("grpc_completion_queue_shutdown(cq=%p)", 1, (cq)); cq->vtable->shutdown(cq); diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue.h b/contrib/libs/grpc/src/core/lib/surface/completion_queue.h index 4a114be828..103e8d4110 100644 --- a/contrib/libs/grpc/src/core/lib/surface/completion_queue.h +++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue.h @@ -91,7 +91,7 @@ grpc_cq_completion_type grpc_get_cq_completion_type(grpc_completion_queue* cc); int grpc_get_cq_poll_num(grpc_completion_queue* cc); grpc_completion_queue* grpc_completion_queue_create_internal( - grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type, - grpc_experimental_completion_queue_functor* shutdown_callback); + grpc_cq_completion_type completion_type, grpc_cq_polling_type polling_type, + grpc_experimental_completion_queue_functor* shutdown_callback); #endif /* GRPC_CORE_LIB_SURFACE_COMPLETION_QUEUE_H */ diff --git a/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc b/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc index 72aa03adfd..f00545cedb 100644 --- a/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc +++ b/contrib/libs/grpc/src/core/lib/surface/completion_queue_factory.cc @@ -30,8 +30,8 @@ static grpc_completion_queue* default_create( const grpc_completion_queue_factory* /*factory*/, const grpc_completion_queue_attributes* attr) { - return grpc_completion_queue_create_internal( - attr->cq_completion_type, attr->cq_polling_type, attr->cq_shutdown_cb); + return grpc_completion_queue_create_internal( + attr->cq_completion_type, attr->cq_polling_type, attr->cq_shutdown_cb); } static grpc_completion_queue_factory_vtable default_vtable = {default_create}; @@ -60,26 +60,26 @@ const grpc_completion_queue_factory* grpc_completion_queue_factory_lookup( grpc_completion_queue* grpc_completion_queue_create_for_next(void* reserved) { GPR_ASSERT(!reserved); grpc_completion_queue_attributes attr = {1, GRPC_CQ_NEXT, - GRPC_CQ_DEFAULT_POLLING, nullptr}; + GRPC_CQ_DEFAULT_POLLING, nullptr}; return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr); } grpc_completion_queue* grpc_completion_queue_create_for_pluck(void* reserved) { GPR_ASSERT(!reserved); grpc_completion_queue_attributes attr = {1, GRPC_CQ_PLUCK, - GRPC_CQ_DEFAULT_POLLING, nullptr}; - return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr); -} - -grpc_completion_queue* grpc_completion_queue_create_for_callback( - grpc_experimental_completion_queue_functor* shutdown_callback, - void* reserved) { - GPR_ASSERT(!reserved); - grpc_completion_queue_attributes attr = { - 2, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING, shutdown_callback}; + GRPC_CQ_DEFAULT_POLLING, nullptr}; return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr); } +grpc_completion_queue* grpc_completion_queue_create_for_callback( + grpc_experimental_completion_queue_functor* shutdown_callback, + void* reserved) { + GPR_ASSERT(!reserved); + grpc_completion_queue_attributes attr = { + 2, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING, shutdown_callback}; + return g_default_cq_factory.vtable->create(&g_default_cq_factory, &attr); +} + grpc_completion_queue* grpc_completion_queue_create( const grpc_completion_queue_factory* factory, const grpc_completion_queue_attributes* attr, void* reserved) { diff --git a/contrib/libs/grpc/src/core/lib/surface/init.cc b/contrib/libs/grpc/src/core/lib/surface/init.cc index 7b79ba426b..28b9e70b08 100644 --- a/contrib/libs/grpc/src/core/lib/surface/init.cc +++ b/contrib/libs/grpc/src/core/lib/surface/init.cc @@ -30,12 +30,12 @@ #include <grpc/support/time.h> #include "src/core/lib/channel/channel_stack.h" -#include "src/core/lib/channel/channelz_registry.h" +#include "src/core/lib/channel/channelz_registry.h" #include "src/core/lib/channel/connected_channel.h" #include "src/core/lib/channel/handshaker_registry.h" #include "src/core/lib/debug/stats.h" #include "src/core/lib/debug/trace.h" -#include "src/core/lib/gprpp/fork.h" +#include "src/core/lib/gprpp/fork.h" #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/http/parser.h" #include "src/core/lib/iomgr/call_combiner.h" @@ -135,20 +135,20 @@ void grpc_init(void) { g_shutting_down = false; gpr_cv_broadcast(g_shutting_down_cv); } - grpc_core::Fork::GlobalInit(); - grpc_fork_handlers_auto_register(); + grpc_core::Fork::GlobalInit(); + grpc_fork_handlers_auto_register(); grpc_stats_init(); grpc_init_static_metadata_ctx(); grpc_slice_intern_init(); grpc_mdctx_global_init(); grpc_channel_init_init(); - grpc_core::channelz::ChannelzRegistry::Init(); + grpc_core::channelz::ChannelzRegistry::Init(); grpc_security_pre_init(); - grpc_core::ApplicationCallbackExecCtx::GlobalInit(); + grpc_core::ApplicationCallbackExecCtx::GlobalInit(); grpc_core::ExecCtx::GlobalInit(); grpc_iomgr_init(); gpr_timers_global_init(); - grpc_core::HandshakerRegistry::Init(); + grpc_core::HandshakerRegistry::Init(); grpc_security_init(); for (i = 0; i < g_number_of_plugins; i++) { if (g_all_of_the_plugins[i].init != nullptr) { diff --git a/contrib/libs/grpc/src/core/lib/surface/init_secure.cc b/contrib/libs/grpc/src/core/lib/surface/init_secure.cc index 428c5815c9..900ecd832b 100644 --- a/contrib/libs/grpc/src/core/lib/surface/init_secure.cc +++ b/contrib/libs/grpc/src/core/lib/surface/init_secure.cc @@ -74,7 +74,7 @@ void grpc_register_security_filters(void) { maybe_prepend_client_auth_filter, nullptr); grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL, INT_MAX - 1, maybe_prepend_client_auth_filter, nullptr); - grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX - 1, + grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX - 1, maybe_prepend_server_auth_filter, nullptr); } diff --git a/contrib/libs/grpc/src/core/lib/surface/server.cc b/contrib/libs/grpc/src/core/lib/surface/server.cc index 0775c6ee4c..984db951a5 100644 --- a/contrib/libs/grpc/src/core/lib/surface/server.cc +++ b/contrib/libs/grpc/src/core/lib/surface/server.cc @@ -61,7 +61,7 @@ TraceFlag grpc_server_channel_trace(false, "server_channel"); // // Server::RequestedCall // - + struct Server::RequestedCall { enum class Type { BATCH_CALL, REGISTERED_CALL }; @@ -948,7 +948,7 @@ class Server::ChannelData::ConnectivityWatcher // Shut down channel. MutexLock lock(&chand_->server_->mu_global_); chand_->Destroy(); - } + } ChannelData* chand_; }; @@ -983,7 +983,7 @@ Server::ChannelData::~ChannelData() { } server_->MaybeFinishShutdown(); } - } + } } void Server::ChannelData::InitTransport(RefCountedPtr<Server> server, @@ -1092,13 +1092,13 @@ void Server::ChannelData::AcceptStream(void* arg, grpc_transport* /*transport*/, grpc_call_create_args args; args.channel = chand->channel_; args.server = chand->server_.get(); - args.parent = nullptr; - args.propagation_mask = 0; - args.cq = nullptr; - args.pollset_set_alternative = nullptr; + args.parent = nullptr; + args.propagation_mask = 0; + args.cq = nullptr; + args.pollset_set_alternative = nullptr; args.server_transport_data = transport_server_data; - args.add_initial_metadata = nullptr; - args.add_initial_metadata_count = 0; + args.add_initial_metadata = nullptr; + args.add_initial_metadata_count = 0; args.send_deadline = GRPC_MILLIS_INF_FUTURE; grpc_call* call; grpc_error* error = grpc_call_create(&args, &call); @@ -1459,12 +1459,12 @@ void grpc_server_register_completion_queue(grpc_server* server, "grpc_server_register_completion_queue(server=%p, cq=%p, reserved=%p)", 3, (server, cq, reserved)); GPR_ASSERT(!reserved); - auto cq_type = grpc_get_cq_completion_type(cq); - if (cq_type != GRPC_CQ_NEXT && cq_type != GRPC_CQ_CALLBACK) { + auto cq_type = grpc_get_cq_completion_type(cq); + if (cq_type != GRPC_CQ_NEXT && cq_type != GRPC_CQ_CALLBACK) { gpr_log(GPR_INFO, - "Completion queue of type %d is being registered as a " - "server-completion-queue", - static_cast<int>(cq_type)); + "Completion queue of type %d is being registered as a " + "server-completion-queue", + static_cast<int>(cq_type)); /* Ideally we should log an error and abort but ruby-wrapped-language API calls grpc_completion_queue_pluck() on server completion queues */ } @@ -1491,7 +1491,7 @@ void grpc_server_start(grpc_server* server) { void grpc_server_shutdown_and_notify(grpc_server* server, grpc_completion_queue* cq, void* tag) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE("grpc_server_shutdown_and_notify(server=%p, cq=%p, tag=%p)", 3, (server, cq, tag)); @@ -1499,14 +1499,14 @@ void grpc_server_shutdown_and_notify(grpc_server* server, } void grpc_server_cancel_all_calls(grpc_server* server) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE("grpc_server_cancel_all_calls(server=%p)", 1, (server)); server->core_server->CancelAllCalls(); } void grpc_server_destroy(grpc_server* server) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_API_TRACE("grpc_server_destroy(server=%p)", 1, (server)); delete server; @@ -1517,7 +1517,7 @@ grpc_call_error grpc_server_request_call( grpc_metadata_array* request_metadata, grpc_completion_queue* cq_bound_to_call, grpc_completion_queue* cq_for_notification, void* tag) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; GRPC_STATS_INC_SERVER_REQUESTED_CALLS(); GRPC_API_TRACE( @@ -1537,9 +1537,9 @@ grpc_call_error grpc_server_request_registered_call( grpc_metadata_array* request_metadata, grpc_byte_buffer** optional_payload, grpc_completion_queue* cq_bound_to_call, grpc_completion_queue* cq_for_notification, void* tag_new) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; - GRPC_STATS_INC_SERVER_REQUESTED_CALLS(); + GRPC_STATS_INC_SERVER_REQUESTED_CALLS(); auto* rm = static_cast<grpc_core::Server::RegisteredMethod*>(rmp); GRPC_API_TRACE( "grpc_server_request_registered_call(" diff --git a/contrib/libs/grpc/src/core/lib/surface/server.h b/contrib/libs/grpc/src/core/lib/surface/server.h index f4f4ff6449..9772f75f3d 100644 --- a/contrib/libs/grpc/src/core/lib/surface/server.h +++ b/contrib/libs/grpc/src/core/lib/surface/server.h @@ -28,7 +28,7 @@ #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/channel/channel_stack.h" -#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/channel/channelz.h" #include "src/core/lib/debug/trace.h" #include "src/core/lib/gprpp/atomic.h" #include "src/core/lib/surface/completion_queue.h" @@ -54,7 +54,7 @@ class Server : public InternallyRefCounted<Server> { grpc_metadata_array* initial_metadata; grpc_call_details* details; }; - + // An object to represent the most relevant characteristics of a // newly-allocated call object when using an // AllocatingRequestMatcherRegistered. @@ -72,7 +72,7 @@ class Server : public InternallyRefCounted<Server> { class ListenerInterface : public Orphanable { public: virtual ~ListenerInterface() = default; - + /// Starts listening. This listener may refer to the pollset object beyond /// this call, so it is a pointer rather than a reference. virtual void Start(Server* server, diff --git a/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc b/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc index 82f34ca150..a627896e14 100644 --- a/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc +++ b/contrib/libs/grpc/src/core/lib/transport/byte_stream.cc @@ -45,7 +45,7 @@ SliceBufferByteStream::SliceBufferByteStream(grpc_slice_buffer* slice_buffer, SliceBufferByteStream::~SliceBufferByteStream() {} void SliceBufferByteStream::Orphan() { - grpc_slice_buffer_destroy_internal(&backing_buffer_); + grpc_slice_buffer_destroy_internal(&backing_buffer_); GRPC_ERROR_UNREF(shutdown_error_); // Note: We do not actually delete the object here, since // SliceBufferByteStream is usually allocated as part of a larger diff --git a/contrib/libs/grpc/src/core/lib/transport/error_utils.cc b/contrib/libs/grpc/src/core/lib/transport/error_utils.cc index 9634f09ad1..c513ba9eca 100644 --- a/contrib/libs/grpc/src/core/lib/transport/error_utils.cc +++ b/contrib/libs/grpc/src/core/lib/transport/error_utils.cc @@ -27,9 +27,9 @@ static grpc_error* recursively_find_error_with_field(grpc_error* error, grpc_error_ints which) { - intptr_t unused; + intptr_t unused; // If the error itself has a status code, return it. - if (grpc_error_get_int(error, which, &unused)) { + if (grpc_error_get_int(error, which, &unused)) { return error; } if (grpc_error_is_special(error)) return nullptr; @@ -137,8 +137,8 @@ y_absl::Status grpc_error_to_absl_status(grpc_error* error) { } bool grpc_error_has_clear_grpc_status(grpc_error* error) { - intptr_t unused; - if (grpc_error_get_int(error, GRPC_ERROR_INT_GRPC_STATUS, &unused)) { + intptr_t unused; + if (grpc_error_get_int(error, GRPC_ERROR_INT_GRPC_STATUS, &unused)) { return true; } uint8_t slot = error->first_err; diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata.cc b/contrib/libs/grpc/src/core/lib/transport/metadata.cc index 33d4d5ac70..62d00770f8 100644 --- a/contrib/libs/grpc/src/core/lib/transport/metadata.cc +++ b/contrib/libs/grpc/src/core/lib/transport/metadata.cc @@ -361,7 +361,7 @@ static grpc_mdelem md_create_must_intern(const grpc_slice& key, template <bool key_definitely_static, bool value_definitely_static = false> static grpc_mdelem md_create( - const grpc_slice& key, const grpc_slice& value, + const grpc_slice& key, const grpc_slice& value, grpc_mdelem_data* compatible_external_backing_store) { // Ensure slices are, in fact, static if we claimed they were. GPR_DEBUG_ASSERT(!key_definitely_static || @@ -510,8 +510,8 @@ static grpc_mdelem md_from_slices(const grpc_slice& key, return out; } -grpc_mdelem grpc_mdelem_from_slices(const grpc_slice& key, - const grpc_slice& value) { +grpc_mdelem grpc_mdelem_from_slices(const grpc_slice& key, + const grpc_slice& value) { return md_from_slices</*key_definitely_static=*/false>(key, value); } diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata.h b/contrib/libs/grpc/src/core/lib/transport/metadata.h index 4bb8d64dd0..26b3309a95 100644 --- a/contrib/libs/grpc/src/core/lib/transport/metadata.h +++ b/contrib/libs/grpc/src/core/lib/transport/metadata.h @@ -119,8 +119,8 @@ struct grpc_mdelem { * the input slices; we unref them. This method is always safe to call; however, * if we know data about the slices in question (e.g. if we knew our key was * static) we can call specializations that save on cycle count. */ -grpc_mdelem grpc_mdelem_from_slices(const grpc_slice& key, - const grpc_slice& value); +grpc_mdelem grpc_mdelem_from_slices(const grpc_slice& key, + const grpc_slice& value); /* Like grpc_mdelem_from_slices, but we know that key is a static slice. This saves us a few branches and a no-op call to md_unref() for the key. */ @@ -149,7 +149,7 @@ grpc_mdelem grpc_mdelem_from_grpc_metadata(grpc_metadata* metadata); compatible_external_backing_store if it is non-NULL (in which case it's the users responsibility to ensure that it outlives usage) */ grpc_mdelem grpc_mdelem_create( - const grpc_slice& key, const grpc_slice& value, + const grpc_slice& key, const grpc_slice& value, grpc_mdelem_data* compatible_external_backing_store); /* Like grpc_mdelem_create, but we know that key is static. */ diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc index 66749b671c..66d17b9365 100644 --- a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc +++ b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.cc @@ -137,7 +137,7 @@ static void maybe_unlink_callout(grpc_metadata_batch* batch, if (idx == GRPC_BATCH_CALLOUTS_COUNT) { return; } - --batch->list.default_count; + --batch->list.default_count; GPR_DEBUG_ASSERT(batch->idx.array[idx] != nullptr); batch->idx.array[idx] = nullptr; } @@ -155,7 +155,7 @@ static void link_head(grpc_mdelem_list* list, grpc_linked_mdelem* storage) { GPR_DEBUG_ASSERT(!GRPC_MDISNULL(storage->md)); storage->prev = nullptr; storage->next = list->head; - storage->reserved = nullptr; + storage->reserved = nullptr; if (list->head != nullptr) { list->head->prev = storage; } else { diff --git a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h index 3101f485a2..7da35b1e76 100644 --- a/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h +++ b/contrib/libs/grpc/src/core/lib/transport/metadata_batch.h @@ -31,11 +31,11 @@ #include "src/core/lib/transport/static_metadata.h" typedef struct grpc_linked_mdelem { - grpc_linked_mdelem() {} - + grpc_linked_mdelem() {} + grpc_mdelem md; - struct grpc_linked_mdelem* next = nullptr; - struct grpc_linked_mdelem* prev = nullptr; + struct grpc_linked_mdelem* next = nullptr; + struct grpc_linked_mdelem* prev = nullptr; void* reserved; } grpc_linked_mdelem; @@ -89,7 +89,7 @@ grpc_error* grpc_metadata_batch_link_head(grpc_metadata_batch* batch, grpc_error* grpc_metadata_batch_link_head( grpc_metadata_batch* batch, grpc_linked_mdelem* storage, grpc_metadata_batch_callouts_index idx) GRPC_MUST_USE_RESULT; - + /** Add \a storage to the end of \a batch. storage->md is assumed to be valid. \a storage is owned by the caller and must survive for the @@ -111,7 +111,7 @@ grpc_error* grpc_metadata_batch_link_tail( grpc_error* grpc_metadata_batch_add_head( grpc_metadata_batch* batch, grpc_linked_mdelem* storage, grpc_mdelem elem_to_add) GRPC_MUST_USE_RESULT; - + // TODO(arjunroy, roth): Remove redundant methods. // add/link_head/tail are almost identical. inline grpc_error* GRPC_MUST_USE_RESULT grpc_metadata_batch_add_head( diff --git a/contrib/libs/grpc/src/core/lib/transport/static_metadata.h b/contrib/libs/grpc/src/core/lib/transport/static_metadata.h index 5d844af558..98dbfac84a 100644 --- a/contrib/libs/grpc/src/core/lib/transport/static_metadata.h +++ b/contrib/libs/grpc/src/core/lib/transport/static_metadata.h @@ -135,12 +135,12 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() { /* "/envoy.service.load_stats.v3.LoadReportingService/StreamLoadStats" */ #define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_LOAD_STATS_DOT_V3_DOT_LOADREPORTINGSERVICE_SLASH_STREAMLOADSTATS \ (grpc_static_slice_table()[36]) -/* "/grpc.health.v1.Health/Watch" */ -#define GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH \ +/* "/grpc.health.v1.Health/Watch" */ +#define GRPC_MDSTR_SLASH_GRPC_DOT_HEALTH_DOT_V1_DOT_HEALTH_SLASH_WATCH \ (grpc_static_slice_table()[37]) -/* "/envoy.service.discovery.v2.AggregatedDiscoveryService/StreamAggregatedResources" - */ -#define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_DISCOVERY_DOT_V2_DOT_AGGREGATEDDISCOVERYSERVICE_SLASH_STREAMAGGREGATEDRESOURCES \ +/* "/envoy.service.discovery.v2.AggregatedDiscoveryService/StreamAggregatedResources" + */ +#define GRPC_MDSTR_SLASH_ENVOY_DOT_SERVICE_DOT_DISCOVERY_DOT_V2_DOT_AGGREGATEDDISCOVERYSERVICE_SLASH_STREAMAGGREGATEDRESOURCES \ (grpc_static_slice_table()[38]) /* "/envoy.service.discovery.v3.AggregatedDiscoveryService/StreamAggregatedResources" */ @@ -152,19 +152,19 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() { #define GRPC_MDSTR_GZIP (grpc_static_slice_table()[41]) /* "stream/gzip" */ #define GRPC_MDSTR_STREAM_SLASH_GZIP (grpc_static_slice_table()[42]) -/* "GET" */ +/* "GET" */ #define GRPC_MDSTR_GET (grpc_static_slice_table()[43]) /* "POST" */ #define GRPC_MDSTR_POST (grpc_static_slice_table()[44]) -/* "/" */ +/* "/" */ #define GRPC_MDSTR_SLASH (grpc_static_slice_table()[45]) -/* "/index.html" */ +/* "/index.html" */ #define GRPC_MDSTR_SLASH_INDEX_DOT_HTML (grpc_static_slice_table()[46]) /* "http" */ #define GRPC_MDSTR_HTTP (grpc_static_slice_table()[47]) /* "https" */ #define GRPC_MDSTR_HTTPS (grpc_static_slice_table()[48]) -/* "200" */ +/* "200" */ #define GRPC_MDSTR_200 (grpc_static_slice_table()[49]) /* "204" */ #define GRPC_MDSTR_204 (grpc_static_slice_table()[50]) @@ -174,7 +174,7 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() { #define GRPC_MDSTR_304 (grpc_static_slice_table()[52]) /* "400" */ #define GRPC_MDSTR_400 (grpc_static_slice_table()[53]) -/* "404" */ +/* "404" */ #define GRPC_MDSTR_404 (grpc_static_slice_table()[54]) /* "500" */ #define GRPC_MDSTR_500 (grpc_static_slice_table()[55]) @@ -264,19 +264,19 @@ inline const grpc_core::StaticMetadataSlice* grpc_static_slice_table() { #define GRPC_MDSTR_VIA (grpc_static_slice_table()[97]) /* "www-authenticate" */ #define GRPC_MDSTR_WWW_AUTHENTICATE (grpc_static_slice_table()[98]) -/* "0" */ +/* "0" */ #define GRPC_MDSTR_0 (grpc_static_slice_table()[99]) -/* "identity" */ +/* "identity" */ #define GRPC_MDSTR_IDENTITY (grpc_static_slice_table()[100]) -/* "trailers" */ +/* "trailers" */ #define GRPC_MDSTR_TRAILERS (grpc_static_slice_table()[101]) -/* "application/grpc" */ +/* "application/grpc" */ #define GRPC_MDSTR_APPLICATION_SLASH_GRPC (grpc_static_slice_table()[102]) -/* "grpc" */ +/* "grpc" */ #define GRPC_MDSTR_GRPC (grpc_static_slice_table()[103]) -/* "PUT" */ +/* "PUT" */ #define GRPC_MDSTR_PUT (grpc_static_slice_table()[104]) -/* "lb-cost-bin" */ +/* "lb-cost-bin" */ #define GRPC_MDSTR_LB_COST_BIN (grpc_static_slice_table()[105]) /* "identity,deflate" */ #define GRPC_MDSTR_IDENTITY_COMMA_DEFLATE (grpc_static_slice_table()[106]) @@ -327,20 +327,20 @@ inline grpc_mdelem* grpc_static_mdelem_manifested() { } extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT]; -/* ":authority": "" */ +/* ":authority": "" */ #define GRPC_MDELEM_AUTHORITY_EMPTY (grpc_static_mdelem_manifested()[0]) -/* ":method": "GET" */ +/* ":method": "GET" */ #define GRPC_MDELEM_METHOD_GET (grpc_static_mdelem_manifested()[1]) -/* ":method": "POST" */ +/* ":method": "POST" */ #define GRPC_MDELEM_METHOD_POST (grpc_static_mdelem_manifested()[2]) -/* ":path": "/" */ +/* ":path": "/" */ #define GRPC_MDELEM_PATH_SLASH (grpc_static_mdelem_manifested()[3]) -/* ":path": "/index.html" */ -#define GRPC_MDELEM_PATH_SLASH_INDEX_DOT_HTML \ +/* ":path": "/index.html" */ +#define GRPC_MDELEM_PATH_SLASH_INDEX_DOT_HTML \ (grpc_static_mdelem_manifested()[4]) -/* ":scheme": "http" */ +/* ":scheme": "http" */ #define GRPC_MDELEM_SCHEME_HTTP (grpc_static_mdelem_manifested()[5]) -/* ":scheme": "https" */ +/* ":scheme": "https" */ #define GRPC_MDELEM_SCHEME_HTTPS (grpc_static_mdelem_manifested()[6]) /* ":status": "200" */ #define GRPC_MDELEM_STATUS_200 (grpc_static_mdelem_manifested()[7]) @@ -352,7 +352,7 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT]; #define GRPC_MDELEM_STATUS_304 (grpc_static_mdelem_manifested()[10]) /* ":status": "400" */ #define GRPC_MDELEM_STATUS_400 (grpc_static_mdelem_manifested()[11]) -/* ":status": "404" */ +/* ":status": "404" */ #define GRPC_MDELEM_STATUS_404 (grpc_static_mdelem_manifested()[12]) /* ":status": "500" */ #define GRPC_MDELEM_STATUS_500 (grpc_static_mdelem_manifested()[13]) @@ -459,35 +459,35 @@ extern uintptr_t grpc_static_mdelem_user_data[GRPC_STATIC_MDELEM_COUNT]; #define GRPC_MDELEM_VIA_EMPTY (grpc_static_mdelem_manifested()[59]) /* "www-authenticate": "" */ #define GRPC_MDELEM_WWW_AUTHENTICATE_EMPTY (grpc_static_mdelem_manifested()[60]) -/* "grpc-status": "0" */ +/* "grpc-status": "0" */ #define GRPC_MDELEM_GRPC_STATUS_0 (grpc_static_mdelem_manifested()[61]) -/* "grpc-status": "1" */ +/* "grpc-status": "1" */ #define GRPC_MDELEM_GRPC_STATUS_1 (grpc_static_mdelem_manifested()[62]) -/* "grpc-status": "2" */ +/* "grpc-status": "2" */ #define GRPC_MDELEM_GRPC_STATUS_2 (grpc_static_mdelem_manifested()[63]) -/* "grpc-encoding": "identity" */ +/* "grpc-encoding": "identity" */ #define GRPC_MDELEM_GRPC_ENCODING_IDENTITY (grpc_static_mdelem_manifested()[64]) -/* "grpc-encoding": "gzip" */ +/* "grpc-encoding": "gzip" */ #define GRPC_MDELEM_GRPC_ENCODING_GZIP (grpc_static_mdelem_manifested()[65]) -/* "grpc-encoding": "deflate" */ +/* "grpc-encoding": "deflate" */ #define GRPC_MDELEM_GRPC_ENCODING_DEFLATE (grpc_static_mdelem_manifested()[66]) -/* "te": "trailers" */ +/* "te": "trailers" */ #define GRPC_MDELEM_TE_TRAILERS (grpc_static_mdelem_manifested()[67]) -/* "content-type": "application/grpc" */ -#define GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC \ +/* "content-type": "application/grpc" */ +#define GRPC_MDELEM_CONTENT_TYPE_APPLICATION_SLASH_GRPC \ (grpc_static_mdelem_manifested()[68]) -/* ":scheme": "grpc" */ +/* ":scheme": "grpc" */ #define GRPC_MDELEM_SCHEME_GRPC (grpc_static_mdelem_manifested()[69]) -/* ":method": "PUT" */ +/* ":method": "PUT" */ #define GRPC_MDELEM_METHOD_PUT (grpc_static_mdelem_manifested()[70]) -/* "accept-encoding": "" */ +/* "accept-encoding": "" */ #define GRPC_MDELEM_ACCEPT_ENCODING_EMPTY (grpc_static_mdelem_manifested()[71]) -/* "content-encoding": "identity" */ -#define GRPC_MDELEM_CONTENT_ENCODING_IDENTITY \ +/* "content-encoding": "identity" */ +#define GRPC_MDELEM_CONTENT_ENCODING_IDENTITY \ (grpc_static_mdelem_manifested()[72]) -/* "content-encoding": "gzip" */ +/* "content-encoding": "gzip" */ #define GRPC_MDELEM_CONTENT_ENCODING_GZIP (grpc_static_mdelem_manifested()[73]) -/* "lb-cost-bin": "" */ +/* "lb-cost-bin": "" */ #define GRPC_MDELEM_LB_COST_BIN_EMPTY (grpc_static_mdelem_manifested()[74]) /* "grpc-accept-encoding": "identity" */ #define GRPC_MDELEM_GRPC_ACCEPT_ENCODING_IDENTITY \ diff --git a/contrib/libs/grpc/src/core/lib/transport/transport.cc b/contrib/libs/grpc/src/core/lib/transport/transport.cc index 99a32980aa..18f7e98ba9 100644 --- a/contrib/libs/grpc/src/core/lib/transport/transport.cc +++ b/contrib/libs/grpc/src/core/lib/transport/transport.cc @@ -27,11 +27,11 @@ #include <grpc/support/log.h> #include <grpc/support/sync.h> -#include "src/core/lib/gpr/alloc.h" +#include "src/core/lib/gpr/alloc.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gprpp/memory.h" #include "src/core/lib/iomgr/executor.h" -#include "src/core/lib/iomgr/iomgr.h" +#include "src/core/lib/iomgr/iomgr.h" #include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/slice/slice_string_helpers.h" #include "src/core/lib/transport/transport_impl.h" @@ -116,7 +116,7 @@ void grpc_transport_move_stats(grpc_transport_stream_stats* from, } size_t grpc_transport_stream_size(grpc_transport* transport) { - return GPR_ROUND_UP_TO_ALIGNMENT_SIZE(transport->vtable->sizeof_stream); + return GPR_ROUND_UP_TO_ALIGNMENT_SIZE(transport->vtable->sizeof_stream); } void grpc_transport_destroy(grpc_transport* transport) { @@ -152,8 +152,8 @@ void grpc_transport_set_pops(grpc_transport* transport, grpc_stream* stream, nullptr) { transport->vtable->set_pollset_set(transport, stream, pollset_set); } else { - // No-op for empty pollset. Empty pollset is possible when using - // non-fd-based event engines such as CFStream. + // No-op for empty pollset. Empty pollset is possible when using + // non-fd-based event engines such as CFStream. } } @@ -180,32 +180,32 @@ void grpc_transport_stream_op_batch_finish_with_failure( if (batch->send_message) { batch->payload->send_message.send_message.reset(); } - if (batch->cancel_stream) { - GRPC_ERROR_UNREF(batch->payload->cancel_stream.cancel_error); + if (batch->cancel_stream) { + GRPC_ERROR_UNREF(batch->payload->cancel_stream.cancel_error); } - // Construct a list of closures to execute. - grpc_core::CallCombinerClosureList closures; + // Construct a list of closures to execute. + grpc_core::CallCombinerClosureList closures; if (batch->recv_initial_metadata) { - closures.Add( + closures.Add( batch->payload->recv_initial_metadata.recv_initial_metadata_ready, GRPC_ERROR_REF(error), "failing recv_initial_metadata_ready"); } - if (batch->recv_message) { - closures.Add(batch->payload->recv_message.recv_message_ready, - GRPC_ERROR_REF(error), "failing recv_message_ready"); + if (batch->recv_message) { + closures.Add(batch->payload->recv_message.recv_message_ready, + GRPC_ERROR_REF(error), "failing recv_message_ready"); } - if (batch->recv_trailing_metadata) { - closures.Add( - batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready, - GRPC_ERROR_REF(error), "failing recv_trailing_metadata_ready"); - } - if (batch->on_complete != nullptr) { - closures.Add(batch->on_complete, GRPC_ERROR_REF(error), - "failing on_complete"); - } - // Execute closures. - closures.RunClosures(call_combiner); - GRPC_ERROR_UNREF(error); + if (batch->recv_trailing_metadata) { + closures.Add( + batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready, + GRPC_ERROR_REF(error), "failing recv_trailing_metadata_ready"); + } + if (batch->on_complete != nullptr) { + closures.Add(batch->on_complete, GRPC_ERROR_REF(error), + "failing on_complete"); + } + // Execute closures. + closures.RunClosures(call_combiner); + GRPC_ERROR_UNREF(error); } struct made_transport_op { diff --git a/contrib/libs/grpc/src/core/lib/transport/transport.h b/contrib/libs/grpc/src/core/lib/transport/transport.h index 2404455f9f..ef00b564a8 100644 --- a/contrib/libs/grpc/src/core/lib/transport/transport.h +++ b/contrib/libs/grpc/src/core/lib/transport/transport.h @@ -119,16 +119,16 @@ inline void grpc_stream_unref(grpc_stream_refcount* refcount) { grpc_slice grpc_slice_from_stream_owned_buffer(grpc_stream_refcount* refcount, void* buffer, size_t length); -struct grpc_transport_one_way_stats { - uint64_t framing_bytes = 0; - uint64_t data_bytes = 0; - uint64_t header_bytes = 0; -}; +struct grpc_transport_one_way_stats { + uint64_t framing_bytes = 0; + uint64_t data_bytes = 0; + uint64_t header_bytes = 0; +}; -struct grpc_transport_stream_stats { +struct grpc_transport_stream_stats { grpc_transport_one_way_stats incoming; grpc_transport_one_way_stats outgoing; -}; +}; void grpc_transport_move_one_way_stats(grpc_transport_one_way_stats* from, grpc_transport_one_way_stats* to); @@ -160,30 +160,30 @@ typedef struct grpc_transport_stream_op_batch_payload /* Transport stream op: a set of operations to perform on a transport against a single stream */ -struct grpc_transport_stream_op_batch { - grpc_transport_stream_op_batch() - : send_initial_metadata(false), - send_trailing_metadata(false), - send_message(false), - recv_initial_metadata(false), - recv_message(false), - recv_trailing_metadata(false), - cancel_stream(false), - is_traced(false) {} - - /** Should be scheduled when all of the non-recv operations in the batch - are complete. - - The recv ops (recv_initial_metadata, recv_message, and - recv_trailing_metadata) each have their own callbacks. If a batch - contains both recv ops and non-recv ops, on_complete should be - scheduled as soon as the non-recv ops are complete, regardless of - whether or not the recv ops are complete. If a batch contains - only recv ops, on_complete can be null. */ - grpc_closure* on_complete = nullptr; - +struct grpc_transport_stream_op_batch { + grpc_transport_stream_op_batch() + : send_initial_metadata(false), + send_trailing_metadata(false), + send_message(false), + recv_initial_metadata(false), + recv_message(false), + recv_trailing_metadata(false), + cancel_stream(false), + is_traced(false) {} + + /** Should be scheduled when all of the non-recv operations in the batch + are complete. + + The recv ops (recv_initial_metadata, recv_message, and + recv_trailing_metadata) each have their own callbacks. If a batch + contains both recv ops and non-recv ops, on_complete should be + scheduled as soon as the non-recv ops are complete, regardless of + whether or not the recv ops are complete. If a batch contains + only recv ops, on_complete can be null. */ + grpc_closure* on_complete = nullptr; + /** Values for the stream op (fields set are determined by flags above) */ - grpc_transport_stream_op_batch_payload* payload = nullptr; + grpc_transport_stream_op_batch_payload* payload = nullptr; /** Send initial metadata to the peer, from the provided metadata batch. */ bool send_initial_metadata : 1; @@ -207,41 +207,41 @@ struct grpc_transport_stream_op_batch { /** Cancel this stream with the provided error */ bool cancel_stream : 1; - /** Is this stream traced */ - bool is_traced : 1; - + /** Is this stream traced */ + bool is_traced : 1; + /*************************************************************************** * remaining fields are initialized and used at the discretion of the * current handler of the op */ grpc_handler_private_op_data handler_private; -}; +}; struct grpc_transport_stream_op_batch_payload { - explicit grpc_transport_stream_op_batch_payload( - grpc_call_context_element* context) - : context(context) {} - ~grpc_transport_stream_op_batch_payload() { - // We don't really own `send_message`, so release ownership and let the - // owner clean the data. - send_message.send_message.release(); - } - + explicit grpc_transport_stream_op_batch_payload( + grpc_call_context_element* context) + : context(context) {} + ~grpc_transport_stream_op_batch_payload() { + // We don't really own `send_message`, so release ownership and let the + // owner clean the data. + send_message.send_message.release(); + } + struct { - grpc_metadata_batch* send_initial_metadata = nullptr; + grpc_metadata_batch* send_initial_metadata = nullptr; /** Iff send_initial_metadata != NULL, flags associated with send_initial_metadata: a bitfield of GRPC_INITIAL_METADATA_xxx */ - uint32_t send_initial_metadata_flags = 0; - // If non-NULL, will be set by the transport to the peer string (a char*). - // The transport retains ownership of the string. + uint32_t send_initial_metadata_flags = 0; + // If non-NULL, will be set by the transport to the peer string (a char*). + // The transport retains ownership of the string. // Note: This pointer may be used by the transport after the // send_initial_metadata op is completed. It must remain valid // until the call is destroyed. - gpr_atm* peer_string = nullptr; + gpr_atm* peer_string = nullptr; } send_initial_metadata; struct { - grpc_metadata_batch* send_trailing_metadata = nullptr; + grpc_metadata_batch* send_trailing_metadata = nullptr; // Set by the transport to true if the stream successfully wrote the // trailing metadata. If this is not set but there was a send trailing // metadata op present, this can indicate that a server call can be marked @@ -271,39 +271,39 @@ struct grpc_transport_stream_op_batch_payload { } send_message; struct { - grpc_metadata_batch* recv_initial_metadata = nullptr; + grpc_metadata_batch* recv_initial_metadata = nullptr; // Flags are used only on the server side. If non-null, will be set to // a bitfield of the GRPC_INITIAL_METADATA_xxx macros (e.g., to // indicate if the call is idempotent). - uint32_t* recv_flags = nullptr; + uint32_t* recv_flags = nullptr; /** Should be enqueued when initial metadata is ready to be processed. */ - grpc_closure* recv_initial_metadata_ready = nullptr; + grpc_closure* recv_initial_metadata_ready = nullptr; // If not NULL, will be set to true if trailing metadata is // immediately available. This may be a signal that we received a // Trailers-Only response. - bool* trailing_metadata_available = nullptr; - // If non-NULL, will be set by the transport to the peer string (a char*). - // The transport retains ownership of the string. + bool* trailing_metadata_available = nullptr; + // If non-NULL, will be set by the transport to the peer string (a char*). + // The transport retains ownership of the string. // Note: This pointer may be used by the transport after the // recv_initial_metadata op is completed. It must remain valid // until the call is destroyed. - gpr_atm* peer_string = nullptr; + gpr_atm* peer_string = nullptr; } recv_initial_metadata; struct { // Will be set by the transport to point to the byte stream // containing a received message. // Will be NULL if trailing metadata is received instead of a message. - grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message = nullptr; + grpc_core::OrphanablePtr<grpc_core::ByteStream>* recv_message = nullptr; /** Should be enqueued when one message is ready to be processed. */ - grpc_closure* recv_message_ready = nullptr; + grpc_closure* recv_message_ready = nullptr; } recv_message; struct { - grpc_metadata_batch* recv_trailing_metadata = nullptr; - grpc_transport_stream_stats* collect_stats = nullptr; + grpc_metadata_batch* recv_trailing_metadata = nullptr; + grpc_transport_stream_stats* collect_stats = nullptr; /** Should be enqueued when trailing metadata is ready to be processed. */ - grpc_closure* recv_trailing_metadata_ready = nullptr; + grpc_closure* recv_trailing_metadata_ready = nullptr; } recv_trailing_metadata; /** Forcefully close this stream. @@ -319,7 +319,7 @@ struct grpc_transport_stream_op_batch_payload { struct { // Error contract: the transport that gets this op must cause cancel_error // to be unref'ed after processing it - grpc_error* cancel_error = GRPC_ERROR_NONE; + grpc_error* cancel_error = GRPC_ERROR_NONE; } cancel_stream; /* Indexes correspond to grpc_context_index enum values */ @@ -364,7 +364,7 @@ typedef struct grpc_transport_op { /** Called when the ping ack is received */ grpc_closure* on_ack = nullptr; } send_ping; - // If true, will reset the channel's connection backoff. + // If true, will reset the channel's connection backoff. bool reset_connect_backoff = false; /*************************************************************************** diff --git a/contrib/libs/grpc/src/core/lib/uri/uri_parser.cc b/contrib/libs/grpc/src/core/lib/uri/uri_parser.cc index 1215e0d206..2c0f48a69f 100644 --- a/contrib/libs/grpc/src/core/lib/uri/uri_parser.cc +++ b/contrib/libs/grpc/src/core/lib/uri/uri_parser.cc @@ -1,309 +1,309 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/lib/uri/uri_parser.h" - -#include <string.h> - +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/lib/uri/uri_parser.h" + +#include <string.h> + #include <util/generic/string.h> #include "y_absl/strings/str_format.h" -#include <grpc/slice_buffer.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/slice/percent_encoding.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/slice/slice_string_helpers.h" - -/** a size_t default value... maps to all 1's */ -#define NOT_SET (~(size_t)0) - +#include <grpc/slice_buffer.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/slice/percent_encoding.h" +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/slice/slice_string_helpers.h" + +/** a size_t default value... maps to all 1's */ +#define NOT_SET (~(size_t)0) + static grpc_uri* bad_uri(y_absl::string_view uri_text, size_t pos, const char* section, bool suppress_errors) { - if (!suppress_errors) { + if (!suppress_errors) { TString line_prefix = y_absl::StrFormat("bad uri.%s: '", section); gpr_log(GPR_ERROR, "%s%s'", line_prefix.c_str(), TString(uri_text).c_str()); size_t pfx_len = line_prefix.size() + pos; gpr_log(GPR_ERROR, "%s^ here", TString(pfx_len, ' ').c_str()); - } - return nullptr; -} - -/** Returns a copy of percent decoded \a src[begin, end) */ + } + return nullptr; +} + +/** Returns a copy of percent decoded \a src[begin, end) */ static char* decode_and_copy_component(y_absl::string_view src, size_t begin, - size_t end) { - grpc_slice component = - (begin == NOT_SET || end == NOT_SET) - ? grpc_empty_slice() + size_t end) { + grpc_slice component = + (begin == NOT_SET || end == NOT_SET) + ? grpc_empty_slice() : grpc_slice_from_copied_buffer(src.data() + begin, end - begin); - grpc_slice decoded_component = - grpc_permissive_percent_decode_slice(component); - char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII); - grpc_slice_unref_internal(component); - grpc_slice_unref_internal(decoded_component); - return out; -} - -static bool valid_hex(char c) { - return ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')) || - ((c >= '0') && (c <= '9')); -} - -/** Returns how many chars to advance if \a uri_text[i] begins a valid \a pchar - * production. If \a uri_text[i] introduces an invalid \a pchar (such as percent - * sign not followed by two hex digits), NOT_SET is returned. */ + grpc_slice decoded_component = + grpc_permissive_percent_decode_slice(component); + char* out = grpc_dump_slice(decoded_component, GPR_DUMP_ASCII); + grpc_slice_unref_internal(component); + grpc_slice_unref_internal(decoded_component); + return out; +} + +static bool valid_hex(char c) { + return ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F')) || + ((c >= '0') && (c <= '9')); +} + +/** Returns how many chars to advance if \a uri_text[i] begins a valid \a pchar + * production. If \a uri_text[i] introduces an invalid \a pchar (such as percent + * sign not followed by two hex digits), NOT_SET is returned. */ static size_t parse_pchar(y_absl::string_view uri_text, size_t i) { - /* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * pct-encoded = "%" HEXDIG HEXDIG - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - / "*" / "+" / "," / ";" / "=" */ - char c = uri_text[i]; - switch (c) { - default: - if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || - ((c >= '0') && (c <= '9'))) { - return 1; - } - break; - case ':': - case '@': - case '-': - case '.': - case '_': - case '~': - case '!': - case '$': - case '&': - case '\'': - case '(': - case ')': - case '*': - case '+': - case ',': - case ';': - case '=': - return 1; - case '%': /* pct-encoded */ + /* pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * pct-encoded = "%" HEXDIG HEXDIG + * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + / "*" / "+" / "," / ";" / "=" */ + char c = uri_text[i]; + switch (c) { + default: + if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || + ((c >= '0') && (c <= '9'))) { + return 1; + } + break; + case ':': + case '@': + case '-': + case '.': + case '_': + case '~': + case '!': + case '$': + case '&': + case '\'': + case '(': + case ')': + case '*': + case '+': + case ',': + case ';': + case '=': + return 1; + case '%': /* pct-encoded */ if (uri_text.size() > i + 2 && valid_hex(uri_text[i + 1]) && valid_hex(uri_text[i + 2])) { - return 2; - } - return NOT_SET; - } - return 0; -} - -/* *( pchar / "?" / "/" ) */ + return 2; + } + return NOT_SET; + } + return 0; +} + +/* *( pchar / "?" / "/" ) */ static int parse_fragment_or_query(y_absl::string_view uri_text, size_t* i) { while (uri_text.size() > *i) { - const size_t advance = parse_pchar(uri_text, *i); /* pchar */ - switch (advance) { - case 0: /* uri_text[i] isn't in pchar */ - /* maybe it's ? or / */ - if (uri_text[*i] == '?' || uri_text[*i] == '/') { - (*i)++; - break; - } else { - return 1; - } - GPR_UNREACHABLE_CODE(return 0); - default: - (*i) += advance; - break; - case NOT_SET: /* uri_text[i] introduces an invalid URI */ - return 0; - } - } - /* *i is the first uri_text position past the \a query production, maybe \0 */ - return 1; -} - -static void parse_query_parts(grpc_uri* uri) { - static const char* QUERY_PARTS_SEPARATOR = "&"; - static const char* QUERY_PARTS_VALUE_SEPARATOR = "="; - GPR_ASSERT(uri->query != nullptr); - if (uri->query[0] == '\0') { - uri->query_parts = nullptr; - uri->query_parts_values = nullptr; - uri->num_query_parts = 0; - return; - } - - gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts, - &uri->num_query_parts); - uri->query_parts_values = - static_cast<char**>(gpr_malloc(uri->num_query_parts * sizeof(char**))); - for (size_t i = 0; i < uri->num_query_parts; i++) { - char** query_param_parts; - size_t num_query_param_parts; - char* full = uri->query_parts[i]; - gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts, - &num_query_param_parts); - GPR_ASSERT(num_query_param_parts > 0); - uri->query_parts[i] = query_param_parts[0]; - if (num_query_param_parts > 1) { - /* TODO(dgq): only the first value after the separator is considered. - * Perhaps all chars after the first separator for the query part should - * be included, even if they include the separator. */ - uri->query_parts_values[i] = query_param_parts[1]; - } else { - uri->query_parts_values[i] = nullptr; - } - for (size_t j = 2; j < num_query_param_parts; j++) { - gpr_free(query_param_parts[j]); - } - gpr_free(query_param_parts); - gpr_free(full); - } -} - + const size_t advance = parse_pchar(uri_text, *i); /* pchar */ + switch (advance) { + case 0: /* uri_text[i] isn't in pchar */ + /* maybe it's ? or / */ + if (uri_text[*i] == '?' || uri_text[*i] == '/') { + (*i)++; + break; + } else { + return 1; + } + GPR_UNREACHABLE_CODE(return 0); + default: + (*i) += advance; + break; + case NOT_SET: /* uri_text[i] introduces an invalid URI */ + return 0; + } + } + /* *i is the first uri_text position past the \a query production, maybe \0 */ + return 1; +} + +static void parse_query_parts(grpc_uri* uri) { + static const char* QUERY_PARTS_SEPARATOR = "&"; + static const char* QUERY_PARTS_VALUE_SEPARATOR = "="; + GPR_ASSERT(uri->query != nullptr); + if (uri->query[0] == '\0') { + uri->query_parts = nullptr; + uri->query_parts_values = nullptr; + uri->num_query_parts = 0; + return; + } + + gpr_string_split(uri->query, QUERY_PARTS_SEPARATOR, &uri->query_parts, + &uri->num_query_parts); + uri->query_parts_values = + static_cast<char**>(gpr_malloc(uri->num_query_parts * sizeof(char**))); + for (size_t i = 0; i < uri->num_query_parts; i++) { + char** query_param_parts; + size_t num_query_param_parts; + char* full = uri->query_parts[i]; + gpr_string_split(full, QUERY_PARTS_VALUE_SEPARATOR, &query_param_parts, + &num_query_param_parts); + GPR_ASSERT(num_query_param_parts > 0); + uri->query_parts[i] = query_param_parts[0]; + if (num_query_param_parts > 1) { + /* TODO(dgq): only the first value after the separator is considered. + * Perhaps all chars after the first separator for the query part should + * be included, even if they include the separator. */ + uri->query_parts_values[i] = query_param_parts[1]; + } else { + uri->query_parts_values[i] = nullptr; + } + for (size_t j = 2; j < num_query_param_parts; j++) { + gpr_free(query_param_parts[j]); + } + gpr_free(query_param_parts); + gpr_free(full); + } +} + grpc_uri* grpc_uri_parse(y_absl::string_view uri_text, bool suppress_errors) { - grpc_uri* uri; - size_t scheme_begin = 0; - size_t scheme_end = NOT_SET; - size_t authority_begin = NOT_SET; - size_t authority_end = NOT_SET; - size_t path_begin = NOT_SET; - size_t path_end = NOT_SET; - size_t query_begin = NOT_SET; - size_t query_end = NOT_SET; - size_t fragment_begin = NOT_SET; - size_t fragment_end = NOT_SET; - size_t i; - + grpc_uri* uri; + size_t scheme_begin = 0; + size_t scheme_end = NOT_SET; + size_t authority_begin = NOT_SET; + size_t authority_end = NOT_SET; + size_t path_begin = NOT_SET; + size_t path_end = NOT_SET; + size_t query_begin = NOT_SET; + size_t query_end = NOT_SET; + size_t fragment_begin = NOT_SET; + size_t fragment_end = NOT_SET; + size_t i; + for (i = scheme_begin; i < uri_text.size(); ++i) { - if (uri_text[i] == ':') { - scheme_end = i; - break; - } - if (uri_text[i] >= 'a' && uri_text[i] <= 'z') continue; - if (uri_text[i] >= 'A' && uri_text[i] <= 'Z') continue; - if (i != scheme_begin) { - if (uri_text[i] >= '0' && uri_text[i] <= '9') continue; - if (uri_text[i] == '+') continue; - if (uri_text[i] == '-') continue; - if (uri_text[i] == '.') continue; - } - break; - } - if (scheme_end == NOT_SET) { - return bad_uri(uri_text, i, "scheme", suppress_errors); - } - + if (uri_text[i] == ':') { + scheme_end = i; + break; + } + if (uri_text[i] >= 'a' && uri_text[i] <= 'z') continue; + if (uri_text[i] >= 'A' && uri_text[i] <= 'Z') continue; + if (i != scheme_begin) { + if (uri_text[i] >= '0' && uri_text[i] <= '9') continue; + if (uri_text[i] == '+') continue; + if (uri_text[i] == '-') continue; + if (uri_text[i] == '.') continue; + } + break; + } + if (scheme_end == NOT_SET) { + return bad_uri(uri_text, i, "scheme", suppress_errors); + } + if (uri_text.size() > scheme_end + 2 && uri_text[scheme_end + 1] == '/' && uri_text[scheme_end + 2] == '/') { - authority_begin = scheme_end + 3; + authority_begin = scheme_end + 3; for (i = authority_begin; uri_text.size() > i && authority_end == NOT_SET; - i++) { - if (uri_text[i] == '/' || uri_text[i] == '?' || uri_text[i] == '#') { - authority_end = i; - } - } + i++) { + if (uri_text[i] == '/' || uri_text[i] == '?' || uri_text[i] == '#') { + authority_end = i; + } + } if (authority_end == NOT_SET && uri_text.size() == i) { - authority_end = i; - } - if (authority_end == NOT_SET) { - return bad_uri(uri_text, i, "authority", suppress_errors); - } - /* TODO(ctiller): parse the authority correctly */ - path_begin = authority_end; - } else { - path_begin = scheme_end + 1; - } - + authority_end = i; + } + if (authority_end == NOT_SET) { + return bad_uri(uri_text, i, "authority", suppress_errors); + } + /* TODO(ctiller): parse the authority correctly */ + path_begin = authority_end; + } else { + path_begin = scheme_end + 1; + } + for (i = path_begin; i < uri_text.size(); ++i) { - if (uri_text[i] == '?' || uri_text[i] == '#') { - path_end = i; - break; - } - } + if (uri_text[i] == '?' || uri_text[i] == '#') { + path_end = i; + break; + } + } if (path_end == NOT_SET && uri_text.size() == i) { - path_end = i; - } - if (path_end == NOT_SET) { - return bad_uri(uri_text, i, "path", suppress_errors); - } - + path_end = i; + } + if (path_end == NOT_SET) { + return bad_uri(uri_text, i, "path", suppress_errors); + } + if (uri_text.size() > i && uri_text[i] == '?') { - query_begin = ++i; - if (!parse_fragment_or_query(uri_text, &i)) { - return bad_uri(uri_text, i, "query", suppress_errors); + query_begin = ++i; + if (!parse_fragment_or_query(uri_text, &i)) { + return bad_uri(uri_text, i, "query", suppress_errors); } else if (uri_text.size() > i && uri_text[i] != '#') { - /* We must be at the end or at the beginning of a fragment */ - return bad_uri(uri_text, i, "query", suppress_errors); - } - query_end = i; - } + /* We must be at the end or at the beginning of a fragment */ + return bad_uri(uri_text, i, "query", suppress_errors); + } + query_end = i; + } if (uri_text.size() > i && uri_text[i] == '#') { - fragment_begin = ++i; - if (!parse_fragment_or_query(uri_text, &i)) { - return bad_uri(uri_text, i - fragment_end, "fragment", suppress_errors); + fragment_begin = ++i; + if (!parse_fragment_or_query(uri_text, &i)) { + return bad_uri(uri_text, i - fragment_end, "fragment", suppress_errors); } else if (uri_text.size() > i) { - /* We must be at the end */ - return bad_uri(uri_text, i, "fragment", suppress_errors); - } - fragment_end = i; - } - - uri = static_cast<grpc_uri*>(gpr_zalloc(sizeof(*uri))); - uri->scheme = decode_and_copy_component(uri_text, scheme_begin, scheme_end); - uri->authority = - decode_and_copy_component(uri_text, authority_begin, authority_end); - uri->path = decode_and_copy_component(uri_text, path_begin, path_end); - uri->query = decode_and_copy_component(uri_text, query_begin, query_end); - uri->fragment = - decode_and_copy_component(uri_text, fragment_begin, fragment_end); - parse_query_parts(uri); - - return uri; -} - -const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) { - GPR_ASSERT(key != nullptr); - if (key[0] == '\0') return nullptr; - - for (size_t i = 0; i < uri->num_query_parts; ++i) { - if (0 == strcmp(key, uri->query_parts[i])) { - return uri->query_parts_values[i]; - } - } - return nullptr; -} - -void grpc_uri_destroy(grpc_uri* uri) { - if (!uri) return; - gpr_free(uri->scheme); - gpr_free(uri->authority); - gpr_free(uri->path); - gpr_free(uri->query); - for (size_t i = 0; i < uri->num_query_parts; ++i) { - gpr_free(uri->query_parts[i]); - gpr_free(uri->query_parts_values[i]); - } - gpr_free(uri->query_parts); - gpr_free(uri->query_parts_values); - gpr_free(uri->fragment); - gpr_free(uri); -} + /* We must be at the end */ + return bad_uri(uri_text, i, "fragment", suppress_errors); + } + fragment_end = i; + } + + uri = static_cast<grpc_uri*>(gpr_zalloc(sizeof(*uri))); + uri->scheme = decode_and_copy_component(uri_text, scheme_begin, scheme_end); + uri->authority = + decode_and_copy_component(uri_text, authority_begin, authority_end); + uri->path = decode_and_copy_component(uri_text, path_begin, path_end); + uri->query = decode_and_copy_component(uri_text, query_begin, query_end); + uri->fragment = + decode_and_copy_component(uri_text, fragment_begin, fragment_end); + parse_query_parts(uri); + + return uri; +} + +const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key) { + GPR_ASSERT(key != nullptr); + if (key[0] == '\0') return nullptr; + + for (size_t i = 0; i < uri->num_query_parts; ++i) { + if (0 == strcmp(key, uri->query_parts[i])) { + return uri->query_parts_values[i]; + } + } + return nullptr; +} + +void grpc_uri_destroy(grpc_uri* uri) { + if (!uri) return; + gpr_free(uri->scheme); + gpr_free(uri->authority); + gpr_free(uri->path); + gpr_free(uri->query); + for (size_t i = 0; i < uri->num_query_parts; ++i) { + gpr_free(uri->query_parts[i]); + gpr_free(uri->query_parts_values[i]); + } + gpr_free(uri->query_parts); + gpr_free(uri->query_parts_values); + gpr_free(uri->fragment); + gpr_free(uri); +} diff --git a/contrib/libs/grpc/src/core/lib/uri/uri_parser.h b/contrib/libs/grpc/src/core/lib/uri/uri_parser.h index ccb9a4f29e..02128b18bb 100644 --- a/contrib/libs/grpc/src/core/lib/uri/uri_parser.h +++ b/contrib/libs/grpc/src/core/lib/uri/uri_parser.h @@ -1,51 +1,51 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_LIB_URI_URI_PARSER_H -#define GRPC_CORE_LIB_URI_URI_PARSER_H - -#include <grpc/support/port_platform.h> - +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_LIB_URI_URI_PARSER_H +#define GRPC_CORE_LIB_URI_URI_PARSER_H + +#include <grpc/support/port_platform.h> + #include "y_absl/strings/string_view.h" -#include <stddef.h> - +#include <stddef.h> + struct grpc_uri { - char* scheme; - char* authority; - char* path; - char* query; - /** Query substrings separated by '&' */ - char** query_parts; - /** Number of elements in \a query_parts and \a query_parts_values */ - size_t num_query_parts; - /** Split each query part by '='. NULL if not present. */ - char** query_parts_values; - char* fragment; + char* scheme; + char* authority; + char* path; + char* query; + /** Query substrings separated by '&' */ + char** query_parts; + /** Number of elements in \a query_parts and \a query_parts_values */ + size_t num_query_parts; + /** Split each query part by '='. NULL if not present. */ + char** query_parts_values; + char* fragment; }; -/** parse a uri, return NULL on failure */ +/** parse a uri, return NULL on failure */ grpc_uri* grpc_uri_parse(y_absl::string_view uri_text, bool suppress_errors); - -/** return the part of a query string after the '=' in "?key=xxx&...", or NULL - * if key is not present */ -const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key); - -/** destroy a uri */ -void grpc_uri_destroy(grpc_uri* uri); - -#endif /* GRPC_CORE_LIB_URI_URI_PARSER_H */ + +/** return the part of a query string after the '=' in "?key=xxx&...", or NULL + * if key is not present */ +const char* grpc_uri_get_query_arg(const grpc_uri* uri, const char* key); + +/** destroy a uri */ +void grpc_uri_destroy(grpc_uri* uri); + +#endif /* GRPC_CORE_LIB_URI_URI_PARSER_H */ diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc index e2f04f7310..6438051dd2 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.cc @@ -29,21 +29,21 @@ #include <grpc/support/log.h> #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/lib/surface/call.h" -#include "src/core/lib/surface/channel.h" -#include "src/core/tsi/alts/handshaker/alts_shared_resource.h" -#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h" -#include "src/core/tsi/alts/handshaker/alts_tsi_utils.h" - -#define TSI_ALTS_INITIAL_BUFFER_SIZE 256 - +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/surface/call.h" +#include "src/core/lib/surface/channel.h" +#include "src/core/tsi/alts/handshaker/alts_shared_resource.h" +#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h" +#include "src/core/tsi/alts/handshaker/alts_tsi_utils.h" + +#define TSI_ALTS_INITIAL_BUFFER_SIZE 256 + const int kHandshakerClientOpNum = 4; -struct alts_handshaker_client { - const alts_handshaker_client_vtable* vtable; -}; - +struct alts_handshaker_client { + const alts_handshaker_client_vtable* vtable; +}; + struct recv_message_result { tsi_result status; const unsigned char* bytes_to_send; @@ -56,42 +56,42 @@ typedef struct alts_grpc_handshaker_client { /* One ref is held by the entity that created this handshaker_client, and * another ref is held by the pending RECEIVE_STATUS_ON_CLIENT op. */ gpr_refcount refs; - alts_tsi_handshaker* handshaker; + alts_tsi_handshaker* handshaker; grpc_call* call; - /* A pointer to a function handling the interaction with handshaker service. - * That is, it points to grpc_call_start_batch_and_execute when the handshaker - * client is used in a non-testing use case and points to a custom function - * that validates the data to be sent to handshaker service in a testing use - * case. */ + /* A pointer to a function handling the interaction with handshaker service. + * That is, it points to grpc_call_start_batch_and_execute when the handshaker + * client is used in a non-testing use case and points to a custom function + * that validates the data to be sent to handshaker service in a testing use + * case. */ alts_grpc_caller grpc_caller; - /* A gRPC closure to be scheduled when the response from handshaker service + /* A gRPC closure to be scheduled when the response from handshaker service * is received. It will be initialized with the injected grpc RPC callback. */ - grpc_closure on_handshaker_service_resp_recv; - /* Buffers containing information to be sent (or received) to (or from) the - * handshaker service. */ - grpc_byte_buffer* send_buffer; - grpc_byte_buffer* recv_buffer; - grpc_status_code status; - /* Initial metadata to be received from handshaker service. */ - grpc_metadata_array recv_initial_metadata; - /* A callback function provided by an application to be invoked when response - * is received from handshaker service. */ - tsi_handshaker_on_next_done_cb cb; - void* user_data; - /* ALTS credential options passed in from the caller. */ - grpc_alts_credentials_options* options; - /* target name information to be passed to handshaker service for server - * authorization check. */ - grpc_slice target_name; - /* boolean flag indicating if the handshaker client is used at client - * (is_client = true) or server (is_client = false) side. */ - bool is_client; - /* a temporary store for data received from handshaker service used to extract - * unused data. */ - grpc_slice recv_bytes; - /* a buffer containing data to be sent to the grpc client or server's peer. */ - unsigned char* buffer; - size_t buffer_size; + grpc_closure on_handshaker_service_resp_recv; + /* Buffers containing information to be sent (or received) to (or from) the + * handshaker service. */ + grpc_byte_buffer* send_buffer; + grpc_byte_buffer* recv_buffer; + grpc_status_code status; + /* Initial metadata to be received from handshaker service. */ + grpc_metadata_array recv_initial_metadata; + /* A callback function provided by an application to be invoked when response + * is received from handshaker service. */ + tsi_handshaker_on_next_done_cb cb; + void* user_data; + /* ALTS credential options passed in from the caller. */ + grpc_alts_credentials_options* options; + /* target name information to be passed to handshaker service for server + * authorization check. */ + grpc_slice target_name; + /* boolean flag indicating if the handshaker client is used at client + * (is_client = true) or server (is_client = false) side. */ + bool is_client; + /* a temporary store for data received from handshaker service used to extract + * unused data. */ + grpc_slice recv_bytes; + /* a buffer containing data to be sent to the grpc client or server's peer. */ + unsigned char* buffer; + size_t buffer_size; /** callback for receiving handshake call status */ grpc_closure on_status_received; /** gRPC status code of handshake call */ @@ -108,21 +108,21 @@ typedef struct alts_grpc_handshaker_client { size_t max_frame_size; } alts_grpc_handshaker_client; -static void handshaker_client_send_buffer_destroy( - alts_grpc_handshaker_client* client) { - GPR_ASSERT(client != nullptr); - grpc_byte_buffer_destroy(client->send_buffer); - client->send_buffer = nullptr; +static void handshaker_client_send_buffer_destroy( + alts_grpc_handshaker_client* client) { + GPR_ASSERT(client != nullptr); + grpc_byte_buffer_destroy(client->send_buffer); + client->send_buffer = nullptr; } static bool is_handshake_finished_properly(grpc_gcp_HandshakerResp* resp) { - GPR_ASSERT(resp != nullptr); + GPR_ASSERT(resp != nullptr); if (grpc_gcp_HandshakerResp_result(resp)) { - return true; - } - return false; -} - + return true; + } + return false; +} + static void alts_grpc_handshaker_client_unref( alts_grpc_handshaker_client* client) { if (gpr_unref(&client->refs)) { @@ -192,55 +192,55 @@ static void handle_response_done(alts_grpc_handshaker_client* client, p /* pending_recv_message_result */); } -void alts_handshaker_client_handle_response(alts_handshaker_client* c, - bool is_ok) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - grpc_byte_buffer* recv_buffer = client->recv_buffer; - grpc_status_code status = client->status; - alts_tsi_handshaker* handshaker = client->handshaker; - /* Invalid input check. */ +void alts_handshaker_client_handle_response(alts_handshaker_client* c, + bool is_ok) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + grpc_byte_buffer* recv_buffer = client->recv_buffer; + grpc_status_code status = client->status; + alts_tsi_handshaker* handshaker = client->handshaker; + /* Invalid input check. */ if (client->cb == nullptr) { - gpr_log(GPR_ERROR, + gpr_log(GPR_ERROR, "client->cb is nullptr in alts_tsi_handshaker_handle_response()"); - return; - } - if (handshaker == nullptr) { - gpr_log(GPR_ERROR, - "handshaker is nullptr in alts_tsi_handshaker_handle_response()"); + return; + } + if (handshaker == nullptr) { + gpr_log(GPR_ERROR, + "handshaker is nullptr in alts_tsi_handshaker_handle_response()"); handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr); - return; - } - /* TSI handshake has been shutdown. */ - if (alts_tsi_handshaker_has_shutdown(handshaker)) { - gpr_log(GPR_ERROR, "TSI handshake shutdown"); + return; + } + /* TSI handshake has been shutdown. */ + if (alts_tsi_handshaker_has_shutdown(handshaker)) { + gpr_log(GPR_ERROR, "TSI handshake shutdown"); handle_response_done(client, TSI_HANDSHAKE_SHUTDOWN, nullptr, 0, nullptr); - return; - } - /* Failed grpc call check. */ - if (!is_ok || status != GRPC_STATUS_OK) { - gpr_log(GPR_ERROR, "grpc call made to handshaker service failed"); + return; + } + /* Failed grpc call check. */ + if (!is_ok || status != GRPC_STATUS_OK) { + gpr_log(GPR_ERROR, "grpc call made to handshaker service failed"); handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr); - return; - } - if (recv_buffer == nullptr) { - gpr_log(GPR_ERROR, - "recv_buffer is nullptr in alts_tsi_handshaker_handle_response()"); + return; + } + if (recv_buffer == nullptr) { + gpr_log(GPR_ERROR, + "recv_buffer is nullptr in alts_tsi_handshaker_handle_response()"); handle_response_done(client, TSI_INTERNAL_ERROR, nullptr, 0, nullptr); - return; - } + return; + } upb::Arena arena; grpc_gcp_HandshakerResp* resp = alts_tsi_utils_deserialize_response(recv_buffer, arena.ptr()); - grpc_byte_buffer_destroy(client->recv_buffer); - client->recv_buffer = nullptr; - /* Invalid handshaker response check. */ - if (resp == nullptr) { - gpr_log(GPR_ERROR, "alts_tsi_utils_deserialize_response() failed"); + grpc_byte_buffer_destroy(client->recv_buffer); + client->recv_buffer = nullptr; + /* Invalid handshaker response check. */ + if (resp == nullptr) { + gpr_log(GPR_ERROR, "alts_tsi_utils_deserialize_response() failed"); handle_response_done(client, TSI_DATA_CORRUPTED, nullptr, 0, nullptr); - return; - } + return; + } const grpc_gcp_HandshakerStatus* resp_status = grpc_gcp_HandshakerResp_status(resp); if (resp_status == nullptr) { @@ -249,20 +249,20 @@ void alts_handshaker_client_handle_response(alts_handshaker_client* c, return; } upb_strview out_frames = grpc_gcp_HandshakerResp_out_frames(resp); - unsigned char* bytes_to_send = nullptr; - size_t bytes_to_send_size = 0; + unsigned char* bytes_to_send = nullptr; + size_t bytes_to_send_size = 0; if (out_frames.size > 0) { bytes_to_send_size = out_frames.size; - while (bytes_to_send_size > client->buffer_size) { - client->buffer_size *= 2; - client->buffer = static_cast<unsigned char*>( - gpr_realloc(client->buffer, client->buffer_size)); - } + while (bytes_to_send_size > client->buffer_size) { + client->buffer_size *= 2; + client->buffer = static_cast<unsigned char*>( + gpr_realloc(client->buffer, client->buffer_size)); + } memcpy(client->buffer, out_frames.data, bytes_to_send_size); - bytes_to_send = client->buffer; - } - tsi_handshaker_result* result = nullptr; - if (is_handshake_finished_properly(resp)) { + bytes_to_send = client->buffer; + } + tsi_handshaker_result* result = nullptr; + if (is_handshake_finished_properly(resp)) { tsi_result status = alts_tsi_handshaker_result_create(resp, client->is_client, &result); if (status != TSI_OK) { @@ -273,26 +273,26 @@ void alts_handshaker_client_handle_response(alts_handshaker_client* c, alts_tsi_handshaker_result_set_unused_bytes( result, &client->recv_bytes, grpc_gcp_HandshakerResp_bytes_consumed(resp)); - } + } grpc_status_code code = static_cast<grpc_status_code>( grpc_gcp_HandshakerStatus_code(resp_status)); - if (code != GRPC_STATUS_OK) { + if (code != GRPC_STATUS_OK) { upb_strview details = grpc_gcp_HandshakerStatus_details(resp_status); if (details.size > 0) { char* error_details = (char*)gpr_zalloc(details.size + 1); memcpy(error_details, details.data, details.size); - gpr_log(GPR_ERROR, "Error from handshaker service:%s", error_details); - gpr_free(error_details); - } - } + gpr_log(GPR_ERROR, "Error from handshaker service:%s", error_details); + gpr_free(error_details); + } + } // TODO(apolcyn): consider short ciruiting handle_response_done and // invoking the TSI callback directly if we aren't done yet, if // handle_response_done's allocation per message received causes // a performance issue. handle_response_done(client, alts_tsi_utils_convert_to_tsi_result(code), bytes_to_send, bytes_to_send_size, result); -} - +} + static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client, bool is_start) { GPR_ASSERT(client != nullptr); @@ -323,22 +323,22 @@ static tsi_result continue_make_grpc_call(alts_grpc_handshaker_client* client, GPR_ASSERT(op - ops <= kHandshakerClientOpNum); op->op = GRPC_OP_RECV_INITIAL_METADATA; op->data.recv_initial_metadata.recv_initial_metadata = - &client->recv_initial_metadata; + &client->recv_initial_metadata; op++; GPR_ASSERT(op - ops <= kHandshakerClientOpNum); } op->op = GRPC_OP_SEND_MESSAGE; - op->data.send_message.send_message = client->send_buffer; + op->data.send_message.send_message = client->send_buffer; op++; GPR_ASSERT(op - ops <= kHandshakerClientOpNum); op->op = GRPC_OP_RECV_MESSAGE; - op->data.recv_message.recv_message = &client->recv_buffer; + op->data.recv_message.recv_message = &client->recv_buffer; op++; GPR_ASSERT(op - ops <= kHandshakerClientOpNum); - GPR_ASSERT(client->grpc_caller != nullptr); - if (client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops), - &client->on_handshaker_service_resp_recv) != - GRPC_CALL_OK) { + GPR_ASSERT(client->grpc_caller != nullptr); + if (client->grpc_caller(client->call, ops, static_cast<size_t>(op - ops), + &client->on_handshaker_service_resp_recv) != + GRPC_CALL_OK) { gpr_log(GPR_ERROR, "Start batch operation failed"); return TSI_INTERNAL_ERROR; } @@ -480,11 +480,11 @@ static grpc_byte_buffer* get_serialized_handshaker_req( } /* Create and populate a client_start handshaker request, then serialize it. */ -static grpc_byte_buffer* get_serialized_start_client( - alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); +static grpc_byte_buffer* get_serialized_start_client( + alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); upb::Arena arena; grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr()); grpc_gcp_StartClientHandshakeReq* start_client = @@ -506,7 +506,7 @@ static grpc_byte_buffer* get_serialized_start_client( GRPC_SLICE_START_PTR(client->target_name)), GRPC_SLICE_LENGTH(client->target_name))); target_service_account* ptr = - (reinterpret_cast<grpc_alts_credentials_client_options*>(client->options)) + (reinterpret_cast<grpc_alts_credentials_client_options*>(client->options)) ->target_account_list_head; while (ptr != nullptr) { grpc_gcp_Identity* target_identity = @@ -521,21 +521,21 @@ static grpc_byte_buffer* get_serialized_start_client( return get_serialized_handshaker_req(req, arena.ptr()); } -static tsi_result handshaker_client_start_client(alts_handshaker_client* c) { - if (c == nullptr) { - gpr_log(GPR_ERROR, "client is nullptr in handshaker_client_start_client()"); +static tsi_result handshaker_client_start_client(alts_handshaker_client* c) { + if (c == nullptr) { + gpr_log(GPR_ERROR, "client is nullptr in handshaker_client_start_client()"); return TSI_INVALID_ARGUMENT; } - grpc_byte_buffer* buffer = get_serialized_start_client(c); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); + grpc_byte_buffer* buffer = get_serialized_start_client(c); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); if (buffer == nullptr) { gpr_log(GPR_ERROR, "get_serialized_start_client() failed"); return TSI_INTERNAL_ERROR; } - handshaker_client_send_buffer_destroy(client); - client->send_buffer = buffer; - tsi_result result = make_grpc_call(&client->base, true /* is_start */); + handshaker_client_send_buffer_destroy(client); + client->send_buffer = buffer; + tsi_result result = make_grpc_call(&client->base, true /* is_start */); if (result != TSI_OK) { gpr_log(GPR_ERROR, "make_grpc_call() failed"); } @@ -544,11 +544,11 @@ static tsi_result handshaker_client_start_client(alts_handshaker_client* c) { /* Create and populate a start_server handshaker request, then serialize it. */ static grpc_byte_buffer* get_serialized_start_server( - alts_handshaker_client* c, grpc_slice* bytes_received) { - GPR_ASSERT(c != nullptr); + alts_handshaker_client* c, grpc_slice* bytes_received) { + GPR_ASSERT(c != nullptr); GPR_ASSERT(bytes_received != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); upb::Arena arena; grpc_gcp_HandshakerReq* req = grpc_gcp_HandshakerReq_new(arena.ptr()); @@ -577,22 +577,22 @@ static grpc_byte_buffer* get_serialized_start_server( return get_serialized_handshaker_req(req, arena.ptr()); } -static tsi_result handshaker_client_start_server(alts_handshaker_client* c, +static tsi_result handshaker_client_start_server(alts_handshaker_client* c, grpc_slice* bytes_received) { - if (c == nullptr || bytes_received == nullptr) { - gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_start_server()"); + if (c == nullptr || bytes_received == nullptr) { + gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_start_server()"); return TSI_INVALID_ARGUMENT; } - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - grpc_byte_buffer* buffer = get_serialized_start_server(c, bytes_received); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + grpc_byte_buffer* buffer = get_serialized_start_server(c, bytes_received); if (buffer == nullptr) { gpr_log(GPR_ERROR, "get_serialized_start_server() failed"); return TSI_INTERNAL_ERROR; } - handshaker_client_send_buffer_destroy(client); - client->send_buffer = buffer; - tsi_result result = make_grpc_call(&client->base, true /* is_start */); + handshaker_client_send_buffer_destroy(client); + client->send_buffer = buffer; + tsi_result result = make_grpc_call(&client->base, true /* is_start */); if (result != TSI_OK) { gpr_log(GPR_ERROR, "make_grpc_call() failed"); } @@ -613,51 +613,51 @@ static grpc_byte_buffer* get_serialized_next(grpc_slice* bytes_received) { return get_serialized_handshaker_req(req, arena.ptr()); } -static tsi_result handshaker_client_next(alts_handshaker_client* c, +static tsi_result handshaker_client_next(alts_handshaker_client* c, grpc_slice* bytes_received) { - if (c == nullptr || bytes_received == nullptr) { - gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_next()"); + if (c == nullptr || bytes_received == nullptr) { + gpr_log(GPR_ERROR, "Invalid arguments to handshaker_client_next()"); return TSI_INVALID_ARGUMENT; } - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - grpc_slice_unref_internal(client->recv_bytes); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + grpc_slice_unref_internal(client->recv_bytes); client->recv_bytes = grpc_slice_ref_internal(*bytes_received); grpc_byte_buffer* buffer = get_serialized_next(bytes_received); if (buffer == nullptr) { gpr_log(GPR_ERROR, "get_serialized_next() failed"); return TSI_INTERNAL_ERROR; } - handshaker_client_send_buffer_destroy(client); - client->send_buffer = buffer; - tsi_result result = make_grpc_call(&client->base, false /* is_start */); + handshaker_client_send_buffer_destroy(client); + client->send_buffer = buffer; + tsi_result result = make_grpc_call(&client->base, false /* is_start */); if (result != TSI_OK) { gpr_log(GPR_ERROR, "make_grpc_call() failed"); } return result; } -static void handshaker_client_shutdown(alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - if (client->call != nullptr) { - grpc_call_cancel_internal(client->call); - } -} - +static void handshaker_client_shutdown(alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + if (client->call != nullptr) { + grpc_call_cancel_internal(client->call); + } +} + static void handshaker_call_unref(void* arg, grpc_error* /* error */) { grpc_call* call = static_cast<grpc_call*>(arg); grpc_call_unref(call); } -static void handshaker_client_destruct(alts_handshaker_client* c) { - if (c == nullptr) { +static void handshaker_client_destruct(alts_handshaker_client* c) { + if (c == nullptr) { return; } - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - if (client->call != nullptr) { + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + if (client->call != nullptr) { // Throw this grpc_call_unref over to the ExecCtx so that // we invoke it at the bottom of the call stack and // prevent lock inversion problems due to nested ExecCtx flushing. @@ -676,22 +676,22 @@ static void handshaker_client_destruct(alts_handshaker_client* c) { grpc_schedule_on_exec_ctx), GRPC_ERROR_NONE); } - } + } } static const alts_handshaker_client_vtable vtable = { handshaker_client_start_client, handshaker_client_start_server, - handshaker_client_next, handshaker_client_shutdown, - handshaker_client_destruct}; + handshaker_client_next, handshaker_client_shutdown, + handshaker_client_destruct}; alts_handshaker_client* alts_grpc_handshaker_client_create( - alts_tsi_handshaker* handshaker, grpc_channel* channel, - const char* handshaker_service_url, grpc_pollset_set* interested_parties, + alts_tsi_handshaker* handshaker, grpc_channel* channel, + const char* handshaker_service_url, grpc_pollset_set* interested_parties, grpc_alts_credentials_options* options, const grpc_slice& target_name, - grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb, - void* user_data, alts_handshaker_client_vtable* vtable_for_testing, + grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb, + void* user_data, alts_handshaker_client_vtable* vtable_for_testing, bool is_client, size_t max_frame_size) { - if (channel == nullptr || handshaker_service_url == nullptr) { + if (channel == nullptr || handshaker_service_url == nullptr) { gpr_log(GPR_ERROR, "Invalid arguments to alts_handshaker_client_create()"); return nullptr; } @@ -699,36 +699,36 @@ alts_handshaker_client* alts_grpc_handshaker_client_create( static_cast<alts_grpc_handshaker_client*>(gpr_zalloc(sizeof(*client))); gpr_mu_init(&client->mu); gpr_ref_init(&client->refs, 1); - client->grpc_caller = grpc_call_start_batch_and_execute; - client->handshaker = handshaker; - client->cb = cb; - client->user_data = user_data; - client->send_buffer = nullptr; - client->recv_buffer = nullptr; - client->options = grpc_alts_credentials_options_copy(options); - client->target_name = grpc_slice_copy(target_name); - client->recv_bytes = grpc_empty_slice(); - grpc_metadata_array_init(&client->recv_initial_metadata); - client->is_client = is_client; + client->grpc_caller = grpc_call_start_batch_and_execute; + client->handshaker = handshaker; + client->cb = cb; + client->user_data = user_data; + client->send_buffer = nullptr; + client->recv_buffer = nullptr; + client->options = grpc_alts_credentials_options_copy(options); + client->target_name = grpc_slice_copy(target_name); + client->recv_bytes = grpc_empty_slice(); + grpc_metadata_array_init(&client->recv_initial_metadata); + client->is_client = is_client; client->max_frame_size = max_frame_size; - client->buffer_size = TSI_ALTS_INITIAL_BUFFER_SIZE; - client->buffer = static_cast<unsigned char*>(gpr_zalloc(client->buffer_size)); + client->buffer_size = TSI_ALTS_INITIAL_BUFFER_SIZE; + client->buffer = static_cast<unsigned char*>(gpr_zalloc(client->buffer_size)); grpc_slice slice = grpc_slice_from_copied_string(handshaker_service_url); - client->call = - strcmp(handshaker_service_url, ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING) == - 0 - ? nullptr - : grpc_channel_create_pollset_set_call( - channel, nullptr, GRPC_PROPAGATE_DEFAULTS, interested_parties, - grpc_slice_from_static_string(ALTS_SERVICE_METHOD), &slice, - GRPC_MILLIS_INF_FUTURE, nullptr); - client->base.vtable = - vtable_for_testing == nullptr ? &vtable : vtable_for_testing; + client->call = + strcmp(handshaker_service_url, ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING) == + 0 + ? nullptr + : grpc_channel_create_pollset_set_call( + channel, nullptr, GRPC_PROPAGATE_DEFAULTS, interested_parties, + grpc_slice_from_static_string(ALTS_SERVICE_METHOD), &slice, + GRPC_MILLIS_INF_FUTURE, nullptr); + client->base.vtable = + vtable_for_testing == nullptr ? &vtable : vtable_for_testing; GRPC_CLOSURE_INIT(&client->on_handshaker_service_resp_recv, grpc_cb, client, grpc_schedule_on_exec_ctx); GRPC_CLOSURE_INIT(&client->on_status_received, on_status_received, client, grpc_schedule_on_exec_ctx); - grpc_slice_unref_internal(slice); + grpc_slice_unref_internal(slice); return &client->base; } @@ -736,107 +736,107 @@ namespace grpc_core { namespace internal { void alts_handshaker_client_set_grpc_caller_for_testing( - alts_handshaker_client* c, alts_grpc_caller caller) { - GPR_ASSERT(c != nullptr && caller != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - client->grpc_caller = caller; -} - -grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing( - alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - return client->send_buffer; -} - -grpc_byte_buffer** alts_handshaker_client_get_recv_buffer_addr_for_testing( - alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - return &client->recv_buffer; -} - -grpc_metadata_array* alts_handshaker_client_get_initial_metadata_for_testing( - alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - return &client->recv_initial_metadata; -} - -void alts_handshaker_client_set_recv_bytes_for_testing( - alts_handshaker_client* c, grpc_slice* recv_bytes) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); + alts_handshaker_client* c, alts_grpc_caller caller) { + GPR_ASSERT(c != nullptr && caller != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + client->grpc_caller = caller; +} + +grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing( + alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + return client->send_buffer; +} + +grpc_byte_buffer** alts_handshaker_client_get_recv_buffer_addr_for_testing( + alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + return &client->recv_buffer; +} + +grpc_metadata_array* alts_handshaker_client_get_initial_metadata_for_testing( + alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + return &client->recv_initial_metadata; +} + +void alts_handshaker_client_set_recv_bytes_for_testing( + alts_handshaker_client* c, grpc_slice* recv_bytes) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); client->recv_bytes = grpc_slice_ref_internal(*recv_bytes); -} - -void alts_handshaker_client_set_fields_for_testing( - alts_handshaker_client* c, alts_tsi_handshaker* handshaker, - tsi_handshaker_on_next_done_cb cb, void* user_data, - grpc_byte_buffer* recv_buffer, grpc_status_code status) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - client->handshaker = handshaker; - client->cb = cb; - client->user_data = user_data; - client->recv_buffer = recv_buffer; - client->status = status; -} - -void alts_handshaker_client_check_fields_for_testing( - alts_handshaker_client* c, tsi_handshaker_on_next_done_cb cb, - void* user_data, bool has_sent_start_message, grpc_slice* recv_bytes) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - GPR_ASSERT(client->cb == cb); - GPR_ASSERT(client->user_data == user_data); - if (recv_bytes != nullptr) { - GPR_ASSERT(grpc_slice_cmp(client->recv_bytes, *recv_bytes) == 0); - } - GPR_ASSERT(alts_tsi_handshaker_get_has_sent_start_message_for_testing( - client->handshaker) == has_sent_start_message); -} - -void alts_handshaker_client_set_vtable_for_testing( - alts_handshaker_client* c, alts_handshaker_client_vtable* vtable) { - GPR_ASSERT(c != nullptr); - GPR_ASSERT(vtable != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - client->base.vtable = vtable; -} - -alts_tsi_handshaker* alts_handshaker_client_get_handshaker_for_testing( - alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - return client->handshaker; -} - -void alts_handshaker_client_set_cb_for_testing( - alts_handshaker_client* c, tsi_handshaker_on_next_done_cb cb) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - client->cb = cb; -} - -grpc_closure* alts_handshaker_client_get_closure_for_testing( - alts_handshaker_client* c) { - GPR_ASSERT(c != nullptr); - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); - return &client->on_handshaker_service_resp_recv; -} - +} + +void alts_handshaker_client_set_fields_for_testing( + alts_handshaker_client* c, alts_tsi_handshaker* handshaker, + tsi_handshaker_on_next_done_cb cb, void* user_data, + grpc_byte_buffer* recv_buffer, grpc_status_code status) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + client->handshaker = handshaker; + client->cb = cb; + client->user_data = user_data; + client->recv_buffer = recv_buffer; + client->status = status; +} + +void alts_handshaker_client_check_fields_for_testing( + alts_handshaker_client* c, tsi_handshaker_on_next_done_cb cb, + void* user_data, bool has_sent_start_message, grpc_slice* recv_bytes) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + GPR_ASSERT(client->cb == cb); + GPR_ASSERT(client->user_data == user_data); + if (recv_bytes != nullptr) { + GPR_ASSERT(grpc_slice_cmp(client->recv_bytes, *recv_bytes) == 0); + } + GPR_ASSERT(alts_tsi_handshaker_get_has_sent_start_message_for_testing( + client->handshaker) == has_sent_start_message); +} + +void alts_handshaker_client_set_vtable_for_testing( + alts_handshaker_client* c, alts_handshaker_client_vtable* vtable) { + GPR_ASSERT(c != nullptr); + GPR_ASSERT(vtable != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + client->base.vtable = vtable; +} + +alts_tsi_handshaker* alts_handshaker_client_get_handshaker_for_testing( + alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + return client->handshaker; +} + +void alts_handshaker_client_set_cb_for_testing( + alts_handshaker_client* c, tsi_handshaker_on_next_done_cb cb) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + client->cb = cb; +} + +grpc_closure* alts_handshaker_client_get_closure_for_testing( + alts_handshaker_client* c) { + GPR_ASSERT(c != nullptr); + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); + return &client->on_handshaker_service_resp_recv; +} + void alts_handshaker_client_ref_for_testing(alts_handshaker_client* c) { alts_grpc_handshaker_client* client = reinterpret_cast<alts_grpc_handshaker_client*>(c); @@ -861,10 +861,10 @@ void alts_handshaker_client_on_status_received_for_testing( } // namespace internal } // namespace grpc_core -tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client) { +tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client) { if (client != nullptr && client->vtable != nullptr && client->vtable->client_start != nullptr) { - return client->vtable->client_start(client); + return client->vtable->client_start(client); } gpr_log(GPR_ERROR, "client or client->vtable has not been initialized properly"); @@ -875,7 +875,7 @@ tsi_result alts_handshaker_client_start_server(alts_handshaker_client* client, grpc_slice* bytes_received) { if (client != nullptr && client->vtable != nullptr && client->vtable->server_start != nullptr) { - return client->vtable->server_start(client, bytes_received); + return client->vtable->server_start(client, bytes_received); } gpr_log(GPR_ERROR, "client or client->vtable has not been initialized properly"); @@ -886,24 +886,24 @@ tsi_result alts_handshaker_client_next(alts_handshaker_client* client, grpc_slice* bytes_received) { if (client != nullptr && client->vtable != nullptr && client->vtable->next != nullptr) { - return client->vtable->next(client, bytes_received); + return client->vtable->next(client, bytes_received); } gpr_log(GPR_ERROR, "client or client->vtable has not been initialized properly"); return TSI_INVALID_ARGUMENT; } -void alts_handshaker_client_shutdown(alts_handshaker_client* client) { - if (client != nullptr && client->vtable != nullptr && - client->vtable->shutdown != nullptr) { - client->vtable->shutdown(client); - } -} - -void alts_handshaker_client_destroy(alts_handshaker_client* c) { - if (c != nullptr) { - alts_grpc_handshaker_client* client = - reinterpret_cast<alts_grpc_handshaker_client*>(c); +void alts_handshaker_client_shutdown(alts_handshaker_client* client) { + if (client != nullptr && client->vtable != nullptr && + client->vtable->shutdown != nullptr) { + client->vtable->shutdown(client); + } +} + +void alts_handshaker_client_destroy(alts_handshaker_client* c) { + if (c != nullptr) { + alts_grpc_handshaker_client* client = + reinterpret_cast<alts_grpc_handshaker_client*>(c); alts_grpc_handshaker_client_unref(client); } } diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h index d8669da01c..463fcf746e 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_handshaker_client.h @@ -21,24 +21,24 @@ #include <grpc/support/port_platform.h> -#include <grpc/byte_buffer.h> -#include <grpc/byte_buffer_reader.h> +#include <grpc/byte_buffer.h> +#include <grpc/byte_buffer_reader.h> #include <grpc/grpc.h> -#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h" -#include "src/core/tsi/transport_security_interface.h" - -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/pollset_set.h" +#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h" +#include "src/core/tsi/transport_security_interface.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/pollset_set.h" + #define ALTS_SERVICE_METHOD "/grpc.gcp.HandshakerService/DoHandshake" #define ALTS_APPLICATION_PROTOCOL "grpc" #define ALTS_RECORD_PROTOCOL "ALTSRP_GCM_AES128_REKEY" -#define ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING "lame" +#define ALTS_HANDSHAKER_SERVICE_URL_FOR_TESTING "lame" const size_t kAltsAes128GcmRekeyKeyLength = 44; -typedef struct alts_tsi_handshaker alts_tsi_handshaker; +typedef struct alts_tsi_handshaker alts_tsi_handshaker; /** * A ALTS handshaker client interface. It is used to communicate with * ALTS handshaker service by scheduling a handshaker request that could be one @@ -49,16 +49,16 @@ typedef struct alts_handshaker_client alts_handshaker_client; /* A function that makes the grpc call to the handshaker service. */ typedef grpc_call_error (*alts_grpc_caller)(grpc_call* call, const grpc_op* ops, - size_t nops, grpc_closure* tag); + size_t nops, grpc_closure* tag); /* V-table for ALTS handshaker client operations. */ typedef struct alts_handshaker_client_vtable { - tsi_result (*client_start)(alts_handshaker_client* client); + tsi_result (*client_start)(alts_handshaker_client* client); tsi_result (*server_start)(alts_handshaker_client* client, - grpc_slice* bytes_received); - tsi_result (*next)(alts_handshaker_client* client, + grpc_slice* bytes_received); + tsi_result (*next)(alts_handshaker_client* client, grpc_slice* bytes_received); - void (*shutdown)(alts_handshaker_client* client); + void (*shutdown)(alts_handshaker_client* client); void (*destruct)(alts_handshaker_client* client); } alts_handshaker_client_vtable; @@ -70,7 +70,7 @@ typedef struct alts_handshaker_client_vtable { * * It returns TSI_OK on success and an error status code on failure. */ -tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client); +tsi_result alts_handshaker_client_start_client(alts_handshaker_client* client); /** * This method schedules a server_start handshaker request to ALTS handshaker @@ -98,40 +98,40 @@ tsi_result alts_handshaker_client_next(alts_handshaker_client* client, grpc_slice* bytes_received); /** - * This method cancels previously scheduled, but yet executed handshaker - * requests to ALTS handshaker service. After this operation, the handshake - * will be shutdown, and no more handshaker requests will get scheduled. + * This method cancels previously scheduled, but yet executed handshaker + * requests to ALTS handshaker service. After this operation, the handshake + * will be shutdown, and no more handshaker requests will get scheduled. * - * - client: ALTS handshaker client instance. - */ -void alts_handshaker_client_shutdown(alts_handshaker_client* client); - -/** - * This method destroys an ALTS handshaker client. - * - * - client: an ALTS handshaker client instance. + * - client: ALTS handshaker client instance. */ +void alts_handshaker_client_shutdown(alts_handshaker_client* client); + +/** + * This method destroys an ALTS handshaker client. + * + * - client: an ALTS handshaker client instance. + */ void alts_handshaker_client_destroy(alts_handshaker_client* client); /** - * This method creates an ALTS handshaker client. + * This method creates an ALTS handshaker client. * - * - handshaker: ALTS TSI handshaker to which the created handshaker client + * - handshaker: ALTS TSI handshaker to which the created handshaker client * belongs to. * - channel: grpc channel to ALTS handshaker service. * - handshaker_service_url: address of ALTS handshaker service in the format of * "host:port". - * - interested_parties: set of pollsets interested in this connection. - * - options: ALTS credentials options containing information passed from TSI - * caller (e.g., rpc protocol versions) - * - target_name: the name of the endpoint that the channel is connecting to, - * and will be used for secure naming check - * - grpc_cb: gRPC provided callbacks passed from TSI handshaker. - * - cb: callback to be executed when tsi_handshaker_next API compltes. - * - user_data: argument passed to cb. - * - vtable_for_testing: ALTS handshaker client vtable instance used for - * testing purpose. - * - is_client: a boolean value indicating if the created handshaker client is + * - interested_parties: set of pollsets interested in this connection. + * - options: ALTS credentials options containing information passed from TSI + * caller (e.g., rpc protocol versions) + * - target_name: the name of the endpoint that the channel is connecting to, + * and will be used for secure naming check + * - grpc_cb: gRPC provided callbacks passed from TSI handshaker. + * - cb: callback to be executed when tsi_handshaker_next API compltes. + * - user_data: argument passed to cb. + * - vtable_for_testing: ALTS handshaker client vtable instance used for + * testing purpose. + * - is_client: a boolean value indicating if the created handshaker client is * used at the client (is_client = true) or server (is_client = false) side. * - max_frame_size: Maximum frame size used by frame protector (User specified * maximum frame size if present or default max frame size). @@ -140,22 +140,22 @@ void alts_handshaker_client_destroy(alts_handshaker_client* client); * on failure. */ alts_handshaker_client* alts_grpc_handshaker_client_create( - alts_tsi_handshaker* handshaker, grpc_channel* channel, - const char* handshaker_service_url, grpc_pollset_set* interested_parties, + alts_tsi_handshaker* handshaker, grpc_channel* channel, + const char* handshaker_service_url, grpc_pollset_set* interested_parties, grpc_alts_credentials_options* options, const grpc_slice& target_name, - grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb, - void* user_data, alts_handshaker_client_vtable* vtable_for_testing, + grpc_iomgr_cb_func grpc_cb, tsi_handshaker_on_next_done_cb cb, + void* user_data, alts_handshaker_client_vtable* vtable_for_testing, bool is_client, size_t max_frame_size); /** - * This method handles handshaker response returned from ALTS handshaker - * service. Note that the only reason the API is exposed is that it is used in - * alts_shared_resources.cc. - * - * - client: an ALTS handshaker client instance. - * - is_ok: a boolean value indicating if the handshaker response is ok to read. + * This method handles handshaker response returned from ALTS handshaker + * service. Note that the only reason the API is exposed is that it is used in + * alts_shared_resources.cc. + * + * - client: an ALTS handshaker client instance. + * - is_ok: a boolean value indicating if the handshaker response is ok to read. */ -void alts_handshaker_client_handle_response(alts_handshaker_client* client, - bool is_ok); +void alts_handshaker_client_handle_response(alts_handshaker_client* client, + bool is_ok); #endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_HANDSHAKER_CLIENT_H */ diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc index 255eda5df3..ff6f1a4326 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.cc @@ -1,83 +1,83 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/tsi/alts/handshaker/alts_shared_resource.h" - -#include <grpc/support/log.h> - -#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h" - -static alts_shared_resource_dedicated g_alts_resource_dedicated; - -alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void) { - return &g_alts_resource_dedicated; -} - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/tsi/alts/handshaker/alts_shared_resource.h" + +#include <grpc/support/log.h> + +#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h" + +static alts_shared_resource_dedicated g_alts_resource_dedicated; + +alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void) { + return &g_alts_resource_dedicated; +} + static void thread_worker(void* /*arg*/) { - while (true) { - grpc_event event = - grpc_completion_queue_next(g_alts_resource_dedicated.cq, - gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); - GPR_ASSERT(event.type != GRPC_QUEUE_TIMEOUT); - if (event.type == GRPC_QUEUE_SHUTDOWN) { - break; - } - GPR_ASSERT(event.type == GRPC_OP_COMPLETE); - alts_handshaker_client* client = - static_cast<alts_handshaker_client*>(event.tag); - alts_handshaker_client_handle_response(client, event.success); - } -} - -void grpc_alts_shared_resource_dedicated_init() { - g_alts_resource_dedicated.cq = nullptr; - gpr_mu_init(&g_alts_resource_dedicated.mu); -} - -void grpc_alts_shared_resource_dedicated_start( - const char* handshaker_service_url) { - gpr_mu_lock(&g_alts_resource_dedicated.mu); - if (g_alts_resource_dedicated.cq == nullptr) { - g_alts_resource_dedicated.channel = - grpc_insecure_channel_create(handshaker_service_url, nullptr, nullptr); - g_alts_resource_dedicated.cq = - grpc_completion_queue_create_for_next(nullptr); - g_alts_resource_dedicated.thread = - grpc_core::Thread("alts_tsi_handshaker", &thread_worker, nullptr); - g_alts_resource_dedicated.interested_parties = grpc_pollset_set_create(); - grpc_pollset_set_add_pollset(g_alts_resource_dedicated.interested_parties, - grpc_cq_pollset(g_alts_resource_dedicated.cq)); - g_alts_resource_dedicated.thread.Start(); - } - gpr_mu_unlock(&g_alts_resource_dedicated.mu); -} - -void grpc_alts_shared_resource_dedicated_shutdown() { - if (g_alts_resource_dedicated.cq != nullptr) { - grpc_pollset_set_del_pollset(g_alts_resource_dedicated.interested_parties, - grpc_cq_pollset(g_alts_resource_dedicated.cq)); - grpc_completion_queue_shutdown(g_alts_resource_dedicated.cq); - g_alts_resource_dedicated.thread.Join(); - grpc_pollset_set_destroy(g_alts_resource_dedicated.interested_parties); - grpc_completion_queue_destroy(g_alts_resource_dedicated.cq); - grpc_channel_destroy(g_alts_resource_dedicated.channel); - } - gpr_mu_destroy(&g_alts_resource_dedicated.mu); -} + while (true) { + grpc_event event = + grpc_completion_queue_next(g_alts_resource_dedicated.cq, + gpr_inf_future(GPR_CLOCK_REALTIME), nullptr); + GPR_ASSERT(event.type != GRPC_QUEUE_TIMEOUT); + if (event.type == GRPC_QUEUE_SHUTDOWN) { + break; + } + GPR_ASSERT(event.type == GRPC_OP_COMPLETE); + alts_handshaker_client* client = + static_cast<alts_handshaker_client*>(event.tag); + alts_handshaker_client_handle_response(client, event.success); + } +} + +void grpc_alts_shared_resource_dedicated_init() { + g_alts_resource_dedicated.cq = nullptr; + gpr_mu_init(&g_alts_resource_dedicated.mu); +} + +void grpc_alts_shared_resource_dedicated_start( + const char* handshaker_service_url) { + gpr_mu_lock(&g_alts_resource_dedicated.mu); + if (g_alts_resource_dedicated.cq == nullptr) { + g_alts_resource_dedicated.channel = + grpc_insecure_channel_create(handshaker_service_url, nullptr, nullptr); + g_alts_resource_dedicated.cq = + grpc_completion_queue_create_for_next(nullptr); + g_alts_resource_dedicated.thread = + grpc_core::Thread("alts_tsi_handshaker", &thread_worker, nullptr); + g_alts_resource_dedicated.interested_parties = grpc_pollset_set_create(); + grpc_pollset_set_add_pollset(g_alts_resource_dedicated.interested_parties, + grpc_cq_pollset(g_alts_resource_dedicated.cq)); + g_alts_resource_dedicated.thread.Start(); + } + gpr_mu_unlock(&g_alts_resource_dedicated.mu); +} + +void grpc_alts_shared_resource_dedicated_shutdown() { + if (g_alts_resource_dedicated.cq != nullptr) { + grpc_pollset_set_del_pollset(g_alts_resource_dedicated.interested_parties, + grpc_cq_pollset(g_alts_resource_dedicated.cq)); + grpc_completion_queue_shutdown(g_alts_resource_dedicated.cq); + g_alts_resource_dedicated.thread.Join(); + grpc_pollset_set_destroy(g_alts_resource_dedicated.interested_parties); + grpc_completion_queue_destroy(g_alts_resource_dedicated.cq); + grpc_channel_destroy(g_alts_resource_dedicated.channel); + } + gpr_mu_destroy(&g_alts_resource_dedicated.mu); +} diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h index d8638e7df6..6fc93b920e 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_shared_resource.h @@ -1,73 +1,73 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_SHARED_RESOURCE_H -#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_SHARED_RESOURCE_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc.h> -#include <grpc/support/sync.h> - -#include "src/core/lib/gprpp/thd.h" -#include "src/core/lib/iomgr/pollset_set.h" -#include "src/core/lib/surface/completion_queue.h" - -/** - * Main struct containing ALTS shared resources used when - * employing the dedicated completion queue and thread. - */ -typedef struct alts_shared_resource_dedicated { - grpc_core::Thread thread; - grpc_completion_queue* cq; - grpc_pollset_set* interested_parties; - grpc_cq_completion storage; - gpr_mu mu; - grpc_channel* channel; -} alts_shared_resource_dedicated; - -/* This method returns the address of alts_shared_resource_dedicated - * object shared by all TSI handshakes. - */ -alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void); - -/** - * This method destroys the alts_shared_resource_dedicated object +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_SHARED_RESOURCE_H +#define GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_SHARED_RESOURCE_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc.h> +#include <grpc/support/sync.h> + +#include "src/core/lib/gprpp/thd.h" +#include "src/core/lib/iomgr/pollset_set.h" +#include "src/core/lib/surface/completion_queue.h" + +/** + * Main struct containing ALTS shared resources used when + * employing the dedicated completion queue and thread. + */ +typedef struct alts_shared_resource_dedicated { + grpc_core::Thread thread; + grpc_completion_queue* cq; + grpc_pollset_set* interested_parties; + grpc_cq_completion storage; + gpr_mu mu; + grpc_channel* channel; +} alts_shared_resource_dedicated; + +/* This method returns the address of alts_shared_resource_dedicated + * object shared by all TSI handshakes. + */ +alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void); + +/** + * This method destroys the alts_shared_resource_dedicated object * shared by all TSI handshakes. The application is responsible for - * invoking the API before calling grpc_shutdown(). - */ -void grpc_alts_shared_resource_dedicated_shutdown(); - -/** - * This method initializes the alts_shared_resource_dedicated object - * shared by all TSI handshakes. The application is responsible for - * invoking the API after calling grpc_init(); - */ -void grpc_alts_shared_resource_dedicated_init(); - -/** - * This method populates various fields of the alts_shared_resource_dedicated - * object shared by all TSI handshakes and start the dedicated thread. - * The API will be invoked by the caller in a lazy manner. That is, - * it will get invoked when ALTS TSI handshake occurs for the first time. - */ -void grpc_alts_shared_resource_dedicated_start( - const char* handshaker_service_url); - -#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_SHARED_RESOURCE_H \ - */ + * invoking the API before calling grpc_shutdown(). + */ +void grpc_alts_shared_resource_dedicated_shutdown(); + +/** + * This method initializes the alts_shared_resource_dedicated object + * shared by all TSI handshakes. The application is responsible for + * invoking the API after calling grpc_init(); + */ +void grpc_alts_shared_resource_dedicated_init(); + +/** + * This method populates various fields of the alts_shared_resource_dedicated + * object shared by all TSI handshakes and start the dedicated thread. + * The API will be invoked by the caller in a lazy manner. That is, + * it will get invoked when ALTS TSI handshake occurs for the first time. + */ +void grpc_alts_shared_resource_dedicated_start( + const char* handshaker_service_url); + +#endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_SHARED_RESOURCE_H \ + */ diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc index 01ef56157a..e884eac02a 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc @@ -28,33 +28,33 @@ #include <grpc/support/alloc.h> #include <grpc/support/log.h> -#include <grpc/support/string_util.h> +#include <grpc/support/string_util.h> #include <grpc/support/sync.h> #include <grpc/support/thd_id.h> #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/gprpp/thd.h" -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/slice/slice_internal.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/slice/slice_internal.h" #include "src/core/lib/surface/channel.h" #include "src/core/tsi/alts/frame_protector/alts_frame_protector.h" #include "src/core/tsi/alts/handshaker/alts_handshaker_client.h" -#include "src/core/tsi/alts/handshaker/alts_shared_resource.h" +#include "src/core/tsi/alts/handshaker/alts_shared_resource.h" #include "src/core/tsi/alts/handshaker/alts_tsi_utils.h" #include "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h" /* Main struct for ALTS TSI handshaker. */ -struct alts_tsi_handshaker { +struct alts_tsi_handshaker { tsi_handshaker base; grpc_slice target_name; bool is_client; bool has_sent_start_message; - bool has_created_handshaker_client; - char* handshaker_service_url; - grpc_pollset_set* interested_parties; + bool has_created_handshaker_client; + char* handshaker_service_url; + grpc_pollset_set* interested_parties; grpc_alts_credentials_options* options; - alts_handshaker_client_vtable* client_vtable_for_testing; - grpc_channel* channel; + alts_handshaker_client_vtable* client_vtable_for_testing; + grpc_channel* channel; bool use_dedicated_cq; // mu synchronizes all fields below. Note these are the // only fields that can be concurrently accessed (due to @@ -67,7 +67,7 @@ struct alts_tsi_handshaker { bool shutdown; // Maximum frame size used by frame protector. size_t max_frame_size; -}; +}; /* Main struct for ALTS TSI handshaker result. */ typedef struct alts_tsi_handshaker_result { @@ -185,8 +185,8 @@ static tsi_result handshaker_result_create_zero_copy_grpc_protector( tsi_result ok = alts_zero_copy_grpc_protector_create( reinterpret_cast<const uint8_t*>(result->key_data), kAltsAes128GcmRekeyKeyLength, /*is_rekey=*/true, result->is_client, - /*is_integrity_only=*/false, /*enable_extra_copy=*/false, - max_output_protected_frame_size, protector); + /*is_integrity_only=*/false, /*enable_extra_copy=*/false, + max_output_protected_frame_size, protector); if (ok != TSI_OK) { gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector"); } @@ -240,7 +240,7 @@ static void handshaker_result_destroy(tsi_handshaker_result* self) { gpr_free(result->peer_identity); gpr_free(result->key_data); gpr_free(result->unused_bytes); - grpc_slice_unref_internal(result->rpc_versions); + grpc_slice_unref_internal(result->rpc_versions); grpc_slice_unref_internal(result->serialized_context); gpr_free(result); } @@ -252,8 +252,8 @@ static const tsi_handshaker_result_vtable result_vtable = { handshaker_result_get_unused_bytes, handshaker_result_destroy}; tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp, - bool is_client, - tsi_handshaker_result** self) { + bool is_client, + tsi_handshaker_result** self) { if (self == nullptr || resp == nullptr) { gpr_log(GPR_ERROR, "Invalid arguments to create_handshaker_result()"); return TSI_INVALID_ARGUMENT; @@ -371,13 +371,13 @@ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp, return TSI_OK; } -/* gRPC provided callback used when gRPC thread model is applied. */ -static void on_handshaker_service_resp_recv(void* arg, grpc_error* error) { - alts_handshaker_client* client = static_cast<alts_handshaker_client*>(arg); - if (client == nullptr) { - gpr_log(GPR_ERROR, "ALTS handshaker client is nullptr"); - return; - } +/* gRPC provided callback used when gRPC thread model is applied. */ +static void on_handshaker_service_resp_recv(void* arg, grpc_error* error) { + alts_handshaker_client* client = static_cast<alts_handshaker_client*>(arg); + if (client == nullptr) { + gpr_log(GPR_ERROR, "ALTS handshaker client is nullptr"); + return; + } bool success = true; if (error != GRPC_ERROR_NONE) { gpr_log(GPR_ERROR, @@ -386,49 +386,49 @@ static void on_handshaker_service_resp_recv(void* arg, grpc_error* error) { success = false; } alts_handshaker_client_handle_response(client, success); -} - -/* gRPC provided callback used when dedicatd CQ and thread are used. - * It serves to safely bring the control back to application. */ -static void on_handshaker_service_resp_recv_dedicated(void* arg, +} + +/* gRPC provided callback used when dedicatd CQ and thread are used. + * It serves to safely bring the control back to application. */ +static void on_handshaker_service_resp_recv_dedicated(void* arg, grpc_error* /*error*/) { - alts_shared_resource_dedicated* resource = - grpc_alts_get_shared_resource_dedicated(); - grpc_cq_end_op(resource->cq, arg, GRPC_ERROR_NONE, + alts_shared_resource_dedicated* resource = + grpc_alts_get_shared_resource_dedicated(); + grpc_cq_end_op(resource->cq, arg, GRPC_ERROR_NONE, [](void* /*done_arg*/, grpc_cq_completion* /*storage*/) {}, nullptr, &resource->storage); -} - +} + /* Returns TSI_OK if and only if no error is encountered. */ static tsi_result alts_tsi_handshaker_continue_handshaker_next( alts_tsi_handshaker* handshaker, const unsigned char* received_bytes, size_t received_bytes_size, tsi_handshaker_on_next_done_cb cb, void* user_data) { - if (!handshaker->has_created_handshaker_client) { - if (handshaker->channel == nullptr) { - grpc_alts_shared_resource_dedicated_start( - handshaker->handshaker_service_url); - handshaker->interested_parties = - grpc_alts_get_shared_resource_dedicated()->interested_parties; - GPR_ASSERT(handshaker->interested_parties != nullptr); - } - grpc_iomgr_cb_func grpc_cb = handshaker->channel == nullptr - ? on_handshaker_service_resp_recv_dedicated - : on_handshaker_service_resp_recv; - grpc_channel* channel = - handshaker->channel == nullptr - ? grpc_alts_get_shared_resource_dedicated()->channel - : handshaker->channel; + if (!handshaker->has_created_handshaker_client) { + if (handshaker->channel == nullptr) { + grpc_alts_shared_resource_dedicated_start( + handshaker->handshaker_service_url); + handshaker->interested_parties = + grpc_alts_get_shared_resource_dedicated()->interested_parties; + GPR_ASSERT(handshaker->interested_parties != nullptr); + } + grpc_iomgr_cb_func grpc_cb = handshaker->channel == nullptr + ? on_handshaker_service_resp_recv_dedicated + : on_handshaker_service_resp_recv; + grpc_channel* channel = + handshaker->channel == nullptr + ? grpc_alts_get_shared_resource_dedicated()->channel + : handshaker->channel; alts_handshaker_client* client = alts_grpc_handshaker_client_create( - handshaker, channel, handshaker->handshaker_service_url, - handshaker->interested_parties, handshaker->options, - handshaker->target_name, grpc_cb, cb, user_data, + handshaker, channel, handshaker->handshaker_service_url, + handshaker->interested_parties, handshaker->options, + handshaker->target_name, grpc_cb, cb, user_data, handshaker->client_vtable_for_testing, handshaker->is_client, handshaker->max_frame_size); if (client == nullptr) { - gpr_log(GPR_ERROR, "Failed to create ALTS handshaker client"); - return TSI_FAILED_PRECONDITION; - } + gpr_log(GPR_ERROR, "Failed to create ALTS handshaker client"); + return TSI_FAILED_PRECONDITION; + } { grpc_core::MutexLock lock(&handshaker->mu); GPR_ASSERT(handshaker->client == nullptr); @@ -438,13 +438,13 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next( return TSI_HANDSHAKE_SHUTDOWN; } } - handshaker->has_created_handshaker_client = true; - } - if (handshaker->channel == nullptr && - handshaker->client_vtable_for_testing == nullptr) { - GPR_ASSERT(grpc_cq_begin_op(grpc_alts_get_shared_resource_dedicated()->cq, - handshaker->client)); + handshaker->has_created_handshaker_client = true; } + if (handshaker->channel == nullptr && + handshaker->client_vtable_for_testing == nullptr) { + GPR_ASSERT(grpc_cq_begin_op(grpc_alts_get_shared_resource_dedicated()->cq, + handshaker->client)); + } grpc_slice slice = (received_bytes == nullptr || received_bytes_size == 0) ? grpc_empty_slice() : grpc_slice_from_copied_buffer( @@ -454,8 +454,8 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next( if (!handshaker->has_sent_start_message) { handshaker->has_sent_start_message = true; ok = handshaker->is_client - ? alts_handshaker_client_start_client(handshaker->client) - : alts_handshaker_client_start_server(handshaker->client, &slice); + ? alts_handshaker_client_start_client(handshaker->client) + : alts_handshaker_client_start_server(handshaker->client, &slice); // It's unsafe for the current thread to access any state in handshaker // at this point, since alts_handshaker_client_start_client/server // have potentially just started an op batch on the handshake call. @@ -464,9 +464,9 @@ static tsi_result alts_tsi_handshaker_continue_handshaker_next( // there is nothing taking ownership of this handshaker to prevent it // from being destroyed. } else { - ok = alts_handshaker_client_next(handshaker->client, &slice); + ok = alts_handshaker_client_next(handshaker->client, &slice); } - grpc_slice_unref_internal(slice); + grpc_slice_unref_internal(slice); return ok; } @@ -548,36 +548,36 @@ static tsi_result handshaker_next( return TSI_ASYNC; } -/* - * This API will be invoked by a non-gRPC application, and an ExecCtx needs - * to be explicitly created in order to invoke ALTS handshaker client API's - * that assumes the caller is inside gRPC core. - */ -static tsi_result handshaker_next_dedicated( - tsi_handshaker* self, const unsigned char* received_bytes, - size_t received_bytes_size, const unsigned char** bytes_to_send, - size_t* bytes_to_send_size, tsi_handshaker_result** result, - tsi_handshaker_on_next_done_cb cb, void* user_data) { - grpc_core::ExecCtx exec_ctx; - return handshaker_next(self, received_bytes, received_bytes_size, - bytes_to_send, bytes_to_send_size, result, cb, - user_data); -} - -static void handshaker_shutdown(tsi_handshaker* self) { - GPR_ASSERT(self != nullptr); +/* + * This API will be invoked by a non-gRPC application, and an ExecCtx needs + * to be explicitly created in order to invoke ALTS handshaker client API's + * that assumes the caller is inside gRPC core. + */ +static tsi_result handshaker_next_dedicated( + tsi_handshaker* self, const unsigned char* received_bytes, + size_t received_bytes_size, const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, tsi_handshaker_result** result, + tsi_handshaker_on_next_done_cb cb, void* user_data) { + grpc_core::ExecCtx exec_ctx; + return handshaker_next(self, received_bytes, received_bytes_size, + bytes_to_send, bytes_to_send_size, result, cb, + user_data); +} + +static void handshaker_shutdown(tsi_handshaker* self) { + GPR_ASSERT(self != nullptr); alts_tsi_handshaker* handshaker = reinterpret_cast<alts_tsi_handshaker*>(self); grpc_core::MutexLock lock(&handshaker->mu); if (handshaker->shutdown) { - return; - } + return; + } if (handshaker->client != nullptr) { alts_handshaker_client_shutdown(handshaker->client); } handshaker->shutdown = true; -} - +} + static void handshaker_destroy(tsi_handshaker* self) { if (self == nullptr) { return; @@ -585,41 +585,41 @@ static void handshaker_destroy(tsi_handshaker* self) { alts_tsi_handshaker* handshaker = reinterpret_cast<alts_tsi_handshaker*>(self); alts_handshaker_client_destroy(handshaker->client); - grpc_slice_unref_internal(handshaker->target_name); + grpc_slice_unref_internal(handshaker->target_name); grpc_alts_credentials_options_destroy(handshaker->options); - if (handshaker->channel != nullptr) { + if (handshaker->channel != nullptr) { grpc_channel_destroy_internal(handshaker->channel); - } - gpr_free(handshaker->handshaker_service_url); + } + gpr_free(handshaker->handshaker_service_url); gpr_mu_destroy(&handshaker->mu); gpr_free(handshaker); } static const tsi_handshaker_vtable handshaker_vtable = { - nullptr, nullptr, - nullptr, nullptr, - nullptr, handshaker_destroy, - handshaker_next, handshaker_shutdown}; - -static const tsi_handshaker_vtable handshaker_vtable_dedicated = { - nullptr, - nullptr, - nullptr, - nullptr, - nullptr, - handshaker_destroy, - handshaker_next_dedicated, - handshaker_shutdown}; - -bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker) { - GPR_ASSERT(handshaker != nullptr); + nullptr, nullptr, + nullptr, nullptr, + nullptr, handshaker_destroy, + handshaker_next, handshaker_shutdown}; + +static const tsi_handshaker_vtable handshaker_vtable_dedicated = { + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + handshaker_destroy, + handshaker_next_dedicated, + handshaker_shutdown}; + +bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker) { + GPR_ASSERT(handshaker != nullptr); grpc_core::MutexLock lock(&handshaker->mu); return handshaker->shutdown; } tsi_result alts_tsi_handshaker_create( const grpc_alts_credentials_options* options, const char* target_name, - const char* handshaker_service_url, bool is_client, + const char* handshaker_service_url, bool is_client, grpc_pollset_set* interested_parties, tsi_handshaker** self, size_t user_specified_max_frame_size) { if (handshaker_service_url == nullptr || self == nullptr || @@ -631,15 +631,15 @@ tsi_result alts_tsi_handshaker_create( static_cast<alts_tsi_handshaker*>(gpr_zalloc(sizeof(*handshaker))); gpr_mu_init(&handshaker->mu); handshaker->use_dedicated_cq = interested_parties == nullptr; - handshaker->client = nullptr; + handshaker->client = nullptr; handshaker->is_client = is_client; handshaker->has_sent_start_message = false; handshaker->target_name = target_name == nullptr ? grpc_empty_slice() : grpc_slice_from_static_string(target_name); - handshaker->interested_parties = interested_parties; - handshaker->has_created_handshaker_client = false; - handshaker->handshaker_service_url = gpr_strdup(handshaker_service_url); + handshaker->interested_parties = interested_parties; + handshaker->has_created_handshaker_client = false; + handshaker->handshaker_service_url = gpr_strdup(handshaker_service_url); handshaker->options = grpc_alts_credentials_options_copy(options); handshaker->max_frame_size = user_specified_max_frame_size != 0 ? user_specified_max_frame_size @@ -651,9 +651,9 @@ tsi_result alts_tsi_handshaker_create( return TSI_OK; } -void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* self, - grpc_slice* recv_bytes, - size_t bytes_consumed) { +void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* self, + grpc_slice* recv_bytes, + size_t bytes_consumed) { GPR_ASSERT(recv_bytes != nullptr && self != nullptr); if (GRPC_SLICE_LENGTH(*recv_bytes) == bytes_consumed) { return; @@ -677,21 +677,21 @@ bool alts_tsi_handshaker_get_has_sent_start_message_for_testing( return handshaker->has_sent_start_message; } -void alts_tsi_handshaker_set_client_vtable_for_testing( - alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable) { - GPR_ASSERT(handshaker != nullptr); - handshaker->client_vtable_for_testing = vtable; -} - +void alts_tsi_handshaker_set_client_vtable_for_testing( + alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable) { + GPR_ASSERT(handshaker != nullptr); + handshaker->client_vtable_for_testing = vtable; +} + bool alts_tsi_handshaker_get_is_client_for_testing( alts_tsi_handshaker* handshaker) { GPR_ASSERT(handshaker != nullptr); return handshaker->is_client; } -alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing( +alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing( alts_tsi_handshaker* handshaker) { - return handshaker->client; + return handshaker->client; } } // namespace internal diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h index e1ae985a84..8be2972089 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker.h @@ -23,9 +23,9 @@ #include <grpc/grpc.h> -#include "src/core/lib/iomgr/pollset_set.h" +#include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/security/credentials/alts/grpc_alts_credentials_options.h" -#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h" +#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h" #include "src/core/tsi/transport_security.h" #include "src/core/tsi/transport_security_interface.h" #include "src/proto/grpc/gcp/altscontext.upb.h" @@ -56,49 +56,49 @@ typedef struct alts_tsi_handshaker alts_tsi_handshaker; * "host:port". * - is_client: boolean value indicating if the handshaker is used at the client * (is_client = true) or server (is_client = false) side. - * - interested_parties: set of pollsets interested in this connection. + * - interested_parties: set of pollsets interested in this connection. * - self: address of ALTS TSI handshaker instance to be returned from the * method. * - user_specified_max_frame_size: Determines the maximum frame size used by * frame protector that is specified via user. If unspecified, the value is 0. * - * It returns TSI_OK on success and an error status code on failure. Note that - * if interested_parties is nullptr, a dedicated TSI thread will be created and - * used. + * It returns TSI_OK on success and an error status code on failure. Note that + * if interested_parties is nullptr, a dedicated TSI thread will be created and + * used. */ tsi_result alts_tsi_handshaker_create( const grpc_alts_credentials_options* options, const char* target_name, - const char* handshaker_service_url, bool is_client, + const char* handshaker_service_url, bool is_client, grpc_pollset_set* interested_parties, tsi_handshaker** self, size_t user_specified_max_frame_size); /** - * This method creates an ALTS TSI handshaker result instance. + * This method creates an ALTS TSI handshaker result instance. * - * - resp: data received from the handshaker service. - * - is_client: a boolean value indicating if the result belongs to a - * client or not. - * - result: address of ALTS TSI handshaker result instance. - */ + * - resp: data received from the handshaker service. + * - is_client: a boolean value indicating if the result belongs to a + * client or not. + * - result: address of ALTS TSI handshaker result instance. + */ tsi_result alts_tsi_handshaker_result_create(grpc_gcp_HandshakerResp* resp, - bool is_client, - tsi_handshaker_result** result); - -/** - * This method sets unused bytes of ALTS TSI handshaker result instance. + bool is_client, + tsi_handshaker_result** result); + +/** + * This method sets unused bytes of ALTS TSI handshaker result instance. * - * - result: an ALTS TSI handshaker result instance. - * - recv_bytes: data received from the handshaker service. - * - bytes_consumed: size of data consumed by the handshaker service. - */ -void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* result, - grpc_slice* recv_bytes, - size_t bytes_consumed); - -/** - * This method returns a boolean value indicating if an ALTS TSI handshaker - * has been shutdown or not. + * - result: an ALTS TSI handshaker result instance. + * - recv_bytes: data received from the handshaker service. + * - bytes_consumed: size of data consumed by the handshaker service. */ -bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker); +void alts_tsi_handshaker_result_set_unused_bytes(tsi_handshaker_result* result, + grpc_slice* recv_bytes, + size_t bytes_consumed); +/** + * This method returns a boolean value indicating if an ALTS TSI handshaker + * has been shutdown or not. + */ +bool alts_tsi_handshaker_has_shutdown(alts_tsi_handshaker* handshaker); + #endif /* GRPC_CORE_TSI_ALTS_HANDSHAKER_ALTS_TSI_HANDSHAKER_H */ diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h index cb99fdcce0..e3f1a35157 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_handshaker_private.h @@ -27,56 +27,56 @@ namespace grpc_core { namespace internal { /** - * Unsafe, use for testing only. */ - -alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing( - alts_tsi_handshaker* handshaker); + * Unsafe, use for testing only. */ +alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing( + alts_tsi_handshaker* handshaker); + bool alts_tsi_handshaker_get_has_sent_start_message_for_testing( alts_tsi_handshaker* handshaker); -void alts_tsi_handshaker_set_client_vtable_for_testing( - alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable); - +void alts_tsi_handshaker_set_client_vtable_for_testing( + alts_tsi_handshaker* handshaker, alts_handshaker_client_vtable* vtable); + bool alts_tsi_handshaker_get_is_client_for_testing( alts_tsi_handshaker* handshaker); -void alts_handshaker_client_set_grpc_caller_for_testing( - alts_handshaker_client* client, alts_grpc_caller caller); - -grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing( - alts_handshaker_client* client); - -grpc_byte_buffer** alts_handshaker_client_get_recv_buffer_addr_for_testing( - alts_handshaker_client* client); - -grpc_metadata_array* alts_handshaker_client_get_initial_metadata_for_testing( - alts_handshaker_client* client); - -void alts_handshaker_client_set_recv_bytes_for_testing( - alts_handshaker_client* client, grpc_slice* recv_bytes); - -void alts_handshaker_client_check_fields_for_testing( - alts_handshaker_client* client, tsi_handshaker_on_next_done_cb cb, - void* user_data, bool has_sent_start_message, grpc_slice* recv_bytes); - -void alts_handshaker_client_set_fields_for_testing( - alts_handshaker_client* client, alts_tsi_handshaker* handshaker, - tsi_handshaker_on_next_done_cb cb, void* user_data, - grpc_byte_buffer* recv_buffer, grpc_status_code status); - -void alts_handshaker_client_set_vtable_for_testing( - alts_handshaker_client* client, alts_handshaker_client_vtable* vtable); - -alts_tsi_handshaker* alts_handshaker_client_get_handshaker_for_testing( - alts_handshaker_client* client); - -void alts_handshaker_client_set_cb_for_testing( - alts_handshaker_client* client, tsi_handshaker_on_next_done_cb cb); - -grpc_closure* alts_handshaker_client_get_closure_for_testing( - alts_handshaker_client* client); - +void alts_handshaker_client_set_grpc_caller_for_testing( + alts_handshaker_client* client, alts_grpc_caller caller); + +grpc_byte_buffer* alts_handshaker_client_get_send_buffer_for_testing( + alts_handshaker_client* client); + +grpc_byte_buffer** alts_handshaker_client_get_recv_buffer_addr_for_testing( + alts_handshaker_client* client); + +grpc_metadata_array* alts_handshaker_client_get_initial_metadata_for_testing( + alts_handshaker_client* client); + +void alts_handshaker_client_set_recv_bytes_for_testing( + alts_handshaker_client* client, grpc_slice* recv_bytes); + +void alts_handshaker_client_check_fields_for_testing( + alts_handshaker_client* client, tsi_handshaker_on_next_done_cb cb, + void* user_data, bool has_sent_start_message, grpc_slice* recv_bytes); + +void alts_handshaker_client_set_fields_for_testing( + alts_handshaker_client* client, alts_tsi_handshaker* handshaker, + tsi_handshaker_on_next_done_cb cb, void* user_data, + grpc_byte_buffer* recv_buffer, grpc_status_code status); + +void alts_handshaker_client_set_vtable_for_testing( + alts_handshaker_client* client, alts_handshaker_client_vtable* vtable); + +alts_tsi_handshaker* alts_handshaker_client_get_handshaker_for_testing( + alts_handshaker_client* client); + +void alts_handshaker_client_set_cb_for_testing( + alts_handshaker_client* client, tsi_handshaker_on_next_done_cb cb); + +grpc_closure* alts_handshaker_client_get_closure_for_testing( + alts_handshaker_client* client); + void alts_handshaker_client_on_status_received_for_testing( alts_handshaker_client* client, grpc_status_code status, grpc_error* error); diff --git a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc index f80498db99..bd72619771 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc +++ b/contrib/libs/grpc/src/core/tsi/alts/handshaker/alts_tsi_utils.cc @@ -22,8 +22,8 @@ #include <grpc/byte_buffer_reader.h> -#include "src/core/lib/slice/slice_internal.h" - +#include "src/core/lib/slice/slice_internal.h" + tsi_result alts_tsi_utils_convert_to_tsi_result(grpc_status_code code) { switch (code) { case GRPC_STATUS_OK: @@ -54,7 +54,7 @@ grpc_gcp_HandshakerResp* alts_tsi_utils_deserialize_response( buf_size); grpc_gcp_HandshakerResp* resp = grpc_gcp_HandshakerResp_parse( reinterpret_cast<char*>(buf), buf_size, arena); - grpc_slice_unref_internal(slice); + grpc_slice_unref_internal(slice); grpc_byte_buffer_reader_destroy(&bbr); if (resp == nullptr) { gpr_log(GPR_ERROR, "grpc_gcp_handshaker_resp_decode() failed"); diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h index 5456d34fad..07c83cd28e 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h +++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.h @@ -38,8 +38,8 @@ * be used at the client or server side. * - is_protect: a flag indicating if the alts_grpc_record_protocol instance * will be used for protect or unprotect. - *- enable_extra_copy: a flag indicating if the instance uses one-copy instead - * of zero-copy in the protect operation. + *- enable_extra_copy: a flag indicating if the instance uses one-copy instead + * of zero-copy in the protect operation. * - rp: an alts_grpc_record_protocol instance to be returned from * the method. * @@ -48,7 +48,7 @@ */ tsi_result alts_grpc_integrity_only_record_protocol_create( gsec_aead_crypter* crypter, size_t overflow_size, bool is_client, - bool is_protect, bool enable_extra_copy, alts_grpc_record_protocol** rp); + bool is_protect, bool enable_extra_copy, alts_grpc_record_protocol** rp); #endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_GRPC_INTEGRITY_ONLY_RECORD_PROTOCOL_H \ */ diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc index 0cdf97465d..e0a6350059 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc +++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc @@ -110,7 +110,7 @@ static bool read_frame_size(const grpc_slice_buffer* sb, */ static tsi_result create_alts_grpc_record_protocol( const uint8_t* key, size_t key_size, bool is_rekey, bool is_client, - bool is_integrity_only, bool is_protect, bool enable_extra_copy, + bool is_integrity_only, bool is_protect, bool enable_extra_copy, alts_grpc_record_protocol** record_protocol) { if (key == nullptr || record_protocol == nullptr) { return TSI_INVALID_ARGUMENT; @@ -130,13 +130,13 @@ static tsi_result create_alts_grpc_record_protocol( : kAltsRecordProtocolFrameLimit; /* Creates alts_grpc_record_protocol with AEAD crypter ownership transferred. */ - tsi_result result = is_integrity_only - ? alts_grpc_integrity_only_record_protocol_create( - crypter, overflow_limit, is_client, is_protect, - enable_extra_copy, record_protocol) - : alts_grpc_privacy_integrity_record_protocol_create( - crypter, overflow_limit, is_client, is_protect, - record_protocol); + tsi_result result = is_integrity_only + ? alts_grpc_integrity_only_record_protocol_create( + crypter, overflow_limit, is_client, is_protect, + enable_extra_copy, record_protocol) + : alts_grpc_privacy_integrity_record_protocol_create( + crypter, overflow_limit, is_client, is_protect, + record_protocol); if (result != TSI_OK) { gsec_aead_crypter_destroy(crypter); return result; @@ -251,8 +251,8 @@ static const tsi_zero_copy_grpc_protector_vtable tsi_result alts_zero_copy_grpc_protector_create( const uint8_t* key, size_t key_size, bool is_rekey, bool is_client, - bool is_integrity_only, bool enable_extra_copy, - size_t* max_protected_frame_size, + bool is_integrity_only, bool enable_extra_copy, + size_t* max_protected_frame_size, tsi_zero_copy_grpc_protector** protector) { if (grpc_core::ExecCtx::Get() == nullptr || key == nullptr || protector == nullptr) { @@ -268,11 +268,11 @@ tsi_result alts_zero_copy_grpc_protector_create( /* Creates alts_grpc_record_protocol objects. */ tsi_result status = create_alts_grpc_record_protocol( key, key_size, is_rekey, is_client, is_integrity_only, - /*is_protect=*/true, enable_extra_copy, &impl->record_protocol); + /*is_protect=*/true, enable_extra_copy, &impl->record_protocol); if (status == TSI_OK) { status = create_alts_grpc_record_protocol( key, key_size, is_rekey, is_client, is_integrity_only, - /*is_protect=*/false, enable_extra_copy, &impl->unrecord_protocol); + /*is_protect=*/false, enable_extra_copy, &impl->unrecord_protocol); if (status == TSI_OK) { /* Sets maximum frame size. */ size_t max_protected_frame_size_to_set = kDefaultFrameLength; diff --git a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h index 515c27ea05..4c3fcd326f 100644 --- a/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h +++ b/contrib/libs/grpc/src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h @@ -35,11 +35,11 @@ * server side. * - is_integrity_only: a flag indicating if the protector instance will be * used for integrity-only or privacy-integrity mode. - * - enable_extra_copy: a flag indicating if the protector instance does one - * extra memory copy during the protect operation for integrity_only mode. - * For the unprotect operation, it is still zero-copy. If application intends - * to modify the data buffer after the protect operation, we can turn on this - * mode to avoid integrity check failure. + * - enable_extra_copy: a flag indicating if the protector instance does one + * extra memory copy during the protect operation for integrity_only mode. + * For the unprotect operation, it is still zero-copy. If application intends + * to modify the data buffer after the protect operation, we can turn on this + * mode to avoid integrity check failure. * - max_protected_frame_size: an in/out parameter indicating max frame size * to be used by the protector. If it is nullptr, the default frame size will * be used. Otherwise, the provided frame size will be adjusted (if not @@ -50,8 +50,8 @@ */ tsi_result alts_zero_copy_grpc_protector_create( const uint8_t* key, size_t key_size, bool is_rekey, bool is_client, - bool is_integrity_only, bool enable_extra_copy, - size_t* max_protected_frame_size, tsi_zero_copy_grpc_protector** protector); + bool is_integrity_only, bool enable_extra_copy, + size_t* max_protected_frame_size, tsi_zero_copy_grpc_protector** protector); #endif /* GRPC_CORE_TSI_ALTS_ZERO_COPY_FRAME_PROTECTOR_ALTS_ZERO_COPY_GRPC_PROTECTOR_H \ */ diff --git a/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc b/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc index 1b6b8ca07b..b877cc2eba 100644 --- a/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc +++ b/contrib/libs/grpc/src/core/tsi/fake_transport_security.cc @@ -739,7 +739,7 @@ static const tsi_handshaker_vtable handshaker_vtable = { nullptr, /* create_frame_protector -- deprecated */ fake_handshaker_destroy, fake_handshaker_next, - nullptr, /* shutdown */ + nullptr, /* shutdown */ }; tsi_handshaker* tsi_create_fake_handshaker(int is_client) { diff --git a/contrib/libs/grpc/src/core/tsi/local_transport_security.cc b/contrib/libs/grpc/src/core/tsi/local_transport_security.cc index f7e004f4a7..96c291192c 100644 --- a/contrib/libs/grpc/src/core/tsi/local_transport_security.cc +++ b/contrib/libs/grpc/src/core/tsi/local_transport_security.cc @@ -1,211 +1,211 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/core/tsi/local_transport_security.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -#include "src/core/lib/iomgr/exec_ctx.h" -#include "src/core/tsi/transport_security_grpc.h" - -/* Main struct for local TSI zero-copy frame protector. */ -typedef struct local_zero_copy_grpc_protector { - tsi_zero_copy_grpc_protector base; -} local_zero_copy_grpc_protector; - -/* Main struct for local TSI handshaker result. */ -typedef struct local_tsi_handshaker_result { - tsi_handshaker_result base; - bool is_client; -} local_tsi_handshaker_result; - -/* Main struct for local TSI handshaker. */ -typedef struct local_tsi_handshaker { - tsi_handshaker base; - bool is_client; -} local_tsi_handshaker; - -/* --- tsi_zero_copy_grpc_protector methods implementation. --- */ - -static tsi_result local_zero_copy_grpc_protector_protect( - tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices, - grpc_slice_buffer* protected_slices) { - if (self == nullptr || unprotected_slices == nullptr || - protected_slices == nullptr) { - gpr_log(GPR_ERROR, "Invalid nullptr arguments to zero-copy grpc protect."); - return TSI_INVALID_ARGUMENT; - } - grpc_slice_buffer_move_into(unprotected_slices, protected_slices); - return TSI_OK; -} - -static tsi_result local_zero_copy_grpc_protector_unprotect( - tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices, - grpc_slice_buffer* unprotected_slices) { - if (self == nullptr || unprotected_slices == nullptr || - protected_slices == nullptr) { - gpr_log(GPR_ERROR, - "Invalid nullptr arguments to zero-copy grpc unprotect."); - return TSI_INVALID_ARGUMENT; - } - grpc_slice_buffer_move_into(protected_slices, unprotected_slices); - return TSI_OK; -} - -static void local_zero_copy_grpc_protector_destroy( - tsi_zero_copy_grpc_protector* self) { - gpr_free(self); -} - -static const tsi_zero_copy_grpc_protector_vtable - local_zero_copy_grpc_protector_vtable = { - local_zero_copy_grpc_protector_protect, - local_zero_copy_grpc_protector_unprotect, +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/core/tsi/local_transport_security.h" + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/tsi/transport_security_grpc.h" + +/* Main struct for local TSI zero-copy frame protector. */ +typedef struct local_zero_copy_grpc_protector { + tsi_zero_copy_grpc_protector base; +} local_zero_copy_grpc_protector; + +/* Main struct for local TSI handshaker result. */ +typedef struct local_tsi_handshaker_result { + tsi_handshaker_result base; + bool is_client; +} local_tsi_handshaker_result; + +/* Main struct for local TSI handshaker. */ +typedef struct local_tsi_handshaker { + tsi_handshaker base; + bool is_client; +} local_tsi_handshaker; + +/* --- tsi_zero_copy_grpc_protector methods implementation. --- */ + +static tsi_result local_zero_copy_grpc_protector_protect( + tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* unprotected_slices, + grpc_slice_buffer* protected_slices) { + if (self == nullptr || unprotected_slices == nullptr || + protected_slices == nullptr) { + gpr_log(GPR_ERROR, "Invalid nullptr arguments to zero-copy grpc protect."); + return TSI_INVALID_ARGUMENT; + } + grpc_slice_buffer_move_into(unprotected_slices, protected_slices); + return TSI_OK; +} + +static tsi_result local_zero_copy_grpc_protector_unprotect( + tsi_zero_copy_grpc_protector* self, grpc_slice_buffer* protected_slices, + grpc_slice_buffer* unprotected_slices) { + if (self == nullptr || unprotected_slices == nullptr || + protected_slices == nullptr) { + gpr_log(GPR_ERROR, + "Invalid nullptr arguments to zero-copy grpc unprotect."); + return TSI_INVALID_ARGUMENT; + } + grpc_slice_buffer_move_into(protected_slices, unprotected_slices); + return TSI_OK; +} + +static void local_zero_copy_grpc_protector_destroy( + tsi_zero_copy_grpc_protector* self) { + gpr_free(self); +} + +static const tsi_zero_copy_grpc_protector_vtable + local_zero_copy_grpc_protector_vtable = { + local_zero_copy_grpc_protector_protect, + local_zero_copy_grpc_protector_unprotect, local_zero_copy_grpc_protector_destroy, nullptr /* local_zero_copy_grpc_protector_max_frame_size */}; - -tsi_result local_zero_copy_grpc_protector_create( - tsi_zero_copy_grpc_protector** protector) { - if (grpc_core::ExecCtx::Get() == nullptr || protector == nullptr) { - gpr_log( - GPR_ERROR, - "Invalid nullptr arguments to local_zero_copy_grpc_protector create."); - return TSI_INVALID_ARGUMENT; - } - local_zero_copy_grpc_protector* impl = - static_cast<local_zero_copy_grpc_protector*>(gpr_zalloc(sizeof(*impl))); - impl->base.vtable = &local_zero_copy_grpc_protector_vtable; - *protector = &impl->base; - return TSI_OK; -} - -/* --- tsi_handshaker_result methods implementation. --- */ - -static tsi_result handshaker_result_extract_peer( + +tsi_result local_zero_copy_grpc_protector_create( + tsi_zero_copy_grpc_protector** protector) { + if (grpc_core::ExecCtx::Get() == nullptr || protector == nullptr) { + gpr_log( + GPR_ERROR, + "Invalid nullptr arguments to local_zero_copy_grpc_protector create."); + return TSI_INVALID_ARGUMENT; + } + local_zero_copy_grpc_protector* impl = + static_cast<local_zero_copy_grpc_protector*>(gpr_zalloc(sizeof(*impl))); + impl->base.vtable = &local_zero_copy_grpc_protector_vtable; + *protector = &impl->base; + return TSI_OK; +} + +/* --- tsi_handshaker_result methods implementation. --- */ + +static tsi_result handshaker_result_extract_peer( const tsi_handshaker_result* /*self*/, tsi_peer* /*peer*/) { - return TSI_OK; -} - -static tsi_result handshaker_result_create_zero_copy_grpc_protector( + return TSI_OK; +} + +static tsi_result handshaker_result_create_zero_copy_grpc_protector( const tsi_handshaker_result* self, size_t* /*max_output_protected_frame_size*/, - tsi_zero_copy_grpc_protector** protector) { - if (self == nullptr || protector == nullptr) { - gpr_log(GPR_ERROR, - "Invalid arguments to create_zero_copy_grpc_protector()"); - return TSI_INVALID_ARGUMENT; - } - tsi_result ok = local_zero_copy_grpc_protector_create(protector); - if (ok != TSI_OK) { - gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector"); - } - return ok; -} - -static void handshaker_result_destroy(tsi_handshaker_result* self) { - if (self == nullptr) { - return; - } - local_tsi_handshaker_result* result = - reinterpret_cast<local_tsi_handshaker_result*>( - const_cast<tsi_handshaker_result*>(self)); - gpr_free(result); -} - -static const tsi_handshaker_result_vtable result_vtable = { - handshaker_result_extract_peer, - handshaker_result_create_zero_copy_grpc_protector, - nullptr, /* handshaker_result_create_frame_protector */ - nullptr, /* handshaker_result_get_unused_bytes */ - handshaker_result_destroy}; - -static tsi_result create_handshaker_result(bool is_client, - tsi_handshaker_result** self) { - if (self == nullptr) { - gpr_log(GPR_ERROR, "Invalid arguments to create_handshaker_result()"); - return TSI_INVALID_ARGUMENT; - } - local_tsi_handshaker_result* result = - static_cast<local_tsi_handshaker_result*>(gpr_zalloc(sizeof(*result))); - result->is_client = is_client; - result->base.vtable = &result_vtable; - *self = &result->base; - return TSI_OK; -} - -/* --- tsi_handshaker methods implementation. --- */ - -static tsi_result handshaker_next( + tsi_zero_copy_grpc_protector** protector) { + if (self == nullptr || protector == nullptr) { + gpr_log(GPR_ERROR, + "Invalid arguments to create_zero_copy_grpc_protector()"); + return TSI_INVALID_ARGUMENT; + } + tsi_result ok = local_zero_copy_grpc_protector_create(protector); + if (ok != TSI_OK) { + gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector"); + } + return ok; +} + +static void handshaker_result_destroy(tsi_handshaker_result* self) { + if (self == nullptr) { + return; + } + local_tsi_handshaker_result* result = + reinterpret_cast<local_tsi_handshaker_result*>( + const_cast<tsi_handshaker_result*>(self)); + gpr_free(result); +} + +static const tsi_handshaker_result_vtable result_vtable = { + handshaker_result_extract_peer, + handshaker_result_create_zero_copy_grpc_protector, + nullptr, /* handshaker_result_create_frame_protector */ + nullptr, /* handshaker_result_get_unused_bytes */ + handshaker_result_destroy}; + +static tsi_result create_handshaker_result(bool is_client, + tsi_handshaker_result** self) { + if (self == nullptr) { + gpr_log(GPR_ERROR, "Invalid arguments to create_handshaker_result()"); + return TSI_INVALID_ARGUMENT; + } + local_tsi_handshaker_result* result = + static_cast<local_tsi_handshaker_result*>(gpr_zalloc(sizeof(*result))); + result->is_client = is_client; + result->base.vtable = &result_vtable; + *self = &result->base; + return TSI_OK; +} + +/* --- tsi_handshaker methods implementation. --- */ + +static tsi_result handshaker_next( tsi_handshaker* self, const unsigned char* /*received_bytes*/, size_t /*received_bytes_size*/, const unsigned char** /*bytes_to_send*/, - size_t* bytes_to_send_size, tsi_handshaker_result** result, + size_t* bytes_to_send_size, tsi_handshaker_result** result, tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) { - if (self == nullptr) { - gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()"); - return TSI_INVALID_ARGUMENT; - } - /* Note that there is no interaction between TSI peers, and all operations are - * local. - */ - local_tsi_handshaker* handshaker = - reinterpret_cast<local_tsi_handshaker*>(self); - *bytes_to_send_size = 0; - create_handshaker_result(handshaker->is_client, result); - return TSI_OK; -} - -static void handshaker_destroy(tsi_handshaker* self) { - if (self == nullptr) { - return; - } - local_tsi_handshaker* handshaker = - reinterpret_cast<local_tsi_handshaker*>(self); - gpr_free(handshaker); -} - -static const tsi_handshaker_vtable handshaker_vtable = { - nullptr, /* get_bytes_to_send_to_peer -- deprecated */ - nullptr, /* process_bytes_from_peer -- deprecated */ - nullptr, /* get_result -- deprecated */ - nullptr, /* extract_peer -- deprecated */ - nullptr, /* create_frame_protector -- deprecated */ - handshaker_destroy, - handshaker_next, - nullptr, /* shutdown */ -}; - -tsi_result local_tsi_handshaker_create(bool is_client, tsi_handshaker** self) { - if (self == nullptr) { - gpr_log(GPR_ERROR, "Invalid arguments to local_tsi_handshaker_create()"); - return TSI_INVALID_ARGUMENT; - } - local_tsi_handshaker* handshaker = - static_cast<local_tsi_handshaker*>(gpr_zalloc(sizeof(*handshaker))); - handshaker->is_client = is_client; - handshaker->base.vtable = &handshaker_vtable; - *self = &handshaker->base; - return TSI_OK; -} + if (self == nullptr) { + gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()"); + return TSI_INVALID_ARGUMENT; + } + /* Note that there is no interaction between TSI peers, and all operations are + * local. + */ + local_tsi_handshaker* handshaker = + reinterpret_cast<local_tsi_handshaker*>(self); + *bytes_to_send_size = 0; + create_handshaker_result(handshaker->is_client, result); + return TSI_OK; +} + +static void handshaker_destroy(tsi_handshaker* self) { + if (self == nullptr) { + return; + } + local_tsi_handshaker* handshaker = + reinterpret_cast<local_tsi_handshaker*>(self); + gpr_free(handshaker); +} + +static const tsi_handshaker_vtable handshaker_vtable = { + nullptr, /* get_bytes_to_send_to_peer -- deprecated */ + nullptr, /* process_bytes_from_peer -- deprecated */ + nullptr, /* get_result -- deprecated */ + nullptr, /* extract_peer -- deprecated */ + nullptr, /* create_frame_protector -- deprecated */ + handshaker_destroy, + handshaker_next, + nullptr, /* shutdown */ +}; + +tsi_result local_tsi_handshaker_create(bool is_client, tsi_handshaker** self) { + if (self == nullptr) { + gpr_log(GPR_ERROR, "Invalid arguments to local_tsi_handshaker_create()"); + return TSI_INVALID_ARGUMENT; + } + local_tsi_handshaker* handshaker = + static_cast<local_tsi_handshaker*>(gpr_zalloc(sizeof(*handshaker))); + handshaker->is_client = is_client; + handshaker->base.vtable = &handshaker_vtable; + *self = &handshaker->base; + return TSI_OK; +} diff --git a/contrib/libs/grpc/src/core/tsi/local_transport_security.h b/contrib/libs/grpc/src/core/tsi/local_transport_security.h index 17213ecf35..7a5a491fd3 100644 --- a/contrib/libs/grpc/src/core/tsi/local_transport_security.h +++ b/contrib/libs/grpc/src/core/tsi/local_transport_security.h @@ -1,51 +1,51 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_CORE_TSI_LOCAL_TRANSPORT_SECURITY_H -#define GRPC_CORE_TSI_LOCAL_TRANSPORT_SECURITY_H - -#include <grpc/support/port_platform.h> - -#include <grpc/grpc.h> - -#include "src/core/tsi/transport_security.h" -#include "src/core/tsi/transport_security_interface.h" - -#define TSI_LOCAL_NUM_OF_PEER_PROPERTIES 1 -#define TSI_LOCAL_PROCESS_ID_PEER_PROPERTY "process_id" - -/** - * Main struct for local TSI handshaker. All APIs in the header are - * thread-comptabile. - */ -typedef struct local_tsi_handshaker local_tsi_handshaker; - -/** - * This method creates a local TSI handshaker instance. - * - * - is_client: boolean value indicating if the handshaker is used at the client - * (is_client = true) or server (is_client = false) side. The parameter is - * added for future extension. - * - self: address of local TSI handshaker instance to be returned from the - * method. - * - * It returns TSI_OK on success and an error status code on failure. - */ -tsi_result local_tsi_handshaker_create(bool is_client, tsi_handshaker** self); - -#endif /* GRPC_CORE_TSI_LOCAL_TRANSPORT_SECURITY_H */ +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_CORE_TSI_LOCAL_TRANSPORT_SECURITY_H +#define GRPC_CORE_TSI_LOCAL_TRANSPORT_SECURITY_H + +#include <grpc/support/port_platform.h> + +#include <grpc/grpc.h> + +#include "src/core/tsi/transport_security.h" +#include "src/core/tsi/transport_security_interface.h" + +#define TSI_LOCAL_NUM_OF_PEER_PROPERTIES 1 +#define TSI_LOCAL_PROCESS_ID_PEER_PROPERTY "process_id" + +/** + * Main struct for local TSI handshaker. All APIs in the header are + * thread-comptabile. + */ +typedef struct local_tsi_handshaker local_tsi_handshaker; + +/** + * This method creates a local TSI handshaker instance. + * + * - is_client: boolean value indicating if the handshaker is used at the client + * (is_client = true) or server (is_client = false) side. The parameter is + * added for future extension. + * - self: address of local TSI handshaker instance to be returned from the + * method. + * + * It returns TSI_OK on success and an error status code on failure. + */ +tsi_result local_tsi_handshaker_create(bool is_client, tsi_handshaker** self); + +#endif /* GRPC_CORE_TSI_LOCAL_TRANSPORT_SECURITY_H */ diff --git a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc index 6da4fb4ee1..403a4b4472 100644 --- a/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc +++ b/contrib/libs/grpc/src/core/tsi/ssl/session_cache/ssl_session_cache.cc @@ -19,8 +19,8 @@ #include <grpc/support/port_platform.h> #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/slice/slice_internal.h" -#include "src/core/tsi/ssl/session_cache/ssl_session.h" +#include "src/core/lib/slice/slice_internal.h" +#include "src/core/tsi/ssl/session_cache/ssl_session.h" #include "src/core/tsi/ssl/session_cache/ssl_session_cache.h" #include <grpc/support/log.h> @@ -56,7 +56,7 @@ class SslSessionLRUCache::Node { SetSession(std::move(session)); } - ~Node() { grpc_slice_unref_internal(key_); } + ~Node() { grpc_slice_unref_internal(key_); } // Not copyable nor movable. Node(const Node&) = delete; @@ -100,7 +100,7 @@ SslSessionLRUCache::~SslSessionLRUCache() { } size_t SslSessionLRUCache::Size() { - grpc_core::MutexLock lock(&lock_); + grpc_core::MutexLock lock(&lock_); return use_order_list_size_; } @@ -120,7 +120,7 @@ SslSessionLRUCache::Node* SslSessionLRUCache::FindLocked( } void SslSessionLRUCache::Put(const char* key, SslSessionPtr session) { - grpc_core::MutexLock lock(&lock_); + grpc_core::MutexLock lock(&lock_); Node* node = FindLocked(grpc_slice_from_static_string(key)); if (node != nullptr) { node->SetSession(std::move(session)); @@ -143,7 +143,7 @@ void SslSessionLRUCache::Put(const char* key, SslSessionPtr session) { } SslSessionPtr SslSessionLRUCache::Get(const char* key) { - grpc_core::MutexLock lock(&lock_); + grpc_core::MutexLock lock(&lock_); // Key is only used for lookups. grpc_slice key_slice = grpc_slice_from_static_string(key); Node* node = FindLocked(key_slice); diff --git a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc index 374f8e583f..155d91c82a 100644 --- a/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc +++ b/contrib/libs/grpc/src/core/tsi/ssl_transport_security.cc @@ -65,7 +65,7 @@ extern "C" { #define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND 16384 #define TSI_SSL_MAX_PROTECTED_FRAME_SIZE_LOWER_BOUND 1024 -#define TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 1024 +#define TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE 1024 /* Putting a macro like this and littering the source file with #if is really bad practice. @@ -114,16 +114,16 @@ struct tsi_ssl_handshaker { SSL* ssl; BIO* network_io; tsi_result result; - unsigned char* outgoing_bytes_buffer; - size_t outgoing_bytes_buffer_size; + unsigned char* outgoing_bytes_buffer; + size_t outgoing_bytes_buffer_size; tsi_ssl_handshaker_factory* factory_ref; }; struct tsi_ssl_handshaker_result { - tsi_handshaker_result base; - SSL* ssl; - BIO* network_io; - unsigned char* unused_bytes; - size_t unused_bytes_size; + tsi_handshaker_result base; + SSL* ssl; + BIO* network_io; + unsigned char* unused_bytes; + size_t unused_bytes_size; }; struct tsi_ssl_frame_protector { tsi_frame_protector base; @@ -136,13 +136,13 @@ struct tsi_ssl_frame_protector { /* --- Library Initialization. ---*/ static gpr_once g_init_openssl_once = GPR_ONCE_INIT; -static int g_ssl_ctx_ex_factory_index = -1; -static const unsigned char kSslSessionIdContext[] = {'g', 'r', 'p', 'c'}; +static int g_ssl_ctx_ex_factory_index = -1; +static const unsigned char kSslSessionIdContext[] = {'g', 'r', 'p', 'c'}; #ifndef OPENSSL_IS_BORINGSSL static const char kSslEnginePrefix[] = "engine:"; #endif - -#if OPENSSL_VERSION_NUMBER < 0x10100000 + +#if OPENSSL_VERSION_NUMBER < 0x10100000 static gpr_mu* g_openssl_mutexes = nullptr; static void openssl_locking_cb(int mode, int type, const char* file, int line) GRPC_UNUSED; @@ -159,31 +159,31 @@ static void openssl_locking_cb(int mode, int type, const char* file, int line) { static unsigned long openssl_thread_id_cb(void) { return static_cast<unsigned long>(gpr_thd_currentid()); } -#endif +#endif static void init_openssl(void) { #if OPENSSL_VERSION_NUMBER >= 0x10100000 OPENSSL_init_ssl(0, nullptr); -#else +#else SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); -#endif -#if OPENSSL_VERSION_NUMBER < 0x10100000 - if (!CRYPTO_get_locking_callback()) { - int num_locks = CRYPTO_num_locks(); - GPR_ASSERT(num_locks > 0); - g_openssl_mutexes = static_cast<gpr_mu*>( - gpr_malloc(static_cast<size_t>(num_locks) * sizeof(gpr_mu))); - for (int i = 0; i < num_locks; i++) { - gpr_mu_init(&g_openssl_mutexes[i]); - } - CRYPTO_set_locking_callback(openssl_locking_cb); - CRYPTO_set_id_callback(openssl_thread_id_cb); - } else { - gpr_log(GPR_INFO, "OpenSSL callback has already been set."); - } -#endif +#endif +#if OPENSSL_VERSION_NUMBER < 0x10100000 + if (!CRYPTO_get_locking_callback()) { + int num_locks = CRYPTO_num_locks(); + GPR_ASSERT(num_locks > 0); + g_openssl_mutexes = static_cast<gpr_mu*>( + gpr_malloc(static_cast<size_t>(num_locks) * sizeof(gpr_mu))); + for (int i = 0; i < num_locks; i++) { + gpr_mu_init(&g_openssl_mutexes[i]); + } + CRYPTO_set_locking_callback(openssl_locking_cb); + CRYPTO_set_id_callback(openssl_thread_id_cb); + } else { + gpr_log(GPR_INFO, "OpenSSL callback has already been set."); + } +#endif g_ssl_ctx_ex_factory_index = SSL_CTX_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); GPR_ASSERT(g_ssl_ctx_ex_factory_index != -1); @@ -238,7 +238,7 @@ static void ssl_log_where_info(const SSL* ssl, int where, int flag, /* Used for debugging. TODO(jboeuf): Remove when code is mature enough. */ static void ssl_info_callback(const SSL* ssl, int where, int ret) { if (ret == 0) { - gpr_log(GPR_ERROR, "ssl_info_callback: error occurred.\n"); + gpr_log(GPR_ERROR, "ssl_info_callback: error occurred.\n"); return; } @@ -281,13 +281,13 @@ static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8, X509_NAME* subject_name = X509_get_subject_name(cert); int utf8_returned_size = 0; if (subject_name == nullptr) { - gpr_log(GPR_INFO, "Could not get subject name from certificate."); + gpr_log(GPR_INFO, "Could not get subject name from certificate."); return TSI_NOT_FOUND; } common_name_index = X509_NAME_get_index_by_NID(subject_name, NID_commonName, -1); if (common_name_index == -1) { - gpr_log(GPR_INFO, "Could not get common name of subject from certificate."); + gpr_log(GPR_INFO, "Could not get common name of subject from certificate."); return TSI_NOT_FOUND; } common_name_entry = X509_NAME_get_entry(subject_name, common_name_index); @@ -750,15 +750,15 @@ static tsi_result x509_store_load_certs(X509_STORE* cert_store, sk_X509_NAME_push(*root_names, root_name); root_name = nullptr; } - ERR_clear_error(); + ERR_clear_error(); if (!X509_STORE_add_cert(cert_store, root)) { - unsigned long error = ERR_get_error(); - if (ERR_GET_LIB(error) != ERR_LIB_X509 || - ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) { - gpr_log(GPR_ERROR, "Could not add root certificate to ssl context."); - result = TSI_INTERNAL_ERROR; - break; - } + unsigned long error = ERR_get_error(); + if (ERR_GET_LIB(error) != ERR_LIB_X509 || + ERR_GET_REASON(error) != X509_R_CERT_ALREADY_IN_HASH_TABLE) { + gpr_log(GPR_ERROR, "Could not add root certificate to ssl context."); + result = TSI_INTERNAL_ERROR; + break; + } } X509_free(root); num_roots++; @@ -786,8 +786,8 @@ static tsi_result ssl_ctx_load_verification_certs(SSL_CTX* context, STACK_OF(X509_NAME) * *root_name) { X509_STORE* cert_store = SSL_CTX_get_cert_store(context); - X509_STORE_set_flags(cert_store, - X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST); + X509_STORE_set_flags(cert_store, + X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_TRUSTED_FIRST); return x509_store_load_certs(cert_store, pem_roots, pem_roots_size, root_name); } @@ -1215,14 +1215,14 @@ tsi_result tsi_ssl_get_cert_chain_contents(STACK_OF(X509) * peer_chain, return result; } -/* --- tsi_handshaker_result methods implementation. ---*/ -static tsi_result ssl_handshaker_result_extract_peer( - const tsi_handshaker_result* self, tsi_peer* peer) { +/* --- tsi_handshaker_result methods implementation. ---*/ +static tsi_result ssl_handshaker_result_extract_peer( + const tsi_handshaker_result* self, tsi_peer* peer) { tsi_result result = TSI_OK; const unsigned char* alpn_selected = nullptr; unsigned int alpn_selected_len; - const tsi_ssl_handshaker_result* impl = - reinterpret_cast<const tsi_ssl_handshaker_result*>(self); + const tsi_ssl_handshaker_result* impl = + reinterpret_cast<const tsi_ssl_handshaker_result*>(self); X509* peer_cert = SSL_get_peer_certificate(impl->ssl); if (peer_cert != nullptr) { result = peer_from_x509(peer_cert, 1, peer); @@ -1275,22 +1275,22 @@ static tsi_result ssl_handshaker_result_extract_peer( peer->property_count++; const char* session_reused = SSL_session_reused(impl->ssl) ? "true" : "false"; - result = tsi_construct_string_peer_property_from_cstring( + result = tsi_construct_string_peer_property_from_cstring( TSI_SSL_SESSION_REUSED_PEER_PROPERTY, session_reused, - &peer->properties[peer->property_count]); + &peer->properties[peer->property_count]); if (result != TSI_OK) return result; peer->property_count++; return result; } -static tsi_result ssl_handshaker_result_create_frame_protector( - const tsi_handshaker_result* self, size_t* max_output_protected_frame_size, +static tsi_result ssl_handshaker_result_create_frame_protector( + const tsi_handshaker_result* self, size_t* max_output_protected_frame_size, tsi_frame_protector** protector) { size_t actual_max_output_protected_frame_size = TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND; - tsi_ssl_handshaker_result* impl = - reinterpret_cast<tsi_ssl_handshaker_result*>( - const_cast<tsi_handshaker_result*>(self)); + tsi_ssl_handshaker_result* impl = + reinterpret_cast<tsi_ssl_handshaker_result*>( + const_cast<tsi_handshaker_result*>(self)); tsi_ssl_frame_protector* protector_impl = static_cast<tsi_ssl_frame_protector*>( gpr_zalloc(sizeof(*protector_impl))); @@ -1318,7 +1318,7 @@ static tsi_result ssl_handshaker_result_create_frame_protector( return TSI_INTERNAL_ERROR; } - /* Transfer ownership of ssl and network_io to the frame protector. */ + /* Transfer ownership of ssl and network_io to the frame protector. */ protector_impl->ssl = impl->ssl; impl->ssl = nullptr; protector_impl->network_io = impl->network_io; @@ -1328,138 +1328,138 @@ static tsi_result ssl_handshaker_result_create_frame_protector( return TSI_OK; } -static tsi_result ssl_handshaker_result_get_unused_bytes( - const tsi_handshaker_result* self, const unsigned char** bytes, - size_t* bytes_size) { - const tsi_ssl_handshaker_result* impl = - reinterpret_cast<const tsi_ssl_handshaker_result*>(self); - *bytes_size = impl->unused_bytes_size; - *bytes = impl->unused_bytes; - return TSI_OK; -} - -static void ssl_handshaker_result_destroy(tsi_handshaker_result* self) { - tsi_ssl_handshaker_result* impl = - reinterpret_cast<tsi_ssl_handshaker_result*>(self); - SSL_free(impl->ssl); - BIO_free(impl->network_io); - gpr_free(impl->unused_bytes); - gpr_free(impl); -} - -static const tsi_handshaker_result_vtable handshaker_result_vtable = { - ssl_handshaker_result_extract_peer, - nullptr, /* create_zero_copy_grpc_protector */ - ssl_handshaker_result_create_frame_protector, - ssl_handshaker_result_get_unused_bytes, - ssl_handshaker_result_destroy, -}; - -static tsi_result ssl_handshaker_result_create( +static tsi_result ssl_handshaker_result_get_unused_bytes( + const tsi_handshaker_result* self, const unsigned char** bytes, + size_t* bytes_size) { + const tsi_ssl_handshaker_result* impl = + reinterpret_cast<const tsi_ssl_handshaker_result*>(self); + *bytes_size = impl->unused_bytes_size; + *bytes = impl->unused_bytes; + return TSI_OK; +} + +static void ssl_handshaker_result_destroy(tsi_handshaker_result* self) { + tsi_ssl_handshaker_result* impl = + reinterpret_cast<tsi_ssl_handshaker_result*>(self); + SSL_free(impl->ssl); + BIO_free(impl->network_io); + gpr_free(impl->unused_bytes); + gpr_free(impl); +} + +static const tsi_handshaker_result_vtable handshaker_result_vtable = { + ssl_handshaker_result_extract_peer, + nullptr, /* create_zero_copy_grpc_protector */ + ssl_handshaker_result_create_frame_protector, + ssl_handshaker_result_get_unused_bytes, + ssl_handshaker_result_destroy, +}; + +static tsi_result ssl_handshaker_result_create( tsi_ssl_handshaker* handshaker, unsigned char* unused_bytes, - size_t unused_bytes_size, tsi_handshaker_result** handshaker_result) { - if (handshaker == nullptr || handshaker_result == nullptr || - (unused_bytes_size > 0 && unused_bytes == nullptr)) { - return TSI_INVALID_ARGUMENT; - } - tsi_ssl_handshaker_result* result = - static_cast<tsi_ssl_handshaker_result*>(gpr_zalloc(sizeof(*result))); - result->base.vtable = &handshaker_result_vtable; - /* Transfer ownership of ssl and network_io to the handshaker result. */ - result->ssl = handshaker->ssl; - handshaker->ssl = nullptr; - result->network_io = handshaker->network_io; - handshaker->network_io = nullptr; + size_t unused_bytes_size, tsi_handshaker_result** handshaker_result) { + if (handshaker == nullptr || handshaker_result == nullptr || + (unused_bytes_size > 0 && unused_bytes == nullptr)) { + return TSI_INVALID_ARGUMENT; + } + tsi_ssl_handshaker_result* result = + static_cast<tsi_ssl_handshaker_result*>(gpr_zalloc(sizeof(*result))); + result->base.vtable = &handshaker_result_vtable; + /* Transfer ownership of ssl and network_io to the handshaker result. */ + result->ssl = handshaker->ssl; + handshaker->ssl = nullptr; + result->network_io = handshaker->network_io; + handshaker->network_io = nullptr; /* Transfer ownership of |unused_bytes| to the handshaker result. */ result->unused_bytes = unused_bytes; - result->unused_bytes_size = unused_bytes_size; - *handshaker_result = &result->base; - return TSI_OK; -} - -/* --- tsi_handshaker methods implementation. ---*/ - -static tsi_result ssl_handshaker_get_bytes_to_send_to_peer( - tsi_ssl_handshaker* impl, unsigned char* bytes, size_t* bytes_size) { - int bytes_read_from_ssl = 0; - if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 || - *bytes_size > INT_MAX) { - return TSI_INVALID_ARGUMENT; - } - GPR_ASSERT(*bytes_size <= INT_MAX); - bytes_read_from_ssl = - BIO_read(impl->network_io, bytes, static_cast<int>(*bytes_size)); - if (bytes_read_from_ssl < 0) { - *bytes_size = 0; - if (!BIO_should_retry(impl->network_io)) { - impl->result = TSI_INTERNAL_ERROR; - return impl->result; - } else { - return TSI_OK; - } - } - *bytes_size = static_cast<size_t>(bytes_read_from_ssl); - return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA; -} - -static tsi_result ssl_handshaker_get_result(tsi_ssl_handshaker* impl) { - if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) && - SSL_is_init_finished(impl->ssl)) { - impl->result = TSI_OK; - } - return impl->result; -} - -static tsi_result ssl_handshaker_process_bytes_from_peer( - tsi_ssl_handshaker* impl, const unsigned char* bytes, size_t* bytes_size) { - int bytes_written_into_ssl_size = 0; - if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) { - return TSI_INVALID_ARGUMENT; - } - GPR_ASSERT(*bytes_size <= INT_MAX); - bytes_written_into_ssl_size = - BIO_write(impl->network_io, bytes, static_cast<int>(*bytes_size)); - if (bytes_written_into_ssl_size < 0) { - gpr_log(GPR_ERROR, "Could not write to memory BIO."); - impl->result = TSI_INTERNAL_ERROR; - return impl->result; - } - *bytes_size = static_cast<size_t>(bytes_written_into_ssl_size); - - if (ssl_handshaker_get_result(impl) != TSI_HANDSHAKE_IN_PROGRESS) { - impl->result = TSI_OK; - return impl->result; - } else { - /* Get ready to get some bytes from SSL. */ - int ssl_result = SSL_do_handshake(impl->ssl); - ssl_result = SSL_get_error(impl->ssl, ssl_result); - switch (ssl_result) { - case SSL_ERROR_WANT_READ: - if (BIO_pending(impl->network_io) == 0) { - /* We need more data. */ - return TSI_INCOMPLETE_DATA; - } else { - return TSI_OK; - } - case SSL_ERROR_NONE: - return TSI_OK; - default: { - char err_str[256]; - ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str)); - gpr_log(GPR_ERROR, "Handshake failed with fatal error %s: %s.", - ssl_error_string(ssl_result), err_str); - impl->result = TSI_PROTOCOL_FAILURE; - return impl->result; - } - } - } -} - + result->unused_bytes_size = unused_bytes_size; + *handshaker_result = &result->base; + return TSI_OK; +} + +/* --- tsi_handshaker methods implementation. ---*/ + +static tsi_result ssl_handshaker_get_bytes_to_send_to_peer( + tsi_ssl_handshaker* impl, unsigned char* bytes, size_t* bytes_size) { + int bytes_read_from_ssl = 0; + if (bytes == nullptr || bytes_size == nullptr || *bytes_size == 0 || + *bytes_size > INT_MAX) { + return TSI_INVALID_ARGUMENT; + } + GPR_ASSERT(*bytes_size <= INT_MAX); + bytes_read_from_ssl = + BIO_read(impl->network_io, bytes, static_cast<int>(*bytes_size)); + if (bytes_read_from_ssl < 0) { + *bytes_size = 0; + if (!BIO_should_retry(impl->network_io)) { + impl->result = TSI_INTERNAL_ERROR; + return impl->result; + } else { + return TSI_OK; + } + } + *bytes_size = static_cast<size_t>(bytes_read_from_ssl); + return BIO_pending(impl->network_io) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA; +} + +static tsi_result ssl_handshaker_get_result(tsi_ssl_handshaker* impl) { + if ((impl->result == TSI_HANDSHAKE_IN_PROGRESS) && + SSL_is_init_finished(impl->ssl)) { + impl->result = TSI_OK; + } + return impl->result; +} + +static tsi_result ssl_handshaker_process_bytes_from_peer( + tsi_ssl_handshaker* impl, const unsigned char* bytes, size_t* bytes_size) { + int bytes_written_into_ssl_size = 0; + if (bytes == nullptr || bytes_size == nullptr || *bytes_size > INT_MAX) { + return TSI_INVALID_ARGUMENT; + } + GPR_ASSERT(*bytes_size <= INT_MAX); + bytes_written_into_ssl_size = + BIO_write(impl->network_io, bytes, static_cast<int>(*bytes_size)); + if (bytes_written_into_ssl_size < 0) { + gpr_log(GPR_ERROR, "Could not write to memory BIO."); + impl->result = TSI_INTERNAL_ERROR; + return impl->result; + } + *bytes_size = static_cast<size_t>(bytes_written_into_ssl_size); + + if (ssl_handshaker_get_result(impl) != TSI_HANDSHAKE_IN_PROGRESS) { + impl->result = TSI_OK; + return impl->result; + } else { + /* Get ready to get some bytes from SSL. */ + int ssl_result = SSL_do_handshake(impl->ssl); + ssl_result = SSL_get_error(impl->ssl, ssl_result); + switch (ssl_result) { + case SSL_ERROR_WANT_READ: + if (BIO_pending(impl->network_io) == 0) { + /* We need more data. */ + return TSI_INCOMPLETE_DATA; + } else { + return TSI_OK; + } + case SSL_ERROR_NONE: + return TSI_OK; + default: { + char err_str[256]; + ERR_error_string_n(ERR_get_error(), err_str, sizeof(err_str)); + gpr_log(GPR_ERROR, "Handshake failed with fatal error %s: %s.", + ssl_error_string(ssl_result), err_str); + impl->result = TSI_PROTOCOL_FAILURE; + return impl->result; + } + } + } +} + static void ssl_handshaker_destroy(tsi_handshaker* self) { tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self); SSL_free(impl->ssl); BIO_free(impl->network_io); - gpr_free(impl->outgoing_bytes_buffer); + gpr_free(impl->outgoing_bytes_buffer); tsi_ssl_handshaker_factory_unref(impl->factory_ref); gpr_free(impl); } @@ -1494,46 +1494,46 @@ static tsi_result ssl_bytes_remaining(tsi_ssl_handshaker* impl, return TSI_OK; } -static tsi_result ssl_handshaker_next( - tsi_handshaker* self, const unsigned char* received_bytes, - size_t received_bytes_size, const unsigned char** bytes_to_send, - size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, +static tsi_result ssl_handshaker_next( + tsi_handshaker* self, const unsigned char* received_bytes, + size_t received_bytes_size, const unsigned char** bytes_to_send, + size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, tsi_handshaker_on_next_done_cb /*cb*/, void* /*user_data*/) { - /* Input sanity check. */ - if ((received_bytes_size > 0 && received_bytes == nullptr) || - bytes_to_send == nullptr || bytes_to_send_size == nullptr || - handshaker_result == nullptr) { - return TSI_INVALID_ARGUMENT; - } - /* If there are received bytes, process them first. */ - tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self); - tsi_result status = TSI_OK; - size_t bytes_consumed = received_bytes_size; - if (received_bytes_size > 0) { - status = ssl_handshaker_process_bytes_from_peer(impl, received_bytes, - &bytes_consumed); - if (status != TSI_OK) return status; - } - /* Get bytes to send to the peer, if available. */ - size_t offset = 0; - do { - size_t to_send_size = impl->outgoing_bytes_buffer_size - offset; - status = ssl_handshaker_get_bytes_to_send_to_peer( - impl, impl->outgoing_bytes_buffer + offset, &to_send_size); - offset += to_send_size; - if (status == TSI_INCOMPLETE_DATA) { - impl->outgoing_bytes_buffer_size *= 2; - impl->outgoing_bytes_buffer = static_cast<unsigned char*>(gpr_realloc( - impl->outgoing_bytes_buffer, impl->outgoing_bytes_buffer_size)); - } - } while (status == TSI_INCOMPLETE_DATA); - if (status != TSI_OK) return status; - *bytes_to_send = impl->outgoing_bytes_buffer; - *bytes_to_send_size = offset; - /* If handshake completes, create tsi_handshaker_result. */ - if (ssl_handshaker_get_result(impl) == TSI_HANDSHAKE_IN_PROGRESS) { - *handshaker_result = nullptr; - } else { + /* Input sanity check. */ + if ((received_bytes_size > 0 && received_bytes == nullptr) || + bytes_to_send == nullptr || bytes_to_send_size == nullptr || + handshaker_result == nullptr) { + return TSI_INVALID_ARGUMENT; + } + /* If there are received bytes, process them first. */ + tsi_ssl_handshaker* impl = reinterpret_cast<tsi_ssl_handshaker*>(self); + tsi_result status = TSI_OK; + size_t bytes_consumed = received_bytes_size; + if (received_bytes_size > 0) { + status = ssl_handshaker_process_bytes_from_peer(impl, received_bytes, + &bytes_consumed); + if (status != TSI_OK) return status; + } + /* Get bytes to send to the peer, if available. */ + size_t offset = 0; + do { + size_t to_send_size = impl->outgoing_bytes_buffer_size - offset; + status = ssl_handshaker_get_bytes_to_send_to_peer( + impl, impl->outgoing_bytes_buffer + offset, &to_send_size); + offset += to_send_size; + if (status == TSI_INCOMPLETE_DATA) { + impl->outgoing_bytes_buffer_size *= 2; + impl->outgoing_bytes_buffer = static_cast<unsigned char*>(gpr_realloc( + impl->outgoing_bytes_buffer, impl->outgoing_bytes_buffer_size)); + } + } while (status == TSI_INCOMPLETE_DATA); + if (status != TSI_OK) return status; + *bytes_to_send = impl->outgoing_bytes_buffer; + *bytes_to_send_size = offset; + /* If handshake completes, create tsi_handshaker_result. */ + if (ssl_handshaker_get_result(impl) == TSI_HANDSHAKE_IN_PROGRESS) { + *handshaker_result = nullptr; + } else { // Any bytes that remain in |impl->ssl|'s read BIO after the handshake is // complete must be extracted and set to the unused bytes of the handshaker // result. This indicates to the gRPC stack that there are bytes from the @@ -1547,26 +1547,26 @@ static tsi_result ssl_handshaker_next( gpr_free(unused_bytes); return TSI_INTERNAL_ERROR; } - status = ssl_handshaker_result_create(impl, unused_bytes, unused_bytes_size, - handshaker_result); - if (status == TSI_OK) { - /* Indicates that the handshake has completed and that a handshaker_result - * has been created. */ - self->handshaker_result_created = true; - } - } - return status; -} - + status = ssl_handshaker_result_create(impl, unused_bytes, unused_bytes_size, + handshaker_result); + if (status == TSI_OK) { + /* Indicates that the handshake has completed and that a handshaker_result + * has been created. */ + self->handshaker_result_created = true; + } + } + return status; +} + static const tsi_handshaker_vtable handshaker_vtable = { - nullptr, /* get_bytes_to_send_to_peer -- deprecated */ - nullptr, /* process_bytes_from_peer -- deprecated */ - nullptr, /* get_result -- deprecated */ - nullptr, /* extract_peer -- deprecated */ - nullptr, /* create_frame_protector -- deprecated */ + nullptr, /* get_bytes_to_send_to_peer -- deprecated */ + nullptr, /* process_bytes_from_peer -- deprecated */ + nullptr, /* get_result -- deprecated */ + nullptr, /* extract_peer -- deprecated */ + nullptr, /* create_frame_protector -- deprecated */ ssl_handshaker_destroy, - ssl_handshaker_next, - nullptr, /* shutdown */ + ssl_handshaker_next, + nullptr, /* shutdown */ }; /* --- tsi_ssl_handshaker_factory common methods. --- */ @@ -1644,10 +1644,10 @@ static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client, impl->ssl = ssl; impl->network_io = network_io; impl->result = TSI_HANDSHAKE_IN_PROGRESS; - impl->outgoing_bytes_buffer_size = - TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE; - impl->outgoing_bytes_buffer = - static_cast<unsigned char*>(gpr_zalloc(impl->outgoing_bytes_buffer_size)); + impl->outgoing_bytes_buffer_size = + TSI_SSL_HANDSHAKER_OUTGOING_BUFFER_INITIAL_SIZE; + impl->outgoing_bytes_buffer = + static_cast<unsigned char*>(gpr_zalloc(impl->outgoing_bytes_buffer_size)); impl->base.vtable = &handshaker_vtable; impl->factory_ref = tsi_ssl_handshaker_factory_ref(factory); *handshaker = &impl->base; @@ -1900,10 +1900,10 @@ tsi_result tsi_create_ssl_client_handshaker_factory_with_options( } #if OPENSSL_VERSION_NUMBER >= 0x10100000 - ssl_context = SSL_CTX_new(TLS_method()); -#else + ssl_context = SSL_CTX_new(TLS_method()); +#else ssl_context = SSL_CTX_new(TLSv1_2_method()); -#endif +#endif result = tsi_set_min_and_max_tls_versions( ssl_context, options->min_tls_version, options->max_tls_version); if (result != TSI_OK) return result; @@ -2067,10 +2067,10 @@ tsi_result tsi_create_ssl_server_handshaker_factory_with_options( for (i = 0; i < options->num_key_cert_pairs; i++) { do { #if OPENSSL_VERSION_NUMBER >= 0x10100000 - impl->ssl_contexts[i] = SSL_CTX_new(TLS_method()); -#else + impl->ssl_contexts[i] = SSL_CTX_new(TLS_method()); +#else impl->ssl_contexts[i] = SSL_CTX_new(TLSv1_2_method()); -#endif +#endif result = tsi_set_min_and_max_tls_versions(impl->ssl_contexts[i], options->min_tls_version, options->max_tls_version); @@ -2119,29 +2119,29 @@ tsi_result tsi_create_ssl_server_handshaker_factory_with_options( } SSL_CTX_set_client_CA_list(impl->ssl_contexts[i], root_names); } - switch (options->client_certificate_request) { - case TSI_DONT_REQUEST_CLIENT_CERTIFICATE: - SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr); - break; - case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: - SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, - NullVerifyCallback); - break; - case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY: - SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr); - break; - case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: - SSL_CTX_set_verify(impl->ssl_contexts[i], - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, - NullVerifyCallback); - break; - case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY: - SSL_CTX_set_verify(impl->ssl_contexts[i], - SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, - nullptr); - break; - } - /* TODO(jboeuf): Add revocation verification. */ + switch (options->client_certificate_request) { + case TSI_DONT_REQUEST_CLIENT_CERTIFICATE: + SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_NONE, nullptr); + break; + case TSI_REQUEST_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: + SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, + NullVerifyCallback); + break; + case TSI_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY: + SSL_CTX_set_verify(impl->ssl_contexts[i], SSL_VERIFY_PEER, nullptr); + break; + case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_BUT_DONT_VERIFY: + SSL_CTX_set_verify(impl->ssl_contexts[i], + SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + NullVerifyCallback); + break; + case TSI_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY: + SSL_CTX_set_verify(impl->ssl_contexts[i], + SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + nullptr); + break; + } + /* TODO(jboeuf): Add revocation verification. */ result = tsi_ssl_extract_x509_subject_names_from_pem_cert( options->pem_key_cert_pairs[i].cert_chain, diff --git a/contrib/libs/grpc/src/core/tsi/transport_security.cc b/contrib/libs/grpc/src/core/tsi/transport_security.cc index 035e7cc545..4aa90b67a4 100644 --- a/contrib/libs/grpc/src/core/tsi/transport_security.cc +++ b/contrib/libs/grpc/src/core/tsi/transport_security.cc @@ -149,7 +149,7 @@ tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self, return TSI_INVALID_ARGUMENT; } if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; + if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; if (self->vtable->get_bytes_to_send_to_peer == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->get_bytes_to_send_to_peer(self, bytes, bytes_size); @@ -163,7 +163,7 @@ tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self, return TSI_INVALID_ARGUMENT; } if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; + if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; if (self->vtable->process_bytes_from_peer == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->process_bytes_from_peer(self, bytes, bytes_size); @@ -172,7 +172,7 @@ tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self, tsi_result tsi_handshaker_get_result(tsi_handshaker* self) { if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT; if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; + if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; if (self->vtable->get_result == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->get_result(self); } @@ -183,7 +183,7 @@ tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer) { } memset(peer, 0, sizeof(tsi_peer)); if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; + if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; if (tsi_handshaker_get_result(self) != TSI_OK) { return TSI_FAILED_PRECONDITION; } @@ -199,7 +199,7 @@ tsi_result tsi_handshaker_create_frame_protector( return TSI_INVALID_ARGUMENT; } if (self->frame_protector_created) return TSI_FAILED_PRECONDITION; - if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; + if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; if (tsi_handshaker_get_result(self) != TSI_OK) return TSI_FAILED_PRECONDITION; if (self->vtable->create_frame_protector == nullptr) return TSI_UNIMPLEMENTED; result = self->vtable->create_frame_protector(self, max_protected_frame_size, @@ -217,21 +217,21 @@ tsi_result tsi_handshaker_next( tsi_handshaker_on_next_done_cb cb, void* user_data) { if (self == nullptr || self->vtable == nullptr) return TSI_INVALID_ARGUMENT; if (self->handshaker_result_created) return TSI_FAILED_PRECONDITION; - if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; + if (self->handshake_shutdown) return TSI_HANDSHAKE_SHUTDOWN; if (self->vtable->next == nullptr) return TSI_UNIMPLEMENTED; return self->vtable->next(self, received_bytes, received_bytes_size, bytes_to_send, bytes_to_send_size, handshaker_result, cb, user_data); } -void tsi_handshaker_shutdown(tsi_handshaker* self) { - if (self == nullptr || self->vtable == nullptr) return; - if (self->vtable->shutdown != nullptr) { - self->vtable->shutdown(self); - } - self->handshake_shutdown = true; -} - +void tsi_handshaker_shutdown(tsi_handshaker* self) { + if (self == nullptr || self->vtable == nullptr) return; + if (self->vtable->shutdown != nullptr) { + self->vtable->shutdown(self); + } + self->handshake_shutdown = true; +} + void tsi_handshaker_destroy(tsi_handshaker* self) { if (self == nullptr) return; self->vtable->destroy(self); @@ -351,20 +351,20 @@ tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer) { } return TSI_OK; } - -const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer, - const char* name) { - size_t i; - if (peer == nullptr) return nullptr; - for (i = 0; i < peer->property_count; i++) { - const tsi_peer_property* property = &peer->properties[i]; - if (name == nullptr && property->name == nullptr) { - return property; - } - if (name != nullptr && property->name != nullptr && - strcmp(property->name, name) == 0) { - return property; - } - } - return nullptr; -} + +const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer, + const char* name) { + size_t i; + if (peer == nullptr) return nullptr; + for (i = 0; i < peer->property_count; i++) { + const tsi_peer_property* property = &peer->properties[i]; + if (name == nullptr && property->name == nullptr) { + return property; + } + if (name != nullptr && property->name != nullptr && + strcmp(property->name, name) == 0) { + return property; + } + } + return nullptr; +} diff --git a/contrib/libs/grpc/src/core/tsi/transport_security.h b/contrib/libs/grpc/src/core/tsi/transport_security.h index d3b1c7f4aa..7778907727 100644 --- a/contrib/libs/grpc/src/core/tsi/transport_security.h +++ b/contrib/libs/grpc/src/core/tsi/transport_security.h @@ -72,13 +72,13 @@ struct tsi_handshaker_vtable { size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, tsi_handshaker_on_next_done_cb cb, void* user_data); - void (*shutdown)(tsi_handshaker* self); + void (*shutdown)(tsi_handshaker* self); }; struct tsi_handshaker { const tsi_handshaker_vtable* vtable; bool frame_protector_created; bool handshaker_result_created; - bool handshake_shutdown; + bool handshake_shutdown; }; /* Base for tsi_handshaker_result implementations. @@ -119,8 +119,8 @@ tsi_result tsi_construct_allocated_string_peer_property( const char* name, size_t value_length, tsi_peer_property* property); tsi_result tsi_construct_string_peer_property_from_cstring( const char* name, const char* value, tsi_peer_property* property); -const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer, - const char* name); +const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* peer, + const char* name); /* Utils. */ char* tsi_strdup(const char* src); /* Sadly, no strdup in C89. */ diff --git a/contrib/libs/grpc/src/core/tsi/transport_security_interface.h b/contrib/libs/grpc/src/core/tsi/transport_security_interface.h index 4608f40091..803a74602b 100644 --- a/contrib/libs/grpc/src/core/tsi/transport_security_interface.h +++ b/contrib/libs/grpc/src/core/tsi/transport_security_interface.h @@ -42,8 +42,8 @@ typedef enum { TSI_PROTOCOL_FAILURE = 10, TSI_HANDSHAKE_IN_PROGRESS = 11, TSI_OUT_OF_RESOURCES = 12, - TSI_ASYNC = 13, - TSI_HANDSHAKE_SHUTDOWN = 14, + TSI_ASYNC = 13, + TSI_HANDSHAKE_SHUTDOWN = 14, TSI_CLOSE_NOTIFY = 15, // Indicates that the connection should be closed. } tsi_result; @@ -350,8 +350,8 @@ void tsi_handshaker_result_destroy(tsi_handshaker_result* self); ------------------------------------------------------------------------ */ typedef struct tsi_handshaker tsi_handshaker; -/* TODO(jiangtaoli2016): Cleans up deprecated methods when we are ready. */ - +/* TODO(jiangtaoli2016): Cleans up deprecated methods when we are ready. */ + /* TO BE DEPRECATED SOON. Use tsi_handshaker_next instead. Gets bytes that need to be sent to the peer. - bytes is the buffer that will be written with the data to be sent to the @@ -460,13 +460,13 @@ tsi_result tsi_handshaker_next( size_t* bytes_to_send_size, tsi_handshaker_result** handshaker_result, tsi_handshaker_on_next_done_cb cb, void* user_data); -/* This method shuts down a TSI handshake that is in progress. - * - * This method will be invoked when TSI handshake should be terminated before - * being finished in order to free any resources being used. - */ -void tsi_handshaker_shutdown(tsi_handshaker* self); - +/* This method shuts down a TSI handshake that is in progress. + * + * This method will be invoked when TSI handshake should be terminated before + * being finished in order to free any resources being used. + */ +void tsi_handshaker_shutdown(tsi_handshaker* self); + /* This method releases the tsi_handshaker object. After this method is called, no other method can be called on the object. */ void tsi_handshaker_destroy(tsi_handshaker* self); diff --git a/contrib/libs/grpc/src/cpp/README.md b/contrib/libs/grpc/src/cpp/README.md index 967a0a43b7..9405d38d92 100755 --- a/contrib/libs/grpc/src/cpp/README.md +++ b/contrib/libs/grpc/src/cpp/README.md @@ -2,44 +2,44 @@ This directory contains the C++ implementation of gRPC. -# To start using gRPC C++ +# To start using gRPC C++ This section describes how to add gRPC as a dependency to your C++ project. -In the C++ world, there's no universally accepted standard for managing project dependencies. -Therefore, gRPC supports several major build systems, which should satisfy most users. +In the C++ world, there's no universally accepted standard for managing project dependencies. +Therefore, gRPC supports several major build systems, which should satisfy most users. ## Bazel - + Bazel is the primary build system used by the core gRPC development team. Bazel provides fast builds and it easily handles dependencies that support bazel. - -To add gRPC as a dependency in bazel: -1. determine commit SHA for the grpc release you want to use + +To add gRPC as a dependency in bazel: +1. determine commit SHA for the grpc release you want to use 2. Use the [http_archive](https://docs.bazel.build/versions/master/repo/http.html#http_archive) bazel rule to include gRPC source - ``` - http_archive( - name = "com_github_grpc_grpc", - urls = [ - "https://github.com/grpc/grpc/archive/YOUR_GRPC_COMMIT_SHA.tar.gz", - ], - strip_prefix = "grpc-YOUR_GRPC_COMMIT_SHA", - ) - - load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") - - grpc_deps() - ``` - + ``` + http_archive( + name = "com_github_grpc_grpc", + urls = [ + "https://github.com/grpc/grpc/archive/YOUR_GRPC_COMMIT_SHA.tar.gz", + ], + strip_prefix = "grpc-YOUR_GRPC_COMMIT_SHA", + ) + + load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") + + grpc_deps() + ``` + ## CMake - + `cmake` is your best option if you cannot use bazel. It supports building on Linux, MacOS and Windows (official support) but also has a good chance of working on other platforms (no promises!). `cmake` has good support for crosscompiling and can be used for targeting the Android platform. - + To build gRPC C++ from source, follow the [BUILDING guide](../../BUILDING.md). - + ### find_package The canonical way to discover dependencies in CMake is the @@ -127,22 +127,22 @@ first install gRPC C++ using CMake, and have your non-CMake project rely on the The default choice for building on UNIX based systems used to be `make`, but we are no longer recommending it. You should use `bazel` or `cmake` instead. -To install gRPC for C++ on your system using `make`, follow the [Building gRPC C++](../../BUILDING.md) -instructions to build from source and then install locally using `make install`. -This also installs the protocol buffer compiler `protoc` (if you don't have it already), -and the C++ gRPC plugin for `protoc`. - -WARNING: After installing with `make install` there is no easy way to uninstall, which can cause issues -if you later want to remove the grpc and/or protobuf installation or upgrade to a newer version. - -## Packaging systems - +To install gRPC for C++ on your system using `make`, follow the [Building gRPC C++](../../BUILDING.md) +instructions to build from source and then install locally using `make install`. +This also installs the protocol buffer compiler `protoc` (if you don't have it already), +and the C++ gRPC plugin for `protoc`. + +WARNING: After installing with `make install` there is no easy way to uninstall, which can cause issues +if you later want to remove the grpc and/or protobuf installation or upgrade to a newer version. + +## Packaging systems + We do not officially support any packaging system for C++, but there are some community-maintained packages that are kept up-to-date and are known to work well. More contributions and support for popular packaging systems are welcome! - + ### Install using vcpkg package gRPC is available using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: - + ``` # install vcpkg package manager on your system using the official instructions git clone https://github.com/Microsoft/vcpkg.git @@ -157,8 +157,8 @@ vcpkg install grpc The gRPC port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. -## Examples & Additional Documentation - +## Examples & Additional Documentation + You can find out how to build and run our simplest gRPC C++ example in our [C++ quick start](../../examples/cpp). @@ -175,6 +175,6 @@ documentation site at [grpc.io](https://grpc.io), specifically: APIs. -# To start developing gRPC C++ +# To start developing gRPC C++ -For instructions on how to build gRPC C++ from source, follow the [Building gRPC C++](../../BUILDING.md) instructions. +For instructions on how to build gRPC C++ from source, follow the [Building gRPC C++](../../BUILDING.md) instructions. diff --git a/contrib/libs/grpc/src/cpp/client/channel_cc.cc b/contrib/libs/grpc/src/cpp/client/channel_cc.cc index ac95c29efc..fab05f2ac4 100644 --- a/contrib/libs/grpc/src/cpp/client/channel_cc.cc +++ b/contrib/libs/grpc/src/cpp/client/channel_cc.cc @@ -18,7 +18,7 @@ #include <grpcpp/channel.h> -#include <cstring> +#include <cstring> #include <memory> #include <grpc/grpc.h> @@ -30,7 +30,7 @@ #include <grpcpp/client_context.h> #include <grpcpp/completion_queue.h> #include <grpcpp/impl/call.h> -#include <grpcpp/impl/codegen/call_op_set.h> +#include <grpcpp/impl/codegen/call_op_set.h> #include <grpcpp/impl/codegen/completion_queue_tag.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/impl/rpc_method.h> @@ -39,7 +39,7 @@ #include <grpcpp/support/config.h> #include <grpcpp/support/status.h> #include "src/core/lib/gpr/string.h" -#include "src/core/lib/surface/completion_queue.h" +#include "src/core/lib/surface/completion_queue.h" namespace grpc { @@ -49,23 +49,23 @@ Channel::Channel(const TString& host, grpc_channel* channel, ::grpc::experimental::ClientInterceptorFactoryInterface>> interceptor_creators) : host_(host), c_channel_(channel) { - interceptor_creators_ = std::move(interceptor_creators); + interceptor_creators_ = std::move(interceptor_creators); g_gli_initializer.summon(); } -Channel::~Channel() { - grpc_channel_destroy(c_channel_); - if (callback_cq_ != nullptr) { - callback_cq_->Shutdown(); - } -} +Channel::~Channel() { + grpc_channel_destroy(c_channel_); + if (callback_cq_ != nullptr) { + callback_cq_->Shutdown(); + } +} namespace { -inline grpc_slice SliceFromArray(const char* arr, size_t len) { +inline grpc_slice SliceFromArray(const char* arr, size_t len) { return g_core_codegen_interface->grpc_slice_from_copied_buffer(arr, len); -} - +} + TString GetChannelInfoField(grpc_channel* channel, grpc_channel_info* channel_info, char*** channel_info_field) { @@ -93,14 +93,14 @@ TString Channel::GetServiceConfigJSON() const { &channel_info.service_config_json); } -namespace experimental { - -void ChannelResetConnectionBackoff(Channel* channel) { - grpc_channel_reset_connect_backoff(channel->c_channel_); -} - -} // namespace experimental - +namespace experimental { + +void ChannelResetConnectionBackoff(Channel* channel) { + grpc_channel_reset_connect_backoff(channel->c_channel_); +} + +} // namespace experimental + ::grpc::internal::Call Channel::CreateCallInternal( const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, size_t interceptor_pos) { @@ -113,13 +113,13 @@ void ChannelResetConnectionBackoff(Channel* channel) { method.channel_tag(), context->raw_deadline(), nullptr); } else { const ::TString* host_str = nullptr; - if (!context->authority_.empty()) { - host_str = &context->authority_; + if (!context->authority_.empty()) { + host_str = &context->authority_; } else if (!host_.empty()) { - host_str = &host_; + host_str = &host_; } - grpc_slice method_slice = - SliceFromArray(method.name(), strlen(method.name())); + grpc_slice method_slice = + SliceFromArray(method.name(), strlen(method.name())); grpc_slice host_slice; if (host_str != nullptr) { host_slice = ::grpc::SliceFromCopiedString(*host_str); @@ -135,28 +135,28 @@ void ChannelResetConnectionBackoff(Channel* channel) { } } grpc_census_call_set_context(c_call, context->census_context()); - - // ClientRpcInfo should be set before call because set_call also checks - // whether the call has been cancelled, and if the call was cancelled, we + + // ClientRpcInfo should be set before call because set_call also checks + // whether the call has been cancelled, and if the call was cancelled, we // should notify the interceptors too. - auto* info = - context->set_client_rpc_info(method.name(), method.method_type(), this, - interceptor_creators_, interceptor_pos); + auto* info = + context->set_client_rpc_info(method.name(), method.method_type(), this, + interceptor_creators_, interceptor_pos); context->set_call(c_call, shared_from_this()); - + return ::grpc::internal::Call(c_call, this, cq, info); } ::grpc::internal::Call Channel::CreateCall( const ::grpc::internal::RpcMethod& method, ::grpc::ClientContext* context, CompletionQueue* cq) { - return CreateCallInternal(method, context, cq, 0); -} - + return CreateCallInternal(method, context, cq, 0); +} + void Channel::PerformOpsOnCall(::grpc::internal::CallOpSetInterface* ops, ::grpc::internal::Call* call) { - ops->FillOps( - call); // Make a copy of call. It's fine since Call just has pointers + ops->FillOps( + call); // Make a copy of call. It's fine since Call just has pointers } void* Channel::RegisterMethod(const char* method) { @@ -205,9 +205,9 @@ bool Channel::WaitForStateChangeImpl(grpc_connectivity_state last_observed, return ok; } -namespace { -class ShutdownCallback : public grpc_experimental_completion_queue_functor { - public: +namespace { +class ShutdownCallback : public grpc_experimental_completion_queue_functor { + public: ShutdownCallback() { functor_run = &ShutdownCallback::Run; // Set inlineable to true since this callback is trivial and thus does not @@ -216,37 +216,37 @@ class ShutdownCallback : public grpc_experimental_completion_queue_functor { // code. inlineable = true; } - // TakeCQ takes ownership of the cq into the shutdown callback - // so that the shutdown callback will be responsible for destroying it + // TakeCQ takes ownership of the cq into the shutdown callback + // so that the shutdown callback will be responsible for destroying it void TakeCQ(::grpc::CompletionQueue* cq) { cq_ = cq; } - - // The Run function will get invoked by the completion queue library - // when the shutdown is actually complete - static void Run(grpc_experimental_completion_queue_functor* cb, int) { - auto* callback = static_cast<ShutdownCallback*>(cb); - delete callback->cq_; - delete callback; - } - - private: + + // The Run function will get invoked by the completion queue library + // when the shutdown is actually complete + static void Run(grpc_experimental_completion_queue_functor* cb, int) { + auto* callback = static_cast<ShutdownCallback*>(cb); + delete callback->cq_; + delete callback; + } + + private: ::grpc::CompletionQueue* cq_ = nullptr; -}; -} // namespace - +}; +} // namespace + ::grpc::CompletionQueue* Channel::CallbackCQ() { - // TODO(vjpai): Consider using a single global CQ for the default CQ - // if there is no explicit per-channel CQ registered + // TODO(vjpai): Consider using a single global CQ for the default CQ + // if there is no explicit per-channel CQ registered grpc::internal::MutexLock l(&mu_); - if (callback_cq_ == nullptr) { - auto* shutdown_callback = new ShutdownCallback; + if (callback_cq_ == nullptr) { + auto* shutdown_callback = new ShutdownCallback; callback_cq_ = new ::grpc::CompletionQueue(grpc_completion_queue_attributes{ - GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING, - shutdown_callback}); - - // Transfer ownership of the new cq to its own shutdown callback - shutdown_callback->TakeCQ(callback_cq_); - } - return callback_cq_; -} - + GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING, + shutdown_callback}); + + // Transfer ownership of the new cq to its own shutdown callback + shutdown_callback->TakeCQ(callback_cq_); + } + return callback_cq_; +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/client_context.cc b/contrib/libs/grpc/src/cpp/client/client_context.cc index b75343d089..b8b123ef37 100644 --- a/contrib/libs/grpc/src/cpp/client/client_context.cc +++ b/contrib/libs/grpc/src/cpp/client/client_context.cc @@ -24,7 +24,7 @@ #include <grpc/support/log.h> #include <grpc/support/string_util.h> -#include <grpcpp/impl/codegen/interceptor_common.h> +#include <grpcpp/impl/codegen/interceptor_common.h> #include <grpcpp/impl/codegen/sync.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/security/credentials.h> @@ -44,10 +44,10 @@ class DefaultGlobalClientCallbacks final }; static internal::GrpcLibraryInitializer g_gli_initializer; -static DefaultGlobalClientCallbacks* g_default_client_callbacks = - new DefaultGlobalClientCallbacks(); +static DefaultGlobalClientCallbacks* g_default_client_callbacks = + new DefaultGlobalClientCallbacks(); static ClientContext::GlobalCallbacks* g_client_callbacks = - g_default_client_callbacks; + g_default_client_callbacks; ClientContext::ClientContext() : initial_metadata_received_(false), @@ -60,7 +60,7 @@ ClientContext::ClientContext() deadline_(gpr_inf_future(GPR_CLOCK_REALTIME)), census_context_(nullptr), propagate_from_call_(nullptr), - compression_algorithm_(GRPC_COMPRESS_NONE), + compression_algorithm_(GRPC_COMPRESS_NONE), initial_metadata_corked_(false) { g_client_callbacks->DefaultConstructor(this); } @@ -119,13 +119,13 @@ void ClientContext::set_call(grpc_call* call, call_ = call; channel_ = channel; if (creds_ && !creds_->ApplyToCall(call_)) { - // TODO(yashykt): should interceptors also see this status? - SendCancelToInterceptors(); + // TODO(yashykt): should interceptors also see this status? + SendCancelToInterceptors(); grpc_call_cancel_with_status(call, GRPC_STATUS_CANCELLED, "Failed to set credentials to rpc.", nullptr); } if (call_canceled_) { - SendCancelToInterceptors(); + SendCancelToInterceptors(); grpc_call_cancel(call_, nullptr); } } @@ -146,20 +146,20 @@ void ClientContext::set_compression_algorithm( void ClientContext::TryCancel() { internal::MutexLock lock(&mu_); if (call_) { - SendCancelToInterceptors(); + SendCancelToInterceptors(); grpc_call_cancel(call_, nullptr); } else { call_canceled_ = true; } } -void ClientContext::SendCancelToInterceptors() { +void ClientContext::SendCancelToInterceptors() { internal::CancelInterceptorBatchMethods cancel_methods; - for (size_t i = 0; i < rpc_info_.interceptors_.size(); i++) { - rpc_info_.RunInterceptor(&cancel_methods, i); - } -} - + for (size_t i = 0; i < rpc_info_.interceptors_.size(); i++) { + rpc_info_.RunInterceptor(&cancel_methods, i); + } +} + TString ClientContext::peer() const { TString peer; if (call_) { @@ -171,9 +171,9 @@ TString ClientContext::peer() const { } void ClientContext::SetGlobalCallbacks(GlobalCallbacks* client_callbacks) { - GPR_ASSERT(g_client_callbacks == g_default_client_callbacks); + GPR_ASSERT(g_client_callbacks == g_default_client_callbacks); GPR_ASSERT(client_callbacks != nullptr); - GPR_ASSERT(client_callbacks != g_default_client_callbacks); + GPR_ASSERT(client_callbacks != g_default_client_callbacks); g_client_callbacks = client_callbacks; } diff --git a/contrib/libs/grpc/src/cpp/client/client_interceptor.cc b/contrib/libs/grpc/src/cpp/client/client_interceptor.cc index a91950cae2..9d98a60171 100644 --- a/contrib/libs/grpc/src/cpp/client/client_interceptor.cc +++ b/contrib/libs/grpc/src/cpp/client/client_interceptor.cc @@ -1,44 +1,44 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpcpp/impl/codegen/client_interceptor.h> - -namespace grpc { - -namespace internal { -experimental::ClientInterceptorFactoryInterface* - g_global_client_interceptor_factory = nullptr; -} - -namespace experimental { -void RegisterGlobalClientInterceptorFactory( - ClientInterceptorFactoryInterface* factory) { +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpcpp/impl/codegen/client_interceptor.h> + +namespace grpc { + +namespace internal { +experimental::ClientInterceptorFactoryInterface* + g_global_client_interceptor_factory = nullptr; +} + +namespace experimental { +void RegisterGlobalClientInterceptorFactory( + ClientInterceptorFactoryInterface* factory) { if (internal::g_global_client_interceptor_factory != nullptr) { GPR_ASSERT(false && "It is illegal to call RegisterGlobalClientInterceptorFactory " "multiple times."); } - internal::g_global_client_interceptor_factory = factory; -} + internal::g_global_client_interceptor_factory = factory; +} // For testing purposes only. void TestOnlyResetGlobalClientInterceptorFactory() { internal::g_global_client_interceptor_factory = nullptr; } -} // namespace experimental -} // namespace grpc +} // namespace experimental +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/create_channel.cc b/contrib/libs/grpc/src/cpp/client/create_channel.cc index 97327490ed..941c2e9290 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel.cc +++ b/contrib/libs/grpc/src/cpp/client/create_channel.cc @@ -41,45 +41,45 @@ std::shared_ptr<grpc::Channel> CreateCustomChannel( init_lib; // We need to call init in case of bad creds. return creds ? creds->CreateChannelImpl(target, args) : grpc::CreateChannelInternal( - "", - grpc_lame_client_channel_create( - nullptr, GRPC_STATUS_INVALID_ARGUMENT, - "Invalid credentials."), - std::vector<std::unique_ptr< + "", + grpc_lame_client_channel_create( + nullptr, GRPC_STATUS_INVALID_ARGUMENT, + "Invalid credentials."), + std::vector<std::unique_ptr< grpc::experimental:: ClientInterceptorFactoryInterface>>()); } -namespace experimental { -/// Create a new \em custom \a Channel pointing to \a target with \a -/// interceptors being invoked per call. -/// -/// \warning For advanced use and testing ONLY. Override default channel -/// arguments only if necessary. -/// -/// \param target The URI of the endpoint to connect to. -/// \param creds Credentials to use for the created channel. If it does not -/// hold an object or is invalid, a lame channel (one on which all operations -/// fail) is returned. -/// \param args Options for channel creation. +namespace experimental { +/// Create a new \em custom \a Channel pointing to \a target with \a +/// interceptors being invoked per call. +/// +/// \warning For advanced use and testing ONLY. Override default channel +/// arguments only if necessary. +/// +/// \param target The URI of the endpoint to connect to. +/// \param creds Credentials to use for the created channel. If it does not +/// hold an object or is invalid, a lame channel (one on which all operations +/// fail) is returned. +/// \param args Options for channel creation. std::shared_ptr<grpc::Channel> CreateCustomChannelWithInterceptors( const TString& target, const std::shared_ptr<grpc::ChannelCredentials>& creds, const grpc::ChannelArguments& args, - std::vector< + std::vector< std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) { + interceptor_creators) { grpc::GrpcLibraryCodegen init_lib; // We need to call init in case of bad creds. - return creds ? creds->CreateChannelWithInterceptors( - target, args, std::move(interceptor_creators)) + return creds ? creds->CreateChannelWithInterceptors( + target, args, std::move(interceptor_creators)) : grpc::CreateChannelInternal( - "", - grpc_lame_client_channel_create( - nullptr, GRPC_STATUS_INVALID_ARGUMENT, - "Invalid credentials."), + "", + grpc_lame_client_channel_create( + nullptr, GRPC_STATUS_INVALID_ARGUMENT, + "Invalid credentials."), std::move(interceptor_creators)); -} -} // namespace experimental - +} +} // namespace experimental + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc index da2a878a22..8e85dbc7ab 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc +++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.cc @@ -24,13 +24,13 @@ struct grpc_channel; namespace grpc { -std::shared_ptr<Channel> CreateChannelInternal( +std::shared_ptr<Channel> CreateChannelInternal( const TString& host, grpc_channel* c_channel, std::vector<std::unique_ptr< ::grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) { - return std::shared_ptr<Channel>( - new Channel(host, c_channel, std::move(interceptor_creators))); + interceptor_creators) { + return std::shared_ptr<Channel>( + new Channel(host, c_channel, std::move(interceptor_creators))); } } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h index 09d4e56b02..d19a63b3c7 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel_internal.h +++ b/contrib/libs/grpc/src/cpp/client/create_channel_internal.h @@ -22,18 +22,18 @@ #include <memory> #include <grpcpp/channel.h> -#include <grpcpp/impl/codegen/client_interceptor.h> +#include <grpcpp/impl/codegen/client_interceptor.h> #include <grpcpp/support/config.h> struct grpc_channel; namespace grpc { -std::shared_ptr<Channel> CreateChannelInternal( +std::shared_ptr<Channel> CreateChannelInternal( const TString& host, grpc_channel* c_channel, std::vector<std::unique_ptr< ::grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators); + interceptor_creators); } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc index db09eda8a6..a10abb759e 100644 --- a/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc +++ b/contrib/libs/grpc/src/cpp/client/create_channel_posix.cc @@ -35,7 +35,7 @@ std::shared_ptr<Channel> CreateInsecureChannelFromFd(const TString& target, grpc::internal::GrpcLibrary init_lib; init_lib.init(); return CreateChannelInternal( - "", grpc_insecure_channel_create_from_fd(target.c_str(), fd, nullptr), + "", grpc_insecure_channel_create_from_fd(target.c_str(), fd, nullptr), std::vector< std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>()); } @@ -47,31 +47,31 @@ std::shared_ptr<Channel> CreateCustomInsecureChannelFromFd( grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); return CreateChannelInternal( - "", - grpc_insecure_channel_create_from_fd(target.c_str(), fd, &channel_args), + "", + grpc_insecure_channel_create_from_fd(target.c_str(), fd, &channel_args), std::vector< std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>()); } -namespace experimental { - +namespace experimental { + std::shared_ptr<Channel> CreateCustomInsecureChannelWithInterceptorsFromFd( const TString& target, int fd, const ChannelArguments& args, - std::vector< + std::vector< std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) { + interceptor_creators) { grpc::internal::GrpcLibrary init_lib; - init_lib.init(); - grpc_channel_args channel_args; - args.SetChannelArgs(&channel_args); + init_lib.init(); + grpc_channel_args channel_args; + args.SetChannelArgs(&channel_args); return CreateChannelInternal( - "", - grpc_insecure_channel_create_from_fd(target.c_str(), fd, &channel_args), - std::move(interceptor_creators)); -} - -} // namespace experimental - + "", + grpc_insecure_channel_create_from_fd(target.c_str(), fd, &channel_args), + std::move(interceptor_creators)); +} + +} // namespace experimental + #endif // GPR_SUPPORT_CHANNELS_FROM_FD } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc index e5bafff70a..ac42944520 100644 --- a/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc +++ b/contrib/libs/grpc/src/cpp/client/insecure_credentials.cc @@ -31,23 +31,23 @@ class InsecureChannelCredentialsImpl final : public ChannelCredentials { public: std::shared_ptr<Channel> CreateChannelImpl( const TString& target, const ChannelArguments& args) override { - return CreateChannelWithInterceptors( - target, args, - std::vector<std::unique_ptr< + return CreateChannelWithInterceptors( + target, args, + std::vector<std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface>>()); - } - + } + std::shared_ptr<Channel> CreateChannelWithInterceptors( const TString& target, const ChannelArguments& args, std::vector<std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) override { + interceptor_creators) override { grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); return ::grpc::CreateChannelInternal( "", - grpc_insecure_channel_create(target.c_str(), &channel_args, nullptr), - std::move(interceptor_creators)); + grpc_insecure_channel_create(target.c_str(), &channel_args, nullptr), + std::move(interceptor_creators)); } SecureChannelCredentials* AsSecureCredentials() override { return nullptr; } diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc index 0f6db3caa5..cb9ffd3e84 100644 --- a/contrib/libs/grpc/src/cpp/client/secure_credentials.cc +++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.cc @@ -49,25 +49,25 @@ SecureChannelCredentials::SecureChannelCredentials( std::shared_ptr<Channel> SecureChannelCredentials::CreateChannelImpl( const TString& target, const ChannelArguments& args) { - return CreateChannelWithInterceptors( - target, args, + return CreateChannelWithInterceptors( + target, args, std::vector<std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface>>()); -} - +} + std::shared_ptr<Channel> -SecureChannelCredentials::CreateChannelWithInterceptors( +SecureChannelCredentials::CreateChannelWithInterceptors( const TString& target, const ChannelArguments& args, - std::vector< + std::vector< std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) { + interceptor_creators) { grpc_channel_args channel_args; args.SetChannelArgs(&channel_args); return ::grpc::CreateChannelInternal( args.GetSslTargetNameOverride(), grpc_secure_channel_create(c_creds_, target.c_str(), &channel_args, - nullptr), - std::move(interceptor_creators)); + nullptr), + std::move(interceptor_creators)); } SecureCallCredentials::SecureCallCredentials(grpc_call_credentials* c_creds) @@ -110,8 +110,8 @@ std::shared_ptr<ChannelCredentials> SslCredentials( grpc_channel_credentials* c_creds = grpc_ssl_credentials_create( options.pem_root_certs.empty() ? nullptr : options.pem_root_certs.c_str(), - options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr, - nullptr); + options.pem_private_key.empty() ? nullptr : &pem_key_cert_pair, nullptr, + nullptr); return WrapChannelCredentials(c_creds); } @@ -280,13 +280,13 @@ std::shared_ptr<ChannelCredentials> AltsCredentials( return WrapChannelCredentials(c_creds); } -// Builds Local Credentials -std::shared_ptr<ChannelCredentials> LocalCredentials( - grpc_local_connect_type type) { +// Builds Local Credentials +std::shared_ptr<ChannelCredentials> LocalCredentials( + grpc_local_connect_type type) { grpc::GrpcLibraryCodegen init; // To call grpc_init(). - return WrapChannelCredentials(grpc_local_credentials_create(type)); -} - + return WrapChannelCredentials(grpc_local_credentials_create(type)); +} + // Builds TLS Credentials given TLS options. std::shared_ptr<ChannelCredentials> TlsCredentials( const TlsCredentialsOptions& options) { @@ -433,10 +433,10 @@ int MetadataCredentialsPluginWrapper::GetMetadata( grpc_auth_metadata_context_copy(&context, &context_copy); // Asynchronous return. w->thread_pool_->Add([w, context_copy, cb, user_data]() mutable { - w->MetadataCredentialsPluginWrapper::InvokePlugin( + w->MetadataCredentialsPluginWrapper::InvokePlugin( context_copy, cb, user_data, nullptr, nullptr, nullptr, nullptr); grpc_auth_metadata_context_reset(&context_copy); - }); + }); return 0; } else { // Synchronous return. @@ -463,10 +463,10 @@ void MetadataCredentialsPluginWrapper::InvokePlugin( grpc_status_code* status_code, const char** error_details) { std::multimap<TString, TString> metadata; - // const_cast is safe since the SecureAuthContext only inc/dec the refcount - // and the object is passed as a const ref to plugin_->GetMetadata. + // const_cast is safe since the SecureAuthContext only inc/dec the refcount + // and the object is passed as a const ref to plugin_->GetMetadata. SecureAuthContext cpp_channel_auth_context( - const_cast<grpc_auth_context*>(context.channel_auth_context)); + const_cast<grpc_auth_context*>(context.channel_auth_context)); Status status = plugin_->GetMetadata(context.service_url, context.method_name, cpp_channel_auth_context, &metadata); diff --git a/contrib/libs/grpc/src/cpp/client/secure_credentials.h b/contrib/libs/grpc/src/cpp/client/secure_credentials.h index 4fc79346bf..329c003474 100644 --- a/contrib/libs/grpc/src/cpp/client/secure_credentials.h +++ b/contrib/libs/grpc/src/cpp/client/secure_credentials.h @@ -26,7 +26,7 @@ #include <grpcpp/support/config.h> #include "y_absl/strings/str_cat.h" -#include "src/core/lib/security/credentials/credentials.h" +#include "src/core/lib/security/credentials/credentials.h" #include "src/cpp/server/thread_pool_interface.h" namespace grpc { @@ -36,14 +36,14 @@ class Channel; class SecureChannelCredentials final : public ChannelCredentials { public: explicit SecureChannelCredentials(grpc_channel_credentials* c_creds); - ~SecureChannelCredentials() { - if (c_creds_ != nullptr) c_creds_->Unref(); - } + ~SecureChannelCredentials() { + if (c_creds_ != nullptr) c_creds_->Unref(); + } grpc_channel_credentials* GetRawCreds() { return c_creds_; } std::shared_ptr<Channel> CreateChannelImpl( const TString& target, const ChannelArguments& args) override; - + SecureChannelCredentials* AsSecureCredentials() override { return this; } private: @@ -51,16 +51,16 @@ class SecureChannelCredentials final : public ChannelCredentials { const TString& target, const ChannelArguments& args, std::vector<std::unique_ptr< ::grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) override; + interceptor_creators) override; grpc_channel_credentials* const c_creds_; }; class SecureCallCredentials final : public CallCredentials { public: explicit SecureCallCredentials(grpc_call_credentials* c_creds); - ~SecureCallCredentials() { - if (c_creds_ != nullptr) c_creds_->Unref(); - } + ~SecureCallCredentials() { + if (c_creds_ != nullptr) c_creds_->Unref(); + } grpc_call_credentials* GetRawCreds() { return c_creds_; } bool ApplyToCall(grpc_call* call) override; diff --git a/contrib/libs/grpc/src/cpp/common/alarm.cc b/contrib/libs/grpc/src/cpp/common/alarm.cc index a2612874b2..83de2f2d3f 100644 --- a/contrib/libs/grpc/src/cpp/common/alarm.cc +++ b/contrib/libs/grpc/src/cpp/common/alarm.cc @@ -35,25 +35,25 @@ namespace grpc { namespace internal { -class AlarmImpl : public ::grpc::internal::CompletionQueueTag { +class AlarmImpl : public ::grpc::internal::CompletionQueueTag { public: AlarmImpl() : cq_(nullptr), tag_(nullptr) { gpr_ref_init(&refs_, 1); grpc_timer_init_unset(&timer_); - } - ~AlarmImpl() {} + } + ~AlarmImpl() {} bool FinalizeResult(void** tag, bool* /*status*/) override { - *tag = tag_; - Unref(); - return true; - } - void Set(::grpc::CompletionQueue* cq, gpr_timespec deadline, void* tag) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; - grpc_core::ExecCtx exec_ctx; - GRPC_CQ_INTERNAL_REF(cq->cq(), "alarm"); - cq_ = cq->cq(); - tag_ = tag; - GPR_ASSERT(grpc_cq_begin_op(cq_, this)); + *tag = tag_; + Unref(); + return true; + } + void Set(::grpc::CompletionQueue* cq, gpr_timespec deadline, void* tag) { + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ExecCtx exec_ctx; + GRPC_CQ_INTERNAL_REF(cq->cq(), "alarm"); + cq_ = cq->cq(); + tag_ = tag; + GPR_ASSERT(grpc_cq_begin_op(cq_, this)); GRPC_CLOSURE_INIT( &on_alarm_, [](void* arg, grpc_error* error) { @@ -71,17 +71,17 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag { GRPC_CQ_INTERNAL_UNREF(cq, "alarm"); }, this, grpc_schedule_on_exec_ctx); - grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline), - &on_alarm_); + grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline), + &on_alarm_); } - void Set(gpr_timespec deadline, std::function<void(bool)> f) { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + void Set(gpr_timespec deadline, std::function<void(bool)> f) { + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; - // Don't use any CQ at all. Instead just use the timer to fire the function - callback_ = std::move(f); - Ref(); - GRPC_CLOSURE_INIT(&on_alarm_, - [](void* arg, grpc_error* error) { + // Don't use any CQ at all. Instead just use the timer to fire the function + callback_ = std::move(f); + Ref(); + GRPC_CLOSURE_INIT(&on_alarm_, + [](void* arg, grpc_error* error) { grpc_core::Executor::Run( GRPC_CLOSURE_CREATE( [](void* arg, grpc_error* error) { @@ -92,13 +92,13 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag { }, arg, nullptr), error); - }, - this, grpc_schedule_on_exec_ctx); + }, + this, grpc_schedule_on_exec_ctx); grpc_timer_init(&timer_, grpc_timespec_to_millis_round_up(deadline), &on_alarm_); } void Cancel() { - grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; + grpc_core::ApplicationCallbackExecCtx callback_exec_ctx; grpc_core::ExecCtx exec_ctx; grpc_timer_cancel(&timer_); } @@ -122,18 +122,18 @@ class AlarmImpl : public ::grpc::internal::CompletionQueueTag { // completion queue where events about this alarm will be posted grpc_completion_queue* cq_; void* tag_; - std::function<void(bool)> callback_; + std::function<void(bool)> callback_; }; } // namespace internal -static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer; +static ::grpc::internal::GrpcLibraryInitializer g_gli_initializer; Alarm::Alarm() : alarm_(new internal::AlarmImpl()) { g_gli_initializer.summon(); } -void Alarm::SetInternal(::grpc::CompletionQueue* cq, gpr_timespec deadline, - void* tag) { +void Alarm::SetInternal(::grpc::CompletionQueue* cq, gpr_timespec deadline, + void* tag) { // Note that we know that alarm_ is actually an internal::AlarmImpl // but we declared it as the base pointer to avoid a forward declaration // or exposing core data structures in the C++ public headers. @@ -142,15 +142,15 @@ void Alarm::SetInternal(::grpc::CompletionQueue* cq, gpr_timespec deadline, static_cast<internal::AlarmImpl*>(alarm_)->Set(cq, deadline, tag); } -void Alarm::SetInternal(gpr_timespec deadline, std::function<void(bool)> f) { - // Note that we know that alarm_ is actually an internal::AlarmImpl - // but we declared it as the base pointer to avoid a forward declaration - // or exposing core data structures in the C++ public headers. - // Thus it is safe to use a static_cast to the subclass here, and the - // C++ style guide allows us to do so in this case - static_cast<internal::AlarmImpl*>(alarm_)->Set(deadline, std::move(f)); -} - +void Alarm::SetInternal(gpr_timespec deadline, std::function<void(bool)> f) { + // Note that we know that alarm_ is actually an internal::AlarmImpl + // but we declared it as the base pointer to avoid a forward declaration + // or exposing core data structures in the C++ public headers. + // Thus it is safe to use a static_cast to the subclass here, and the + // C++ style guide allows us to do so in this case + static_cast<internal::AlarmImpl*>(alarm_)->Set(deadline, std::move(f)); +} + Alarm::~Alarm() { if (alarm_ != nullptr) { static_cast<internal::AlarmImpl*>(alarm_)->Destroy(); diff --git a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc index 5a5dd91b5e..23be69f72a 100644 --- a/contrib/libs/grpc/src/cpp/common/channel_arguments.cc +++ b/contrib/libs/grpc/src/cpp/common/channel_arguments.cc @@ -108,7 +108,7 @@ void ChannelArguments::SetSocketMutator(grpc_socket_mutator* mutator) { if (!replaced) { strings_.push_back(TString(mutator_arg.key)); args_.push_back(mutator_arg); - args_.back().key = const_cast<char*>(strings_.back().c_str()); + args_.back().key = const_cast<char*>(strings_.back().c_str()); } } diff --git a/contrib/libs/grpc/src/cpp/common/channel_filter.h b/contrib/libs/grpc/src/cpp/common/channel_filter.h index 5ce720b307..fab1c7744f 100644 --- a/contrib/libs/grpc/src/cpp/common/channel_filter.h +++ b/contrib/libs/grpc/src/cpp/common/channel_filter.h @@ -207,18 +207,18 @@ class TransportStreamOpBatch { op_->payload->context[GRPC_CONTEXT_TRACING].value); } - const gpr_atm* get_peer_string() const { - if (op_->send_initial_metadata && - op_->payload->send_initial_metadata.peer_string != nullptr) { - return op_->payload->send_initial_metadata.peer_string; - } else if (op_->recv_initial_metadata && - op_->payload->recv_initial_metadata.peer_string != nullptr) { - return op_->payload->recv_initial_metadata.peer_string; - } else { - return nullptr; - } - } - + const gpr_atm* get_peer_string() const { + if (op_->send_initial_metadata && + op_->payload->send_initial_metadata.peer_string != nullptr) { + return op_->payload->send_initial_metadata.peer_string; + } else if (op_->recv_initial_metadata && + op_->payload->recv_initial_metadata.peer_string != nullptr) { + return op_->payload->recv_initial_metadata.peer_string; + } else { + return nullptr; + } + } + private: grpc_transport_stream_op_batch* op_; // Not owned. MetadataBatch send_initial_metadata_; @@ -366,11 +366,11 @@ void ChannelFilterPluginShutdown(); /// The \a include_filter argument specifies a function that will be called /// to determine at run-time whether or not to add the filter. If the /// value is nullptr, the filter will be added unconditionally. -/// If the channel stack type is GRPC_CLIENT_SUBCHANNEL, the caller should -/// ensure that subchannels with different filter lists will always have -/// different channel args. This requires setting a channel arg in case the -/// registration function relies on some condition other than channel args to -/// decide whether to add a filter or not. +/// If the channel stack type is GRPC_CLIENT_SUBCHANNEL, the caller should +/// ensure that subchannels with different filter lists will always have +/// different channel args. This requires setting a channel arg in case the +/// registration function relies on some condition other than channel args to +/// decide whether to add a filter or not. template <typename ChannelDataType, typename CallDataType> void RegisterChannelFilter( const char* name, grpc_channel_stack_type stack_type, int priority, diff --git a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc index 96a7105eaf..109b2ceb02 100644 --- a/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc +++ b/contrib/libs/grpc/src/cpp/common/completion_queue_cc.cc @@ -61,8 +61,8 @@ CompletionQueue::NextStatus CompletionQueue::AsyncNextInternal( auto core_cq_tag = static_cast<::grpc::internal::CompletionQueueTag*>(ev.tag); *ok = ev.success != 0; - *tag = core_cq_tag; - if (core_cq_tag->FinalizeResult(tag, ok)) { + *tag = core_cq_tag; + if (core_cq_tag->FinalizeResult(tag, ok)) { return GOT_EVENT; } break; @@ -89,7 +89,7 @@ bool CompletionQueue::CompletionQueueTLSCache::Flush(void** tag, bool* ok) { auto core_cq_tag = static_cast<::grpc::internal::CompletionQueueTag*>(res_tag); *ok = res == 1; - if (core_cq_tag->FinalizeResult(tag, ok)) { + if (core_cq_tag->FinalizeResult(tag, ok)) { return true; } } diff --git a/contrib/libs/grpc/src/cpp/common/core_codegen.cc b/contrib/libs/grpc/src/cpp/common/core_codegen.cc index 75383ed511..794154f79c 100644 --- a/contrib/libs/grpc/src/cpp/common/core_codegen.cc +++ b/contrib/libs/grpc/src/cpp/common/core_codegen.cc @@ -59,10 +59,10 @@ grpc_completion_queue* CoreCodegen::grpc_completion_queue_create_for_pluck( return ::grpc_completion_queue_create_for_pluck(reserved); } -void CoreCodegen::grpc_completion_queue_shutdown(grpc_completion_queue* cq) { - ::grpc_completion_queue_shutdown(cq); -} - +void CoreCodegen::grpc_completion_queue_shutdown(grpc_completion_queue* cq) { + ::grpc_completion_queue_shutdown(cq); +} + void CoreCodegen::grpc_completion_queue_destroy(grpc_completion_queue* cq) { ::grpc_completion_queue_destroy(cq); } @@ -106,13 +106,13 @@ size_t CoreCodegen::grpc_byte_buffer_length(grpc_byte_buffer* bb) { return ::grpc_byte_buffer_length(bb); } -grpc_call_error CoreCodegen::grpc_call_start_batch(grpc_call* call, - const grpc_op* ops, - size_t nops, void* tag, - void* reserved) { - return ::grpc_call_start_batch(call, ops, nops, tag, reserved); -} - +grpc_call_error CoreCodegen::grpc_call_start_batch(grpc_call* call, + const grpc_op* ops, + size_t nops, void* tag, + void* reserved) { + return ::grpc_call_start_batch(call, ops, nops, tag, reserved); +} + grpc_call_error CoreCodegen::grpc_call_cancel_with_status( grpc_call* call, grpc_status_code status, const char* description, void* reserved) { diff --git a/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc b/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc index 64abff9633..a4afbae45a 100644 --- a/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc +++ b/contrib/libs/grpc/src/cpp/common/resource_quota_cc.cc @@ -33,8 +33,8 @@ ResourceQuota& ResourceQuota::Resize(size_t new_size) { return *this; } -ResourceQuota& ResourceQuota::SetMaxThreads(int new_max_threads) { - grpc_resource_quota_set_max_threads(impl_, new_max_threads); - return *this; -} +ResourceQuota& ResourceQuota::SetMaxThreads(int new_max_threads) { + grpc_resource_quota_set_max_threads(impl_, new_max_threads); + return *this; +} } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc b/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc index e1f97889c8..9690358343 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc +++ b/contrib/libs/grpc/src/cpp/common/secure_auth_context.cc @@ -23,11 +23,11 @@ namespace grpc { std::vector<grpc::string_ref> SecureAuthContext::GetPeerIdentity() const { - if (ctx_ == nullptr) { + if (ctx_ == nullptr) { return std::vector<grpc::string_ref>(); } - grpc_auth_property_iterator iter = - grpc_auth_context_peer_identity(ctx_.get()); + grpc_auth_property_iterator iter = + grpc_auth_context_peer_identity(ctx_.get()); std::vector<grpc::string_ref> identity; const grpc_auth_property* property = nullptr; while ((property = grpc_auth_property_iterator_next(&iter))) { @@ -38,20 +38,20 @@ std::vector<grpc::string_ref> SecureAuthContext::GetPeerIdentity() const { } TString SecureAuthContext::GetPeerIdentityPropertyName() const { - if (ctx_ == nullptr) { + if (ctx_ == nullptr) { return ""; } - const char* name = grpc_auth_context_peer_identity_property_name(ctx_.get()); + const char* name = grpc_auth_context_peer_identity_property_name(ctx_.get()); return name == nullptr ? "" : name; } std::vector<grpc::string_ref> SecureAuthContext::FindPropertyValues( const TString& name) const { - if (ctx_ == nullptr) { + if (ctx_ == nullptr) { return std::vector<grpc::string_ref>(); } grpc_auth_property_iterator iter = - grpc_auth_context_find_properties_by_name(ctx_.get(), name.c_str()); + grpc_auth_context_find_properties_by_name(ctx_.get(), name.c_str()); const grpc_auth_property* property = nullptr; std::vector<grpc::string_ref> values; while ((property = grpc_auth_property_iterator_next(&iter))) { @@ -61,9 +61,9 @@ std::vector<grpc::string_ref> SecureAuthContext::FindPropertyValues( } AuthPropertyIterator SecureAuthContext::begin() const { - if (ctx_ != nullptr) { + if (ctx_ != nullptr) { grpc_auth_property_iterator iter = - grpc_auth_context_property_iterator(ctx_.get()); + grpc_auth_context_property_iterator(ctx_.get()); const grpc_auth_property* property = grpc_auth_property_iterator_next(&iter); return AuthPropertyIterator(property, &iter); @@ -78,20 +78,20 @@ AuthPropertyIterator SecureAuthContext::end() const { void SecureAuthContext::AddProperty(const TString& key, const grpc::string_ref& value) { - if (ctx_ == nullptr) return; - grpc_auth_context_add_property(ctx_.get(), key.c_str(), value.data(), - value.size()); + if (ctx_ == nullptr) return; + grpc_auth_context_add_property(ctx_.get(), key.c_str(), value.data(), + value.size()); } bool SecureAuthContext::SetPeerIdentityPropertyName(const TString& name) { - if (ctx_ == nullptr) return false; - return grpc_auth_context_set_peer_identity_property_name(ctx_.get(), + if (ctx_ == nullptr) return false; + return grpc_auth_context_set_peer_identity_property_name(ctx_.get(), name.c_str()) != 0; } bool SecureAuthContext::IsPeerAuthenticated() const { - if (ctx_ == nullptr) return false; - return grpc_auth_context_peer_is_authenticated(ctx_.get()) != 0; + if (ctx_ == nullptr) return false; + return grpc_auth_context_peer_is_authenticated(ctx_.get()) != 0; } } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/secure_auth_context.h b/contrib/libs/grpc/src/cpp/common/secure_auth_context.h index 51013efac7..40d1007dd6 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_auth_context.h +++ b/contrib/libs/grpc/src/cpp/common/secure_auth_context.h @@ -21,17 +21,17 @@ #include <grpcpp/security/auth_context.h> -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/security/context/security_context.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/security/context/security_context.h" namespace grpc { class SecureAuthContext final : public AuthContext { public: - explicit SecureAuthContext(grpc_auth_context* ctx) - : ctx_(ctx != nullptr ? ctx->Ref() : nullptr) {} + explicit SecureAuthContext(grpc_auth_context* ctx) + : ctx_(ctx != nullptr ? ctx->Ref() : nullptr) {} - ~SecureAuthContext() override = default; + ~SecureAuthContext() override = default; bool IsPeerAuthenticated() const override; @@ -52,7 +52,7 @@ class SecureAuthContext final : public AuthContext { virtual bool SetPeerIdentityPropertyName(const TString& name) override; private: - grpc_core::RefCountedPtr<grpc_auth_context> ctx_; + grpc_core::RefCountedPtr<grpc_auth_context> ctx_; }; } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc b/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc index 908c46629e..5883d5c3a7 100644 --- a/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc +++ b/contrib/libs/grpc/src/cpp/common/secure_create_auth_context.cc @@ -20,7 +20,7 @@ #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpcpp/security/auth_context.h> -#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" #include "src/cpp/common/secure_auth_context.h" namespace grpc { @@ -29,8 +29,8 @@ std::shared_ptr<const AuthContext> CreateAuthContext(grpc_call* call) { if (call == nullptr) { return std::shared_ptr<const AuthContext>(); } - grpc_core::RefCountedPtr<grpc_auth_context> ctx(grpc_call_auth_context(call)); - return std::make_shared<SecureAuthContext>(ctx.get()); + grpc_core::RefCountedPtr<grpc_auth_context> ctx(grpc_call_auth_context(call)); + return std::make_shared<SecureAuthContext>(ctx.get()); } } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc index 6dcf84bf40..b707f3c476 100644 --- a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc +++ b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.cc @@ -1,29 +1,29 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include "src/cpp/server/channelz/channelz_service.h" - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> - -namespace grpc { +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include "src/cpp/server/channelz/channelz_service.h" + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> + +namespace grpc { namespace { @@ -33,121 +33,121 @@ grpc::protobuf::util::Status ParseJson(const char* json_str, options.case_insensitive_enum_parsing = true; return grpc::protobuf::json::JsonStringToMessage(json_str, message, options); } - + } // namespace -Status ChannelzService::GetTopChannels( +Status ChannelzService::GetTopChannels( ServerContext* /*unused*/, const channelz::v1::GetTopChannelsRequest* request, - channelz::v1::GetTopChannelsResponse* response) { - char* json_str = grpc_channelz_get_top_channels(request->start_channel_id()); - if (json_str == nullptr) { - return Status(StatusCode::INTERNAL, - "grpc_channelz_get_top_channels returned null"); - } + channelz::v1::GetTopChannelsResponse* response) { + char* json_str = grpc_channelz_get_top_channels(request->start_channel_id()); + if (json_str == nullptr) { + return Status(StatusCode::INTERNAL, + "grpc_channelz_get_top_channels returned null"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - -Status ChannelzService::GetServers( + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + +Status ChannelzService::GetServers( ServerContext* /*unused*/, const channelz::v1::GetServersRequest* request, - channelz::v1::GetServersResponse* response) { - char* json_str = grpc_channelz_get_servers(request->start_server_id()); - if (json_str == nullptr) { - return Status(StatusCode::INTERNAL, - "grpc_channelz_get_servers returned null"); - } + channelz::v1::GetServersResponse* response) { + char* json_str = grpc_channelz_get_servers(request->start_server_id()); + if (json_str == nullptr) { + return Status(StatusCode::INTERNAL, + "grpc_channelz_get_servers returned null"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + Status ChannelzService::GetServer(ServerContext* /*unused*/, - const channelz::v1::GetServerRequest* request, - channelz::v1::GetServerResponse* response) { - char* json_str = grpc_channelz_get_server(request->server_id()); - if (json_str == nullptr) { - return Status(StatusCode::INTERNAL, - "grpc_channelz_get_server returned null"); - } + const channelz::v1::GetServerRequest* request, + channelz::v1::GetServerResponse* response) { + char* json_str = grpc_channelz_get_server(request->server_id()); + if (json_str == nullptr) { + return Status(StatusCode::INTERNAL, + "grpc_channelz_get_server returned null"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - -Status ChannelzService::GetServerSockets( + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + +Status ChannelzService::GetServerSockets( ServerContext* /*unused*/, const channelz::v1::GetServerSocketsRequest* request, - channelz::v1::GetServerSocketsResponse* response) { - char* json_str = grpc_channelz_get_server_sockets( - request->server_id(), request->start_socket_id(), request->max_results()); - if (json_str == nullptr) { - return Status(StatusCode::INTERNAL, - "grpc_channelz_get_server_sockets returned null"); - } + channelz::v1::GetServerSocketsResponse* response) { + char* json_str = grpc_channelz_get_server_sockets( + request->server_id(), request->start_socket_id(), request->max_results()); + if (json_str == nullptr) { + return Status(StatusCode::INTERNAL, + "grpc_channelz_get_server_sockets returned null"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - -Status ChannelzService::GetChannel( + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + +Status ChannelzService::GetChannel( ServerContext* /*unused*/, const channelz::v1::GetChannelRequest* request, - channelz::v1::GetChannelResponse* response) { - char* json_str = grpc_channelz_get_channel(request->channel_id()); - if (json_str == nullptr) { - return Status(StatusCode::NOT_FOUND, "No object found for that ChannelId"); - } + channelz::v1::GetChannelResponse* response) { + char* json_str = grpc_channelz_get_channel(request->channel_id()); + if (json_str == nullptr) { + return Status(StatusCode::NOT_FOUND, "No object found for that ChannelId"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - -Status ChannelzService::GetSubchannel( + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + +Status ChannelzService::GetSubchannel( ServerContext* /*unused*/, const channelz::v1::GetSubchannelRequest* request, - channelz::v1::GetSubchannelResponse* response) { - char* json_str = grpc_channelz_get_subchannel(request->subchannel_id()); - if (json_str == nullptr) { - return Status(StatusCode::NOT_FOUND, - "No object found for that SubchannelId"); - } + channelz::v1::GetSubchannelResponse* response) { + char* json_str = grpc_channelz_get_subchannel(request->subchannel_id()); + if (json_str == nullptr) { + return Status(StatusCode::NOT_FOUND, + "No object found for that SubchannelId"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + Status ChannelzService::GetSocket(ServerContext* /*unused*/, - const channelz::v1::GetSocketRequest* request, - channelz::v1::GetSocketResponse* response) { - char* json_str = grpc_channelz_get_socket(request->socket_id()); - if (json_str == nullptr) { - return Status(StatusCode::NOT_FOUND, "No object found for that SocketId"); - } + const channelz::v1::GetSocketRequest* request, + channelz::v1::GetSocketResponse* response) { + char* json_str = grpc_channelz_get_socket(request->socket_id()); + if (json_str == nullptr) { + return Status(StatusCode::NOT_FOUND, "No object found for that SocketId"); + } grpc::protobuf::util::Status s = ParseJson(json_str, response); - gpr_free(json_str); - if (!s.ok()) { - return Status(StatusCode::INTERNAL, s.ToString()); - } - return Status::OK; -} - -} // namespace grpc + gpr_free(json_str); + if (!s.ok()) { + return Status(StatusCode::INTERNAL, s.ToString()); + } + return Status::OK; +} + +} // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.h b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.h index b4a66ba1c6..72818a0d72 100644 --- a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.h +++ b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service.h @@ -1,64 +1,64 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_INTERNAL_CPP_SERVER_CHANNELZ_SERVICE_H -#define GRPC_INTERNAL_CPP_SERVER_CHANNELZ_SERVICE_H - -#include <grpc/support/port_platform.h> - -#include <grpcpp/grpcpp.h> -#include "src/proto/grpc/channelz/channelz.grpc.pb.h" - -namespace grpc { - -class ChannelzService final : public channelz::v1::Channelz::Service { - private: - // implementation of GetTopChannels rpc - Status GetTopChannels( - ServerContext* unused, const channelz::v1::GetTopChannelsRequest* request, - channelz::v1::GetTopChannelsResponse* response) override; - // implementation of GetServers rpc - Status GetServers(ServerContext* unused, - const channelz::v1::GetServersRequest* request, - channelz::v1::GetServersResponse* response) override; - // implementation of GetServer rpc - Status GetServer(ServerContext* unused, - const channelz::v1::GetServerRequest* request, - channelz::v1::GetServerResponse* response) override; - // implementation of GetServerSockets rpc - Status GetServerSockets( - ServerContext* unused, - const channelz::v1::GetServerSocketsRequest* request, - channelz::v1::GetServerSocketsResponse* response) override; - // implementation of GetChannel rpc - Status GetChannel(ServerContext* unused, - const channelz::v1::GetChannelRequest* request, - channelz::v1::GetChannelResponse* response) override; - // implementation of GetSubchannel rpc - Status GetSubchannel(ServerContext* unused, - const channelz::v1::GetSubchannelRequest* request, - channelz::v1::GetSubchannelResponse* response) override; - // implementation of GetSocket rpc - Status GetSocket(ServerContext* unused, - const channelz::v1::GetSocketRequest* request, - channelz::v1::GetSocketResponse* response) override; -}; - -} // namespace grpc - -#endif // GRPC_INTERNAL_CPP_SERVER_CHANNELZ_SERVICE_H +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_INTERNAL_CPP_SERVER_CHANNELZ_SERVICE_H +#define GRPC_INTERNAL_CPP_SERVER_CHANNELZ_SERVICE_H + +#include <grpc/support/port_platform.h> + +#include <grpcpp/grpcpp.h> +#include "src/proto/grpc/channelz/channelz.grpc.pb.h" + +namespace grpc { + +class ChannelzService final : public channelz::v1::Channelz::Service { + private: + // implementation of GetTopChannels rpc + Status GetTopChannels( + ServerContext* unused, const channelz::v1::GetTopChannelsRequest* request, + channelz::v1::GetTopChannelsResponse* response) override; + // implementation of GetServers rpc + Status GetServers(ServerContext* unused, + const channelz::v1::GetServersRequest* request, + channelz::v1::GetServersResponse* response) override; + // implementation of GetServer rpc + Status GetServer(ServerContext* unused, + const channelz::v1::GetServerRequest* request, + channelz::v1::GetServerResponse* response) override; + // implementation of GetServerSockets rpc + Status GetServerSockets( + ServerContext* unused, + const channelz::v1::GetServerSocketsRequest* request, + channelz::v1::GetServerSocketsResponse* response) override; + // implementation of GetChannel rpc + Status GetChannel(ServerContext* unused, + const channelz::v1::GetChannelRequest* request, + channelz::v1::GetChannelResponse* response) override; + // implementation of GetSubchannel rpc + Status GetSubchannel(ServerContext* unused, + const channelz::v1::GetSubchannelRequest* request, + channelz::v1::GetSubchannelResponse* response) override; + // implementation of GetSocket rpc + Status GetSocket(ServerContext* unused, + const channelz::v1::GetSocketRequest* request, + channelz::v1::GetSocketResponse* response) override; +}; + +} // namespace grpc + +#endif // GRPC_INTERNAL_CPP_SERVER_CHANNELZ_SERVICE_H diff --git a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc index ae26a447ab..35ecd08125 100644 --- a/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc +++ b/contrib/libs/grpc/src/cpp/server/channelz/channelz_service_plugin.cc @@ -1,72 +1,72 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#include <grpcpp/ext/channelz_service_plugin.h> -#include <grpcpp/impl/server_builder_plugin.h> -#include <grpcpp/impl/server_initializer.h> -#include <grpcpp/server.h> - -#include "src/cpp/server/channelz/channelz_service.h" - -namespace grpc { -namespace channelz { -namespace experimental { - -class ChannelzServicePlugin : public ::grpc::ServerBuilderPlugin { - public: - ChannelzServicePlugin() : channelz_service_(new grpc::ChannelzService()) {} - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#include <grpcpp/ext/channelz_service_plugin.h> +#include <grpcpp/impl/server_builder_plugin.h> +#include <grpcpp/impl/server_initializer.h> +#include <grpcpp/server.h> + +#include "src/cpp/server/channelz/channelz_service.h" + +namespace grpc { +namespace channelz { +namespace experimental { + +class ChannelzServicePlugin : public ::grpc::ServerBuilderPlugin { + public: + ChannelzServicePlugin() : channelz_service_(new grpc::ChannelzService()) {} + TString name() override { return "channelz_service"; } - - void InitServer(grpc::ServerInitializer* si) override { - si->RegisterService(channelz_service_); - } - + + void InitServer(grpc::ServerInitializer* si) override { + si->RegisterService(channelz_service_); + } + void Finish(grpc::ServerInitializer* /*si*/) override {} - + void ChangeArguments(const TString& /*name*/, void* /*value*/) override {} - - bool has_sync_methods() const override { - if (channelz_service_) { - return channelz_service_->has_synchronous_methods(); - } - return false; - } - - bool has_async_methods() const override { - if (channelz_service_) { - return channelz_service_->has_async_methods(); - } - return false; - } - - private: - std::shared_ptr<grpc::ChannelzService> channelz_service_; -}; - -static std::unique_ptr< ::grpc::ServerBuilderPlugin> -CreateChannelzServicePlugin() { - return std::unique_ptr< ::grpc::ServerBuilderPlugin>( - new ChannelzServicePlugin()); -} - + + bool has_sync_methods() const override { + if (channelz_service_) { + return channelz_service_->has_synchronous_methods(); + } + return false; + } + + bool has_async_methods() const override { + if (channelz_service_) { + return channelz_service_->has_async_methods(); + } + return false; + } + + private: + std::shared_ptr<grpc::ChannelzService> channelz_service_; +}; + +static std::unique_ptr< ::grpc::ServerBuilderPlugin> +CreateChannelzServicePlugin() { + return std::unique_ptr< ::grpc::ServerBuilderPlugin>( + new ChannelzServicePlugin()); +} + } // namespace experimental } // namespace channelz } // namespace grpc @@ -74,15 +74,15 @@ namespace grpc_impl { namespace channelz { namespace experimental { -void InitChannelzService() { +void InitChannelzService() { static struct Initializer { Initializer() { ::grpc::ServerBuilder::InternalAddPluginFactory( &grpc::channelz::experimental::CreateChannelzServicePlugin); } } initialize; -} - -} // namespace experimental -} // namespace channelz +} + +} // namespace experimental +} // namespace channelz } // namespace grpc_impl diff --git a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc index 3cc508d0cb..5f70ce0540 100644 --- a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc +++ b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.cc @@ -25,191 +25,191 @@ #include <grpc/support/log.h> #include <grpcpp/impl/codegen/method_handler.h> -#include "src/cpp/server/health/default_health_check_service.h" +#include "src/cpp/server/health/default_health_check_service.h" #include "src/proto/grpc/health/v1/health.upb.h" #include "upb/upb.hpp" #define MAX_SERVICE_NAME_LENGTH 200 namespace grpc { - -// -// DefaultHealthCheckService -// - -DefaultHealthCheckService::DefaultHealthCheckService() { - services_map_[""].SetServingStatus(SERVING); -} - -void DefaultHealthCheckService::SetServingStatus( + +// +// DefaultHealthCheckService +// + +DefaultHealthCheckService::DefaultHealthCheckService() { + services_map_[""].SetServingStatus(SERVING); +} + +void DefaultHealthCheckService::SetServingStatus( const TString& service_name, bool serving) { grpc_core::MutexLock lock(&mu_); - if (shutdown_) { - // Set to NOT_SERVING in case service_name is not in the map. - serving = false; - } - services_map_[service_name].SetServingStatus(serving ? SERVING : NOT_SERVING); -} - -void DefaultHealthCheckService::SetServingStatus(bool serving) { - const ServingStatus status = serving ? SERVING : NOT_SERVING; + if (shutdown_) { + // Set to NOT_SERVING in case service_name is not in the map. + serving = false; + } + services_map_[service_name].SetServingStatus(serving ? SERVING : NOT_SERVING); +} + +void DefaultHealthCheckService::SetServingStatus(bool serving) { + const ServingStatus status = serving ? SERVING : NOT_SERVING; grpc_core::MutexLock lock(&mu_); - if (shutdown_) { - return; - } - for (auto& p : services_map_) { - ServiceData& service_data = p.second; - service_data.SetServingStatus(status); - } -} - -void DefaultHealthCheckService::Shutdown() { + if (shutdown_) { + return; + } + for (auto& p : services_map_) { + ServiceData& service_data = p.second; + service_data.SetServingStatus(status); + } +} + +void DefaultHealthCheckService::Shutdown() { grpc_core::MutexLock lock(&mu_); - if (shutdown_) { - return; - } - shutdown_ = true; - for (auto& p : services_map_) { - ServiceData& service_data = p.second; - service_data.SetServingStatus(NOT_SERVING); - } -} - -DefaultHealthCheckService::ServingStatus -DefaultHealthCheckService::GetServingStatus( + if (shutdown_) { + return; + } + shutdown_ = true; + for (auto& p : services_map_) { + ServiceData& service_data = p.second; + service_data.SetServingStatus(NOT_SERVING); + } +} + +DefaultHealthCheckService::ServingStatus +DefaultHealthCheckService::GetServingStatus( const TString& service_name) const { grpc_core::MutexLock lock(&mu_); - auto it = services_map_.find(service_name); - if (it == services_map_.end()) { - return NOT_FOUND; - } - const ServiceData& service_data = it->second; - return service_data.GetServingStatus(); -} - -void DefaultHealthCheckService::RegisterCallHandler( + auto it = services_map_.find(service_name); + if (it == services_map_.end()) { + return NOT_FOUND; + } + const ServiceData& service_data = it->second; + return service_data.GetServingStatus(); +} + +void DefaultHealthCheckService::RegisterCallHandler( const TString& service_name, - std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler) { + std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler) { grpc_core::MutexLock lock(&mu_); - ServiceData& service_data = services_map_[service_name]; - service_data.AddCallHandler(handler /* copies ref */); - HealthCheckServiceImpl::CallHandler* h = handler.get(); - h->SendHealth(std::move(handler), service_data.GetServingStatus()); -} - -void DefaultHealthCheckService::UnregisterCallHandler( + ServiceData& service_data = services_map_[service_name]; + service_data.AddCallHandler(handler /* copies ref */); + HealthCheckServiceImpl::CallHandler* h = handler.get(); + h->SendHealth(std::move(handler), service_data.GetServingStatus()); +} + +void DefaultHealthCheckService::UnregisterCallHandler( const TString& service_name, - const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler) { + const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler) { grpc_core::MutexLock lock(&mu_); - auto it = services_map_.find(service_name); - if (it == services_map_.end()) return; - ServiceData& service_data = it->second; - service_data.RemoveCallHandler(handler); - if (service_data.Unused()) { - services_map_.erase(it); - } -} - -DefaultHealthCheckService::HealthCheckServiceImpl* -DefaultHealthCheckService::GetHealthCheckService( - std::unique_ptr<ServerCompletionQueue> cq) { - GPR_ASSERT(impl_ == nullptr); - impl_.reset(new HealthCheckServiceImpl(this, std::move(cq))); - return impl_.get(); -} - -// -// DefaultHealthCheckService::ServiceData -// - -void DefaultHealthCheckService::ServiceData::SetServingStatus( - ServingStatus status) { - status_ = status; - for (auto& call_handler : call_handlers_) { - call_handler->SendHealth(call_handler /* copies ref */, status); - } -} - -void DefaultHealthCheckService::ServiceData::AddCallHandler( - std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler) { - call_handlers_.insert(std::move(handler)); -} - -void DefaultHealthCheckService::ServiceData::RemoveCallHandler( - const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler) { - call_handlers_.erase(handler); -} - -// -// DefaultHealthCheckService::HealthCheckServiceImpl -// - + auto it = services_map_.find(service_name); + if (it == services_map_.end()) return; + ServiceData& service_data = it->second; + service_data.RemoveCallHandler(handler); + if (service_data.Unused()) { + services_map_.erase(it); + } +} + +DefaultHealthCheckService::HealthCheckServiceImpl* +DefaultHealthCheckService::GetHealthCheckService( + std::unique_ptr<ServerCompletionQueue> cq) { + GPR_ASSERT(impl_ == nullptr); + impl_.reset(new HealthCheckServiceImpl(this, std::move(cq))); + return impl_.get(); +} + +// +// DefaultHealthCheckService::ServiceData +// + +void DefaultHealthCheckService::ServiceData::SetServingStatus( + ServingStatus status) { + status_ = status; + for (auto& call_handler : call_handlers_) { + call_handler->SendHealth(call_handler /* copies ref */, status); + } +} + +void DefaultHealthCheckService::ServiceData::AddCallHandler( + std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler) { + call_handlers_.insert(std::move(handler)); +} + +void DefaultHealthCheckService::ServiceData::RemoveCallHandler( + const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler) { + call_handlers_.erase(handler); +} + +// +// DefaultHealthCheckService::HealthCheckServiceImpl +// + namespace { const char kHealthCheckMethodName[] = "/grpc.health.v1.Health/Check"; -const char kHealthWatchMethodName[] = "/grpc.health.v1.Health/Watch"; +const char kHealthWatchMethodName[] = "/grpc.health.v1.Health/Watch"; } // namespace DefaultHealthCheckService::HealthCheckServiceImpl::HealthCheckServiceImpl( - DefaultHealthCheckService* database, - std::unique_ptr<ServerCompletionQueue> cq) - : database_(database), cq_(std::move(cq)) { - // Add Check() method. - AddMethod(new internal::RpcServiceMethod( - kHealthCheckMethodName, internal::RpcMethod::NORMAL_RPC, nullptr)); - // Add Watch() method. - AddMethod(new internal::RpcServiceMethod( - kHealthWatchMethodName, internal::RpcMethod::SERVER_STREAMING, nullptr)); - // Create serving thread. - thread_ = std::unique_ptr<::grpc_core::Thread>( - new ::grpc_core::Thread("grpc_health_check_service", Serve, this)); + DefaultHealthCheckService* database, + std::unique_ptr<ServerCompletionQueue> cq) + : database_(database), cq_(std::move(cq)) { + // Add Check() method. + AddMethod(new internal::RpcServiceMethod( + kHealthCheckMethodName, internal::RpcMethod::NORMAL_RPC, nullptr)); + // Add Watch() method. + AddMethod(new internal::RpcServiceMethod( + kHealthWatchMethodName, internal::RpcMethod::SERVER_STREAMING, nullptr)); + // Create serving thread. + thread_ = std::unique_ptr<::grpc_core::Thread>( + new ::grpc_core::Thread("grpc_health_check_service", Serve, this)); } -DefaultHealthCheckService::HealthCheckServiceImpl::~HealthCheckServiceImpl() { - // We will reach here after the server starts shutting down. - shutdown_ = true; - { +DefaultHealthCheckService::HealthCheckServiceImpl::~HealthCheckServiceImpl() { + // We will reach here after the server starts shutting down. + shutdown_ = true; + { grpc_core::MutexLock lock(&cq_shutdown_mu_); - cq_->Shutdown(); - } - thread_->Join(); -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::StartServingThread() { - // Request the calls we're interested in. - // We do this before starting the serving thread, so that we know it's - // done before server startup is complete. - CheckCallHandler::CreateAndStart(cq_.get(), database_, this); - WatchCallHandler::CreateAndStart(cq_.get(), database_, this); - // Start serving thread. - thread_->Start(); -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::Serve(void* arg) { + cq_->Shutdown(); + } + thread_->Join(); +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::StartServingThread() { + // Request the calls we're interested in. + // We do this before starting the serving thread, so that we know it's + // done before server startup is complete. + CheckCallHandler::CreateAndStart(cq_.get(), database_, this); + WatchCallHandler::CreateAndStart(cq_.get(), database_, this); + // Start serving thread. + thread_->Start(); +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::Serve(void* arg) { HealthCheckServiceImpl* service = static_cast<HealthCheckServiceImpl*>(arg); - void* tag; - bool ok; - while (true) { - if (!service->cq_->Next(&tag, &ok)) { - // The completion queue is shutting down. - GPR_ASSERT(service->shutdown_); - break; - } - auto* next_step = static_cast<CallableTag*>(tag); - next_step->Run(ok); - } -} - -bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest( + void* tag; + bool ok; + while (true) { + if (!service->cq_->Next(&tag, &ok)) { + // The completion queue is shutting down. + GPR_ASSERT(service->shutdown_); + break; + } + auto* next_step = static_cast<CallableTag*>(tag); + next_step->Run(ok); + } +} + +bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest( const ByteBuffer& request, TString* service_name) { std::vector<Slice> slices; - if (!request.Dump(&slices).ok()) return false; + if (!request.Dump(&slices).ok()) return false; uint8_t* request_bytes = nullptr; size_t request_size = 0; - if (slices.size() == 1) { + if (slices.size() == 1) { request_bytes = const_cast<uint8_t*>(slices[0].begin()); request_size = slices[0].size(); - } else if (slices.size() > 1) { - request_bytes = static_cast<uint8_t*>(gpr_malloc(request.Length())); + } else if (slices.size() > 1) { + request_bytes = static_cast<uint8_t*>(gpr_malloc(request.Length())); uint8_t* copy_to = request_bytes; for (size_t i = 0; i < slices.size(); i++) { memcpy(copy_to, slices[i].begin(), slices[i].size()); @@ -220,8 +220,8 @@ bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest( grpc_health_v1_HealthCheckRequest* request_struct = grpc_health_v1_HealthCheckRequest_parse( reinterpret_cast<char*>(request_bytes), request_size, arena.ptr()); - if (slices.size() > 1) { - gpr_free(request_bytes); + if (slices.size() > 1) { + gpr_free(request_bytes); } if (request_struct == nullptr) { return false; @@ -232,17 +232,17 @@ bool DefaultHealthCheckService::HealthCheckServiceImpl::DecodeRequest( return false; } service_name->assign(service.data, service.size); - return true; -} + return true; +} -bool DefaultHealthCheckService::HealthCheckServiceImpl::EncodeResponse( - ServingStatus status, ByteBuffer* response) { +bool DefaultHealthCheckService::HealthCheckServiceImpl::EncodeResponse( + ServingStatus status, ByteBuffer* response) { upb::Arena arena; grpc_health_v1_HealthCheckResponse* response_struct = grpc_health_v1_HealthCheckResponse_new(arena.ptr()); grpc_health_v1_HealthCheckResponse_set_status( response_struct, - status == NOT_FOUND + status == NOT_FOUND ? grpc_health_v1_HealthCheckResponse_SERVICE_UNKNOWN : status == SERVING ? grpc_health_v1_HealthCheckResponse_SERVING : grpc_health_v1_HealthCheckResponse_NOT_SERVING); @@ -256,249 +256,249 @@ bool DefaultHealthCheckService::HealthCheckServiceImpl::EncodeResponse( Slice encoded_response(response_slice, Slice::STEAL_REF); ByteBuffer response_buffer(&encoded_response, 1); response->Swap(&response_buffer); - return true; + return true; } -// -// DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler -// - -void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: - CreateAndStart(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service) { - std::shared_ptr<CallHandler> self = - std::make_shared<CheckCallHandler>(cq, database, service); - CheckCallHandler* handler = static_cast<CheckCallHandler*>(self.get()); - { +// +// DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler +// + +void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: + CreateAndStart(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service) { + std::shared_ptr<CallHandler> self = + std::make_shared<CheckCallHandler>(cq, database, service); + CheckCallHandler* handler = static_cast<CheckCallHandler*>(self.get()); + { grpc_core::MutexLock lock(&service->cq_shutdown_mu_); - if (service->shutdown_) return; - // Request a Check() call. - handler->next_ = - CallableTag(std::bind(&CheckCallHandler::OnCallReceived, handler, - std::placeholders::_1, std::placeholders::_2), - std::move(self)); - service->RequestAsyncUnary(0, &handler->ctx_, &handler->request_, - &handler->writer_, cq, cq, &handler->next_); - } + if (service->shutdown_) return; + // Request a Check() call. + handler->next_ = + CallableTag(std::bind(&CheckCallHandler::OnCallReceived, handler, + std::placeholders::_1, std::placeholders::_2), + std::move(self)); + service->RequestAsyncUnary(0, &handler->ctx_, &handler->request_, + &handler->writer_, cq, cq, &handler->next_); + } } -DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: - CheckCallHandler(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service) - : cq_(cq), database_(database), service_(service), writer_(&ctx_) {} - -void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: - OnCallReceived(std::shared_ptr<CallHandler> self, bool ok) { - if (!ok) { - // The value of ok being false means that the server is shutting down. - return; - } - // Spawn a new handler instance to serve the next new client. Every handler - // instance will deallocate itself when it's done. - CreateAndStart(cq_, database_, service_); - // Process request. - gpr_log(GPR_DEBUG, "[HCS %p] Health check started for handler %p", service_, - this); +DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: + CheckCallHandler(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service) + : cq_(cq), database_(database), service_(service), writer_(&ctx_) {} + +void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: + OnCallReceived(std::shared_ptr<CallHandler> self, bool ok) { + if (!ok) { + // The value of ok being false means that the server is shutting down. + return; + } + // Spawn a new handler instance to serve the next new client. Every handler + // instance will deallocate itself when it's done. + CreateAndStart(cq_, database_, service_); + // Process request. + gpr_log(GPR_DEBUG, "[HCS %p] Health check started for handler %p", service_, + this); TString service_name; - grpc::Status status = Status::OK; - ByteBuffer response; - if (!service_->DecodeRequest(request_, &service_name)) { - status = Status(StatusCode::INVALID_ARGUMENT, "could not parse request"); - } else { - ServingStatus serving_status = database_->GetServingStatus(service_name); - if (serving_status == NOT_FOUND) { - status = Status(StatusCode::NOT_FOUND, "service name unknown"); - } else if (!service_->EncodeResponse(serving_status, &response)) { - status = Status(StatusCode::INTERNAL, "could not encode response"); - } - } - // Send response. - { + grpc::Status status = Status::OK; + ByteBuffer response; + if (!service_->DecodeRequest(request_, &service_name)) { + status = Status(StatusCode::INVALID_ARGUMENT, "could not parse request"); + } else { + ServingStatus serving_status = database_->GetServingStatus(service_name); + if (serving_status == NOT_FOUND) { + status = Status(StatusCode::NOT_FOUND, "service name unknown"); + } else if (!service_->EncodeResponse(serving_status, &response)) { + status = Status(StatusCode::INTERNAL, "could not encode response"); + } + } + // Send response. + { grpc_core::MutexLock lock(&service_->cq_shutdown_mu_); - if (!service_->shutdown_) { - next_ = - CallableTag(std::bind(&CheckCallHandler::OnFinishDone, this, - std::placeholders::_1, std::placeholders::_2), - std::move(self)); - if (status.ok()) { - writer_.Finish(response, status, &next_); - } else { - writer_.FinishWithError(status, &next_); - } - } - } + if (!service_->shutdown_) { + next_ = + CallableTag(std::bind(&CheckCallHandler::OnFinishDone, this, + std::placeholders::_1, std::placeholders::_2), + std::move(self)); + if (status.ok()) { + writer_.Finish(response, status, &next_); + } else { + writer_.FinishWithError(status, &next_); + } + } + } } -void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: - OnFinishDone(std::shared_ptr<CallHandler> self, bool ok) { - if (ok) { - gpr_log(GPR_DEBUG, "[HCS %p] Health check call finished for handler %p", - service_, this); +void DefaultHealthCheckService::HealthCheckServiceImpl::CheckCallHandler:: + OnFinishDone(std::shared_ptr<CallHandler> self, bool ok) { + if (ok) { + gpr_log(GPR_DEBUG, "[HCS %p] Health check call finished for handler %p", + service_, this); } - self.reset(); // To appease clang-tidy. + self.reset(); // To appease clang-tidy. } -// -// DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler -// - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - CreateAndStart(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service) { - std::shared_ptr<CallHandler> self = - std::make_shared<WatchCallHandler>(cq, database, service); - WatchCallHandler* handler = static_cast<WatchCallHandler*>(self.get()); - { +// +// DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler +// + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + CreateAndStart(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service) { + std::shared_ptr<CallHandler> self = + std::make_shared<WatchCallHandler>(cq, database, service); + WatchCallHandler* handler = static_cast<WatchCallHandler*>(self.get()); + { grpc_core::MutexLock lock(&service->cq_shutdown_mu_); - if (service->shutdown_) return; - // Request AsyncNotifyWhenDone(). - handler->on_done_notified_ = - CallableTag(std::bind(&WatchCallHandler::OnDoneNotified, handler, - std::placeholders::_1, std::placeholders::_2), - self /* copies ref */); - handler->ctx_.AsyncNotifyWhenDone(&handler->on_done_notified_); - // Request a Watch() call. - handler->next_ = - CallableTag(std::bind(&WatchCallHandler::OnCallReceived, handler, - std::placeholders::_1, std::placeholders::_2), - std::move(self)); - service->RequestAsyncServerStreaming(1, &handler->ctx_, &handler->request_, - &handler->stream_, cq, cq, - &handler->next_); + if (service->shutdown_) return; + // Request AsyncNotifyWhenDone(). + handler->on_done_notified_ = + CallableTag(std::bind(&WatchCallHandler::OnDoneNotified, handler, + std::placeholders::_1, std::placeholders::_2), + self /* copies ref */); + handler->ctx_.AsyncNotifyWhenDone(&handler->on_done_notified_); + // Request a Watch() call. + handler->next_ = + CallableTag(std::bind(&WatchCallHandler::OnCallReceived, handler, + std::placeholders::_1, std::placeholders::_2), + std::move(self)); + service->RequestAsyncServerStreaming(1, &handler->ctx_, &handler->request_, + &handler->stream_, cq, cq, + &handler->next_); } } -DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - WatchCallHandler(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service) - : cq_(cq), database_(database), service_(service), stream_(&ctx_) {} - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - OnCallReceived(std::shared_ptr<CallHandler> self, bool ok) { - if (!ok) { - // Server shutting down. - // - // AsyncNotifyWhenDone() needs to be called before the call starts, but the - // tag will not pop out if the call never starts ( - // https://github.com/grpc/grpc/issues/10136). So we need to manually - // release the ownership of the handler in this case. - GPR_ASSERT(on_done_notified_.ReleaseHandler() != nullptr); - return; - } - // Spawn a new handler instance to serve the next new client. Every handler - // instance will deallocate itself when it's done. - CreateAndStart(cq_, database_, service_); - // Parse request. - if (!service_->DecodeRequest(request_, &service_name_)) { - SendFinish(std::move(self), - Status(StatusCode::INVALID_ARGUMENT, "could not parse request")); - return; - } - // Register the call for updates to the service. - gpr_log(GPR_DEBUG, - "[HCS %p] Health watch started for service \"%s\" (handler: %p)", - service_, service_name_.c_str(), this); - database_->RegisterCallHandler(service_name_, std::move(self)); +DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + WatchCallHandler(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service) + : cq_(cq), database_(database), service_(service), stream_(&ctx_) {} + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + OnCallReceived(std::shared_ptr<CallHandler> self, bool ok) { + if (!ok) { + // Server shutting down. + // + // AsyncNotifyWhenDone() needs to be called before the call starts, but the + // tag will not pop out if the call never starts ( + // https://github.com/grpc/grpc/issues/10136). So we need to manually + // release the ownership of the handler in this case. + GPR_ASSERT(on_done_notified_.ReleaseHandler() != nullptr); + return; + } + // Spawn a new handler instance to serve the next new client. Every handler + // instance will deallocate itself when it's done. + CreateAndStart(cq_, database_, service_); + // Parse request. + if (!service_->DecodeRequest(request_, &service_name_)) { + SendFinish(std::move(self), + Status(StatusCode::INVALID_ARGUMENT, "could not parse request")); + return; + } + // Register the call for updates to the service. + gpr_log(GPR_DEBUG, + "[HCS %p] Health watch started for service \"%s\" (handler: %p)", + service_, service_name_.c_str(), this); + database_->RegisterCallHandler(service_name_, std::move(self)); } -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - SendHealth(std::shared_ptr<CallHandler> self, ServingStatus status) { +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + SendHealth(std::shared_ptr<CallHandler> self, ServingStatus status) { grpc_core::MutexLock lock(&send_mu_); - // If there's already a send in flight, cache the new status, and - // we'll start a new send for it when the one in flight completes. - if (send_in_flight_) { - pending_status_ = status; - return; - } - // Start a send. - SendHealthLocked(std::move(self), status); -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - SendHealthLocked(std::shared_ptr<CallHandler> self, ServingStatus status) { - send_in_flight_ = true; - // Construct response. - ByteBuffer response; - bool success = service_->EncodeResponse(status, &response); - // Grab shutdown lock and send response. + // If there's already a send in flight, cache the new status, and + // we'll start a new send for it when the one in flight completes. + if (send_in_flight_) { + pending_status_ = status; + return; + } + // Start a send. + SendHealthLocked(std::move(self), status); +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + SendHealthLocked(std::shared_ptr<CallHandler> self, ServingStatus status) { + send_in_flight_ = true; + // Construct response. + ByteBuffer response; + bool success = service_->EncodeResponse(status, &response); + // Grab shutdown lock and send response. grpc_core::MutexLock cq_lock(&service_->cq_shutdown_mu_); - if (service_->shutdown_) { - SendFinishLocked(std::move(self), Status::CANCELLED); - return; - } - if (!success) { - SendFinishLocked(std::move(self), - Status(StatusCode::INTERNAL, "could not encode response")); - return; - } - next_ = CallableTag(std::bind(&WatchCallHandler::OnSendHealthDone, this, - std::placeholders::_1, std::placeholders::_2), - std::move(self)); - stream_.Write(response, &next_); -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - OnSendHealthDone(std::shared_ptr<CallHandler> self, bool ok) { - if (!ok) { - SendFinish(std::move(self), Status::CANCELLED); - return; - } + if (service_->shutdown_) { + SendFinishLocked(std::move(self), Status::CANCELLED); + return; + } + if (!success) { + SendFinishLocked(std::move(self), + Status(StatusCode::INTERNAL, "could not encode response")); + return; + } + next_ = CallableTag(std::bind(&WatchCallHandler::OnSendHealthDone, this, + std::placeholders::_1, std::placeholders::_2), + std::move(self)); + stream_.Write(response, &next_); +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + OnSendHealthDone(std::shared_ptr<CallHandler> self, bool ok) { + if (!ok) { + SendFinish(std::move(self), Status::CANCELLED); + return; + } grpc_core::MutexLock lock(&send_mu_); - send_in_flight_ = false; - // If we got a new status since we started the last send, start a - // new send for it. - if (pending_status_ != NOT_FOUND) { - auto status = pending_status_; - pending_status_ = NOT_FOUND; - SendHealthLocked(std::move(self), status); - } -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - SendFinish(std::shared_ptr<CallHandler> self, const Status& status) { - if (finish_called_) return; + send_in_flight_ = false; + // If we got a new status since we started the last send, start a + // new send for it. + if (pending_status_ != NOT_FOUND) { + auto status = pending_status_; + pending_status_ = NOT_FOUND; + SendHealthLocked(std::move(self), status); + } +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + SendFinish(std::shared_ptr<CallHandler> self, const Status& status) { + if (finish_called_) return; grpc_core::MutexLock cq_lock(&service_->cq_shutdown_mu_); - if (service_->shutdown_) return; - SendFinishLocked(std::move(self), status); -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - SendFinishLocked(std::shared_ptr<CallHandler> self, const Status& status) { - on_finish_done_ = - CallableTag(std::bind(&WatchCallHandler::OnFinishDone, this, - std::placeholders::_1, std::placeholders::_2), - std::move(self)); - stream_.Finish(status, &on_finish_done_); - finish_called_ = true; -} - -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - OnFinishDone(std::shared_ptr<CallHandler> self, bool ok) { - if (ok) { - gpr_log(GPR_DEBUG, - "[HCS %p] Health watch call finished (service_name: \"%s\", " - "handler: %p).", - service_, service_name_.c_str(), this); - } - self.reset(); // To appease clang-tidy. -} - -// TODO(roth): This method currently assumes that there will be only one -// thread polling the cq and invoking the corresponding callbacks. If -// that changes, we will need to add synchronization here. -void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: - OnDoneNotified(std::shared_ptr<CallHandler> self, bool ok) { - GPR_ASSERT(ok); - gpr_log(GPR_DEBUG, - "[HCS %p] Health watch call is notified done (handler: %p, " - "is_cancelled: %d).", - service_, this, static_cast<int>(ctx_.IsCancelled())); - database_->UnregisterCallHandler(service_name_, self); - SendFinish(std::move(self), Status::CANCELLED); -} - + if (service_->shutdown_) return; + SendFinishLocked(std::move(self), status); +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + SendFinishLocked(std::shared_ptr<CallHandler> self, const Status& status) { + on_finish_done_ = + CallableTag(std::bind(&WatchCallHandler::OnFinishDone, this, + std::placeholders::_1, std::placeholders::_2), + std::move(self)); + stream_.Finish(status, &on_finish_done_); + finish_called_ = true; +} + +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + OnFinishDone(std::shared_ptr<CallHandler> self, bool ok) { + if (ok) { + gpr_log(GPR_DEBUG, + "[HCS %p] Health watch call finished (service_name: \"%s\", " + "handler: %p).", + service_, service_name_.c_str(), this); + } + self.reset(); // To appease clang-tidy. +} + +// TODO(roth): This method currently assumes that there will be only one +// thread polling the cq and invoking the corresponding callbacks. If +// that changes, we will need to add synchronization here. +void DefaultHealthCheckService::HealthCheckServiceImpl::WatchCallHandler:: + OnDoneNotified(std::shared_ptr<CallHandler> self, bool ok) { + GPR_ASSERT(ok); + gpr_log(GPR_DEBUG, + "[HCS %p] Health watch call is notified done (handler: %p, " + "is_cancelled: %d).", + service_, this, static_cast<int>(ctx_.IsCancelled())); + database_->UnregisterCallHandler(service_name_, self); + SendFinish(std::move(self), Status::CANCELLED); +} + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h index 9da1dfc15f..5da0ef935a 100644 --- a/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h +++ b/contrib/libs/grpc/src/cpp/server/health/default_health_check_service.h @@ -19,260 +19,260 @@ #ifndef GRPC_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H #define GRPC_INTERNAL_CPP_SERVER_DEFAULT_HEALTH_CHECK_SERVICE_H -#include <atomic> -#include <set> +#include <atomic> +#include <set> -#include <grpc/support/log.h> -#include <grpcpp/grpcpp.h> +#include <grpc/support/log.h> +#include <grpcpp/grpcpp.h> #include <grpcpp/health_check_service_interface.h> -#include <grpcpp/impl/codegen/async_generic_service.h> -#include <grpcpp/impl/codegen/async_unary_call.h> +#include <grpcpp/impl/codegen/async_generic_service.h> +#include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/completion_queue.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/support/byte_buffer.h> #include "src/core/lib/gprpp/sync.h" -#include "src/core/lib/gprpp/thd.h" - +#include "src/core/lib/gprpp/thd.h" + namespace grpc { // Default implementation of HealthCheckServiceInterface. Server will create and // own it. class DefaultHealthCheckService final : public HealthCheckServiceInterface { public: - enum ServingStatus { NOT_FOUND, SERVING, NOT_SERVING }; - + enum ServingStatus { NOT_FOUND, SERVING, NOT_SERVING }; + // The service impl to register with the server. class HealthCheckServiceImpl : public Service { public: - // Base class for call handlers. - class CallHandler { - public: - virtual ~CallHandler() = default; - virtual void SendHealth(std::shared_ptr<CallHandler> self, - ServingStatus status) = 0; - }; - - HealthCheckServiceImpl(DefaultHealthCheckService* database, - std::unique_ptr<ServerCompletionQueue> cq); - - ~HealthCheckServiceImpl(); - - void StartServingThread(); - + // Base class for call handlers. + class CallHandler { + public: + virtual ~CallHandler() = default; + virtual void SendHealth(std::shared_ptr<CallHandler> self, + ServingStatus status) = 0; + }; + + HealthCheckServiceImpl(DefaultHealthCheckService* database, + std::unique_ptr<ServerCompletionQueue> cq); + + ~HealthCheckServiceImpl(); + + void StartServingThread(); + private: - // A tag that can be called with a bool argument. It's tailored for - // CallHandler's use. Before being used, it should be constructed with a - // method of CallHandler and a shared pointer to the handler. The - // shared pointer will be moved to the invoked function and the function - // can only be invoked once. That makes ref counting of the handler easier, - // because the shared pointer is not bound to the function and can be gone - // once the invoked function returns (if not used any more). - class CallableTag { - public: - using HandlerFunction = - std::function<void(std::shared_ptr<CallHandler>, bool)>; - - CallableTag() {} - - CallableTag(HandlerFunction func, std::shared_ptr<CallHandler> handler) - : handler_function_(std::move(func)), handler_(std::move(handler)) { - GPR_ASSERT(handler_function_ != nullptr); - GPR_ASSERT(handler_ != nullptr); - } - - // Runs the tag. This should be called only once. The handler is no - // longer owned by this tag after this method is invoked. - void Run(bool ok) { - GPR_ASSERT(handler_function_ != nullptr); - GPR_ASSERT(handler_ != nullptr); - handler_function_(std::move(handler_), ok); - } - - // Releases and returns the shared pointer to the handler. - std::shared_ptr<CallHandler> ReleaseHandler() { - return std::move(handler_); - } - - private: - HandlerFunction handler_function_ = nullptr; - std::shared_ptr<CallHandler> handler_; - }; - - // Call handler for Check method. - // Each handler takes care of one call. It contains per-call data and it - // will access the members of the parent class (i.e., - // DefaultHealthCheckService) for per-service health data. - class CheckCallHandler : public CallHandler { - public: - // Instantiates a CheckCallHandler and requests the next health check - // call. The handler object will manage its own lifetime, so no action is - // needed from the caller any more regarding that object. - static void CreateAndStart(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service); - - // This ctor is public because we want to use std::make_shared<> in - // CreateAndStart(). This ctor shouldn't be used elsewhere. - CheckCallHandler(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service); - - // Not used for Check. + // A tag that can be called with a bool argument. It's tailored for + // CallHandler's use. Before being used, it should be constructed with a + // method of CallHandler and a shared pointer to the handler. The + // shared pointer will be moved to the invoked function and the function + // can only be invoked once. That makes ref counting of the handler easier, + // because the shared pointer is not bound to the function and can be gone + // once the invoked function returns (if not used any more). + class CallableTag { + public: + using HandlerFunction = + std::function<void(std::shared_ptr<CallHandler>, bool)>; + + CallableTag() {} + + CallableTag(HandlerFunction func, std::shared_ptr<CallHandler> handler) + : handler_function_(std::move(func)), handler_(std::move(handler)) { + GPR_ASSERT(handler_function_ != nullptr); + GPR_ASSERT(handler_ != nullptr); + } + + // Runs the tag. This should be called only once. The handler is no + // longer owned by this tag after this method is invoked. + void Run(bool ok) { + GPR_ASSERT(handler_function_ != nullptr); + GPR_ASSERT(handler_ != nullptr); + handler_function_(std::move(handler_), ok); + } + + // Releases and returns the shared pointer to the handler. + std::shared_ptr<CallHandler> ReleaseHandler() { + return std::move(handler_); + } + + private: + HandlerFunction handler_function_ = nullptr; + std::shared_ptr<CallHandler> handler_; + }; + + // Call handler for Check method. + // Each handler takes care of one call. It contains per-call data and it + // will access the members of the parent class (i.e., + // DefaultHealthCheckService) for per-service health data. + class CheckCallHandler : public CallHandler { + public: + // Instantiates a CheckCallHandler and requests the next health check + // call. The handler object will manage its own lifetime, so no action is + // needed from the caller any more regarding that object. + static void CreateAndStart(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service); + + // This ctor is public because we want to use std::make_shared<> in + // CreateAndStart(). This ctor shouldn't be used elsewhere. + CheckCallHandler(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service); + + // Not used for Check. void SendHealth(std::shared_ptr<CallHandler> /*self*/, ServingStatus /*status*/) override {} - - private: - // Called when we receive a call. - // Spawns a new handler so that we can keep servicing future calls. - void OnCallReceived(std::shared_ptr<CallHandler> self, bool ok); - - // Called when Finish() is done. - void OnFinishDone(std::shared_ptr<CallHandler> self, bool ok); - - // The members passed down from HealthCheckServiceImpl. - ServerCompletionQueue* cq_; - DefaultHealthCheckService* database_; - HealthCheckServiceImpl* service_; - - ByteBuffer request_; - GenericServerAsyncResponseWriter writer_; - ServerContext ctx_; - - CallableTag next_; - }; - - // Call handler for Watch method. - // Each handler takes care of one call. It contains per-call data and it - // will access the members of the parent class (i.e., - // DefaultHealthCheckService) for per-service health data. - class WatchCallHandler : public CallHandler { - public: - // Instantiates a WatchCallHandler and requests the next health check - // call. The handler object will manage its own lifetime, so no action is - // needed from the caller any more regarding that object. - static void CreateAndStart(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service); - - // This ctor is public because we want to use std::make_shared<> in - // CreateAndStart(). This ctor shouldn't be used elsewhere. - WatchCallHandler(ServerCompletionQueue* cq, - DefaultHealthCheckService* database, - HealthCheckServiceImpl* service); - - void SendHealth(std::shared_ptr<CallHandler> self, - ServingStatus status) override; - - private: - // Called when we receive a call. - // Spawns a new handler so that we can keep servicing future calls. - void OnCallReceived(std::shared_ptr<CallHandler> self, bool ok); - - // Requires holding send_mu_. - void SendHealthLocked(std::shared_ptr<CallHandler> self, - ServingStatus status); - - // When sending a health result finishes. - void OnSendHealthDone(std::shared_ptr<CallHandler> self, bool ok); - - void SendFinish(std::shared_ptr<CallHandler> self, const Status& status); - - // Requires holding service_->cq_shutdown_mu_. - void SendFinishLocked(std::shared_ptr<CallHandler> self, - const Status& status); - - // Called when Finish() is done. - void OnFinishDone(std::shared_ptr<CallHandler> self, bool ok); - - // Called when AsyncNotifyWhenDone() notifies us. - void OnDoneNotified(std::shared_ptr<CallHandler> self, bool ok); - - // The members passed down from HealthCheckServiceImpl. - ServerCompletionQueue* cq_; - DefaultHealthCheckService* database_; - HealthCheckServiceImpl* service_; - - ByteBuffer request_; + + private: + // Called when we receive a call. + // Spawns a new handler so that we can keep servicing future calls. + void OnCallReceived(std::shared_ptr<CallHandler> self, bool ok); + + // Called when Finish() is done. + void OnFinishDone(std::shared_ptr<CallHandler> self, bool ok); + + // The members passed down from HealthCheckServiceImpl. + ServerCompletionQueue* cq_; + DefaultHealthCheckService* database_; + HealthCheckServiceImpl* service_; + + ByteBuffer request_; + GenericServerAsyncResponseWriter writer_; + ServerContext ctx_; + + CallableTag next_; + }; + + // Call handler for Watch method. + // Each handler takes care of one call. It contains per-call data and it + // will access the members of the parent class (i.e., + // DefaultHealthCheckService) for per-service health data. + class WatchCallHandler : public CallHandler { + public: + // Instantiates a WatchCallHandler and requests the next health check + // call. The handler object will manage its own lifetime, so no action is + // needed from the caller any more regarding that object. + static void CreateAndStart(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service); + + // This ctor is public because we want to use std::make_shared<> in + // CreateAndStart(). This ctor shouldn't be used elsewhere. + WatchCallHandler(ServerCompletionQueue* cq, + DefaultHealthCheckService* database, + HealthCheckServiceImpl* service); + + void SendHealth(std::shared_ptr<CallHandler> self, + ServingStatus status) override; + + private: + // Called when we receive a call. + // Spawns a new handler so that we can keep servicing future calls. + void OnCallReceived(std::shared_ptr<CallHandler> self, bool ok); + + // Requires holding send_mu_. + void SendHealthLocked(std::shared_ptr<CallHandler> self, + ServingStatus status); + + // When sending a health result finishes. + void OnSendHealthDone(std::shared_ptr<CallHandler> self, bool ok); + + void SendFinish(std::shared_ptr<CallHandler> self, const Status& status); + + // Requires holding service_->cq_shutdown_mu_. + void SendFinishLocked(std::shared_ptr<CallHandler> self, + const Status& status); + + // Called when Finish() is done. + void OnFinishDone(std::shared_ptr<CallHandler> self, bool ok); + + // Called when AsyncNotifyWhenDone() notifies us. + void OnDoneNotified(std::shared_ptr<CallHandler> self, bool ok); + + // The members passed down from HealthCheckServiceImpl. + ServerCompletionQueue* cq_; + DefaultHealthCheckService* database_; + HealthCheckServiceImpl* service_; + + ByteBuffer request_; TString service_name_; - GenericServerAsyncWriter stream_; - ServerContext ctx_; - + GenericServerAsyncWriter stream_; + ServerContext ctx_; + grpc_core::Mutex send_mu_; - bool send_in_flight_ = false; // Guarded by mu_. - ServingStatus pending_status_ = NOT_FOUND; // Guarded by mu_. - - bool finish_called_ = false; - CallableTag next_; - CallableTag on_done_notified_; - CallableTag on_finish_done_; - }; - - // Handles the incoming requests and drives the completion queue in a loop. - static void Serve(void* arg); - - // Returns true on success. - static bool DecodeRequest(const ByteBuffer& request, + bool send_in_flight_ = false; // Guarded by mu_. + ServingStatus pending_status_ = NOT_FOUND; // Guarded by mu_. + + bool finish_called_ = false; + CallableTag next_; + CallableTag on_done_notified_; + CallableTag on_finish_done_; + }; + + // Handles the incoming requests and drives the completion queue in a loop. + static void Serve(void* arg); + + // Returns true on success. + static bool DecodeRequest(const ByteBuffer& request, TString* service_name); - static bool EncodeResponse(ServingStatus status, ByteBuffer* response); - - // Needed to appease Windows compilers, which don't seem to allow - // nested classes to access protected members in the parent's - // superclass. - using Service::RequestAsyncServerStreaming; - using Service::RequestAsyncUnary; - - DefaultHealthCheckService* database_; - std::unique_ptr<ServerCompletionQueue> cq_; - - // To synchronize the operations related to shutdown state of cq_, so that - // we don't enqueue new tags into cq_ after it is already shut down. + static bool EncodeResponse(ServingStatus status, ByteBuffer* response); + + // Needed to appease Windows compilers, which don't seem to allow + // nested classes to access protected members in the parent's + // superclass. + using Service::RequestAsyncServerStreaming; + using Service::RequestAsyncUnary; + + DefaultHealthCheckService* database_; + std::unique_ptr<ServerCompletionQueue> cq_; + + // To synchronize the operations related to shutdown state of cq_, so that + // we don't enqueue new tags into cq_ after it is already shut down. grpc_core::Mutex cq_shutdown_mu_; - std::atomic_bool shutdown_{false}; - std::unique_ptr<::grpc_core::Thread> thread_; + std::atomic_bool shutdown_{false}; + std::unique_ptr<::grpc_core::Thread> thread_; }; DefaultHealthCheckService(); - + void SetServingStatus(const TString& service_name, bool serving) override; void SetServingStatus(bool serving) override; - - void Shutdown() override; - + + void Shutdown() override; + ServingStatus GetServingStatus(const TString& service_name) const; - HealthCheckServiceImpl* GetHealthCheckService( - std::unique_ptr<ServerCompletionQueue> cq); - + HealthCheckServiceImpl* GetHealthCheckService( + std::unique_ptr<ServerCompletionQueue> cq); + private: - // Stores the current serving status of a service and any call - // handlers registered for updates when the service's status changes. - class ServiceData { - public: - void SetServingStatus(ServingStatus status); - ServingStatus GetServingStatus() const { return status_; } - void AddCallHandler( - std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler); - void RemoveCallHandler( - const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler); - bool Unused() const { - return call_handlers_.empty() && status_ == NOT_FOUND; - } - - private: - ServingStatus status_ = NOT_FOUND; - std::set<std::shared_ptr<HealthCheckServiceImpl::CallHandler>> - call_handlers_; - }; - - void RegisterCallHandler( + // Stores the current serving status of a service and any call + // handlers registered for updates when the service's status changes. + class ServiceData { + public: + void SetServingStatus(ServingStatus status); + ServingStatus GetServingStatus() const { return status_; } + void AddCallHandler( + std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler); + void RemoveCallHandler( + const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler); + bool Unused() const { + return call_handlers_.empty() && status_ == NOT_FOUND; + } + + private: + ServingStatus status_ = NOT_FOUND; + std::set<std::shared_ptr<HealthCheckServiceImpl::CallHandler>> + call_handlers_; + }; + + void RegisterCallHandler( const TString& service_name, - std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler); - - void UnregisterCallHandler( + std::shared_ptr<HealthCheckServiceImpl::CallHandler> handler); + + void UnregisterCallHandler( const TString& service_name, - const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler); - + const std::shared_ptr<HealthCheckServiceImpl::CallHandler>& handler); + mutable grpc_core::Mutex mu_; bool shutdown_ = false; // Guarded by mu_. std::map<TString, ServiceData> services_map_; // Guarded by mu_. diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/constants.h b/contrib/libs/grpc/src/cpp/server/load_reporter/constants.h index 00ad794a04..eabed9711e 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/constants.h +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/constants.h @@ -1,81 +1,81 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_SRC_CPP_SERVER_LOAD_REPORTER_UTIL_H -#define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_UTIL_H - -#include <grpc/impl/codegen/port_platform.h> - -namespace grpc { -namespace load_reporter { - -// TODO(juanlishen): Update the version number with the PR number every time -// there is any change to the server load reporter. -constexpr uint32_t kVersion = 15853; - -// TODO(juanlishen): This window size is from the internal spec for the load -// reporter. Need to ask the gRPC LB team whether we should make this and the -// fetching interval configurable. -constexpr uint32_t kFeedbackSampleWindowSeconds = 10; -constexpr uint32_t kFetchAndSampleIntervalSeconds = 1; - -constexpr size_t kLbIdLength = 8; -constexpr size_t kIpv4AddressLength = 8; -constexpr size_t kIpv6AddressLength = 32; - -constexpr char kInvalidLbId[] = "<INVALID_LBID_238dsb234890rb>"; - -// Call statuses. - -constexpr char kCallStatusOk[] = "OK"; -constexpr char kCallStatusServerError[] = "5XX"; -constexpr char kCallStatusClientError[] = "4XX"; - -// Tag keys. - -constexpr char kTagKeyToken[] = "token"; -constexpr char kTagKeyHost[] = "host"; -constexpr char kTagKeyUserId[] = "user_id"; -constexpr char kTagKeyStatus[] = "status"; -constexpr char kTagKeyMetricName[] = "metric_name"; - -// Measure names. - -constexpr char kMeasureStartCount[] = "grpc.io/lb/start_count"; -constexpr char kMeasureEndCount[] = "grpc.io/lb/end_count"; -constexpr char kMeasureEndBytesSent[] = "grpc.io/lb/bytes_sent"; -constexpr char kMeasureEndBytesReceived[] = "grpc.io/lb/bytes_received"; -constexpr char kMeasureEndLatencyMs[] = "grpc.io/lb/latency_ms"; -constexpr char kMeasureOtherCallMetric[] = "grpc.io/lb/other_call_metric"; - -// View names. - -constexpr char kViewStartCount[] = "grpc.io/lb_view/start_count"; -constexpr char kViewEndCount[] = "grpc.io/lb_view/end_count"; -constexpr char kViewEndBytesSent[] = "grpc.io/lb_view/bytes_sent"; -constexpr char kViewEndBytesReceived[] = "grpc.io/lb_view/bytes_received"; -constexpr char kViewEndLatencyMs[] = "grpc.io/lb_view/latency_ms"; -constexpr char kViewOtherCallMetricCount[] = - "grpc.io/lb_view/other_call_metric_count"; -constexpr char kViewOtherCallMetricValue[] = - "grpc.io/lb_view/other_call_metric_value"; - -} // namespace load_reporter -} // namespace grpc - -#endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_UTIL_H +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_SRC_CPP_SERVER_LOAD_REPORTER_UTIL_H +#define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_UTIL_H + +#include <grpc/impl/codegen/port_platform.h> + +namespace grpc { +namespace load_reporter { + +// TODO(juanlishen): Update the version number with the PR number every time +// there is any change to the server load reporter. +constexpr uint32_t kVersion = 15853; + +// TODO(juanlishen): This window size is from the internal spec for the load +// reporter. Need to ask the gRPC LB team whether we should make this and the +// fetching interval configurable. +constexpr uint32_t kFeedbackSampleWindowSeconds = 10; +constexpr uint32_t kFetchAndSampleIntervalSeconds = 1; + +constexpr size_t kLbIdLength = 8; +constexpr size_t kIpv4AddressLength = 8; +constexpr size_t kIpv6AddressLength = 32; + +constexpr char kInvalidLbId[] = "<INVALID_LBID_238dsb234890rb>"; + +// Call statuses. + +constexpr char kCallStatusOk[] = "OK"; +constexpr char kCallStatusServerError[] = "5XX"; +constexpr char kCallStatusClientError[] = "4XX"; + +// Tag keys. + +constexpr char kTagKeyToken[] = "token"; +constexpr char kTagKeyHost[] = "host"; +constexpr char kTagKeyUserId[] = "user_id"; +constexpr char kTagKeyStatus[] = "status"; +constexpr char kTagKeyMetricName[] = "metric_name"; + +// Measure names. + +constexpr char kMeasureStartCount[] = "grpc.io/lb/start_count"; +constexpr char kMeasureEndCount[] = "grpc.io/lb/end_count"; +constexpr char kMeasureEndBytesSent[] = "grpc.io/lb/bytes_sent"; +constexpr char kMeasureEndBytesReceived[] = "grpc.io/lb/bytes_received"; +constexpr char kMeasureEndLatencyMs[] = "grpc.io/lb/latency_ms"; +constexpr char kMeasureOtherCallMetric[] = "grpc.io/lb/other_call_metric"; + +// View names. + +constexpr char kViewStartCount[] = "grpc.io/lb_view/start_count"; +constexpr char kViewEndCount[] = "grpc.io/lb_view/end_count"; +constexpr char kViewEndBytesSent[] = "grpc.io/lb_view/bytes_sent"; +constexpr char kViewEndBytesReceived[] = "grpc.io/lb_view/bytes_received"; +constexpr char kViewEndLatencyMs[] = "grpc.io/lb_view/latency_ms"; +constexpr char kViewOtherCallMetricCount[] = + "grpc.io/lb_view/other_call_metric_count"; +constexpr char kViewOtherCallMetricValue[] = + "grpc.io/lb_view/other_call_metric_value"; + +} // namespace load_reporter +} // namespace grpc + +#endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_UTIL_H diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats.h b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats.h index f514b0752f..8544b05417 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats.h +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats.h @@ -1,36 +1,36 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_SRC_CPP_SERVER_LOAD_REPORTER_GET_CPU_STATS_H -#define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_GET_CPU_STATS_H - -#include <grpc/impl/codegen/port_platform.h> - -#include <utility> - -namespace grpc { -namespace load_reporter { - -// Reads the CPU stats (in a pair of busy and total numbers) from the system. -// The units of the stats should be the same. -std::pair<uint64_t, uint64_t> GetCpuStatsImpl(); - -} // namespace load_reporter -} // namespace grpc - -#endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_GET_CPU_STATS_H +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_SRC_CPP_SERVER_LOAD_REPORTER_GET_CPU_STATS_H +#define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_GET_CPU_STATS_H + +#include <grpc/impl/codegen/port_platform.h> + +#include <utility> + +namespace grpc { +namespace load_reporter { + +// Reads the CPU stats (in a pair of busy and total numbers) from the system. +// The units of the stats should be the same. +std::pair<uint64_t, uint64_t> GetCpuStatsImpl(); + +} // namespace load_reporter +} // namespace grpc + +#endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_GET_CPU_STATS_H diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc index 561d4f5048..8565d384a8 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_linux.cc @@ -1,48 +1,48 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#ifdef GPR_LINUX - -#include <cstdio> - -#include "src/cpp/server/load_reporter/get_cpu_stats.h" - -namespace grpc { -namespace load_reporter { - -std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { - uint64_t busy = 0, total = 0; - FILE* fp; - fp = fopen("/proc/stat", "r"); - uint64_t user, nice, system, idle; +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#ifdef GPR_LINUX + +#include <cstdio> + +#include "src/cpp/server/load_reporter/get_cpu_stats.h" + +namespace grpc { +namespace load_reporter { + +std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { + uint64_t busy = 0, total = 0; + FILE* fp; + fp = fopen("/proc/stat", "r"); + uint64_t user, nice, system, idle; if (fscanf(fp, "cpu %lu %lu %lu %lu", &user, &nice, &system, &idle) != 4) { // Something bad happened with the information, so assume it's all invalid user = nice = system = idle = 0; } - fclose(fp); - busy = user + nice + system; - total = busy + idle; - return std::make_pair(busy, total); -} - -} // namespace load_reporter -} // namespace grpc - -#endif // GPR_LINUX + fclose(fp); + busy = user + nice + system; + total = busy + idle; + return std::make_pair(busy, total); +} + +} // namespace load_reporter +} // namespace grpc + +#endif // GPR_LINUX diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_macos.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_macos.cc index dbdde304c2..125631a3d1 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_macos.cc +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_macos.cc @@ -1,45 +1,45 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#ifdef GPR_APPLE - -#include <mach/mach.h> - -#include "src/cpp/server/load_reporter/get_cpu_stats.h" - -namespace grpc { -namespace load_reporter { - -std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { - uint64_t busy = 0, total = 0; - host_cpu_load_info_data_t cpuinfo; - mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; - if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, - (host_info_t)&cpuinfo, &count) == KERN_SUCCESS) { - for (int i = 0; i < CPU_STATE_MAX; i++) total += cpuinfo.cpu_ticks[i]; - busy = total - cpuinfo.cpu_ticks[CPU_STATE_IDLE]; - } - return std::make_pair(busy, total); -} - -} // namespace load_reporter -} // namespace grpc - -#endif // GPR_APPLE +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#ifdef GPR_APPLE + +#include <mach/mach.h> + +#include "src/cpp/server/load_reporter/get_cpu_stats.h" + +namespace grpc { +namespace load_reporter { + +std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { + uint64_t busy = 0, total = 0; + host_cpu_load_info_data_t cpuinfo; + mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT; + if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, + (host_info_t)&cpuinfo, &count) == KERN_SUCCESS) { + for (int i = 0; i < CPU_STATE_MAX; i++) total += cpuinfo.cpu_ticks[i]; + busy = total - cpuinfo.cpu_ticks[CPU_STATE_IDLE]; + } + return std::make_pair(busy, total); +} + +} // namespace load_reporter +} // namespace grpc + +#endif // GPR_APPLE diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_unsupported.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_unsupported.cc index 80fb8b6da1..e2d61859c8 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_unsupported.cc +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_unsupported.cc @@ -1,40 +1,40 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#if !defined(GPR_LINUX) && !defined(GPR_WINDOWS) && !defined(GPR_APPLE) - -#include <grpc/support/log.h> - -#include "src/cpp/server/load_reporter/get_cpu_stats.h" - -namespace grpc { -namespace load_reporter { - -std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { - uint64_t busy = 0, total = 0; - gpr_log(GPR_ERROR, - "Platforms other than Linux, Windows, and MacOS are not supported."); - return std::make_pair(busy, total); -} - -} // namespace load_reporter -} // namespace grpc - -#endif // !defined(GPR_LINUX) && !defined(GPR_WINDOWS) && !defined(GPR_APPLE) +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#if !defined(GPR_LINUX) && !defined(GPR_WINDOWS) && !defined(GPR_APPLE) + +#include <grpc/support/log.h> + +#include "src/cpp/server/load_reporter/get_cpu_stats.h" + +namespace grpc { +namespace load_reporter { + +std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { + uint64_t busy = 0, total = 0; + gpr_log(GPR_ERROR, + "Platforms other than Linux, Windows, and MacOS are not supported."); + return std::make_pair(busy, total); +} + +} // namespace load_reporter +} // namespace grpc + +#endif // !defined(GPR_LINUX) && !defined(GPR_WINDOWS) && !defined(GPR_APPLE) diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_windows.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_windows.cc index 0a98e848a2..bc5718a056 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_windows.cc +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/get_cpu_stats_windows.cc @@ -1,55 +1,55 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/support/port_platform.h> - -#ifdef GPR_WINDOWS - -#include <windows.h> -#include <cstdint> - -#include "src/cpp/server/load_reporter/get_cpu_stats.h" - -namespace grpc { -namespace load_reporter { - -namespace { - -uint64_t FiletimeToInt(const FILETIME& ft) { - ULARGE_INTEGER i; - i.LowPart = ft.dwLowDateTime; - i.HighPart = ft.dwHighDateTime; - return i.QuadPart; -} - -} // namespace - -std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { - uint64_t busy = 0, total = 0; - FILETIME idle, kernel, user; - if (GetSystemTimes(&idle, &kernel, &user) != 0) { - total = FiletimeToInt(kernel) + FiletimeToInt(user); - busy = total - FiletimeToInt(idle); - } - return std::make_pair(busy, total); -} - -} // namespace load_reporter -} // namespace grpc - -#endif // GPR_WINDOWS +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/support/port_platform.h> + +#ifdef GPR_WINDOWS + +#include <windows.h> +#include <cstdint> + +#include "src/cpp/server/load_reporter/get_cpu_stats.h" + +namespace grpc { +namespace load_reporter { + +namespace { + +uint64_t FiletimeToInt(const FILETIME& ft) { + ULARGE_INTEGER i; + i.LowPart = ft.dwLowDateTime; + i.HighPart = ft.dwHighDateTime; + return i.QuadPart; +} + +} // namespace + +std::pair<uint64_t, uint64_t> GetCpuStatsImpl() { + uint64_t busy = 0, total = 0; + FILETIME idle, kernel, user; + if (GetSystemTimes(&idle, &kernel, &user) != 0) { + total = FiletimeToInt(kernel) + FiletimeToInt(user); + busy = total - FiletimeToInt(idle); + } + return std::make_pair(busy, total); +} + +} // namespace load_reporter +} // namespace grpc + +#endif // GPR_WINDOWS diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc index f07fa812a7..12e8203fe1 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.cc @@ -16,15 +16,15 @@ * */ -#include <grpc/impl/codegen/port_platform.h> - -#include <stdio.h> +#include <grpc/impl/codegen/port_platform.h> + +#include <stdio.h> #include <cstdlib> #include <set> #include <unordered_map> #include <vector> -#include "src/core/lib/iomgr/socket_utils.h" +#include "src/core/lib/iomgr/socket_utils.h" #include "src/cpp/server/load_reporter/load_data_store.h" namespace grpc { @@ -79,65 +79,65 @@ const typename C::value_type* RandomElement(const C& container) { LoadRecordKey::LoadRecordKey(const TString& client_ip_and_token, TString user_id) - : user_id_(std::move(user_id)) { - GPR_ASSERT(client_ip_and_token.size() >= 2); - int ip_hex_size; - GPR_ASSERT(sscanf(client_ip_and_token.substr(0, 2).c_str(), "%d", - &ip_hex_size) == 1); - GPR_ASSERT(ip_hex_size == 0 || ip_hex_size == kIpv4AddressLength || - ip_hex_size == kIpv6AddressLength); - size_t cur_pos = 2; - client_ip_hex_ = client_ip_and_token.substr(cur_pos, ip_hex_size); - cur_pos += ip_hex_size; - if (client_ip_and_token.size() - cur_pos < kLbIdLength) { - lb_id_ = kInvalidLbId; - lb_tag_ = ""; - } else { - lb_id_ = client_ip_and_token.substr(cur_pos, kLbIdLength); - lb_tag_ = client_ip_and_token.substr(cur_pos + kLbIdLength); - } -} - + : user_id_(std::move(user_id)) { + GPR_ASSERT(client_ip_and_token.size() >= 2); + int ip_hex_size; + GPR_ASSERT(sscanf(client_ip_and_token.substr(0, 2).c_str(), "%d", + &ip_hex_size) == 1); + GPR_ASSERT(ip_hex_size == 0 || ip_hex_size == kIpv4AddressLength || + ip_hex_size == kIpv6AddressLength); + size_t cur_pos = 2; + client_ip_hex_ = client_ip_and_token.substr(cur_pos, ip_hex_size); + cur_pos += ip_hex_size; + if (client_ip_and_token.size() - cur_pos < kLbIdLength) { + lb_id_ = kInvalidLbId; + lb_tag_ = ""; + } else { + lb_id_ = client_ip_and_token.substr(cur_pos, kLbIdLength); + lb_tag_ = client_ip_and_token.substr(cur_pos + kLbIdLength); + } +} + TString LoadRecordKey::GetClientIpBytes() const { - if (client_ip_hex_.empty()) { - return ""; - } else if (client_ip_hex_.size() == kIpv4AddressLength) { - uint32_t ip_bytes; - if (sscanf(client_ip_hex_.c_str(), "%x", &ip_bytes) != 1) { - gpr_log(GPR_ERROR, - "Can't parse client IP (%s) from a hex string to an integer.", - client_ip_hex_.c_str()); - return ""; - } - ip_bytes = grpc_htonl(ip_bytes); + if (client_ip_hex_.empty()) { + return ""; + } else if (client_ip_hex_.size() == kIpv4AddressLength) { + uint32_t ip_bytes; + if (sscanf(client_ip_hex_.c_str(), "%x", &ip_bytes) != 1) { + gpr_log(GPR_ERROR, + "Can't parse client IP (%s) from a hex string to an integer.", + client_ip_hex_.c_str()); + return ""; + } + ip_bytes = grpc_htonl(ip_bytes); return TString(reinterpret_cast<const char*>(&ip_bytes), sizeof(ip_bytes)); - } else if (client_ip_hex_.size() == kIpv6AddressLength) { - uint32_t ip_bytes[4]; - for (size_t i = 0; i < 4; ++i) { - if (sscanf(client_ip_hex_.substr(i * 8, (i + 1) * 8).c_str(), "%x", - ip_bytes + i) != 1) { - gpr_log( - GPR_ERROR, - "Can't parse client IP part (%s) from a hex string to an integer.", - client_ip_hex_.substr(i * 8, (i + 1) * 8).c_str()); - return ""; - } - ip_bytes[i] = grpc_htonl(ip_bytes[i]); - } + } else if (client_ip_hex_.size() == kIpv6AddressLength) { + uint32_t ip_bytes[4]; + for (size_t i = 0; i < 4; ++i) { + if (sscanf(client_ip_hex_.substr(i * 8, (i + 1) * 8).c_str(), "%x", + ip_bytes + i) != 1) { + gpr_log( + GPR_ERROR, + "Can't parse client IP part (%s) from a hex string to an integer.", + client_ip_hex_.substr(i * 8, (i + 1) * 8).c_str()); + return ""; + } + ip_bytes[i] = grpc_htonl(ip_bytes[i]); + } return TString(reinterpret_cast<const char*>(ip_bytes), sizeof(ip_bytes)); - } else { - GPR_UNREACHABLE_CODE(return ""); - } -} - + } else { + GPR_UNREACHABLE_CODE(return ""); + } +} + LoadRecordValue::LoadRecordValue(TString metric_name, uint64_t num_calls, - double total_metric_value) { - call_metrics_.emplace(std::move(metric_name), - CallMetricValue(num_calls, total_metric_value)); -} - + double total_metric_value) { + call_metrics_.emplace(std::move(metric_name), + CallMetricValue(num_calls, total_metric_value)); +} + void PerBalancerStore::MergeRow(const LoadRecordKey& key, const LoadRecordValue& value) { // During suspension, the load data received will be dropped. diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h index 61ba618331..7047488c0e 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/load_data_store.h @@ -28,8 +28,8 @@ #include <grpc/support/log.h> #include <grpcpp/impl/codegen/config.h> -#include "src/cpp/server/load_reporter/constants.h" - +#include "src/cpp/server/load_reporter/constants.h" + #include <util/string/cast.h> namespace grpc { @@ -76,9 +76,9 @@ class LoadRecordKey { user_id_(std::move(user_id)), client_ip_hex_(std::move(client_ip_hex)) {} - // Parses the input client_ip_and_token to set client IP, LB ID, and LB tag. + // Parses the input client_ip_and_token to set client IP, LB ID, and LB tag. LoadRecordKey(const TString& client_ip_and_token, TString user_id); - + TString ToString() const { return "[lb_id_=" + lb_id_ + ", lb_tag_=" + lb_tag_ + ", user_id_=" + user_id_ + ", client_ip_hex_=" + client_ip_hex_ + @@ -90,9 +90,9 @@ class LoadRecordKey { user_id_ == other.user_id_ && client_ip_hex_ == other.client_ip_hex_; } - // Gets the client IP bytes in network order (i.e., big-endian). + // Gets the client IP bytes in network order (i.e., big-endian). TString GetClientIpBytes() const; - + // Getters. const TString& lb_id() const { return lb_id_; } const TString& lb_tag() const { return lb_tag_; } @@ -126,8 +126,8 @@ class LoadRecordKey { class LoadRecordValue { public: explicit LoadRecordValue(uint64_t start_count = 0, uint64_t ok_count = 0, - uint64_t error_count = 0, uint64_t bytes_sent = 0, - uint64_t bytes_recv = 0, uint64_t latency_ms = 0) + uint64_t error_count = 0, uint64_t bytes_sent = 0, + uint64_t bytes_recv = 0, uint64_t latency_ms = 0) : start_count_(start_count), ok_count_(ok_count), error_count_(error_count), @@ -136,8 +136,8 @@ class LoadRecordValue { latency_ms_(latency_ms) {} LoadRecordValue(TString metric_name, uint64_t num_calls, - double total_metric_value); - + double total_metric_value); + void MergeFrom(const LoadRecordValue& other) { start_count_ += other.start_count_; ok_count_ += other.ok_count_; @@ -175,9 +175,9 @@ class LoadRecordValue { uint64_t start_count() const { return start_count_; } uint64_t ok_count() const { return ok_count_; } uint64_t error_count() const { return error_count_; } - uint64_t bytes_sent() const { return bytes_sent_; } - uint64_t bytes_recv() const { return bytes_recv_; } - uint64_t latency_ms() const { return latency_ms_; } + uint64_t bytes_sent() const { return bytes_sent_; } + uint64_t bytes_recv() const { return bytes_recv_; } + uint64_t latency_ms() const { return latency_ms_; } const std::unordered_map<TString, CallMetricValue>& call_metrics() const { return call_metrics_; } @@ -186,9 +186,9 @@ class LoadRecordValue { uint64_t start_count_ = 0; uint64_t ok_count_ = 0; uint64_t error_count_ = 0; - uint64_t bytes_sent_ = 0; - uint64_t bytes_recv_ = 0; - uint64_t latency_ms_ = 0; + uint64_t bytes_sent_ = 0; + uint64_t bytes_recv_ = 0; + uint64_t latency_ms_ = 0; std::unordered_map<TString, CallMetricValue> call_metrics_; }; diff --git a/contrib/libs/grpc/src/cpp/server/load_reporter/util.cc b/contrib/libs/grpc/src/cpp/server/load_reporter/util.cc index 24ad9f3f24..a57ddc4715 100644 --- a/contrib/libs/grpc/src/cpp/server/load_reporter/util.cc +++ b/contrib/libs/grpc/src/cpp/server/load_reporter/util.cc @@ -1,47 +1,47 @@ -/* - * - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include <grpc/impl/codegen/port_platform.h> - -#include <grpcpp/ext/server_load_reporting.h> - -#include <cmath> - -#include <grpc/support/log.h> - +/* + * + * Copyright 2018 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <grpc/impl/codegen/port_platform.h> + +#include <grpcpp/ext/server_load_reporting.h> + +#include <cmath> + +#include <grpc/support/log.h> + namespace grpc { -namespace load_reporter { -namespace experimental { - -void AddLoadReportingCost(grpc::ServerContext* ctx, +namespace load_reporter { +namespace experimental { + +void AddLoadReportingCost(grpc::ServerContext* ctx, const TString& cost_name, double cost_value) { - if (std::isnormal(cost_value)) { + if (std::isnormal(cost_value)) { TString buf; - buf.resize(sizeof(cost_value) + cost_name.size()); - memcpy(&(*buf.begin()), &cost_value, sizeof(cost_value)); - memcpy(&(*buf.begin()) + sizeof(cost_value), cost_name.data(), - cost_name.size()); - ctx->AddTrailingMetadata(GRPC_LB_COST_MD_KEY, buf); - } else { - gpr_log(GPR_ERROR, "Call metric value is not normal."); - } -} - -} // namespace experimental -} // namespace load_reporter + buf.resize(sizeof(cost_value) + cost_name.size()); + memcpy(&(*buf.begin()), &cost_value, sizeof(cost_value)); + memcpy(&(*buf.begin()) + sizeof(cost_value), cost_name.data(), + cost_name.size()); + ctx->AddTrailingMetadata(GRPC_LB_COST_MD_KEY, buf); + } else { + gpr_log(GPR_ERROR, "Call metric value is not normal."); + } +} + +} // namespace experimental +} // namespace load_reporter } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc index 732602bcb7..3b73453515 100644 --- a/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc +++ b/contrib/libs/grpc/src/cpp/server/secure_server_credentials.cc @@ -44,10 +44,10 @@ void AuthMetadataProcessorAyncWrapper::Process( return; } if (w->processor_->IsBlocking()) { - w->thread_pool_->Add([w, context, md, num_md, cb, user_data] { - w->AuthMetadataProcessorAyncWrapper::InvokeProcessor(context, md, num_md, - cb, user_data); - }); + w->thread_pool_->Add([w, context, md, num_md, cb, user_data] { + w->AuthMetadataProcessorAyncWrapper::InvokeProcessor(context, md, num_md, + cb, user_data); + }); } else { // invoke directly. w->InvokeProcessor(context, md, num_md, cb, user_data); @@ -62,7 +62,7 @@ void AuthMetadataProcessorAyncWrapper::InvokeProcessor( metadata.insert(std::make_pair(StringRefFromSlice(&md[i].key), StringRefFromSlice(&md[i].value))); } - SecureAuthContext context(ctx); + SecureAuthContext context(ctx); AuthMetadataProcessor::OutputMetadata consumed_metadata; AuthMetadataProcessor::OutputMetadata response_metadata; @@ -138,12 +138,12 @@ std::shared_ptr<ServerCredentials> AltsServerCredentials( new SecureServerCredentials(c_creds)); } -std::shared_ptr<ServerCredentials> LocalServerCredentials( - grpc_local_connect_type type) { - return std::shared_ptr<ServerCredentials>( - new SecureServerCredentials(grpc_local_server_credentials_create(type))); -} - +std::shared_ptr<ServerCredentials> LocalServerCredentials( + grpc_local_connect_type type) { + return std::shared_ptr<ServerCredentials>( + new SecureServerCredentials(grpc_local_server_credentials_create(type))); +} + std::shared_ptr<ServerCredentials> TlsServerCredentials( const grpc::experimental::TlsCredentialsOptions& options) { grpc::GrpcLibraryCodegen init; diff --git a/contrib/libs/grpc/src/cpp/server/server_builder.cc b/contrib/libs/grpc/src/cpp/server/server_builder.cc index 0cc00b365f..ec5d4eec8c 100644 --- a/contrib/libs/grpc/src/cpp/server/server_builder.cc +++ b/contrib/libs/grpc/src/cpp/server/server_builder.cc @@ -24,8 +24,8 @@ #include <grpcpp/resource_quota.h> #include <grpcpp/server.h> -#include <utility> - +#include <utility> + #include "src/core/lib/channel/channel_args.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/useful.h" @@ -44,8 +44,8 @@ static void do_plugin_list_init(void) { } ServerBuilder::ServerBuilder() - : max_receive_message_size_(INT_MIN), - max_send_message_size_(INT_MIN), + : max_receive_message_size_(INT_MIN), + max_send_message_size_(INT_MIN), sync_server_settings_(SyncServerSettings()), resource_quota_(nullptr) { gpr_once_init(&once_init_plugin_list, do_plugin_list_init); @@ -71,9 +71,9 @@ ServerBuilder::~ServerBuilder() { std::unique_ptr<grpc::ServerCompletionQueue> ServerBuilder::AddCompletionQueue( bool is_frequently_polled) { grpc::ServerCompletionQueue* cq = new grpc::ServerCompletionQueue( - GRPC_CQ_NEXT, - is_frequently_polled ? GRPC_CQ_DEFAULT_POLLING : GRPC_CQ_NON_LISTENING, - nullptr); + GRPC_CQ_NEXT, + is_frequently_polled ? GRPC_CQ_DEFAULT_POLLING : GRPC_CQ_NON_LISTENING, + nullptr); cqs_.push_back(cq); return std::unique_ptr<grpc::ServerCompletionQueue>(cq); } @@ -180,7 +180,7 @@ ServerBuilder& ServerBuilder::SetCompressionAlgorithmSupportStatus( ServerBuilder& ServerBuilder::SetDefaultCompressionLevel( grpc_compression_level level) { - maybe_default_compression_level_.is_set = true; + maybe_default_compression_level_.is_set = true; maybe_default_compression_level_.level = level; return *this; } @@ -212,14 +212,14 @@ ServerBuilder& ServerBuilder::AddListeningPort( while (addr_uri[pos] == '/') ++pos; // Skip slashes. addr = addr_uri.substr(pos); } - Port port = {addr, std::move(creds), selected_port}; + Port port = {addr, std::move(creds), selected_port}; ports_.push_back(port); return *this; } std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { grpc::ChannelArguments args; - if (max_receive_message_size_ >= -1) { + if (max_receive_message_size_ >= -1) { args.SetInt(GRPC_ARG_MAX_RECEIVE_MESSAGE_LENGTH, max_receive_message_size_); } if (max_send_message_size_ >= -1) { @@ -306,14 +306,14 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { // 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( + sync_server_cqs->emplace_back( new grpc::ServerCompletionQueue(GRPC_CQ_NEXT, polling_type, nullptr)); } } - // TODO(vjpai): Add a section here for plugins once they can support callback - // methods - + // TODO(vjpai): Add a section here for plugins once they can support callback + // methods + if (has_sync_methods) { // This is a Sync server gpr_log(GPR_INFO, @@ -324,16 +324,16 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { sync_server_settings_.cq_timeout_msec); } - if (has_callback_methods) { - gpr_log(GPR_INFO, "Callback server."); - } - + if (has_callback_methods) { + gpr_log(GPR_INFO, "Callback server."); + } + std::unique_ptr<grpc::Server> server(new grpc::Server( &args, sync_server_cqs, sync_server_settings_.min_pollers, sync_server_settings_.max_pollers, sync_server_settings_.cq_timeout_msec, std::move(acceptors_), resource_quota_, std::move(interceptor_creators_))); - + ServerInitializer* initializer = server->initializer(); // Register all the completion queues with the server. i.e @@ -347,10 +347,10 @@ std::unique_ptr<grpc::Server> ServerBuilder::BuildAndStart() { } if (has_callback_methods || callback_generic_service_ != nullptr) { - auto* cq = server->CallbackCQ(); - grpc_server_register_completion_queue(server->server_, cq->cq(), nullptr); - } - + auto* cq = server->CallbackCQ(); + grpc_server_register_completion_queue(server->server_, cq->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 diff --git a/contrib/libs/grpc/src/cpp/server/server_cc.cc b/contrib/libs/grpc/src/cpp/server/server_cc.cc index c2a911c7f7..56bf75d730 100644 --- a/contrib/libs/grpc/src/cpp/server/server_cc.cc +++ b/contrib/libs/grpc/src/cpp/server/server_cc.cc @@ -30,10 +30,10 @@ #include <grpcpp/generic/async_generic_service.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/byte_buffer.h> -#include <grpcpp/impl/codegen/call.h> +#include <grpcpp/impl/codegen/call.h> #include <grpcpp/impl/codegen/completion_queue_tag.h> #include <grpcpp/impl/codegen/method_handler.h> -#include <grpcpp/impl/codegen/server_interceptor.h> +#include <grpcpp/impl/codegen/server_interceptor.h> #include <grpcpp/impl/grpc_library.h> #include <grpcpp/impl/rpc_service_method.h> #include <grpcpp/impl/server_initializer.h> @@ -43,10 +43,10 @@ #include <grpcpp/support/time.h> #include "src/core/ext/transport/inproc/inproc_transport.h" -#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/exec_ctx.h" #include "src/core/lib/profiling/timers.h" #include "src/core/lib/surface/call.h" -#include "src/core/lib/surface/completion_queue.h" +#include "src/core/lib/surface/completion_queue.h" #include "src/core/lib/surface/server.h" #include "src/cpp/client/create_channel_internal.h" #include "src/cpp/server/external_connection_acceptor_impl.h" @@ -58,13 +58,13 @@ namespace grpc { namespace { -// The default value for maximum number of threads that can be created in the -// sync server. This value of INT_MAX is chosen to match the default behavior if -// no ResourceQuota is set. To modify the max number of threads in a sync -// server, pass a custom ResourceQuota object (with the desired number of -// max-threads set) to the server builder. -#define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX - +// The default value for maximum number of threads that can be created in the +// sync server. This value of INT_MAX is chosen to match the default behavior if +// no ResourceQuota is set. To modify the max number of threads in a sync +// server, pass a custom ResourceQuota object (with the desired number of +// max-threads set) to the server builder. +#define DEFAULT_MAX_SYNC_SERVER_THREADS INT_MAX + class DefaultGlobalCallbacks final : public Server::GlobalCallbacks { public: ~DefaultGlobalCallbacks() override {} @@ -319,10 +319,10 @@ class Server::UnimplementedAsyncResponse final grpc::internal::CallOpSendInitialMetadata, grpc::internal::CallOpServerSendStatus>::FinalizeResult(tag, status)) { - delete this; - } else { - // The tag was swallowed due to interception. We will see it again. - } + delete this; + } else { + // The tag was swallowed due to interception. We will see it again. + } return false; } @@ -334,7 +334,7 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { public: SyncRequest(grpc::internal::RpcServiceMethod* method, void* method_tag) : method_(method), - method_tag_(method_tag), + method_tag_(method_tag), in_flight_(false), has_request_payload_(method->method_type() == grpc::internal::RpcMethod::NORMAL_RPC || @@ -362,11 +362,11 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { void Request(grpc_server* server, grpc_completion_queue* notify_cq) { GPR_ASSERT(cq_ && !in_flight_); in_flight_ = true; - if (method_tag_) { - if (grpc_server_request_registered_call( - server, method_tag_, &call_, &deadline_, &request_metadata_, + if (method_tag_) { + if (grpc_server_request_registered_call( + server, method_tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, - notify_cq, this) != GRPC_CALL_OK) { + notify_cq, this) != GRPC_CALL_OK) { TeardownRequest(); return; } @@ -384,21 +384,21 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { } } - void PostShutdownCleanup() { - if (call_) { - grpc_call_unref(call_); - call_ = nullptr; - } - if (cq_) { - grpc_completion_queue_destroy(cq_); - cq_ = nullptr; - } - } - + void PostShutdownCleanup() { + if (call_) { + grpc_call_unref(call_); + call_ = nullptr; + } + if (cq_) { + grpc_completion_queue_destroy(cq_); + cq_ = nullptr; + } + } + bool FinalizeResult(void** /*tag*/, bool* status) override { if (!*status) { grpc_completion_queue_destroy(cq_); - cq_ = nullptr; + cq_ = nullptr; } if (call_details_) { deadline_ = call_details_->deadline; @@ -408,26 +408,26 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { return true; } - // The CallData class represents a call that is "active" as opposed - // to just being requested. It wraps and takes ownership of the cq from - // the call request + // The CallData class represents a call that is "active" as opposed + // to just being requested. It wraps and takes ownership of the cq from + // the call request class CallData final { public: explicit CallData(Server* server, SyncRequest* mrd) : cq_(mrd->cq_), ctx_(mrd->deadline_, &mrd->request_metadata_), has_request_payload_(mrd->has_request_payload_), - request_payload_(has_request_payload_ ? mrd->request_payload_ - : nullptr), - request_(nullptr), - method_(mrd->method_), - call_( - mrd->call_, server, &cq_, server->max_receive_message_size(), - ctx_.set_server_rpc_info(method_->name(), method_->method_type(), - server->interceptor_creators_)), - server_(server), - global_callbacks_(nullptr), - resources_(false) { + request_payload_(has_request_payload_ ? mrd->request_payload_ + : nullptr), + request_(nullptr), + method_(mrd->method_), + call_( + mrd->call_, server, &cq_, server->max_receive_message_size(), + ctx_.set_server_rpc_info(method_->name(), method_->method_type(), + server->interceptor_creators_)), + server_(server), + global_callbacks_(nullptr), + resources_(false) { ctx_.set_call(mrd->call_); ctx_.cq_ = &cq_; GPR_ASSERT(mrd->in_flight_); @@ -441,82 +441,82 @@ class Server::SyncRequest final : public grpc::internal::CompletionQueueTag { } } - void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks, - bool resources) { - global_callbacks_ = global_callbacks; - resources_ = resources; + void Run(const std::shared_ptr<GlobalCallbacks>& global_callbacks, + bool resources) { + global_callbacks_ = global_callbacks; + resources_ = resources; - interceptor_methods_.SetCall(&call_); - interceptor_methods_.SetReverse(); - // Set interception point for RECV INITIAL METADATA - interceptor_methods_.AddInterceptionHookPoint( + interceptor_methods_.SetCall(&call_); + interceptor_methods_.SetReverse(); + // Set interception point for RECV INITIAL METADATA + interceptor_methods_.AddInterceptionHookPoint( grpc::experimental::InterceptionHookPoints:: POST_RECV_INITIAL_METADATA); - interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_); + interceptor_methods_.SetRecvInitialMetadata(&ctx_.client_metadata_); - if (has_request_payload_) { - // Set interception point for RECV MESSAGE - auto* handler = resources_ ? method_->handler() - : server_->resource_exhausted_handler_.get(); - request_ = handler->Deserialize(call_.call(), request_payload_, + if (has_request_payload_) { + // Set interception point for RECV MESSAGE + auto* handler = resources_ ? method_->handler() + : server_->resource_exhausted_handler_.get(); + request_ = handler->Deserialize(call_.call(), request_payload_, &request_status_, nullptr); - request_payload_ = nullptr; - interceptor_methods_.AddInterceptionHookPoint( + request_payload_ = nullptr; + interceptor_methods_.AddInterceptionHookPoint( grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE); - interceptor_methods_.SetRecvMessage(request_, nullptr); - } - - if (interceptor_methods_.RunInterceptors( - [this]() { ContinueRunAfterInterception(); })) { - ContinueRunAfterInterception(); - } else { - // There were interceptors to be run, so ContinueRunAfterInterception - // will be run when interceptors are done. - } + interceptor_methods_.SetRecvMessage(request_, nullptr); + } + + if (interceptor_methods_.RunInterceptors( + [this]() { ContinueRunAfterInterception(); })) { + ContinueRunAfterInterception(); + } else { + // There were interceptors to be run, so ContinueRunAfterInterception + // will be run when interceptors are done. + } } - void ContinueRunAfterInterception() { - { - ctx_.BeginCompletionOp(&call_, nullptr, nullptr); - global_callbacks_->PreSynchronousRequest(&ctx_); - auto* handler = resources_ ? method_->handler() - : server_->resource_exhausted_handler_.get(); + void ContinueRunAfterInterception() { + { + ctx_.BeginCompletionOp(&call_, nullptr, nullptr); + global_callbacks_->PreSynchronousRequest(&ctx_); + auto* handler = resources_ ? method_->handler() + : server_->resource_exhausted_handler_.get(); handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter( &call_, &ctx_, request_, request_status_, nullptr, nullptr)); - request_ = nullptr; - global_callbacks_->PostSynchronousRequest(&ctx_); - - cq_.Shutdown(); - + request_ = nullptr; + global_callbacks_->PostSynchronousRequest(&ctx_); + + cq_.Shutdown(); + grpc::internal::CompletionQueueTag* op_tag = ctx_.GetCompletionOpTag(); - cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME)); - - /* Ensure the cq_ is shutdown */ + cq_.TryPluck(op_tag, gpr_inf_future(GPR_CLOCK_REALTIME)); + + /* Ensure the cq_ is shutdown */ grpc::DummyTag ignored_tag; - GPR_ASSERT(cq_.Pluck(&ignored_tag) == false); - } - delete this; - } - + GPR_ASSERT(cq_.Pluck(&ignored_tag) == false); + } + delete this; + } + private: grpc::CompletionQueue cq_; grpc::ServerContext ctx_; const bool has_request_payload_; grpc_byte_buffer* request_payload_; - void* request_; + void* request_; grpc::Status request_status_; grpc::internal::RpcServiceMethod* const method_; grpc::internal::Call call_; - Server* server_; - std::shared_ptr<GlobalCallbacks> global_callbacks_; - bool resources_; + Server* server_; + std::shared_ptr<GlobalCallbacks> global_callbacks_; + bool resources_; grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; }; private: grpc::internal::RpcServiceMethod* const method_; - void* const method_tag_; + void* const method_tag_; bool in_flight_; const bool has_request_payload_; grpc_call* call_; @@ -541,19 +541,19 @@ class Server::CallbackRequest final CallbackRequest(Server* server, grpc::internal::RpcServiceMethod* method, grpc::CompletionQueue* cq, grpc_core::Server::RegisteredCallAllocation* data) - : server_(server), - method_(method), + : server_(server), + method_(method), has_request_payload_(method->method_type() == grpc::internal::RpcMethod::NORMAL_RPC || method->method_type() == grpc::internal::RpcMethod::SERVER_STREAMING), cq_(cq), - tag_(this) { + tag_(this) { CommonSetup(server, data); data->deadline = &deadline_; data->optional_payload = has_request_payload_ ? &request_payload_ : nullptr; - } - + } + // For generic services, method is nullptr since these services don't have // pre-defined methods. CallbackRequest(Server* server, grpc::CompletionQueue* cq, @@ -567,8 +567,8 @@ class Server::CallbackRequest final CommonSetup(server, data); grpc_call_details_init(call_details_); data->details = call_details_; - } - + } + ~CallbackRequest() { delete call_details_; grpc_metadata_array_destroy(&request_metadata_); @@ -576,21 +576,21 @@ class Server::CallbackRequest final grpc_byte_buffer_destroy(request_payload_); } server_->UnrefWithPossibleNotify(); - } - + } + // Needs specialization to account for different processing of metadata // in generic API bool FinalizeResult(void** tag, bool* status) override; - - private: + + private: // method_name needs to be specialized between named method and generic const char* method_name() const; - class CallbackCallTag : public grpc_experimental_completion_queue_functor { - public: + class CallbackCallTag : public grpc_experimental_completion_queue_functor { + public: CallbackCallTag(Server::CallbackRequest<ServerContextType>* req) : req_(req) { - functor_run = &CallbackCallTag::StaticRun; + functor_run = &CallbackCallTag::StaticRun; // Set inlineable to true since this callback is internally-controlled // without taking any locks, and thus does not need to be run from the // executor (which triggers a thread hop). This should only be used by @@ -598,42 +598,42 @@ class Server::CallbackRequest final // here is actually non-trivial, but there is no chance of having user // locks conflict with each other so it's ok to run inlined. inlineable = true; - } - - // force_run can not be performed on a tag if operations using this tag - // have been sent to PerformOpsOnCall. It is intended for error conditions - // that are detected before the operations are internally processed. - void force_run(bool ok) { Run(ok); } - - private: + } + + // force_run can not be performed on a tag if operations using this tag + // have been sent to PerformOpsOnCall. It is intended for error conditions + // that are detected before the operations are internally processed. + void force_run(bool ok) { Run(ok); } + + private: Server::CallbackRequest<ServerContextType>* req_; grpc::internal::Call* call_; - - static void StaticRun(grpc_experimental_completion_queue_functor* cb, - int ok) { - static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok)); - } - void Run(bool ok) { - void* ignored = req_; - bool new_ok = ok; - GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok)); - GPR_ASSERT(ignored == req_); - - if (!ok) { - // The call has been shutdown. - // Delete its contents to free up the request. - delete req_; - return; - } - - // Bind the call, deadline, and metadata from what we got - req_->ctx_.set_call(req_->call_); - req_->ctx_.cq_ = req_->cq_; - req_->ctx_.BindDeadlineAndMetadata(req_->deadline_, - &req_->request_metadata_); - req_->request_metadata_.count = 0; - - // Create a C++ Call to control the underlying core call + + static void StaticRun(grpc_experimental_completion_queue_functor* cb, + int ok) { + static_cast<CallbackCallTag*>(cb)->Run(static_cast<bool>(ok)); + } + void Run(bool ok) { + void* ignored = req_; + bool new_ok = ok; + GPR_ASSERT(!req_->FinalizeResult(&ignored, &new_ok)); + GPR_ASSERT(ignored == req_); + + if (!ok) { + // The call has been shutdown. + // Delete its contents to free up the request. + delete req_; + return; + } + + // Bind the call, deadline, and metadata from what we got + req_->ctx_.set_call(req_->call_); + req_->ctx_.cq_ = req_->cq_; + req_->ctx_.BindDeadlineAndMetadata(req_->deadline_, + &req_->request_metadata_); + req_->request_metadata_.count = 0; + + // Create a C++ Call to control the underlying core call call_ = new (grpc_call_arena_alloc(req_->call_, sizeof(grpc::internal::Call))) grpc::internal::Call( @@ -645,71 +645,71 @@ class Server::CallbackRequest final ? req_->method_->method_type() : grpc::internal::RpcMethod::BIDI_STREAMING, req_->server_->interceptor_creators_)); - - req_->interceptor_methods_.SetCall(call_); - req_->interceptor_methods_.SetReverse(); - // Set interception point for RECV INITIAL METADATA - req_->interceptor_methods_.AddInterceptionHookPoint( + + req_->interceptor_methods_.SetCall(call_); + req_->interceptor_methods_.SetReverse(); + // Set interception point for RECV INITIAL METADATA + req_->interceptor_methods_.AddInterceptionHookPoint( grpc::experimental::InterceptionHookPoints:: POST_RECV_INITIAL_METADATA); - req_->interceptor_methods_.SetRecvInitialMetadata( - &req_->ctx_.client_metadata_); - - if (req_->has_request_payload_) { - // Set interception point for RECV MESSAGE - req_->request_ = req_->method_->handler()->Deserialize( + req_->interceptor_methods_.SetRecvInitialMetadata( + &req_->ctx_.client_metadata_); + + if (req_->has_request_payload_) { + // Set interception point for RECV MESSAGE + req_->request_ = req_->method_->handler()->Deserialize( req_->call_, req_->request_payload_, &req_->request_status_, &req_->handler_data_); - req_->request_payload_ = nullptr; - req_->interceptor_methods_.AddInterceptionHookPoint( + req_->request_payload_ = nullptr; + req_->interceptor_methods_.AddInterceptionHookPoint( grpc::experimental::InterceptionHookPoints::POST_RECV_MESSAGE); - req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr); - } - - if (req_->interceptor_methods_.RunInterceptors( - [this] { ContinueRunAfterInterception(); })) { - ContinueRunAfterInterception(); - } else { - // There were interceptors to be run, so ContinueRunAfterInterception - // will be run when interceptors are done. - } - } - void ContinueRunAfterInterception() { + req_->interceptor_methods_.SetRecvMessage(req_->request_, nullptr); + } + + if (req_->interceptor_methods_.RunInterceptors( + [this] { ContinueRunAfterInterception(); })) { + ContinueRunAfterInterception(); + } else { + // There were interceptors to be run, so ContinueRunAfterInterception + // will be run when interceptors are done. + } + } + void ContinueRunAfterInterception() { auto* handler = (req_->method_ != nullptr) ? req_->method_->handler() : req_->server_->generic_handler_.get(); handler->RunHandler(grpc::internal::MethodHandler::HandlerParameter( call_, &req_->ctx_, req_->request_, req_->request_status_, req_->handler_data_, [this] { delete req_; })); - } - }; - + } + }; + template <class CallAllocation> void CommonSetup(Server* server, CallAllocation* data) { server->Ref(); - grpc_metadata_array_init(&request_metadata_); + grpc_metadata_array_init(&request_metadata_); data->tag = &tag_; data->call = &call_; data->initial_metadata = &request_metadata_; - } - - Server* const server_; + } + + Server* const server_; grpc::internal::RpcServiceMethod* const method_; - const bool has_request_payload_; + const bool has_request_payload_; grpc_byte_buffer* request_payload_ = nullptr; void* request_ = nullptr; void* handler_data_ = nullptr; grpc::Status request_status_; grpc_call_details* const call_details_ = nullptr; - grpc_call* call_; - gpr_timespec deadline_; - grpc_metadata_array request_metadata_; + grpc_call* call_; + gpr_timespec deadline_; + grpc_metadata_array request_metadata_; grpc::CompletionQueue* const cq_; - CallbackCallTag tag_; + CallbackCallTag tag_; ServerContextType ctx_; grpc::internal::InterceptorBatchMethodsImpl interceptor_methods_; -}; - +}; + template <> bool Server::CallbackRequest<grpc::CallbackServerContext>::FinalizeResult( void** /*tag*/, bool* /*status*/) { @@ -750,13 +750,13 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { public: SyncRequestThreadManager(Server* server, grpc::CompletionQueue* server_cq, std::shared_ptr<GlobalCallbacks> global_callbacks, - grpc_resource_quota* rq, int min_pollers, - int max_pollers, int cq_timeout_msec) - : ThreadManager("SyncServer", rq, min_pollers, max_pollers), + grpc_resource_quota* rq, int min_pollers, + int max_pollers, int cq_timeout_msec) + : ThreadManager("SyncServer", rq, min_pollers, max_pollers), server_(server), server_cq_(server_cq), cq_timeout_msec_(cq_timeout_msec), - global_callbacks_(std::move(global_callbacks)) {} + global_callbacks_(std::move(global_callbacks)) {} WorkStatus PollForWork(void** tag, bool* ok) override { *tag = nullptr; @@ -778,7 +778,7 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { GPR_UNREACHABLE_CODE(return TIMEOUT); } - void DoWork(void* tag, bool ok, bool resources) override { + void DoWork(void* tag, bool ok, bool resources) override { SyncRequest* sync_req = static_cast<SyncRequest*>(tag); if (!sync_req) { @@ -789,9 +789,9 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { } if (ok) { - // Calldata takes ownership of the completion queue and interceptors - // inside sync_req - auto* cd = new SyncRequest::CallData(server_, sync_req); + // Calldata takes ownership of the completion queue and interceptors + // inside sync_req + auto* cd = new SyncRequest::CallData(server_, sync_req); // Prepare for the next request if (!IsShutdown()) { sync_req->SetupRequest(); // Create new completion queue for sync_req @@ -799,7 +799,7 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { } GPR_TIMER_SCOPE("cd.Run()", 0); - cd->Run(global_callbacks_, resources); + cd->Run(global_callbacks_, resources); } // 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 @@ -831,17 +831,17 @@ class Server::SyncRequestThreadManager : public grpc::ThreadManager { void* tag; bool ok; while (server_cq_->Next(&tag, &ok)) { - if (ok) { - // If a request was pulled off the queue, it means that the thread - // handling the request added it to the completion queue after shutdown - // was called - because the thread had already started and checked the - // shutdown flag before shutdown was called. In this case, we simply - // clean it up here, *after* calling wait on all the worker threads, at - // which point we are certain no in-flight requests will add more to the - // queue. This fixes an intermittent memory leak on shutdown. - SyncRequest* sync_req = static_cast<SyncRequest*>(tag); - sync_req->PostShutdownCleanup(); - } + if (ok) { + // If a request was pulled off the queue, it means that the thread + // handling the request added it to the completion queue after shutdown + // was called - because the thread had already started and checked the + // shutdown flag before shutdown was called. In this case, we simply + // clean it up here, *after* calling wait on all the worker threads, at + // which point we are certain no in-flight requests will add more to the + // queue. This fixes an intermittent memory leak on shutdown. + SyncRequest* sync_req = static_cast<SyncRequest*>(tag); + sync_req->PostShutdownCleanup(); + } } } @@ -870,17 +870,17 @@ Server::Server( grpc::ChannelArguments* args, std::shared_ptr<std::vector<std::unique_ptr<grpc::ServerCompletionQueue>>> sync_server_cqs, - int min_pollers, int max_pollers, int sync_cq_timeout_msec, + int min_pollers, int max_pollers, int sync_cq_timeout_msec, std::vector<std::shared_ptr<grpc::internal::ExternalConnectionAcceptorImpl>> acceptors, - grpc_resource_quota* server_rq, - std::vector< + grpc_resource_quota* server_rq, + std::vector< std::unique_ptr<grpc::experimental::ServerInterceptorFactoryInterface>> - interceptor_creators) + interceptor_creators) : acceptors_(std::move(acceptors)), interceptor_creators_(std::move(interceptor_creators)), max_receive_message_size_(INT_MIN), - sync_server_cqs_(std::move(sync_server_cqs)), + sync_server_cqs_(std::move(sync_server_cqs)), started_(false), shutdown_(false), shutdown_notified_(false), @@ -893,23 +893,23 @@ Server::Server( global_callbacks_->UpdateArguments(args); if (sync_server_cqs_ != nullptr) { - bool default_rq_created = false; - if (server_rq == nullptr) { - server_rq = grpc_resource_quota_create("SyncServer-default-rq"); - grpc_resource_quota_set_max_threads(server_rq, - DEFAULT_MAX_SYNC_SERVER_THREADS); - default_rq_created = true; - } - + bool default_rq_created = false; + if (server_rq == nullptr) { + server_rq = grpc_resource_quota_create("SyncServer-default-rq"); + grpc_resource_quota_set_max_threads(server_rq, + DEFAULT_MAX_SYNC_SERVER_THREADS); + default_rq_created = true; + } + for (const auto& it : *sync_server_cqs_) { sync_req_mgrs_.emplace_back(new SyncRequestThreadManager( - this, it.get(), global_callbacks_, server_rq, min_pollers, - max_pollers, sync_cq_timeout_msec)); - } - - if (default_rq_created) { - grpc_resource_quota_unref(server_rq); + this, it.get(), global_callbacks_, server_rq, min_pollers, + max_pollers, sync_cq_timeout_msec)); } + + if (default_rq_created) { + grpc_resource_quota_unref(server_rq); + } } for (auto& acceptor : acceptors_) { @@ -974,24 +974,24 @@ std::shared_ptr<grpc::Channel> Server::InProcessChannel( const grpc::ChannelArguments& args) { grpc_channel_args channel_args = args.c_channel_args(); return grpc::CreateChannelInternal( - "inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr), + "inproc", grpc_inproc_channel_create(server_, &channel_args, nullptr), std::vector<std::unique_ptr< grpc::experimental::ClientInterceptorFactoryInterface>>()); } std::shared_ptr<grpc::Channel> -Server::experimental_type::InProcessChannelWithInterceptors( +Server::experimental_type::InProcessChannelWithInterceptors( const grpc::ChannelArguments& args, - std::vector< + std::vector< std::unique_ptr<grpc::experimental::ClientInterceptorFactoryInterface>> - interceptor_creators) { - grpc_channel_args channel_args = args.c_channel_args(); + interceptor_creators) { + grpc_channel_args channel_args = args.c_channel_args(); return grpc::CreateChannelInternal( - "inproc", - grpc_inproc_channel_create(server_->server_, &channel_args, nullptr), - std::move(interceptor_creators)); -} - + "inproc", + grpc_inproc_channel_create(server_->server_, &channel_args, nullptr), + std::move(interceptor_creators)); +} + static grpc_server_register_method_payload_handling PayloadHandlingForMethod( grpc::internal::RpcServiceMethod* method) { switch (method->method_type()) { @@ -1014,29 +1014,29 @@ bool Server::RegisterService(const TString* host, grpc::Service* service) { } const char* method_name = nullptr; - + for (const auto& method : service->methods_) { if (method.get() == nullptr) { // Handled by generic service if any. continue; } - void* method_registration_tag = grpc_server_register_method( + void* method_registration_tag = grpc_server_register_method( server_, method->name(), host ? host->c_str() : nullptr, PayloadHandlingForMethod(method.get()), 0); - if (method_registration_tag == nullptr) { + if (method_registration_tag == nullptr) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } - if (method->handler() == nullptr) { // Async method without handler - method->set_server_tag(method_registration_tag); - } else if (method->api_type() == + if (method->handler() == nullptr) { // Async method without handler + method->set_server_tag(method_registration_tag); + } else if (method->api_type() == grpc::internal::RpcServiceMethod::ApiType::SYNC) { for (const auto& value : sync_req_mgrs_) { value->AddSyncMethod(method.get(), method_registration_tag); } - } else { + } else { has_callback_methods_ = true; grpc::internal::RpcServiceMethod* method_value = method.get(); grpc::CompletionQueue* cq = CallbackCQ(); @@ -1130,23 +1130,23 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { // explicit one. grpc::ServerCompletionQueue* health_check_cq = nullptr; grpc::DefaultHealthCheckService::HealthCheckServiceImpl* - default_health_check_service_impl = nullptr; + default_health_check_service_impl = nullptr; if (health_check_service_ == nullptr && !health_check_service_disabled_ && grpc::DefaultHealthCheckServiceEnabled()) { auto* default_hc_service = new grpc::DefaultHealthCheckService; - health_check_service_.reset(default_hc_service); - // We create a non-polling CQ to avoid impacting application - // performance. This ensures that we don't introduce thread hops - // for application requests that wind up on this CQ, which is polled - // in its own thread. + health_check_service_.reset(default_hc_service); + // We create a non-polling CQ to avoid impacting application + // performance. This ensures that we don't introduce thread hops + // for application requests that wind up on this CQ, which is polled + // in its own thread. health_check_cq = new grpc::ServerCompletionQueue( GRPC_CQ_NEXT, GRPC_CQ_NON_POLLING, nullptr); - grpc_server_register_completion_queue(server_, health_check_cq->cq(), - nullptr); - default_health_check_service_impl = - default_hc_service->GetHealthCheckService( + grpc_server_register_completion_queue(server_, health_check_cq->cq(), + nullptr); + default_health_check_service_impl = + default_hc_service->GetHealthCheckService( std::unique_ptr<grpc::ServerCompletionQueue>(health_check_cq)); - RegisterService(nullptr, default_health_check_service_impl); + RegisterService(nullptr, default_health_check_service_impl); } for (auto& acceptor : acceptors_) { @@ -1179,26 +1179,26 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { new UnimplementedAsyncRequest(this, cqs[i]); } } - if (health_check_cq != nullptr) { - new UnimplementedAsyncRequest(this, health_check_cq); - } + if (health_check_cq != nullptr) { + new UnimplementedAsyncRequest(this, health_check_cq); + } } - // If this server has any support for synchronous methods (has any sync - // server CQs), make sure that we have a ResourceExhausted handler - // to deal with the case of thread exhaustion - if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) { + // If this server has any support for synchronous methods (has any sync + // server CQs), make sure that we have a ResourceExhausted handler + // to deal with the case of thread exhaustion + if (sync_server_cqs_ != nullptr && !sync_server_cqs_->empty()) { resource_exhausted_handler_.reset( new grpc::internal::ResourceExhaustedHandler); - } - + } + for (const auto& value : sync_req_mgrs_) { value->Start(); } - - if (default_health_check_service_impl != nullptr) { - default_health_check_service_impl->StartServingThread(); - } + + if (default_health_check_service_impl != nullptr) { + default_health_check_service_impl->StartServingThread(); + } for (auto& acceptor : acceptors_) { acceptor->Start(); @@ -1207,50 +1207,50 @@ void Server::Start(grpc::ServerCompletionQueue** cqs, size_t num_cqs) { void Server::ShutdownInternal(gpr_timespec deadline) { grpc::internal::MutexLock lock(&mu_); - if (shutdown_) { - return; - } + if (shutdown_) { + return; + } - shutdown_ = true; + shutdown_ = true; for (auto& acceptor : acceptors_) { acceptor->Shutdown(); } - /// The completion queue to use for server shutdown completion notification + /// The completion queue to use for server shutdown completion notification grpc::CompletionQueue shutdown_cq; grpc::ShutdownTag shutdown_tag; // Dummy shutdown tag - grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag); + grpc_server_shutdown_and_notify(server_, shutdown_cq.cq(), &shutdown_tag); - shutdown_cq.Shutdown(); + shutdown_cq.Shutdown(); - void* tag; - bool ok; + void* tag; + bool ok; grpc::CompletionQueue::NextStatus status = - shutdown_cq.AsyncNext(&tag, &ok, deadline); + 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 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 == grpc::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 + grpc_server_cancel_all_calls(server_); + } + // Else in case of SHUTDOWN or GOT_EVENT, it means that the server has + // successfully shutdown - // Shutdown all ThreadManagers. This will try to gracefully stop all the - // threads in the ThreadManagers (once they process any inflight requests) + // Shutdown all ThreadManagers. This will try to gracefully stop all the + // threads in the ThreadManagers (once they process any inflight requests) for (const auto& value : sync_req_mgrs_) { value->Shutdown(); // ThreadManager's Shutdown() - } + } - // Wait for threads in all ThreadManagers to terminate + // Wait for threads in all ThreadManagers to terminate for (const auto& value : sync_req_mgrs_) { value->Wait(); - } + } // Drop the shutdown ref and wait for all other refs to drop as well. UnrefAndWaitLocked(); - + // Shutdown the callback CQ. The CQ is owned by its own shutdown tag, so it // will delete itself at true shutdown. if (callback_cq_ != nullptr) { @@ -1258,13 +1258,13 @@ void Server::ShutdownInternal(gpr_timespec deadline) { callback_cq_ = nullptr; } - // 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; + // 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; shutdown_cv_.Broadcast(); #ifndef NDEBUG @@ -1286,23 +1286,23 @@ void Server::Wait() { void Server::PerformOpsOnCall(grpc::internal::CallOpSetInterface* ops, grpc::internal::Call* call) { - ops->FillOps(call); + ops->FillOps(call); } bool Server::UnimplementedAsyncRequest::FinalizeResult(void** tag, bool* status) { - if (GenericAsyncRequest::FinalizeResult(tag, status)) { - // We either had no interceptors run or we are done intercepting - if (*status) { + if (GenericAsyncRequest::FinalizeResult(tag, status)) { + // We either had no interceptors run or we are done intercepting + if (*status) { // Create a new request/response pair using the server and CQ values // stored in this object's base class. new UnimplementedAsyncRequest(server_, notification_cq_); - new UnimplementedAsyncResponse(this); - } else { - delete this; - } + new UnimplementedAsyncResponse(this); + } else { + delete this; + } } else { - // The tag was swallowed due to interception. We will see it again. + // The tag was swallowed due to interception. We will see it again. } return false; } @@ -1320,8 +1320,8 @@ grpc::ServerInitializer* Server::initializer() { } grpc::CompletionQueue* Server::CallbackCQ() { - // TODO(vjpai): Consider using a single global CQ for the default CQ - // if there is no explicit per-server CQ registered + // TODO(vjpai): Consider using a single global CQ for the default CQ + // if there is no explicit per-server CQ registered grpc::internal::MutexLock l(&mu_); if (callback_cq_ != nullptr) { return callback_cq_; @@ -1330,11 +1330,11 @@ grpc::CompletionQueue* Server::CallbackCQ() { callback_cq_ = new grpc::CompletionQueue(grpc_completion_queue_attributes{ GRPC_CQ_CURRENT_VERSION, GRPC_CQ_CALLBACK, GRPC_CQ_DEFAULT_POLLING, shutdown_callback}); - + // Transfer ownership of the new cq to its own shutdown callback shutdown_callback->TakeCQ(callback_cq_); - return callback_cq_; + return callback_cq_; } - + } // namespace grpc diff --git a/contrib/libs/grpc/src/cpp/server/server_context.cc b/contrib/libs/grpc/src/cpp/server/server_context.cc index 458ac20d87..fea258e6e7 100644 --- a/contrib/libs/grpc/src/cpp/server/server_context.cc +++ b/contrib/libs/grpc/src/cpp/server/server_context.cc @@ -43,50 +43,50 @@ class ServerContextBase::CompletionOp final : public internal::CallOpSetInterface { public: // initial refs: one in the server context, one in the cq - // must ref the call before calling constructor and after deleting this + // must ref the call before calling constructor and after deleting this CompletionOp(internal::Call* call, ::grpc::internal::ServerCallbackCall* callback_controller) - : call_(*call), + : call_(*call), callback_controller_(callback_controller), - has_tag_(false), + has_tag_(false), tag_(nullptr), - core_cq_tag_(this), + core_cq_tag_(this), refs_(2), finalized_(false), - cancelled_(0), - done_intercepting_(false) {} - - // CompletionOp isn't copyable or movable - CompletionOp(const CompletionOp&) = delete; - CompletionOp& operator=(const CompletionOp&) = delete; - CompletionOp(CompletionOp&&) = delete; - CompletionOp& operator=(CompletionOp&&) = delete; - - ~CompletionOp() { - if (call_.server_rpc_info()) { - call_.server_rpc_info()->Unref(); - } - } - + cancelled_(0), + done_intercepting_(false) {} + + // CompletionOp isn't copyable or movable + CompletionOp(const CompletionOp&) = delete; + CompletionOp& operator=(const CompletionOp&) = delete; + CompletionOp(CompletionOp&&) = delete; + CompletionOp& operator=(CompletionOp&&) = delete; + + ~CompletionOp() { + if (call_.server_rpc_info()) { + call_.server_rpc_info()->Unref(); + } + } + void FillOps(internal::Call* call) override; - - // This should always be arena allocated in the call, so override delete. - // But this class is not trivially destructible, so must actually call delete - // before allowing the arena to be freed + + // This should always be arena allocated in the call, so override delete. + // But this class is not trivially destructible, so must actually call delete + // before allowing the arena to be freed static void operator delete(void* /*ptr*/, std::size_t size) { // Use size to avoid unused-parameter warning since assert seems to be // compiled out and treated as unused in some gcc optimized versions. (void)size; - assert(size == sizeof(CompletionOp)); - } - - // This operator should never be called as the memory should be freed as part - // of the arena destruction. It only exists to provide a matching operator - // delete to the operator new so that some compilers will not complain (see - // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this - // there are no tests catching the compiler warning. - static void operator delete(void*, void*) { assert(0); } - + assert(size == sizeof(CompletionOp)); + } + + // This operator should never be called as the memory should be freed as part + // of the arena destruction. It only exists to provide a matching operator + // delete to the operator new so that some compilers will not complain (see + // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this + // there are no tests catching the compiler warning. + static void operator delete(void*, void*) { assert(0); } + bool FinalizeResult(void** tag, bool* status) override; bool CheckCancelled(CompletionQueue* cq) { @@ -100,36 +100,36 @@ class ServerContextBase::CompletionOp final tag_ = tag; } - void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } - - void* core_cq_tag() override { return core_cq_tag_; } - + void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; } + + void* core_cq_tag() override { return core_cq_tag_; } + void Unref(); - // This will be called while interceptors are run if the RPC is a hijacked - // RPC. This should set hijacking state for each of the ops. - void SetHijackingState() override { - /* Servers don't allow hijacking */ + // This will be called while interceptors are run if the RPC is a hijacked + // RPC. This should set hijacking state for each of the ops. + void SetHijackingState() override { + /* Servers don't allow hijacking */ GPR_ASSERT(false); - } - - /* Should be called after interceptors are done running */ - void ContinueFillOpsAfterInterception() override {} - - /* Should be called after interceptors are done running on the finalize result - * path */ - void ContinueFinalizeResultAfterInterception() override { - done_intercepting_ = true; - if (!has_tag_) { - /* We don't have a tag to return. */ + } + + /* Should be called after interceptors are done running */ + void ContinueFillOpsAfterInterception() override {} + + /* Should be called after interceptors are done running on the finalize result + * path */ + void ContinueFinalizeResultAfterInterception() override { + done_intercepting_ = true; + if (!has_tag_) { + /* We don't have a tag to return. */ Unref(); - return; - } - /* Start a dummy op so that we can return the tag */ + return; + } + /* Start a dummy op so that we can return the tag */ GPR_ASSERT(grpc_call_start_batch(call_.call(), nullptr, 0, core_cq_tag_, nullptr) == GRPC_CALL_OK); - } - + } + private: bool CheckCancelledNoPluck() { grpc_core::MutexLock lock(&mu_); @@ -140,37 +140,37 @@ class ServerContextBase::CompletionOp final ::grpc::internal::ServerCallbackCall* const callback_controller_; bool has_tag_; void* tag_; - void* core_cq_tag_; + void* core_cq_tag_; grpc_core::RefCount refs_; grpc_core::Mutex mu_; bool finalized_; - int cancelled_; // This is an int (not bool) because it is passed to core - bool done_intercepting_; + int cancelled_; // This is an int (not bool) because it is passed to core + bool done_intercepting_; internal::InterceptorBatchMethodsImpl interceptor_methods_; }; void ServerContextBase::CompletionOp::Unref() { if (refs_.Unref()) { - grpc_call* call = call_.call(); + grpc_call* call = call_.call(); delete this; - grpc_call_unref(call); + grpc_call_unref(call); } } void ServerContextBase::CompletionOp::FillOps(internal::Call* call) { - grpc_op ops; - ops.op = GRPC_OP_RECV_CLOSE_ON_SERVER; - ops.data.recv_close_on_server.cancelled = &cancelled_; - ops.flags = 0; - ops.reserved = nullptr; - interceptor_methods_.SetCall(&call_); - interceptor_methods_.SetReverse(); - interceptor_methods_.SetCallOpSetInterface(this); + grpc_op ops; + ops.op = GRPC_OP_RECV_CLOSE_ON_SERVER; + ops.data.recv_close_on_server.cancelled = &cancelled_; + ops.flags = 0; + ops.reserved = nullptr; + interceptor_methods_.SetCall(&call_); + interceptor_methods_.SetReverse(); + interceptor_methods_.SetCallOpSetInterface(this); // The following call_start_batch is internally-generated so no need for an // explanatory log on failure. GPR_ASSERT(grpc_call_start_batch(call->call(), &ops, 1, core_cq_tag_, nullptr) == GRPC_CALL_OK); - /* No interceptors to run here */ + /* No interceptors to run here */ } bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { @@ -187,9 +187,9 @@ bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { } Unref(); return has_tag; - } + } finalized_ = true; - + // If for some reason the incoming status is false, mark that as a // cancellation. // TODO(vjpai): does this ever happen? @@ -200,24 +200,24 @@ bool ServerContextBase::CompletionOp::FinalizeResult(void** tag, bool* status) { call_cancel = (cancelled_ != 0); // Release the lock since we may call a callback and interceptors. } - + if (call_cancel && callback_controller_ != nullptr) { callback_controller_->MaybeCallOnCancel(); } - /* Add interception point and run through interceptors */ - interceptor_methods_.AddInterceptionHookPoint( + /* Add interception point and run through interceptors */ + interceptor_methods_.AddInterceptionHookPoint( experimental::InterceptionHookPoints::POST_RECV_CLOSE); - if (interceptor_methods_.RunInterceptors()) { + if (interceptor_methods_.RunInterceptors()) { // No interceptors were run bool has_tag = has_tag_; if (has_tag) { - *tag = tag_; - } + *tag = tag_; + } Unref(); return has_tag; - } + } // There are interceptors to be run. Return false for now. - return false; + return false; } // ServerContextBase body @@ -233,17 +233,17 @@ ServerContextBase::ServerContextBase(gpr_timespec deadline, void ServerContextBase::BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr) { - deadline_ = deadline; - std::swap(*client_metadata_.arr(), *arr); -} - + deadline_ = deadline; + std::swap(*client_metadata_.arr(), *arr); +} + ServerContextBase::~ServerContextBase() { if (completion_op_) { completion_op_->Unref(); } - if (rpc_info_) { - rpc_info_->Unref(); - } + if (rpc_info_) { + rpc_info_->Unref(); + } if (default_reactor_used_.load(std::memory_order_relaxed)) { reinterpret_cast<Reactor*>(&default_reactor_)->~Reactor(); } @@ -261,19 +261,19 @@ void ServerContextBase::BeginCompletionOp( internal::Call* call, std::function<void(bool)> callback, ::grpc::internal::ServerCallbackCall* callback_controller) { GPR_ASSERT(!completion_op_); - if (rpc_info_) { - rpc_info_->Ref(); - } - grpc_call_ref(call->call()); - completion_op_ = - new (grpc_call_arena_alloc(call->call(), sizeof(CompletionOp))) + if (rpc_info_) { + rpc_info_->Ref(); + } + grpc_call_ref(call->call()); + completion_op_ = + new (grpc_call_arena_alloc(call->call(), sizeof(CompletionOp))) CompletionOp(call, callback_controller); if (callback_controller != nullptr) { completion_tag_.Set(call->call(), std::move(callback), completion_op_, true); - completion_op_->set_core_cq_tag(&completion_tag_); - completion_op_->set_tag(completion_op_); - } else if (has_notify_when_done_tag_) { + completion_op_->set_core_cq_tag(&completion_tag_); + completion_op_->set_tag(completion_op_); + } else if (has_notify_when_done_tag_) { completion_op_->set_tag(async_notify_when_done_tag_); } call->PerformOps(completion_op_); @@ -295,11 +295,11 @@ void ServerContextBase::AddTrailingMetadata(const TString& key, void ServerContextBase::TryCancel() const { internal::CancelInterceptorBatchMethods cancel_methods; - if (rpc_info_) { - for (size_t i = 0; i < rpc_info_->interceptors_.size(); i++) { - rpc_info_->RunInterceptor(&cancel_methods, i); - } - } + if (rpc_info_) { + for (size_t i = 0; i < rpc_info_->interceptors_.size(); i++) { + rpc_info_->RunInterceptor(&cancel_methods, i); + } + } grpc_call_error err = grpc_call_cancel_with_status(call_.call, GRPC_STATUS_CANCELLED, "Cancelled on the server side", nullptr); @@ -309,15 +309,15 @@ void ServerContextBase::TryCancel() const { } bool ServerContextBase::IsCancelled() const { - if (completion_tag_) { - // When using callback API, this result is always valid. - return completion_op_->CheckCancelledAsync(); - } else if (has_notify_when_done_tag_) { - // When using async API, the result is only valid + if (completion_tag_) { + // When using callback API, this result is always valid. + return completion_op_->CheckCancelledAsync(); + } else if (has_notify_when_done_tag_) { + // When using async API, the result is only valid // if the tag has already been delivered at the completion queue return completion_op_ && completion_op_->CheckCancelledAsync(); } else { - // when using sync API, the result is always valid + // when using sync API, the result is always valid return completion_op_ && completion_op_->CheckCancelled(cq_); } } diff --git a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc index c8560aa81d..c93129dc5f 100644 --- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc +++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.cc @@ -22,7 +22,7 @@ #include <grpc/support/log.h> #include "src/core/lib/gprpp/thd.h" -#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/exec_ctx.h" namespace grpc { @@ -49,17 +49,17 @@ ThreadManager::WorkerThread::~WorkerThread() { thd_.Join(); } -ThreadManager::ThreadManager(const char* name, - grpc_resource_quota* resource_quota, - int min_pollers, int max_pollers) +ThreadManager::ThreadManager(const char* name, + grpc_resource_quota* resource_quota, + 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), - max_active_threads_sofar_(0) { - resource_user_ = grpc_resource_user_create(resource_quota, name); -} + num_threads_(0), + max_active_threads_sofar_(0) { + resource_user_ = grpc_resource_user_create(resource_quota, name); +} ThreadManager::~ThreadManager() { { @@ -67,8 +67,8 @@ ThreadManager::~ThreadManager() { GPR_ASSERT(num_threads_ == 0); } - grpc_core::ExecCtx exec_ctx; // grpc_resource_user_unref needs an exec_ctx - grpc_resource_user_unref(resource_user_); + grpc_core::ExecCtx exec_ctx; // grpc_resource_user_unref needs an exec_ctx + grpc_resource_user_unref(resource_user_); CleanupCompletedThreads(); } @@ -89,27 +89,27 @@ bool ThreadManager::IsShutdown() { return shutdown_; } -int ThreadManager::GetMaxActiveThreadsSoFar() { +int ThreadManager::GetMaxActiveThreadsSoFar() { grpc_core::MutexLock list_lock(&list_mu_); - return max_active_threads_sofar_; -} - + return max_active_threads_sofar_; +} + void ThreadManager::MarkAsCompleted(WorkerThread* thd) { { grpc_core::MutexLock list_lock(&list_mu_); completed_threads_.push_back(thd); } - { + { grpc_core::MutexLock lock(&mu_); - num_threads_--; - if (num_threads_ == 0) { + num_threads_--; + if (num_threads_ == 0) { shutdown_cv_.Signal(); - } + } } - - // Give a thread back to the resource quota - grpc_resource_user_free_threads(resource_user_, 1); + + // Give a thread back to the resource quota + grpc_resource_user_free_threads(resource_user_, 1); } void ThreadManager::CleanupCompletedThreads() { @@ -124,19 +124,19 @@ void ThreadManager::CleanupCompletedThreads() { } void ThreadManager::Initialize() { - if (!grpc_resource_user_allocate_threads(resource_user_, min_pollers_)) { - gpr_log(GPR_ERROR, - "No thread quota available to even create the minimum required " - "polling threads (i.e %d). Unable to start the thread manager", - min_pollers_); - abort(); - } - + if (!grpc_resource_user_allocate_threads(resource_user_, min_pollers_)) { + gpr_log(GPR_ERROR, + "No thread quota available to even create the minimum required " + "polling threads (i.e %d). Unable to start the thread manager", + min_pollers_); + abort(); + } + { grpc_core::MutexLock lock(&mu_); num_pollers_ = min_pollers_; num_threads_ = min_pollers_; - max_active_threads_sofar_ = min_pollers_; + max_active_threads_sofar_ = min_pollers_; } for (int i = 0; i < min_pollers_; i++) { @@ -167,18 +167,18 @@ void ThreadManager::MainWorkLoop() { done = true; break; case WORK_FOUND: - // If we got work and there are now insufficient pollers and there is - // quota available to create a new thread, start a new poller thread - bool resource_exhausted = false; + // If we got work and there are now insufficient pollers and there is + // quota available to create a new thread, start a new poller thread + bool resource_exhausted = false; if (!shutdown_ && num_pollers_ < min_pollers_) { - if (grpc_resource_user_allocate_threads(resource_user_, 1)) { - // We can allocate a new poller thread - num_pollers_++; - num_threads_++; - if (num_threads_ > max_active_threads_sofar_) { - max_active_threads_sofar_ = num_threads_; - } - // Drop lock before spawning thread to avoid contention + if (grpc_resource_user_allocate_threads(resource_user_, 1)) { + // We can allocate a new poller thread + num_pollers_++; + num_threads_++; + if (num_threads_ > max_active_threads_sofar_) { + max_active_threads_sofar_ = num_threads_; + } + // Drop lock before spawning thread to avoid contention lock.Unlock(); WorkerThread* worker = new WorkerThread(this); if (worker->created()) { @@ -191,26 +191,26 @@ void ThreadManager::MainWorkLoop() { resource_exhausted = true; delete worker; } - } else if (num_pollers_ > 0) { - // There is still at least some thread polling, so we can go on - // even though we are below the number of pollers that we would - // like to have (min_pollers_) + } else if (num_pollers_ > 0) { + // There is still at least some thread polling, so we can go on + // even though we are below the number of pollers that we would + // like to have (min_pollers_) lock.Unlock(); - } else { - // There are no pollers to spare and we couldn't allocate - // a new thread, so resources are exhausted! + } else { + // There are no pollers to spare and we couldn't allocate + // a new thread, so resources are exhausted! lock.Unlock(); - resource_exhausted = true; - } + resource_exhausted = true; + } } else { - // There are a sufficient number of pollers available so we can do - // the work and continue polling with our existing poller threads + // There are a sufficient number of pollers available so we can do + // the work and continue polling with our existing poller threads lock.Unlock(); } // Lock is always released at this point - do the application work - // or return resource exhausted if there is new work but we couldn't - // get a thread in which to do it. - DoWork(tag, ok, !resource_exhausted); + // or return resource exhausted if there is new work but we couldn't + // get a thread in which to do it. + DoWork(tag, ok, !resource_exhausted); // Take the lock again to check post conditions lock.Lock(); // If we're shutdown, we should finish at this point. @@ -254,8 +254,8 @@ void ThreadManager::MainWorkLoop() { } }; - // This thread is exiting. Do some cleanup work i.e delete already completed - // worker threads + // This thread is exiting. Do some cleanup work i.e delete already completed + // worker threads CleanupCompletedThreads(); // If we are here, either ThreadManager is shutting down or it already has diff --git a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h index 43f1fd5585..902b237cfd 100644 --- a/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h +++ b/contrib/libs/grpc/src/cpp/thread_manager/thread_manager.h @@ -26,14 +26,14 @@ #include "src/core/lib/gprpp/sync.h" #include "src/core/lib/gprpp/thd.h" -#include "src/core/lib/iomgr/resource_quota.h" +#include "src/core/lib/iomgr/resource_quota.h" namespace grpc { class ThreadManager { public: - explicit ThreadManager(const char* name, grpc_resource_quota* resource_quota, - int min_pollers, int max_pollers); + explicit ThreadManager(const char* name, grpc_resource_quota* resource_quota, + int min_pollers, int max_pollers); virtual ~ThreadManager(); // Initializes and Starts the Rpc Manager threads @@ -66,14 +66,14 @@ class ThreadManager { // 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 resources parameter indicates that the call actually - // has the resources available for performing the RPC's work. If it doesn't, - // the implementation should fail it appropriately. + // PollForWork(). The resources parameter indicates that the call actually + // has the resources available for performing the RPC's work. If it doesn't, + // the implementation should fail it appropriately. // // 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, bool resources) = 0; + virtual void DoWork(void* tag, bool ok, bool resources) = 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 @@ -87,11 +87,11 @@ class ThreadManager { // all the threads have drained all the outstanding work virtual void Wait(); - // Max number of concurrent threads that were ever active in this thread - // manager so far. This is useful for debugging purposes (and in unit tests) - // to check if resource_quota is properly being enforced. - int GetMaxActiveThreadsSoFar(); - + // Max number of concurrent threads that were ever active in this thread + // manager so far. This is useful for debugging purposes (and in unit tests) + // to check if resource_quota is properly being enforced. + int GetMaxActiveThreadsSoFar(); + private: // Helper wrapper class around grpc_core::Thread. Takes a ThreadManager object // and starts a new grpc_core::Thread to calls the Run() function. @@ -99,24 +99,24 @@ class ThreadManager { // The Run() function calls ThreadManager::MainWorkLoop() function and once // that completes, it marks the WorkerThread completed by calling // ThreadManager::MarkAsCompleted() - // - // WHY IS THIS NEEDED?: - // When a thread terminates, some other thread *must* call Join() on that - // thread so that the resources are released. Having a WorkerThread wrapper - // will make this easier. Once Run() completes, each thread calls the - // following two functions: - // ThreadManager::CleanupCompletedThreads() - // ThreadManager::MarkAsCompleted() - // - // - MarkAsCompleted() puts the WorkerThread object in the ThreadManger's - // completed_threads_ list - // - CleanupCompletedThreads() calls "Join()" on the threads that are already - // in the completed_threads_ list (since a thread cannot call Join() on - // itself, it calls CleanupCompletedThreads() *before* calling - // MarkAsCompleted()) - // - // TODO(sreek): Consider creating the threads 'detached' so that Join() need - // not be called (and the need for this WorkerThread class is eliminated) + // + // WHY IS THIS NEEDED?: + // When a thread terminates, some other thread *must* call Join() on that + // thread so that the resources are released. Having a WorkerThread wrapper + // will make this easier. Once Run() completes, each thread calls the + // following two functions: + // ThreadManager::CleanupCompletedThreads() + // ThreadManager::MarkAsCompleted() + // + // - MarkAsCompleted() puts the WorkerThread object in the ThreadManger's + // completed_threads_ list + // - CleanupCompletedThreads() calls "Join()" on the threads that are already + // in the completed_threads_ list (since a thread cannot call Join() on + // itself, it calls CleanupCompletedThreads() *before* calling + // MarkAsCompleted()) + // + // TODO(sreek): Consider creating the threads 'detached' so that Join() need + // not be called (and the need for this WorkerThread class is eliminated) class WorkerThread { public: WorkerThread(ThreadManager* thd_mgr); @@ -141,21 +141,21 @@ class ThreadManager { void MarkAsCompleted(WorkerThread* thd); void CleanupCompletedThreads(); - // Protects shutdown_, num_pollers_, num_threads_ and - // max_active_threads_sofar_ + // Protects shutdown_, num_pollers_, num_threads_ and + // max_active_threads_sofar_ grpc_core::Mutex mu_; bool shutdown_; grpc_core::CondVar shutdown_cv_; - // The resource user object to use when requesting quota to create threads - // - // Note: The user of this ThreadManager object must create grpc_resource_quota - // object (that contains the actual max thread quota) and a grpc_resource_user + // The resource user object to use when requesting quota to create threads + // + // Note: The user of this ThreadManager object must create grpc_resource_quota + // object (that contains the actual max thread quota) and a grpc_resource_user // object through which quota is requested whenever new threads need to be - // created - grpc_resource_user* resource_user_; - + // created + grpc_resource_user* resource_user_; + // Number of threads doing polling int num_pollers_; @@ -163,15 +163,15 @@ class ThreadManager { int min_pollers_; int max_pollers_; - // The total number of threads currently active (includes threads includes the - // threads that are currently polling i.e num_pollers_) + // The total number of threads currently active (includes threads includes the + // threads that are currently polling i.e num_pollers_) int num_threads_; - // See GetMaxActiveThreadsSoFar()'s description. - // To be more specific, this variable tracks the max value num_threads_ was - // ever set so far - int max_active_threads_sofar_; - + // See GetMaxActiveThreadsSoFar()'s description. + // To be more specific, this variable tracks the max value num_threads_ was + // ever set so far + int max_active_threads_sofar_; + grpc_core::Mutex list_mu_; std::list<WorkerThread*> completed_threads_; }; diff --git a/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto b/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto index d0781094ea..13fbdc818e 100644 --- a/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto +++ b/contrib/libs/grpc/src/proto/grpc/channelz/channelz.proto @@ -1,4 +1,4 @@ -// Copyright 2018 The gRPC Authors +// Copyright 2018 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,26 +12,26 @@ // See the License for the specific language governing permissions and // limitations under the License. -// This file defines an interface for exporting monitoring information -// out of gRPC servers. See the full design at -// https://github.com/grpc/proposal/blob/master/A14-channelz.md -// -// The canonical version of this proto can be found at -// https://github.com/grpc/grpc-proto/blob/master/grpc/channelz/v1/channelz.proto - +// This file defines an interface for exporting monitoring information +// out of gRPC servers. See the full design at +// https://github.com/grpc/proposal/blob/master/A14-channelz.md +// +// The canonical version of this proto can be found at +// https://github.com/grpc/grpc-proto/blob/master/grpc/channelz/v1/channelz.proto + syntax = "proto3"; -package grpc.channelz.v1; +package grpc.channelz.v1; import "google/protobuf/any.proto"; import "google/protobuf/duration.proto"; import "google/protobuf/timestamp.proto"; import "google/protobuf/wrappers.proto"; -option go_package = "google.golang.org/grpc/channelz/grpc_channelz_v1"; -option java_multiple_files = true; -option java_package = "io.grpc.channelz.v1"; -option java_outer_classname = "ChannelzProto"; +option go_package = "google.golang.org/grpc/channelz/grpc_channelz_v1"; +option java_multiple_files = true; +option java_package = "io.grpc.channelz.v1"; +option java_outer_classname = "ChannelzProto"; // Channel is a logical grouping of channels, subchannels, and sockets. message Channel { @@ -53,7 +53,7 @@ message Channel { repeated SubchannelRef subchannel_ref = 4; // There are no ordering guarantees on the order of sockets. - repeated SocketRef socket_ref = 5; + repeated SocketRef socket_ref = 5; } // Subchannel is a logical grouping of channels, subchannels, and sockets. @@ -77,7 +77,7 @@ message Subchannel { repeated SubchannelRef subchannel_ref = 4; // There are no ordering guarantees on the order of sockets. - repeated SocketRef socket_ref = 5; + repeated SocketRef socket_ref = 5; } // These come from the specified states in this document: @@ -94,23 +94,23 @@ message ChannelConnectivityState { State state = 1; } -// Channel data is data related to a specific Channel or Subchannel. +// Channel data is data related to a specific Channel or Subchannel. message ChannelData { - // The connectivity state of the channel or subchannel. Implementations - // should always set this. + // The connectivity state of the channel or subchannel. Implementations + // should always set this. ChannelConnectivityState state = 1; // The target this channel originally tried to connect to. May be absent string target = 2; - // A trace of recent events on the channel. May be absent. + // A trace of recent events on the channel. May be absent. ChannelTrace trace = 3; // The number of calls started on the channel int64 calls_started = 4; // The number of calls that have completed with an OK status int64 calls_succeeded = 5; - // The number of calls that have completed with a non-OK status + // The number of calls that have completed with a non-OK status int64 calls_failed = 6; // The last time a call was started on the channel. @@ -143,26 +143,26 @@ message ChannelTraceEvent { } } -// ChannelTrace represents the recent events that have occurred on the channel. +// ChannelTrace represents the recent events that have occurred on the channel. message ChannelTrace { // Number of events ever logged in this tracing object. This can differ from // events.size() because events can be overwritten or garbage collected by // implementations. int64 num_events_logged = 1; // Time that this channel was created. - google.protobuf.Timestamp creation_timestamp = 2; + google.protobuf.Timestamp creation_timestamp = 2; // List of events that have occurred on this channel. repeated ChannelTraceEvent events = 3; } -// ChannelRef is a reference to a Channel. +// ChannelRef is a reference to a Channel. message ChannelRef { // The globally unique id for this channel. Must be a positive number. int64 channel_id = 1; // An optional name associated with the channel. string name = 2; // Intentionally don't use field numbers from other refs. - reserved 3, 4, 5, 6, 7, 8; + reserved 3, 4, 5, 6, 7, 8; } // SubchannelRef is a reference to a Subchannel. @@ -175,9 +175,9 @@ message SubchannelRef { reserved 1, 2, 3, 4, 5, 6; } -// SocketRef is a reference to a Socket. +// SocketRef is a reference to a Socket. message SocketRef { - // The globally unique id for this socket. Must be a positive number. + // The globally unique id for this socket. Must be a positive number. int64 socket_id = 3; // An optional name associated with the socket. string name = 4; @@ -185,9 +185,9 @@ message SocketRef { reserved 1, 2, 5, 6, 7, 8; } -// ServerRef is a reference to a Server. +// ServerRef is a reference to a Server. message ServerRef { - // A globally unique identifier for this server. Must be a positive number. + // A globally unique identifier for this server. Must be a positive number. int64 server_id = 5; // An optional name associated with the server. string name = 6; @@ -195,22 +195,22 @@ message ServerRef { reserved 1, 2, 3, 4, 7, 8; } -// Server represents a single server. There may be multiple servers in a single -// program. +// Server represents a single server. There may be multiple servers in a single +// program. message Server { - // The identifier for a Server. This should be set. + // The identifier for a Server. This should be set. ServerRef ref = 1; - // The associated data of the Server. + // The associated data of the Server. ServerData data = 2; // The sockets that the server is listening on. There are no ordering - // guarantees. This may be absent. + // guarantees. This may be absent. repeated SocketRef listen_socket = 3; } -// ServerData is data for a specific Server. +// ServerData is data for a specific Server. message ServerData { - // A trace of recent events on the server. May be absent. + // A trace of recent events on the server. May be absent. ChannelTrace trace = 1; // The number of incoming calls started on the server @@ -226,17 +226,17 @@ message ServerData { // Information about an actual connection. Pronounced "sock-ay". message Socket { - // The identifier for the Socket. + // The identifier for the Socket. SocketRef ref = 1; - // Data specific to this Socket. + // Data specific to this Socket. SocketData data = 2; // The locally bound address. Address local = 3; // The remote bound address. May be absent. Address remote = 4; - // Security details for this socket. May be absent if not available, or - // there is no security on the socket. + // Security details for this socket. May be absent if not available, or + // there is no security on the socket. Security security = 5; // Optional, represents the name of the remote endpoint, if different than @@ -244,23 +244,23 @@ message Socket { string remote_name = 6; } -// SocketData is data associated for a specific Socket. The fields present -// are specific to the implementation, so there may be minor differences in -// the semantics. (e.g. flow control windows) +// SocketData is data associated for a specific Socket. The fields present +// are specific to the implementation, so there may be minor differences in +// the semantics. (e.g. flow control windows) message SocketData { // The number of streams that have been started. int64 streams_started = 1; - // The number of streams that have ended successfully: - // On client side, received frame with eos bit set; - // On server side, sent frame with eos bit set. + // The number of streams that have ended successfully: + // On client side, received frame with eos bit set; + // On server side, sent frame with eos bit set. int64 streams_succeeded = 2; - // The number of streams that have ended unsuccessfully: - // On client side, ended without receiving frame with eos bit set; - // On server side, ended without sending frame with eos bit set. + // The number of streams that have ended unsuccessfully: + // On client side, ended without receiving frame with eos bit set; + // On server side, ended without sending frame with eos bit set. int64 streams_failed = 3; - // The number of grpc messages successfully sent on this socket. + // The number of grpc messages successfully sent on this socket. int64 messages_sent = 4; - // The number of grpc messages received on this socket. + // The number of grpc messages received on this socket. int64 messages_received = 5; // The number of keep alives sent. This is typically implemented with HTTP/2 @@ -289,15 +289,15 @@ message SocketData { // include stream level or TCP level flow control info. google.protobuf.Int64Value remote_flow_control_window = 12; - // Socket options set on this socket. May be absent if 'summary' is set - // on GetSocketRequest. + // Socket options set on this socket. May be absent if 'summary' is set + // on GetSocketRequest. repeated SocketOption option = 13; } -// Address represents the address used to create the socket. +// Address represents the address used to create the socket. message Address { message TcpIpAddress { - // Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + // Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 // bytes in length. bytes ip_address = 1; // 0-64k, or -1 if not appropriate. @@ -309,7 +309,7 @@ message Address { } // An address type not included above. message OtherAddress { - // The human readable version of the value. This value should be set. + // The human readable version of the value. This value should be set. string name = 1; // The actual address message. google.protobuf.Any value = 2; @@ -322,17 +322,17 @@ message Address { } } -// Security represents details about how secure the socket is. +// Security represents details about how secure the socket is. message Security { message Tls { - oneof cipher_suite { - // The cipher suite name in the RFC 4346 format: - // https://tools.ietf.org/html/rfc4346#appendix-C - string standard_name = 1; - // Some other way to describe the cipher suite if - // the RFC 4346 name is not available. - string other_name = 2; - } + oneof cipher_suite { + // The cipher suite name in the RFC 4346 format: + // https://tools.ietf.org/html/rfc4346#appendix-C + string standard_name = 1; + // Some other way to describe the cipher suite if + // the RFC 4346 name is not available. + string other_name = 2; + } // the certificate used by this endpoint. bytes local_certificate = 3; // the certificate used by the remote endpoint. @@ -350,11 +350,11 @@ message Security { } } -// SocketOption represents socket options for a socket. Specifically, these -// are the options returned by getsockopt(). +// SocketOption represents socket options for a socket. Specifically, these +// are the options returned by getsockopt(). message SocketOption { - // The full name of the socket option. Typically this will be the upper case - // name, such as "SO_REUSEPORT". + // The full name of the socket option. Typically this will be the upper case + // name, such as "SO_REUSEPORT". string name = 1; // The human readable value of this socket option. At least one of value or // additional will be set. @@ -370,17 +370,17 @@ message SocketOptionTimeout { google.protobuf.Duration duration = 1; } -// For use with SocketOption's additional field. This is primarily used for -// SO_LINGER. +// For use with SocketOption's additional field. This is primarily used for +// SO_LINGER. message SocketOptionLinger { - // active maps to `struct linger.l_onoff` + // active maps to `struct linger.l_onoff` bool active = 1; - // duration maps to `struct linger.l_linger` + // duration maps to `struct linger.l_linger` google.protobuf.Duration duration = 2; } -// For use with SocketOption's additional field. Tcp info for -// SOL_TCP and TCP_INFO. +// For use with SocketOption's additional field. Tcp info for +// SOL_TCP and TCP_INFO. message SocketOptionTcpInfo { uint32 tcpi_state = 1; @@ -418,16 +418,16 @@ message SocketOptionTcpInfo { uint32 tcpi_reordering = 29; } -// Channelz is a service exposed by gRPC servers that provides detailed debug -// information. +// Channelz is a service exposed by gRPC servers that provides detailed debug +// information. service Channelz { - // Gets all root channels (i.e. channels the application has directly + // Gets all root channels (i.e. channels the application has directly // created). This does not include subchannels nor non-top level channels. rpc GetTopChannels(GetTopChannelsRequest) returns (GetTopChannelsResponse); // Gets all servers that exist in the process. rpc GetServers(GetServersRequest) returns (GetServersResponse); - // Returns a single Server, or else a NOT_FOUND code. - rpc GetServer(GetServerRequest) returns (GetServerResponse); + // Returns a single Server, or else a NOT_FOUND code. + rpc GetServer(GetServerRequest) returns (GetServerResponse); // Gets all server sockets that exist in the process. rpc GetServerSockets(GetServerSocketsRequest) returns (GetServerSocketsResponse); // Returns a single Channel, or else a NOT_FOUND code. @@ -438,49 +438,49 @@ service Channelz { rpc GetSocket(GetSocketRequest) returns (GetSocketResponse); } -message GetTopChannelsRequest { - // start_channel_id indicates that only channels at or above this id should be - // included in the results. - // To request the first page, this should be set to 0. To request - // subsequent pages, the client generates this value by adding 1 to - // the highest seen result ID. - int64 start_channel_id = 1; - - // If non-zero, the server will return a page of results containing - // at most this many items. If zero, the server will choose a - // reasonable page size. Must never be negative. - int64 max_results = 2; -} - -message GetTopChannelsResponse { - // list of channels that the connection detail service knows about. Sorted in - // ascending channel_id order. - // Must contain at least 1 result, otherwise 'end' must be true. - repeated Channel channel = 1; - // If set, indicates that the list of channels is the final list. Requesting - // more channels can only return more if they are created after this RPC - // completes. - bool end = 2; -} - +message GetTopChannelsRequest { + // start_channel_id indicates that only channels at or above this id should be + // included in the results. + // To request the first page, this should be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_channel_id = 1; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 2; +} + +message GetTopChannelsResponse { + // list of channels that the connection detail service knows about. Sorted in + // ascending channel_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated Channel channel = 1; + // If set, indicates that the list of channels is the final list. Requesting + // more channels can only return more if they are created after this RPC + // completes. + bool end = 2; +} + message GetServersRequest { // start_server_id indicates that only servers at or above this id should be // included in the results. - // To request the first page, this must be set to 0. To request - // subsequent pages, the client generates this value by adding 1 to - // the highest seen result ID. + // To request the first page, this must be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. int64 start_server_id = 1; - - // If non-zero, the server will return a page of results containing - // at most this many items. If zero, the server will choose a - // reasonable page size. Must never be negative. - int64 max_results = 2; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 2; } message GetServersResponse { // list of servers that the connection detail service knows about. Sorted in // ascending server_id order. - // Must contain at least 1 result, otherwise 'end' must be true. + // Must contain at least 1 result, otherwise 'end' must be true. repeated Server server = 1; // If set, indicates that the list of servers is the final list. Requesting // more servers will only return more if they are created after this RPC @@ -488,36 +488,36 @@ message GetServersResponse { bool end = 2; } -message GetServerRequest { - // server_id is the identifier of the specific server to get. - int64 server_id = 1; -} - -message GetServerResponse { - // The Server that corresponds to the requested server_id. This field - // should be set. - Server server = 1; -} - +message GetServerRequest { + // server_id is the identifier of the specific server to get. + int64 server_id = 1; +} + +message GetServerResponse { + // The Server that corresponds to the requested server_id. This field + // should be set. + Server server = 1; +} + message GetServerSocketsRequest { int64 server_id = 1; // start_socket_id indicates that only sockets at or above this id should be // included in the results. - // To request the first page, this must be set to 0. To request - // subsequent pages, the client generates this value by adding 1 to - // the highest seen result ID. + // To request the first page, this must be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. int64 start_socket_id = 2; - - // If non-zero, the server will return a page of results containing - // at most this many items. If zero, the server will choose a - // reasonable page size. Must never be negative. - int64 max_results = 3; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 3; } message GetServerSocketsResponse { // list of socket refs that the connection detail service knows about. Sorted in // ascending socket_id order. - // Must contain at least 1 result, otherwise 'end' must be true. + // Must contain at least 1 result, otherwise 'end' must be true. repeated SocketRef socket_ref = 1; // If set, indicates that the list of sockets is the final list. Requesting // more sockets will only return more if they are created after this RPC @@ -526,39 +526,39 @@ message GetServerSocketsResponse { } message GetChannelRequest { - // channel_id is the identifier of the specific channel to get. + // channel_id is the identifier of the specific channel to get. int64 channel_id = 1; } message GetChannelResponse { - // The Channel that corresponds to the requested channel_id. This field - // should be set. + // The Channel that corresponds to the requested channel_id. This field + // should be set. Channel channel = 1; } message GetSubchannelRequest { - // subchannel_id is the identifier of the specific subchannel to get. + // subchannel_id is the identifier of the specific subchannel to get. int64 subchannel_id = 1; } message GetSubchannelResponse { - // The Subchannel that corresponds to the requested subchannel_id. This - // field should be set. + // The Subchannel that corresponds to the requested subchannel_id. This + // field should be set. Subchannel subchannel = 1; } message GetSocketRequest { - // socket_id is the identifier of the specific socket to get. + // socket_id is the identifier of the specific socket to get. int64 socket_id = 1; - - // If true, the response will contain only high level information - // that is inexpensive to obtain. Fields thay may be omitted are - // documented. - bool summary = 2; + + // If true, the response will contain only high level information + // that is inexpensive to obtain. Fields thay may be omitted are + // documented. + bool summary = 2; } message GetSocketResponse { - // The Socket that corresponds to the requested socket_id. This field - // should be set. + // The Socket that corresponds to the requested socket_id. This field + // should be set. Socket socket = 1; } diff --git a/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto b/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto index 38843ff1e7..0998112828 100644 --- a/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto +++ b/contrib/libs/grpc/src/proto/grpc/health/v1/health.proto @@ -1,4 +1,4 @@ -// Copyright 2015 The gRPC Authors +// Copyright 2015 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,18 +12,18 @@ // See the License for the specific language governing permissions and // limitations under the License. -// The canonical version of this proto can be found at -// https://github.com/grpc/grpc-proto/blob/master/grpc/health/v1/health.proto - +// The canonical version of this proto can be found at +// https://github.com/grpc/grpc-proto/blob/master/grpc/health/v1/health.proto + syntax = "proto3"; package grpc.health.v1; - + option csharp_namespace = "Grpc.Health.V1"; -option go_package = "google.golang.org/grpc/health/grpc_health_v1"; -option java_multiple_files = true; -option java_outer_classname = "HealthProto"; -option java_package = "io.grpc.health.v1"; +option go_package = "google.golang.org/grpc/health/grpc_health_v1"; +option java_multiple_files = true; +option java_outer_classname = "HealthProto"; +option java_package = "io.grpc.health.v1"; message HealthCheckRequest { string service = 1; @@ -34,30 +34,30 @@ message HealthCheckResponse { UNKNOWN = 0; SERVING = 1; NOT_SERVING = 2; - SERVICE_UNKNOWN = 3; // Used only by the Watch method. + SERVICE_UNKNOWN = 3; // Used only by the Watch method. } ServingStatus status = 1; } service Health { - // If the requested service is unknown, the call will fail with status - // NOT_FOUND. + // If the requested service is unknown, the call will fail with status + // NOT_FOUND. rpc Check(HealthCheckRequest) returns (HealthCheckResponse); - - // Performs a watch for the serving status of the requested service. - // The server will immediately send back a message indicating the current - // serving status. It will then subsequently send a new message whenever - // the service's serving status changes. - // - // If the requested service is unknown when the call is received, the - // server will send a message setting the serving status to - // SERVICE_UNKNOWN but will *not* terminate the call. If at some - // future point, the serving status of the service becomes known, the - // server will send a new message with the service's serving status. - // - // If the call terminates with status UNIMPLEMENTED, then clients - // should assume this method is not supported and should not retry the - // call. If the call terminates with any other status (including OK), - // clients should retry the call with appropriate exponential backoff. - rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse); + + // Performs a watch for the serving status of the requested service. + // The server will immediately send back a message indicating the current + // serving status. It will then subsequently send a new message whenever + // the service's serving status changes. + // + // If the requested service is unknown when the call is received, the + // server will send a message setting the serving status to + // SERVICE_UNKNOWN but will *not* terminate the call. If at some + // future point, the serving status of the service becomes known, the + // server will send a new message with the service's serving status. + // + // If the call terminates with status UNIMPLEMENTED, then clients + // should assume this method is not supported and should not retry the + // call. If the call terminates with any other status (including OK), + // clients should retry the call with appropriate exponential backoff. + rpc Watch(HealthCheckRequest) returns (stream HealthCheckResponse); } diff --git a/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto b/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto index ccf2efd629..2c29b19c4b 100644 --- a/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto +++ b/contrib/libs/grpc/src/proto/grpc/lb/v1/load_balancer.proto @@ -1,4 +1,4 @@ -// Copyright 2015 The gRPC Authors +// Copyright 2015 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -12,25 +12,25 @@ // See the License for the specific language governing permissions and // limitations under the License. -// This file defines the GRPCLB LoadBalancing protocol. -// -// The canonical version of this proto can be found at -// https://github.com/grpc/grpc-proto/blob/master/grpc/lb/v1/load_balancer.proto +// This file defines the GRPCLB LoadBalancing protocol. +// +// The canonical version of this proto can be found at +// https://github.com/grpc/grpc-proto/blob/master/grpc/lb/v1/load_balancer.proto syntax = "proto3"; package grpc.lb.v1; -import "google/protobuf/duration.proto"; -import "google/protobuf/timestamp.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; -option go_package = "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1"; -option java_multiple_files = true; -option java_outer_classname = "LoadBalancerProto"; -option java_package = "io.grpc.grpclb"; +option go_package = "google.golang.org/grpc/balancer/grpclb/grpc_lb_v1"; +option java_multiple_files = true; +option java_outer_classname = "LoadBalancerProto"; +option java_package = "io.grpc.grpclb"; service LoadBalancer { // Bidirectional rpc to get a list of servers. - rpc BalanceLoad(stream LoadBalanceRequest) returns (stream LoadBalanceResponse); + rpc BalanceLoad(stream LoadBalanceRequest) returns (stream LoadBalanceResponse); } message LoadBalanceRequest { @@ -45,10 +45,10 @@ message LoadBalanceRequest { } message InitialLoadBalanceRequest { - // The name of the load balanced service (e.g., service.googleapis.com). Its + // The name of the load balanced service (e.g., service.googleapis.com). Its // length should be less than 256 bytes. - // The name might include a port number. How to handle the port number is up - // to the balancer. + // The name might include a port number. How to handle the port number is up + // to the balancer. string name = 1; } @@ -65,7 +65,7 @@ message ClientStatsPerToken { // count except the timestamp should be reset to zero after reporting the stats. message ClientStats { // The timestamp of generating the report. - google.protobuf.Timestamp timestamp = 1; + google.protobuf.Timestamp timestamp = 1; // The total number of RPCs that started. int64 num_calls_started = 2; @@ -113,7 +113,7 @@ message InitialLoadBalanceResponse { // This interval defines how often the client should send the client stats // to the load balancer. Stats should only be reported when the duration is // positive. - google.protobuf.Duration client_stats_report_interval = 2; + google.protobuf.Duration client_stats_report_interval = 2; } message ServerList { @@ -137,13 +137,13 @@ message Server { // A resolved port number for the server. int32 port = 2; - // An opaque but printable token for load reporting. The client must include - // the token of the picked server into the initial metadata when it starts a - // call to that server. The token is used by the server to verify the request - // and to allow the server to report load to the gRPC LB system. The token is - // also used in client stats for reporting dropped calls. + // An opaque but printable token for load reporting. The client must include + // the token of the picked server into the initial metadata when it starts a + // call to that server. The token is used by the server to verify the request + // and to allow the server to report load to the gRPC LB system. The token is + // also used in client stats for reporting dropped calls. // - // Its length can be variable but must be less than 50 bytes. + // Its length can be variable but must be less than 50 bytes. string load_balance_token = 3; // Indicates whether this particular request should be dropped by the client. diff --git a/contrib/libs/grpc/src/proto/grpc/lb/v1/load_reporter.proto b/contrib/libs/grpc/src/proto/grpc/lb/v1/load_reporter.proto index d57a37fed7..d259658367 100644 --- a/contrib/libs/grpc/src/proto/grpc/lb/v1/load_reporter.proto +++ b/contrib/libs/grpc/src/proto/grpc/lb/v1/load_reporter.proto @@ -1,184 +1,184 @@ -// Copyright 2018 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.lb.v1; - -import "google/protobuf/duration.proto"; - -// The LoadReporter service. -service LoadReporter { - // Report load from server to lb. - rpc ReportLoad(stream LoadReportRequest) - returns (stream LoadReportResponse) { - }; -} - -message LoadReportRequest { - // This message should be sent on the first request to the gRPC server. - InitialLoadReportRequest initial_request = 1; -} - -message InitialLoadReportRequest { - // The hostname this load reporter client is requesting load for. - string load_balanced_hostname = 1; - - // Additional information to disambiguate orphaned load: load that should have - // gone to this load reporter client, but was not able to be sent since the - // load reporter client has disconnected. load_key is sent in orphaned load - // reports; see Load.load_key. - bytes load_key = 2; - - // This interval defines how often the server should send load reports to - // the load balancer. - google.protobuf.Duration load_report_interval = 3; -} - -message LoadReportResponse { - // This message should be sent on the first response to the load balancer. - InitialLoadReportResponse initial_response = 1; - - // Reports server-wide statistics for load balancing. - // This should be reported with every response. - LoadBalancingFeedback load_balancing_feedback = 2; - - // A load report for each <tag, user_id> tuple. This could be considered to be - // a multimap indexed by <tag, user_id>. It is not strictly necessary to - // aggregate all entries into one entry per <tag, user_id> tuple, although it - // is preferred to do so. - repeated Load load = 3; -} - -message InitialLoadReportResponse { - // Initial response returns the Load balancer ID. This must be plain text - // (printable ASCII). - string load_balancer_id = 1; - - enum ImplementationIdentifier { - IMPL_UNSPECIFIED = 0; - CPP = 1; // Standard Google C++ implementation. - JAVA = 2; // Standard Google Java implementation. - GO = 3; // Standard Google Go implementation. - } - // Optional identifier of this implementation of the load reporting server. - ImplementationIdentifier implementation_id = 2; - - // Optional server_version should be a value that is modified (and - // monotonically increased) when changes are made to the server - // implementation. - int64 server_version = 3; -} - -message LoadBalancingFeedback { - // Reports the current utilization of the server (typical range [0.0 - 1.0]). - float server_utilization = 1; - - // The total rate of calls handled by this server (including errors). - float calls_per_second = 2; - - // The total rate of error responses sent by this server. - float errors_per_second = 3; -} - -message Load { - // The (plain text) tag used by the calls covered by this load report. The - // tag is that part of the load balancer token after removing the load - // balancer id. Empty is equivalent to non-existent tag. - string load_balance_tag = 1; - - // The user identity authenticated by the calls covered by this load - // report. Empty is equivalent to no known user_id. - string user_id = 3; - - // IP address of the client that sent these requests, serialized in - // network-byte-order. It may either be an IPv4 or IPv6 address. - bytes client_ip_address = 15; - - // The number of calls started (since the last report) with the given tag and - // user_id. - int64 num_calls_started = 4; - - // Indicates whether this load report is an in-progress load report in which - // num_calls_in_progress is the only valid entry. If in_progress_report is not - // set, num_calls_in_progress will be ignored. If in_progress_report is set, - // fields other than num_calls_in_progress and orphaned_load will be ignored. - // TODO(juanlishen): A Load is either an in_progress_report or not. We should - // make this explicit in hierarchy. From the log, I see in_progress_report_ - // has a random num_calls_in_progress_ when not set, which might lead to bug - // when the balancer process the load report. - oneof in_progress_report { - // The number of calls in progress (instantaneously) per load balancer id. - int64 num_calls_in_progress = 5; - } - - // The following values are counts or totals of call statistics that finished - // with the given tag and user_id. - int64 num_calls_finished_without_error = 6; // Calls with status OK. - int64 num_calls_finished_with_error = 7; // Calls with status non-OK. - // Calls that finished with a status that maps to HTTP 5XX (see - // googleapis/google/rpc/code.proto). Note that this is a subset of - // num_calls_finished_with_error. - int64 num_calls_finished_with_server_error = 16; - - // Totals are from calls that with _and_ without error. - int64 total_bytes_sent = 8; - int64 total_bytes_received = 9; - google.protobuf.Duration total_latency = 10; - - // Optional metrics reported for the call(s). Requires that metric_name is - // unique. - repeated CallMetricData metric_data = 11; - - // The following two fields are used for reporting orphaned load: load that - // could not be reported to the originating balancer either since the balancer - // is no longer connected or because the frontend sent an invalid token. These - // fields must not be set with normal (unorphaned) load reports. - oneof orphaned_load { - // Load_key is the load_key from the initial_request from the originating - // balancer. - bytes load_key = 12 [deprecated=true]; - - // If true then this load report is for calls that had an invalid token; the - // user is probably abusing the gRPC protocol. - // TODO(yankaiz): Rename load_key_unknown. - bool load_key_unknown = 13; - - // load_key and balancer_id are included in order to identify orphaned load - // from different origins. - OrphanedLoadIdentifier orphaned_load_identifier = 14; - } - - reserved 2; -} - -message CallMetricData { - // Name of the metric; may be empty. - string metric_name = 1; - - // Number of calls that finished and included this metric. - int64 num_calls_finished_with_metric = 2; - - // Sum of metric values across all calls that finished with this metric. - double total_metric_value = 3; -} - -message OrphanedLoadIdentifier { - // The load_key from the initial_request from the originating balancer. - bytes load_key = 1; - - // The unique ID generated by LoadReporter to identify balancers. Here it - // distinguishes orphaned load with a same load_key. - string load_balancer_id = 2; -} +// Copyright 2018 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package grpc.lb.v1; + +import "google/protobuf/duration.proto"; + +// The LoadReporter service. +service LoadReporter { + // Report load from server to lb. + rpc ReportLoad(stream LoadReportRequest) + returns (stream LoadReportResponse) { + }; +} + +message LoadReportRequest { + // This message should be sent on the first request to the gRPC server. + InitialLoadReportRequest initial_request = 1; +} + +message InitialLoadReportRequest { + // The hostname this load reporter client is requesting load for. + string load_balanced_hostname = 1; + + // Additional information to disambiguate orphaned load: load that should have + // gone to this load reporter client, but was not able to be sent since the + // load reporter client has disconnected. load_key is sent in orphaned load + // reports; see Load.load_key. + bytes load_key = 2; + + // This interval defines how often the server should send load reports to + // the load balancer. + google.protobuf.Duration load_report_interval = 3; +} + +message LoadReportResponse { + // This message should be sent on the first response to the load balancer. + InitialLoadReportResponse initial_response = 1; + + // Reports server-wide statistics for load balancing. + // This should be reported with every response. + LoadBalancingFeedback load_balancing_feedback = 2; + + // A load report for each <tag, user_id> tuple. This could be considered to be + // a multimap indexed by <tag, user_id>. It is not strictly necessary to + // aggregate all entries into one entry per <tag, user_id> tuple, although it + // is preferred to do so. + repeated Load load = 3; +} + +message InitialLoadReportResponse { + // Initial response returns the Load balancer ID. This must be plain text + // (printable ASCII). + string load_balancer_id = 1; + + enum ImplementationIdentifier { + IMPL_UNSPECIFIED = 0; + CPP = 1; // Standard Google C++ implementation. + JAVA = 2; // Standard Google Java implementation. + GO = 3; // Standard Google Go implementation. + } + // Optional identifier of this implementation of the load reporting server. + ImplementationIdentifier implementation_id = 2; + + // Optional server_version should be a value that is modified (and + // monotonically increased) when changes are made to the server + // implementation. + int64 server_version = 3; +} + +message LoadBalancingFeedback { + // Reports the current utilization of the server (typical range [0.0 - 1.0]). + float server_utilization = 1; + + // The total rate of calls handled by this server (including errors). + float calls_per_second = 2; + + // The total rate of error responses sent by this server. + float errors_per_second = 3; +} + +message Load { + // The (plain text) tag used by the calls covered by this load report. The + // tag is that part of the load balancer token after removing the load + // balancer id. Empty is equivalent to non-existent tag. + string load_balance_tag = 1; + + // The user identity authenticated by the calls covered by this load + // report. Empty is equivalent to no known user_id. + string user_id = 3; + + // IP address of the client that sent these requests, serialized in + // network-byte-order. It may either be an IPv4 or IPv6 address. + bytes client_ip_address = 15; + + // The number of calls started (since the last report) with the given tag and + // user_id. + int64 num_calls_started = 4; + + // Indicates whether this load report is an in-progress load report in which + // num_calls_in_progress is the only valid entry. If in_progress_report is not + // set, num_calls_in_progress will be ignored. If in_progress_report is set, + // fields other than num_calls_in_progress and orphaned_load will be ignored. + // TODO(juanlishen): A Load is either an in_progress_report or not. We should + // make this explicit in hierarchy. From the log, I see in_progress_report_ + // has a random num_calls_in_progress_ when not set, which might lead to bug + // when the balancer process the load report. + oneof in_progress_report { + // The number of calls in progress (instantaneously) per load balancer id. + int64 num_calls_in_progress = 5; + } + + // The following values are counts or totals of call statistics that finished + // with the given tag and user_id. + int64 num_calls_finished_without_error = 6; // Calls with status OK. + int64 num_calls_finished_with_error = 7; // Calls with status non-OK. + // Calls that finished with a status that maps to HTTP 5XX (see + // googleapis/google/rpc/code.proto). Note that this is a subset of + // num_calls_finished_with_error. + int64 num_calls_finished_with_server_error = 16; + + // Totals are from calls that with _and_ without error. + int64 total_bytes_sent = 8; + int64 total_bytes_received = 9; + google.protobuf.Duration total_latency = 10; + + // Optional metrics reported for the call(s). Requires that metric_name is + // unique. + repeated CallMetricData metric_data = 11; + + // The following two fields are used for reporting orphaned load: load that + // could not be reported to the originating balancer either since the balancer + // is no longer connected or because the frontend sent an invalid token. These + // fields must not be set with normal (unorphaned) load reports. + oneof orphaned_load { + // Load_key is the load_key from the initial_request from the originating + // balancer. + bytes load_key = 12 [deprecated=true]; + + // If true then this load report is for calls that had an invalid token; the + // user is probably abusing the gRPC protocol. + // TODO(yankaiz): Rename load_key_unknown. + bool load_key_unknown = 13; + + // load_key and balancer_id are included in order to identify orphaned load + // from different origins. + OrphanedLoadIdentifier orphaned_load_identifier = 14; + } + + reserved 2; +} + +message CallMetricData { + // Name of the metric; may be empty. + string metric_name = 1; + + // Number of calls that finished and included this metric. + int64 num_calls_finished_with_metric = 2; + + // Sum of metric values across all calls that finished with this metric. + double total_metric_value = 3; +} + +message OrphanedLoadIdentifier { + // The load_key from the initial_request from the originating balancer. + bytes load_key = 1; + + // The unique ID generated by LoadReporter to identify balancers. Here it + // distinguishes orphaned load with a same load_key. + string load_balancer_id = 2; +} diff --git a/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto b/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto index 9fa5590a59..29180858d5 100644 --- a/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto +++ b/contrib/libs/grpc/src/proto/grpc/testing/compiler_test.proto @@ -20,9 +20,9 @@ syntax = "proto3"; // Ignored detached comment -// The comments in this file are not meant for readability -// but rather to test to make sure that the code generator -// properly preserves comments on files, services, and RPCs +// The comments in this file are not meant for readability +// but rather to test to make sure that the code generator +// properly preserves comments on files, services, and RPCs // Ignored package leading comment package grpc.testing; diff --git a/contrib/libs/grpc/src/proto/grpc/testing/control.proto b/contrib/libs/grpc/src/proto/grpc/testing/control.proto index 742b21926e..4fa672c483 100644 --- a/contrib/libs/grpc/src/proto/grpc/testing/control.proto +++ b/contrib/libs/grpc/src/proto/grpc/testing/control.proto @@ -25,7 +25,7 @@ enum ClientType { SYNC_CLIENT = 0; ASYNC_CLIENT = 1; OTHER_CLIENT = 2; // used for some language-specific variants - CALLBACK_CLIENT = 3; + CALLBACK_CLIENT = 3; } enum ServerType { @@ -33,7 +33,7 @@ enum ServerType { ASYNC_SERVER = 1; ASYNC_GENERIC_SERVER = 2; OTHER_SERVER = 3; // used for some language-specific variants - CALLBACK_SERVER = 4; + CALLBACK_SERVER = 4; } enum RpcType { @@ -113,10 +113,10 @@ message ClientConfig { // Use coalescing API when possible. bool use_coalesce_api = 19; - - // If 0, disabled. Else, specifies the period between gathering latency - // medians in milliseconds. - int32 median_latency_collection_interval_millis = 20; + + // If 0, disabled. Else, specifies the period between gathering latency + // medians in milliseconds. + int32 median_latency_collection_interval_millis = 20; // Number of client processes. 0 indicates no restriction. int32 client_processes = 21; diff --git a/contrib/libs/grpc/src/proto/grpc/testing/echo.proto b/contrib/libs/grpc/src/proto/grpc/testing/echo.proto index 33db111864..d490fa8661 100644 --- a/contrib/libs/grpc/src/proto/grpc/testing/echo.proto +++ b/contrib/libs/grpc/src/proto/grpc/testing/echo.proto @@ -18,7 +18,7 @@ syntax = "proto3"; package grpc.testing; import "src/proto/grpc/testing/echo_messages.proto"; -import "src/proto/grpc/testing/simple_messages.proto"; +import "src/proto/grpc/testing/simple_messages.proto"; service EchoTestService { rpc Echo(EchoRequest) returns (EchoResponse); @@ -26,8 +26,8 @@ service EchoTestService { rpc Echo2(EchoRequest) returns (EchoResponse); rpc CheckDeadlineUpperBound(SimpleRequest42) returns (StringValue); rpc CheckDeadlineSet(SimpleRequest42) returns (StringValue); - // A service which checks that the initial metadata sent over contains some - // expected key value pair + // A service which checks that the initial metadata sent over contains some + // expected key value pair rpc CheckClientInitialMetadata(SimpleRequest42) returns (SimpleResponse42); rpc RequestStream(stream EchoRequest) returns (EchoResponse); rpc ResponseStream(EchoRequest) returns (stream EchoResponse); diff --git a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto index 6f1e5f3404..3ef9608ad3 100644 --- a/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto +++ b/contrib/libs/grpc/src/proto/grpc/testing/echo_messages.proto @@ -48,7 +48,7 @@ message RequestParams { string binary_error_details = 13; ErrorStatus expected_error = 14; int32 server_sleep_us = 15; // sleep when invoking server for deadline tests - int32 backend_channel_idx = 16; // which backend to send request to + int32 backend_channel_idx = 16; // which backend to send request to bool echo_metadata_initially = 17; bool server_notify_client_when_started = 18; } diff --git a/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto b/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto index 157629b7a4..d5e5ad931e 100644 --- a/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto +++ b/contrib/libs/grpc/src/proto/grpc/testing/empty_service.proto @@ -1,23 +1,23 @@ - -// Copyright 2018 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - -// A service that has zero methods. -// See https://github.com/grpc/grpc/issues/15574 -service EmptyService { -} + +// Copyright 2018 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package grpc.testing; + +// A service that has zero methods. +// See https://github.com/grpc/grpc/issues/15574 +service EmptyService { +} diff --git a/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto b/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto index 6fbb395a44..cae8a42774 100644 --- a/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto +++ b/contrib/libs/grpc/src/proto/grpc/testing/simple_messages.proto @@ -1,26 +1,26 @@ - -// Copyright 2018 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -syntax = "proto3"; - -package grpc.testing; - + +// Copyright 2018 gRPC authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package grpc.testing; + message SimpleRequest42 {} - + message SimpleResponse42 {} message StringValue { string message = 1; -} +} diff --git a/contrib/libs/grpc/src/python/grpcio/_parallel_compile_patch.py b/contrib/libs/grpc/src/python/grpcio/_parallel_compile_patch.py index e4d50c3831..93934eca79 100644 --- a/contrib/libs/grpc/src/python/grpcio/_parallel_compile_patch.py +++ b/contrib/libs/grpc/src/python/grpcio/_parallel_compile_patch.py @@ -1,66 +1,66 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Patches the compile() to allow enable parallel compilation of C/C++. - -build_ext has lots of C/C++ files and normally them one by one. -Enabling parallel build helps a lot. -""" - -import distutils.ccompiler -import os - -try: - BUILD_EXT_COMPILER_JOBS = int( +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Patches the compile() to allow enable parallel compilation of C/C++. + +build_ext has lots of C/C++ files and normally them one by one. +Enabling parallel build helps a lot. +""" + +import distutils.ccompiler +import os + +try: + BUILD_EXT_COMPILER_JOBS = int( os.environ['GRPC_PYTHON_BUILD_EXT_COMPILER_JOBS']) except KeyError: import multiprocessing BUILD_EXT_COMPILER_JOBS = multiprocessing.cpu_count() -except ValueError: - BUILD_EXT_COMPILER_JOBS = 1 - - -# monkey-patch for parallel compilation -def _parallel_compile(self, - sources, - output_dir=None, - macros=None, - include_dirs=None, - debug=0, - extra_preargs=None, - extra_postargs=None, - depends=None): - # setup the same way as distutils.ccompiler.CCompiler - # https://github.com/python/cpython/blob/31368a4f0e531c19affe2a1becd25fc316bc7501/Lib/distutils/ccompiler.py#L564 - macros, objects, extra_postargs, pp_opts, build = self._setup_compile( - str(output_dir), macros, include_dirs, sources, depends, extra_postargs) - cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) - - def _compile_single_file(obj): - try: - src, ext = build[obj] - except KeyError: - return - self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) - - # run compilation of individual files in parallel - import multiprocessing.pool - multiprocessing.pool.ThreadPool(BUILD_EXT_COMPILER_JOBS).map( - _compile_single_file, objects) - return objects - - -def monkeypatch_compile_maybe(): - """Monkeypatching is dumb, but the build speed gain is worth it.""" - if BUILD_EXT_COMPILER_JOBS > 1: - distutils.ccompiler.CCompiler.compile = _parallel_compile +except ValueError: + BUILD_EXT_COMPILER_JOBS = 1 + + +# monkey-patch for parallel compilation +def _parallel_compile(self, + sources, + output_dir=None, + macros=None, + include_dirs=None, + debug=0, + extra_preargs=None, + extra_postargs=None, + depends=None): + # setup the same way as distutils.ccompiler.CCompiler + # https://github.com/python/cpython/blob/31368a4f0e531c19affe2a1becd25fc316bc7501/Lib/distutils/ccompiler.py#L564 + macros, objects, extra_postargs, pp_opts, build = self._setup_compile( + str(output_dir), macros, include_dirs, sources, depends, extra_postargs) + cc_args = self._get_cc_args(pp_opts, debug, extra_preargs) + + def _compile_single_file(obj): + try: + src, ext = build[obj] + except KeyError: + return + self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts) + + # run compilation of individual files in parallel + import multiprocessing.pool + multiprocessing.pool.ThreadPool(BUILD_EXT_COMPILER_JOBS).map( + _compile_single_file, objects) + return objects + + +def monkeypatch_compile_maybe(): + """Monkeypatching is dumb, but the build speed gain is worth it.""" + if BUILD_EXT_COMPILER_JOBS > 1: + distutils.ccompiler.CCompiler.compile = _parallel_compile diff --git a/contrib/libs/grpc/src/python/grpcio/commands.py b/contrib/libs/grpc/src/python/grpcio/commands.py index 8240beb295..cabb742948 100644 --- a/contrib/libs/grpc/src/python/grpcio/commands.py +++ b/contrib/libs/grpc/src/python/grpcio/commands.py @@ -96,14 +96,14 @@ class SphinxDocumentation(setuptools.Command): def run(self): # We import here to ensure that setup.py has had a chance to install the # relevant package eggs first. - import sphinx.cmd.build - source_dir = os.path.join(GRPC_STEM, 'doc', 'python', 'sphinx') - target_dir = os.path.join(GRPC_STEM, 'doc', 'build') - exit_code = sphinx.cmd.build.build_main( - ['-b', 'html', '-W', '--keep-going', source_dir, target_dir]) + import sphinx.cmd.build + source_dir = os.path.join(GRPC_STEM, 'doc', 'python', 'sphinx') + target_dir = os.path.join(GRPC_STEM, 'doc', 'build') + exit_code = sphinx.cmd.build.build_main( + ['-b', 'html', '-W', '--keep-going', source_dir, target_dir]) if exit_code != 0: - raise CommandError( - "Documentation generation has warnings or errors") + raise CommandError( + "Documentation generation has warnings or errors") class BuildProjectMetadata(setuptools.Command): @@ -227,10 +227,10 @@ class BuildExt(build_ext.build_ext): _, cc_err = cc_test.communicate(input=b'int main(){return 0;}') return not 'invalid argument' in str(cc_err) - # This special conditioning is here due to difference of compiler - # behavior in gcc and clang. The clang doesn't take --stdc++11 - # flags but gcc does. Since the setuptools of Python only support - # all C or all C++ compilation, the mix of C and C++ will crash. + # This special conditioning is here due to difference of compiler + # behavior in gcc and clang. The clang doesn't take --stdc++11 + # flags but gcc does. Since the setuptools of Python only support + # all C or all C++ compilation, the mix of C and C++ will crash. # *By default*, macOS and FreBSD use clang and Linux use gcc # # If we are not using a permissive compiler that's OK with being diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py b/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py index abe87458c4..2e16c4d679 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/__init__.py @@ -16,20 +16,20 @@ import abc import contextlib import enum -import logging +import logging import sys import six from grpc._cython import cygrpc as _cygrpc from grpc import _compression -logging.getLogger(__name__).addHandler(logging.NullHandler()) - -try: - from grpc._grpcio_metadata import __version__ -except ImportError: - __version__ = "dev0" - +logging.getLogger(__name__).addHandler(logging.NullHandler()) + +try: + from grpc._grpcio_metadata import __version__ +except ImportError: + __version__ = "dev0" + ############################## Future Interface ############################### @@ -57,13 +57,13 @@ class Future(six.with_metaclass(abc.ABCMeta)): Returns: bool: Returns True if the computation was canceled. - + Returns False under all other circumstances, for example: - + 1. computation has begun and could not be canceled. 2. computation has finished 3. computation is scheduled for execution and it is impossible - to determine its state without blocking. + to determine its state without blocking. """ raise NotImplementedError() @@ -77,9 +77,9 @@ class Future(six.with_metaclass(abc.ABCMeta)): bool: Returns True if the computation was cancelled before its result became available. - - Returns False under all other circumstances, for example: - + + Returns False under all other circumstances, for example: + 1. computation was not cancelled. 2. computation's result is available. """ @@ -94,7 +94,7 @@ class Future(six.with_metaclass(abc.ABCMeta)): Returns: Returns True if the computation is scheduled for execution or currently executing. - + Returns False if the computation already executed or was cancelled. """ raise NotImplementedError() @@ -226,33 +226,33 @@ class ChannelConnectivity(enum.Enum): @enum.unique class StatusCode(enum.Enum): - """Mirrors grpc_status_code in the gRPC Core. - - Attributes: - OK: Not an error; returned on success - CANCELLED: The operation was cancelled (typically by the caller). - UNKNOWN: Unknown error. - INVALID_ARGUMENT: Client specified an invalid argument. - DEADLINE_EXCEEDED: Deadline expired before operation could complete. - NOT_FOUND: Some requested entity (e.g., file or directory) was not found. - ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory) - already exists. - PERMISSION_DENIED: The caller does not have permission to execute the specified - operation. - UNAUTHENTICATED: The request does not have valid authentication credentials for the - operation. - RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or - perhaps the entire file system is out of space. - FAILED_PRECONDITION: Operation was rejected because the system is not in a state - required for the operation's execution. - ABORTED: The operation was aborted, typically due to a concurrency issue - like sequencer check failures, transaction aborts, etc. - UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service. - INTERNAL: Internal errors. Means some invariants expected by underlying - system has been broken. - UNAVAILABLE: The service is currently unavailable. - DATA_LOSS: Unrecoverable data loss or corruption. - """ + """Mirrors grpc_status_code in the gRPC Core. + + Attributes: + OK: Not an error; returned on success + CANCELLED: The operation was cancelled (typically by the caller). + UNKNOWN: Unknown error. + INVALID_ARGUMENT: Client specified an invalid argument. + DEADLINE_EXCEEDED: Deadline expired before operation could complete. + NOT_FOUND: Some requested entity (e.g., file or directory) was not found. + ALREADY_EXISTS: Some entity that we attempted to create (e.g., file or directory) + already exists. + PERMISSION_DENIED: The caller does not have permission to execute the specified + operation. + UNAUTHENTICATED: The request does not have valid authentication credentials for the + operation. + RESOURCE_EXHAUSTED: Some resource has been exhausted, perhaps a per-user quota, or + perhaps the entire file system is out of space. + FAILED_PRECONDITION: Operation was rejected because the system is not in a state + required for the operation's execution. + ABORTED: The operation was aborted, typically due to a concurrency issue + like sequencer check failures, transaction aborts, etc. + UNIMPLEMENTED: Operation is not implemented or not supported/enabled in this service. + INTERNAL: Internal errors. Means some invariants expected by underlying + system has been broken. + UNAVAILABLE: The service is currently unavailable. + DATA_LOSS: Unrecoverable data loss or corruption. + """ OK = (_cygrpc.StatusCode.ok, 'ok') CANCELLED = (_cygrpc.StatusCode.cancelled, 'cancelled') UNKNOWN = (_cygrpc.StatusCode.unknown, 'unknown') @@ -276,22 +276,22 @@ class StatusCode(enum.Enum): UNAUTHENTICATED = (_cygrpc.StatusCode.unauthenticated, 'unauthenticated') -############################# gRPC Status ################################ - - -class Status(six.with_metaclass(abc.ABCMeta)): - """Describes the status of an RPC. - - This is an EXPERIMENTAL API. - - Attributes: - code: A StatusCode object to be sent to the client. +############################# gRPC Status ################################ + + +class Status(six.with_metaclass(abc.ABCMeta)): + """Describes the status of an RPC. + + This is an EXPERIMENTAL API. + + Attributes: + code: A StatusCode object to be sent to the client. details: A UTF-8-encodable string to be sent to the client upon - termination of the RPC. - trailing_metadata: The trailing :term:`metadata` in the RPC. - """ - - + termination of the RPC. + trailing_metadata: The trailing :term:`metadata` in the RPC. + """ + + ############################# gRPC Exceptions ################################ @@ -511,7 +511,7 @@ class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)): actual RPC on the underlying Channel. It is the interceptor's responsibility to call it if it decides to move the RPC forward. The interceptor can use - `response_future = continuation(client_call_details, request_iterator)` + `response_future = continuation(client_call_details, request_iterator)` to continue with the RPC. `continuation` returns an object that is both a Call for the RPC and a Future. In the event of RPC completion, the return Call-Future's result value will be the response message @@ -522,11 +522,11 @@ class StreamUnaryClientInterceptor(six.with_metaclass(abc.ABCMeta)): request_iterator: An iterator that yields request values for the RPC. Returns: - An object that is both a Call for the RPC and a Future. - In the event of RPC completion, the return Call-Future's - result value will be the response message of the RPC. - Should the event terminate with non-OK status, the returned - Call-Future's exception value will be an RpcError. + An object that is both a Call for the RPC and a Future. + In the event of RPC completion, the return Call-Future's + result value will be the response message of the RPC. + Should the event terminate with non-OK status, the returned + Call-Future's exception value will be an RpcError. """ raise NotImplementedError() @@ -542,13 +542,13 @@ class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)): request_iterator): """Intercepts a stream-stream invocation. - Args: + Args: continuation: A function that proceeds with the invocation by executing the next interceptor in chain or invoking the actual RPC on the underlying Channel. It is the interceptor's responsibility to call it if it decides to move the RPC forward. The interceptor can use - `response_iterator = continuation(client_call_details, request_iterator)` + `response_iterator = continuation(client_call_details, request_iterator)` to continue with the RPC. `continuation` returns an object that is both a Call for the RPC and an iterator for response values. Drawing response values from the returned Call-iterator may @@ -559,10 +559,10 @@ class StreamStreamClientInterceptor(six.with_metaclass(abc.ABCMeta)): request_iterator: An iterator that yields request values for the RPC. Returns: - An object that is both a Call for the RPC and an iterator of - response values. Drawing response values from the returned - Call-iterator may raise RpcError indicating termination of - the RPC with non-OK status. + An object that is both a Call for the RPC and an iterator of + response values. Drawing response values from the returned + Call-iterator may raise RpcError indicating termination of + the RPC with non-OK status. """ raise NotImplementedError() @@ -672,11 +672,11 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): """Affords invoking a unary-unary RPC from client-side.""" @abc.abstractmethod - def __call__(self, - request, - timeout=None, - metadata=None, - credentials=None, + def __call__(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): """Synchronously invokes the underlying RPC. @@ -689,7 +689,7 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -705,11 +705,11 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): raise NotImplementedError() @abc.abstractmethod - def with_call(self, - request, - timeout=None, - metadata=None, - credentials=None, + def with_call(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): """Synchronously invokes the underlying RPC. @@ -722,7 +722,7 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -738,11 +738,11 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): raise NotImplementedError() @abc.abstractmethod - def future(self, - request, - timeout=None, - metadata=None, - credentials=None, + def future(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): """Asynchronously invokes the underlying RPC. @@ -755,7 +755,7 @@ class UnaryUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -774,11 +774,11 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)): """Affords invoking a unary-stream RPC from client-side.""" @abc.abstractmethod - def __call__(self, - request, - timeout=None, - metadata=None, - credentials=None, + def __call__(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): """Invokes the underlying RPC. @@ -791,7 +791,7 @@ class UnaryStreamMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -813,7 +813,7 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): """Synchronously invokes the underlying RPC. @@ -827,7 +827,7 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -847,7 +847,7 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): """Synchronously invokes the underlying RPC on the client. @@ -861,7 +861,7 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -881,7 +881,7 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): """Asynchronously invokes the underlying RPC on the client. @@ -894,7 +894,7 @@ class StreamUnaryMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -917,7 +917,7 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): """Invokes the underlying RPC on the client. @@ -930,7 +930,7 @@ class StreamStreamMultiCallable(six.with_metaclass(abc.ABCMeta)): service-side of the RPC. credentials: An optional CallCredentials for the RPC. Only valid for secure Channel. - wait_for_ready: This is an EXPERIMENTAL argument. An optional + wait_for_ready: This is an EXPERIMENTAL argument. An optional flag to enable :term:`wait_for_ready` mechanism. compression: An element of grpc.compression, e.g. grpc.compression.Gzip. This is an EXPERIMENTAL option. @@ -1115,7 +1115,7 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)): """Gets one or more peer identity(s). Equivalent to - servicer_context.auth_context().get(servicer_context.peer_identity_key()) + servicer_context.auth_context().get(servicer_context.peer_identity_key()) Returns: An iterable of the identities, or None if the call is not @@ -1206,25 +1206,25 @@ class ServicerContext(six.with_metaclass(abc.ABCMeta, RpcContext)): raise NotImplementedError() @abc.abstractmethod - def abort_with_status(self, status): - """Raises an exception to terminate the RPC with a non-OK status. - - The status passed as argument will supercede any existing status code, - status message and trailing metadata. - - This is an EXPERIMENTAL API. - - Args: - status: A grpc.Status object. The status code in it must not be - StatusCode.OK. - - Raises: - Exception: An exception is always raised to signal the abortion the - RPC to the gRPC runtime. - """ - raise NotImplementedError() - - @abc.abstractmethod + def abort_with_status(self, status): + """Raises an exception to terminate the RPC with a non-OK status. + + The status passed as argument will supercede any existing status code, + status message and trailing metadata. + + This is an EXPERIMENTAL API. + + Args: + status: A grpc.Status object. The status code in it must not be + StatusCode.OK. + + Raises: + Exception: An exception is always raised to signal the abortion the + RPC to the gRPC runtime. + """ + raise NotImplementedError() + + @abc.abstractmethod def set_code(self, code): """Sets the value to be used as status code upon RPC completion. @@ -1436,20 +1436,20 @@ class Server(six.with_metaclass(abc.ABCMeta)): """Stops this Server. This method immediately stop service of new RPCs in all cases. - + If a grace period is specified, this method returns immediately and all RPCs active at the end of the grace period are aborted. - If a grace period is not specified (by passing None for `grace`), - all existing RPCs are aborted immediately and this method - blocks until the last RPC handler terminates. + If a grace period is not specified (by passing None for `grace`), + all existing RPCs are aborted immediately and this method + blocks until the last RPC handler terminates. This method is idempotent and may be called at any time. - Passing a smaller grace value in a subsequent call will have - the effect of stopping the Server sooner (passing None will - have the effect of stopping the server immediately). Passing - a larger grace value in a subsequent call *will not* have the - effect of stopping the server later (i.e. the most restrictive - grace value is used). + Passing a smaller grace value in a subsequent call will have + the effect of stopping the Server sooner (passing None will + have the effect of stopping the server immediately). Passing + a larger grace value in a subsequent call *will not* have the + effect of stopping the server later (i.e. the most restrictive + grace value is used). Args: grace: A duration of time in seconds or None. @@ -1691,7 +1691,7 @@ def ssl_server_credentials(private_key_certificate_chain_pairs, A ServerCredentials for use with an SSL-enabled Server. Typically, this object is an argument to add_secure_port() method during server setup. """ - if not private_key_certificate_chain_pairs: + if not private_key_certificate_chain_pairs: raise ValueError( 'At least one private key-certificate chain pair is required!') elif require_client_auth and root_certificates is None: @@ -1721,15 +1721,15 @@ def ssl_server_certificate_configuration(private_key_certificate_chain_pairs, A ServerCertificateConfiguration that can be returned in the certificate configuration fetching callback. """ - if private_key_certificate_chain_pairs: + if private_key_certificate_chain_pairs: return ServerCertificateConfiguration( _cygrpc.server_certificate_config_ssl(root_certificates, [ _cygrpc.SslPemKeyCertPair(key, pem) for key, pem in private_key_certificate_chain_pairs ])) - else: - raise ValueError( - 'At least one private key-certificate chain pair is required!') + else: + raise ValueError( + 'At least one private key-certificate chain pair is required!') def dynamic_ssl_server_credentials(initial_certificate_configuration, @@ -1905,8 +1905,8 @@ def channel_ready_future(channel): def insecure_channel(target, options=None, compression=None): """Creates an insecure Channel to a server. - The returned Channel is thread-safe. - + The returned Channel is thread-safe. + Args: target: The server address options: An optional list of key-value pairs (:term:`channel_arguments` @@ -1915,7 +1915,7 @@ def insecure_channel(target, options=None, compression=None): used over the lifetime of the channel. This is an EXPERIMENTAL option. Returns: - A Channel. + A Channel. """ from grpc import _channel # pylint: disable=cyclic-import return _channel.Channel(target, () if options is None else options, None, @@ -1925,8 +1925,8 @@ def insecure_channel(target, options=None, compression=None): def secure_channel(target, credentials, options=None, compression=None): """Creates a secure Channel to a server. - The returned Channel is thread-safe. - + The returned Channel is thread-safe. + Args: target: The server address. credentials: A ChannelCredentials instance. @@ -1936,7 +1936,7 @@ def secure_channel(target, credentials, options=None, compression=None): used over the lifetime of the channel. This is an EXPERIMENTAL option. Returns: - A Channel. + A Channel. """ from grpc import _channel # pylint: disable=cyclic-import from grpc.experimental import _insecure_channel_credentials @@ -1995,7 +1995,7 @@ def server(thread_pool, handlers. The interceptors are given control in the order they are specified. This is an EXPERIMENTAL API. options: An optional list of key-value pairs (:term:`channel_arguments` in gRPC runtime) - to configure the channel. + to configure the channel. maximum_concurrent_rpcs: The maximum number of concurrent RPCs this server will service before returning RESOURCE_EXHAUSTED status, or None to indicate no limit. @@ -2048,7 +2048,7 @@ __all__ = ( 'Future', 'ChannelConnectivity', 'StatusCode', - 'Status', + 'Status', 'RpcError', 'RpcContext', 'Call', diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py b/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py index 2d38320aff..4f3a6726ed 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_auth.py @@ -30,7 +30,7 @@ class GoogleCallCredentials(grpc.AuthMetadataPlugin): self._credentials = credentials # Hack to determine if these are JWT creds and we need to pass # additional_claims when getting a token - self._is_jwt = 'additional_claims' in inspect.getargspec( # pylint: disable=deprecated-method + self._is_jwt = 'additional_claims' in inspect.getargspec( # pylint: disable=deprecated-method credentials.get_access_token).args def __call__(self, context, callback): diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py b/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py index 11921d7883..c9facece19 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_channel.py @@ -28,8 +28,8 @@ from grpc import _common from grpc import _grpcio_metadata from grpc._cython import cygrpc -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + _USER_AGENT = 'grpc-python/{}'.format(_grpcio_metadata.__version__) _EMPTY_FLAGS = 0 @@ -70,17 +70,17 @@ _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE = ( 'Exception calling channel subscription callback!') _OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n' - '\tstatus = {}\n' - '\tdetails = "{}"\n' - '>') + '\tstatus = {}\n' + '\tdetails = "{}"\n' + '>') _NON_OK_RENDEZVOUS_REPR_FORMAT = ('<{} of RPC that terminated with:\n' - '\tstatus = {}\n' - '\tdetails = "{}"\n' - '\tdebug_error_string = "{}"\n' - '>') - - + '\tstatus = {}\n' + '\tdetails = "{}"\n' + '\tdebug_error_string = "{}"\n' + '>') + + def _deadline(timeout): return None if timeout is None else time.time() + timeout @@ -102,19 +102,19 @@ class _RPCState(object): self.trailing_metadata = trailing_metadata self.code = code self.details = details - self.debug_error_string = None + self.debug_error_string = None # The semantics of grpc.Future.cancel and grpc.Future.cancelled are # slightly wonky, so they have to be tracked separately from the rest of the # result of the RPC. This field tracks whether cancellation was requested # prior to termination of the RPC. self.cancelled = False self.callbacks = [] - self.fork_epoch = cygrpc.get_fork_epoch() - - def reset_postfork_child(self): - self.condition = threading.Condition() + self.fork_epoch = cygrpc.get_fork_epoch() + def reset_postfork_child(self): + self.condition = threading.Condition() + def _abort(state, code, details): if state.code is None: state.code = code @@ -153,7 +153,7 @@ def _handle_event(event, state, response_deserializer): else: state.code = code state.details = batch_operation.details() - state.debug_error_string = batch_operation.error_string() + state.debug_error_string = batch_operation.error_string() callbacks.extend(state.callbacks) state.callbacks = None return callbacks @@ -174,12 +174,12 @@ def _event_handler(state, response_deserializer): # kill the channel spin thread. logging.error('Exception in callback %s: %s', repr(callback.func), repr(e)) - return done and state.fork_epoch >= cygrpc.get_fork_epoch() + return done and state.fork_epoch >= cygrpc.get_fork_epoch() return handle_event -#pylint: disable=too-many-statements +#pylint: disable=too-many-statements def _consume_request_iterator(request_iterator, state, call, request_serializer, event_handler): """Consume a request iterator supplied by the user.""" @@ -188,31 +188,31 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer, # Iterate over the request iterator until it is exhausted or an error # condition is encountered. while True: - return_from_user_request_generator_invoked = False + return_from_user_request_generator_invoked = False try: - # The thread may die in user-code. Do not block fork for this. - cygrpc.enter_user_request_generator() + # The thread may die in user-code. Do not block fork for this. + cygrpc.enter_user_request_generator() request = next(request_iterator) except StopIteration: break except Exception: # pylint: disable=broad-except - cygrpc.return_from_user_request_generator() - return_from_user_request_generator_invoked = True + cygrpc.return_from_user_request_generator() + return_from_user_request_generator_invoked = True code = grpc.StatusCode.UNKNOWN details = 'Exception iterating requests!' - _LOGGER.exception(details) + _LOGGER.exception(details) call.cancel(_common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], details) _abort(state, code, details) return - finally: - if not return_from_user_request_generator_invoked: - cygrpc.return_from_user_request_generator() + finally: + if not return_from_user_request_generator_invoked: + cygrpc.return_from_user_request_generator() serialized_request = _common.serialize(request, request_serializer) with state.condition: if state.code is None and not state.cancelled: if serialized_request is None: - code = grpc.StatusCode.INTERNAL + code = grpc.StatusCode.INTERNAL details = 'Exception serializing request!' call.cancel( _common.STATUS_CODE_TO_CYGRPC_STATUS_CODE[code], @@ -250,9 +250,9 @@ def _consume_request_iterator(request_iterator, state, call, request_serializer, if operating: state.due.add(cygrpc.OperationType.send_close_from_client) - consumption_thread = cygrpc.ForkManagedThread( - target=consume_request_iterator) - consumption_thread.setDaemon(True) + consumption_thread = cygrpc.ForkManagedThread( + target=consume_request_iterator) + consumption_thread.setDaemon(True) consumption_thread.start() @@ -826,11 +826,11 @@ def _end_unary_response_blocking(state, call, with_call, deadline): raise _InactiveRpcError(state) -def _stream_unary_invocation_operationses(metadata, initial_metadata_flags): +def _stream_unary_invocation_operationses(metadata, initial_metadata_flags): return ( ( - cygrpc.SendInitialMetadataOperation(metadata, - initial_metadata_flags), + cygrpc.SendInitialMetadataOperation(metadata, + initial_metadata_flags), cygrpc.ReceiveMessageOperation(_EMPTY_FLAGS), cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS), ), @@ -838,8 +838,8 @@ def _stream_unary_invocation_operationses(metadata, initial_metadata_flags): ) -def _stream_unary_invocation_operationses_and_tags(metadata, - initial_metadata_flags): +def _stream_unary_invocation_operationses_and_tags(metadata, + initial_metadata_flags): return tuple(( operations, None, @@ -861,7 +861,7 @@ def _determine_deadline(user_deadline): class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): - # pylint: disable=too-many-arguments + # pylint: disable=too-many-arguments def __init__(self, channel, managed_call, method, request_serializer, response_deserializer): self._channel = channel @@ -869,13 +869,13 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): self._method = method self._request_serializer = request_serializer self._response_deserializer = response_deserializer - self._context = cygrpc.build_census_context() + self._context = cygrpc.build_census_context() def _prepare(self, request, timeout, metadata, wait_for_ready, compression): deadline, serialized_request, rendezvous = _start_unary_request( request, timeout, self._request_serializer) - initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( - wait_for_ready) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready) augmented_metadata = _compression.augment_metadata( metadata, compression) if serialized_request is None: @@ -884,7 +884,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): state = _RPCState(_UNARY_UNARY_INITIAL_DUE, None, None, None, None) operations = ( cygrpc.SendInitialMetadataOperation(augmented_metadata, - initial_metadata_flags), + initial_metadata_flags), cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS), cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS), cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS), @@ -898,59 +898,59 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): state, operations, deadline, rendezvous = self._prepare( request, timeout, metadata, wait_for_ready, compression) if state is None: - raise rendezvous # pylint: disable-msg=raising-bad-type + raise rendezvous # pylint: disable-msg=raising-bad-type else: call = self._channel.segregated_call( - cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, None, _determine_deadline(deadline), metadata, None if credentials is None else credentials._credentials, (( operations, None, - ),), self._context) + ),), self._context) event = call.next_event() _handle_event(event, state, self._response_deserializer) - return state, call + return state, call - def __call__(self, - request, - timeout=None, - metadata=None, - credentials=None, + def __call__(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): - state, call, = self._blocking(request, timeout, metadata, credentials, + state, call, = self._blocking(request, timeout, metadata, credentials, wait_for_ready, compression) return _end_unary_response_blocking(state, call, False, None) - def with_call(self, - request, - timeout=None, - metadata=None, - credentials=None, + def with_call(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): - state, call, = self._blocking(request, timeout, metadata, credentials, + state, call, = self._blocking(request, timeout, metadata, credentials, wait_for_ready, compression) return _end_unary_response_blocking(state, call, True, None) - def future(self, - request, - timeout=None, - metadata=None, - credentials=None, + def future(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): state, operations, deadline, rendezvous = self._prepare( request, timeout, metadata, wait_for_ready, compression) if state is None: - raise rendezvous # pylint: disable-msg=raising-bad-type + raise rendezvous # pylint: disable-msg=raising-bad-type else: event_handler = _event_handler(state, self._response_deserializer) call = self._managed_call( - cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, None, deadline, metadata, None if credentials is None else credentials._credentials, - (operations,), event_handler, self._context) + (operations,), event_handler, self._context) return _MultiThreadedRendezvous(state, call, self._response_deserializer, deadline) @@ -1008,7 +1008,7 @@ class _SingleThreadedUnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): - # pylint: disable=too-many-arguments + # pylint: disable=too-many-arguments def __init__(self, channel, managed_call, method, request_serializer, response_deserializer): self._channel = channel @@ -1016,7 +1016,7 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): self._method = method self._request_serializer = request_serializer self._response_deserializer = response_deserializer - self._context = cygrpc.build_census_context() + self._context = cygrpc.build_census_context() def __call__( # pylint: disable=too-many-locals self, @@ -1028,10 +1028,10 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): compression=None): deadline, serialized_request, rendezvous = _start_unary_request( request, timeout, self._request_serializer) - initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( - wait_for_ready) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready) if serialized_request is None: - raise rendezvous # pylint: disable-msg=raising-bad-type + raise rendezvous # pylint: disable-msg=raising-bad-type else: augmented_metadata = _compression.augment_metadata( metadata, compression) @@ -1039,7 +1039,7 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): operationses = ( ( cygrpc.SendInitialMetadataOperation(augmented_metadata, - initial_metadata_flags), + initial_metadata_flags), cygrpc.SendMessageOperation(serialized_request, _EMPTY_FLAGS), cygrpc.SendCloseFromClientOperation(_EMPTY_FLAGS), @@ -1048,7 +1048,7 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),), ) call = self._managed_call( - cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, None, _determine_deadline(deadline), metadata, None if credentials is None else credentials._credentials, operationses, _event_handler(state, @@ -1061,7 +1061,7 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): - # pylint: disable=too-many-arguments + # pylint: disable=too-many-arguments def __init__(self, channel, managed_call, method, request_serializer, response_deserializer): self._channel = channel @@ -1069,21 +1069,21 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): self._method = method self._request_serializer = request_serializer self._response_deserializer = response_deserializer - self._context = cygrpc.build_census_context() + self._context = cygrpc.build_census_context() - def _blocking(self, request_iterator, timeout, metadata, credentials, + def _blocking(self, request_iterator, timeout, metadata, credentials, wait_for_ready, compression): deadline = _deadline(timeout) state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None) - initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( - wait_for_ready) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready) augmented_metadata = _compression.augment_metadata( metadata, compression) call = self._channel.segregated_call( - cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, None, _determine_deadline(deadline), augmented_metadata, None if credentials is None else credentials._credentials, - _stream_unary_invocation_operationses_and_tags( + _stream_unary_invocation_operationses_and_tags( augmented_metadata, initial_metadata_flags), self._context) _consume_request_iterator(request_iterator, state, call, self._request_serializer, None) @@ -1094,13 +1094,13 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): state.condition.notify_all() if not state.due: break - return state, call + return state, call def __call__(self, request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): state, call, = self._blocking(request_iterator, timeout, metadata, @@ -1111,7 +1111,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): state, call, = self._blocking(request_iterator, timeout, metadata, @@ -1122,18 +1122,18 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): deadline = _deadline(timeout) state = _RPCState(_STREAM_UNARY_INITIAL_DUE, None, None, None, None) event_handler = _event_handler(state, self._response_deserializer) - initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( - wait_for_ready) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready) augmented_metadata = _compression.augment_metadata( metadata, compression) call = self._managed_call( - cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, None, deadline, augmented_metadata, None if credentials is None else credentials._credentials, _stream_unary_invocation_operationses(metadata, @@ -1147,7 +1147,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): - # pylint: disable=too-many-arguments + # pylint: disable=too-many-arguments def __init__(self, channel, managed_call, method, request_serializer, response_deserializer): self._channel = channel @@ -1155,32 +1155,32 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): self._method = method self._request_serializer = request_serializer self._response_deserializer = response_deserializer - self._context = cygrpc.build_census_context() + self._context = cygrpc.build_census_context() def __call__(self, request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): deadline = _deadline(timeout) state = _RPCState(_STREAM_STREAM_INITIAL_DUE, None, None, None, None) - initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( - wait_for_ready) + initial_metadata_flags = _InitialMetadataFlags().with_wait_for_ready( + wait_for_ready) augmented_metadata = _compression.augment_metadata( metadata, compression) operationses = ( ( cygrpc.SendInitialMetadataOperation(augmented_metadata, - initial_metadata_flags), + initial_metadata_flags), cygrpc.ReceiveStatusOnClientOperation(_EMPTY_FLAGS), ), (cygrpc.ReceiveInitialMetadataOperation(_EMPTY_FLAGS),), ) event_handler = _event_handler(state, self._response_deserializer) call = self._managed_call( - cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, + cygrpc.PropagationConstants.GRPC_PROPAGATE_DEFAULTS, self._method, None, _determine_deadline(deadline), augmented_metadata, None if credentials is None else credentials._credentials, operationses, event_handler, self._context) @@ -1190,34 +1190,34 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): self._response_deserializer, deadline) -class _InitialMetadataFlags(int): - """Stores immutable initial metadata flags""" - - def __new__(cls, value=_EMPTY_FLAGS): - value &= cygrpc.InitialMetadataFlags.used_mask - return super(_InitialMetadataFlags, cls).__new__(cls, value) - - def with_wait_for_ready(self, wait_for_ready): - if wait_for_ready is not None: - if wait_for_ready: - return self.__class__(self | cygrpc.InitialMetadataFlags.wait_for_ready | \ - cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set) - elif not wait_for_ready: - return self.__class__(self & ~cygrpc.InitialMetadataFlags.wait_for_ready | \ - cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set) - return self - - +class _InitialMetadataFlags(int): + """Stores immutable initial metadata flags""" + + def __new__(cls, value=_EMPTY_FLAGS): + value &= cygrpc.InitialMetadataFlags.used_mask + return super(_InitialMetadataFlags, cls).__new__(cls, value) + + def with_wait_for_ready(self, wait_for_ready): + if wait_for_ready is not None: + if wait_for_ready: + return self.__class__(self | cygrpc.InitialMetadataFlags.wait_for_ready | \ + cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set) + elif not wait_for_ready: + return self.__class__(self & ~cygrpc.InitialMetadataFlags.wait_for_ready | \ + cygrpc.InitialMetadataFlags.wait_for_ready_explicitly_set) + return self + + class _ChannelCallState(object): def __init__(self, channel): self.lock = threading.Lock() self.channel = channel self.managed_calls = 0 - self.threading = False + self.threading = False - def reset_postfork_child(self): - self.managed_calls = 0 + def reset_postfork_child(self): + self.managed_calls = 0 def __del__(self): try: @@ -1225,16 +1225,16 @@ class _ChannelCallState(object): 'Channel deallocated!') except (TypeError, AttributeError): pass - + def _run_channel_spin_thread(state): def channel_spin(): while True: - cygrpc.block_if_fork_in_progress(state) + cygrpc.block_if_fork_in_progress(state) event = state.channel.next_call_event() - if event.completion_type == cygrpc.CompletionType.queue_timeout: - continue + if event.completion_type == cygrpc.CompletionType.queue_timeout: + continue call_completed = event.tag(event) if call_completed: with state.lock: @@ -1242,8 +1242,8 @@ def _run_channel_spin_thread(state): if state.managed_calls == 0: return - channel_spin_thread = cygrpc.ForkManagedThread(target=channel_spin) - channel_spin_thread.setDaemon(True) + channel_spin_thread = cygrpc.ForkManagedThread(target=channel_spin) + channel_spin_thread.setDaemon(True) channel_spin_thread.start() @@ -1251,7 +1251,7 @@ def _channel_managed_call_management(state): # pylint: disable=too-many-arguments def create(flags, method, host, deadline, metadata, credentials, - operationses, event_handler, context): + operationses, event_handler, context): """Creates a cygrpc.IntegratedCall. Args: @@ -1266,7 +1266,7 @@ def _channel_managed_call_management(state): started on the call. event_handler: A behavior to call to handle the events resultant from the operations on the call. - context: Context object for distributed tracing. + context: Context object for distributed tracing. Returns: A cygrpc.IntegratedCall with which to conduct an RPC. """ @@ -1277,7 +1277,7 @@ def _channel_managed_call_management(state): with state.lock: call = state.channel.integrated_call(flags, method, host, deadline, metadata, credentials, - operationses_and_tags, context) + operationses_and_tags, context) if state.managed_calls == 0: state.managed_calls = 1 _run_channel_spin_thread(state) @@ -1299,14 +1299,14 @@ class _ChannelConnectivityState(object): self.callbacks_and_connectivities = [] self.delivering = False - def reset_postfork_child(self): - self.polling = False - self.connectivity = None - self.try_to_connect = False - self.callbacks_and_connectivities = [] - self.delivering = False - + def reset_postfork_child(self): + self.polling = False + self.connectivity = None + self.try_to_connect = False + self.callbacks_and_connectivities = [] + self.delivering = False + def _deliveries(state): callbacks_needing_update = [] for callback_and_connectivity in state.callbacks_and_connectivities: @@ -1322,12 +1322,12 @@ def _deliver(state, initial_connectivity, initial_callbacks): callbacks = initial_callbacks while True: for callback in callbacks: - cygrpc.block_if_fork_in_progress(state) - try: - callback(connectivity) - except Exception: # pylint: disable=broad-except - _LOGGER.exception( - _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE) + cygrpc.block_if_fork_in_progress(state) + try: + callback(connectivity) + except Exception: # pylint: disable=broad-except + _LOGGER.exception( + _CHANNEL_SUBSCRIPTION_CALLBACK_ERROR_LOG_MESSAGE) with state.lock: callbacks = _deliveries(state) if callbacks: @@ -1367,7 +1367,7 @@ def _poll_connectivity(state, channel, initial_try_to_connect): while True: event = channel.watch_connectivity_state(connectivity, time.time() + 0.2) - cygrpc.block_if_fork_in_progress(state) + cygrpc.block_if_fork_in_progress(state) with state.lock: if not state.callbacks_and_connectivities and not state.try_to_connect: state.polling = False @@ -1382,7 +1382,7 @@ def _poll_connectivity(state, channel, initial_try_to_connect): _common.CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY[ connectivity]) if not state.delivering: - callbacks = _deliveries(state) + callbacks = _deliveries(state) if callbacks: _spawn_delivery(state, callbacks) @@ -1390,10 +1390,10 @@ def _poll_connectivity(state, channel, initial_try_to_connect): def _subscribe(state, callback, try_to_connect): with state.lock: if not state.callbacks_and_connectivities and not state.polling: - polling_thread = cygrpc.ForkManagedThread( + polling_thread = cygrpc.ForkManagedThread( target=_poll_connectivity, args=(state, state.channel, bool(try_to_connect))) - polling_thread.setDaemon(True) + polling_thread.setDaemon(True) polling_thread.start() state.polling = True state.callbacks_and_connectivities.append([callback, None]) @@ -1457,7 +1457,7 @@ class Channel(grpc.Channel): credentials) self._call_state = _ChannelCallState(self._channel) self._connectivity_state = _ChannelConnectivityState(self._channel) - cygrpc.fork_register_channel(self) + cygrpc.fork_register_channel(self) def _process_python_options(self, python_options): """Sets channel attributes according to python-only channel options.""" @@ -1525,11 +1525,11 @@ class Channel(grpc.Channel): self._channel.close(cygrpc.StatusCode.cancelled, 'Channel closed!') cygrpc.fork_unregister_channel(self) - def _close_on_fork(self): + def _close_on_fork(self): self._unsubscribe_all() - self._channel.close_on_fork(cygrpc.StatusCode.cancelled, - 'Channel closed due to fork') - + self._channel.close_on_fork(cygrpc.StatusCode.cancelled, + 'Channel closed due to fork') + def __enter__(self): return self diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_common.py b/contrib/libs/grpc/src/python/grpcio/grpc/_common.py index 128124c325..ef2d3939c7 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_common.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_common.py @@ -20,8 +20,8 @@ import six import grpc from grpc._cython import cygrpc -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + CYGRPC_CONNECTIVITY_STATE_TO_CHANNEL_CONNECTIVITY = { cygrpc.ConnectivityState.idle: grpc.ChannelConnectivity.IDLE, @@ -69,13 +69,13 @@ def encode(s): if isinstance(s, bytes): return s else: - return s.encode('utf8') + return s.encode('utf8') def decode(b): - if isinstance(b, bytes): - return b.decode('utf-8', 'replace') - return b + if isinstance(b, bytes): + return b.decode('utf-8', 'replace') + return b def _transform(message, transformer, exception_message): @@ -85,7 +85,7 @@ def _transform(message, transformer, exception_message): try: return transformer(message) except Exception: # pylint: disable=broad-except - _LOGGER.exception(exception_message) + _LOGGER.exception(exception_message) return None diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pxd.pxi index 3eb10f5275..30db9de3ff 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pxd.pxi @@ -1,16 +1,16 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -cdef object _custom_op_on_c_call(int op, grpc_call *call) +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +cdef object _custom_op_on_c_call(int op, grpc_call *call) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi index de4d71b819..3bfab34593 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/_hooks.pyx.pxi @@ -1,35 +1,35 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -cdef object _custom_op_on_c_call(int op, grpc_call *call): - raise NotImplementedError("No custom hooks are implemented") - +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +cdef object _custom_op_on_c_call(int op, grpc_call *call): + raise NotImplementedError("No custom hooks are implemented") + def install_context_from_request_call_event(RequestCallEvent event): - pass - -def uninstall_context(): - pass - -def build_census_context(): - pass - -cdef class CensusContext: - pass - -def set_census_context_on_call(_CallState call_state, CensusContext census_ctx): - pass + pass + +def uninstall_context(): + pass + +def build_census_context(): + pass + +cdef class CensusContext: + pass + +def set_census_context_on_call(_CallState call_state, CensusContext census_ctx): + pass def get_deadline_from_context(): return None diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi index 251efe15b3..c0692004de 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pxd.pxi @@ -1,4 +1,4 @@ -# Copyright 2018 The gRPC Authors +# Copyright 2018 The gRPC Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,24 +13,24 @@ # limitations under the License. -cdef tuple _wrap_grpc_arg(grpc_arg arg) - - -cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg) - - -cdef class _ChannelArg: +cdef tuple _wrap_grpc_arg(grpc_arg arg) + +cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg) + + +cdef class _ChannelArg: + cdef grpc_arg c_argument cdef void c(self, argument, references) except * -cdef class _ChannelArgs: +cdef class _ChannelArgs: cdef readonly tuple _arguments - cdef list _channel_args + cdef list _channel_args cdef readonly list _references cdef grpc_channel_args _c_arguments - cdef grpc_channel_args *c_args(self) except * + cdef grpc_channel_args *c_args(self) except * diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi index 9df308cdbc..950aef8de7 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/arguments.pyx.pxi @@ -13,24 +13,24 @@ # limitations under the License. -cdef class _GrpcArgWrapper: - - cdef grpc_arg arg - - -cdef tuple _wrap_grpc_arg(grpc_arg arg): - wrapped = _GrpcArgWrapper() - wrapped.arg = arg - return ("grpc.python._cygrpc._GrpcArgWrapper", wrapped) - - -cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg): - cdef _GrpcArgWrapper wrapped = wrapped_arg[1] - return wrapped.arg - - -cdef class _ChannelArg: +cdef class _GrpcArgWrapper: + cdef grpc_arg arg + + +cdef tuple _wrap_grpc_arg(grpc_arg arg): + wrapped = _GrpcArgWrapper() + wrapped.arg = arg + return ("grpc.python._cygrpc._GrpcArgWrapper", wrapped) + + +cdef grpc_arg _unwrap_grpc_arg(tuple wrapped_arg): + cdef _GrpcArgWrapper wrapped = wrapped_arg[1] + return wrapped.arg + + +cdef class _ChannelArg: + cdef void c(self, argument, references) except *: key, value = argument cdef bytes encoded_key = _encode(key) @@ -46,8 +46,8 @@ cdef class _ChannelArg: if encoded_value is not value: references.append(encoded_value) self.c_argument.value.string = encoded_value - elif isinstance(value, _GrpcArgWrapper): - self.c_argument = (<_GrpcArgWrapper>value).arg + elif isinstance(value, _GrpcArgWrapper): + self.c_argument = (<_GrpcArgWrapper>value).arg elif hasattr(value, '__int__'): # Pointer objects must override __int__() to return # the underlying C address (Python ints are word size). The @@ -61,25 +61,25 @@ cdef class _ChannelArg: 'Expected int, bytes, or behavior, got {}'.format(type(value))) -cdef class _ChannelArgs: +cdef class _ChannelArgs: def __cinit__(self, arguments): self._arguments = () if arguments is None else tuple(arguments) - self._channel_args = [] + self._channel_args = [] self._references = [] self._c_arguments.arguments_length = len(self._arguments) - if self._c_arguments.arguments_length != 0: + if self._c_arguments.arguments_length != 0: self._c_arguments.arguments = <grpc_arg *>gpr_malloc( self._c_arguments.arguments_length * sizeof(grpc_arg)) for index, argument in enumerate(self._arguments): - channel_arg = _ChannelArg() + channel_arg = _ChannelArg() channel_arg.c(argument, self._references) - self._c_arguments.arguments[index] = channel_arg.c_argument - self._channel_args.append(channel_arg) - - cdef grpc_channel_args *c_args(self) except *: - return &self._c_arguments + self._c_arguments.arguments[index] = channel_arg.c_argument + self._channel_args.append(channel_arg) - def __dealloc__(self): - if self._c_arguments.arguments != NULL: + cdef grpc_channel_args *c_args(self) except *: + return &self._c_arguments + + def __dealloc__(self): + if self._c_arguments.arguments != NULL: gpr_free(self._c_arguments.arguments) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi index bdd155bea9..4eda7821d6 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/call.pyx.pxi @@ -17,7 +17,7 @@ cdef class Call: def __cinit__(self): # Create an *empty* call - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() self.c_call = NULL self.references = [] @@ -93,5 +93,5 @@ cdef class Call: def is_valid(self): return self.c_call != NULL - def _custom_op_on_c_call(self, int op): - return _custom_op_on_c_call(op, self.c_call) + def _custom_op_on_c_call(self, int op): + return _custom_op_on_c_call(op, self.c_call) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi index eb27f2df7a..e868338ee4 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pxd.pxi @@ -40,7 +40,7 @@ cdef class _ChannelState: # field and just use the NULLness of c_channel as an indication that the # channel is closed. cdef object open - cdef object closed_reason + cdef object closed_reason # A dict from _BatchOperationTag to _CallState cdef dict integrated_call_states @@ -69,6 +69,6 @@ cdef class SegregatedCall: cdef class Channel: cdef _ChannelState _state - - # TODO(https://github.com/grpc/grpc/issues/15662): Eliminate this. - cdef tuple _arguments + + # TODO(https://github.com/grpc/grpc/issues/15662): Eliminate this. + cdef tuple _arguments diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi index 74c7f6c140..c4187f7c3d 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channel.pyx.pxi @@ -80,7 +80,7 @@ cdef class _ChannelState: self.integrated_call_states = {} self.segregated_call_states = set() self.connectivity_due = set() - self.closed_reason = None + self.closed_reason = None cdef tuple _operate(grpc_call *c_call, object operations, object user_tag): @@ -140,7 +140,7 @@ cdef _cancel( _check_and_raise_call_error_no_metadata(c_call_error) -cdef _next_call_event( +cdef _next_call_event( _ChannelState channel_state, grpc_completion_queue *c_completion_queue, on_success, on_failure, deadline): """Block on the next event out of the completion queue. @@ -179,8 +179,8 @@ cdef void _call( _ChannelState channel_state, _CallState call_state, grpc_completion_queue *c_completion_queue, on_success, int flags, method, host, object deadline, CallCredentials credentials, - object operationses_and_user_tags, object metadata, - object context) except *: + object operationses_and_user_tags, object metadata, + object context) except *: """Invokes an RPC. Args: @@ -206,7 +206,7 @@ cdef void _call( which is an object to be used as a tag. A SendInitialMetadataOperation must be present in the first element of this value. metadata: The metadata for this call. - context: Context object for distributed tracing. + context: Context object for distributed tracing. """ cdef grpc_slice method_slice cdef grpc_slice host_slice @@ -230,8 +230,8 @@ cdef void _call( grpc_slice_unref(method_slice) if host_slice_ptr: grpc_slice_unref(host_slice) - if context is not None: - set_census_context_on_call(call_state, context) + if context is not None: + set_census_context_on_call(call_state, context) if credentials is not None: c_call_credentials = credentials.c() c_call_error = grpc_call_set_credentials( @@ -255,7 +255,7 @@ cdef void _call( call_state.due.update(started_tags) on_success(started_tags) else: - raise ValueError('Cannot invoke RPC: %s' % channel_state.closed_reason) + raise ValueError('Cannot invoke RPC: %s' % channel_state.closed_reason) cdef void _process_integrated_call_tag( @@ -283,8 +283,8 @@ cdef class IntegratedCall: cdef IntegratedCall _integrated_call( _ChannelState state, int flags, method, host, object deadline, - object metadata, CallCredentials credentials, operationses_and_user_tags, - object context): + object metadata, CallCredentials credentials, operationses_and_user_tags, + object context): call_state = _CallState() def on_success(started_tags): @@ -293,7 +293,7 @@ cdef IntegratedCall _integrated_call( _call( state, call_state, state.c_call_completion_queue, on_success, flags, - method, host, deadline, credentials, operationses_and_user_tags, metadata, context) + method, host, deadline, credentials, operationses_and_user_tags, metadata, context) return IntegratedCall(state, call_state) @@ -328,7 +328,7 @@ cdef class SegregatedCall: def next_event(self): def on_success(tag): _process_segregated_call_tag( - self._channel_state, self._call_state, self._c_completion_queue, tag) + self._channel_state, self._call_state, self._c_completion_queue, tag) def on_failure(): self._call_state.due.clear() grpc_call_unref(self._call_state.c_call) @@ -341,26 +341,26 @@ cdef class SegregatedCall: cdef SegregatedCall _segregated_call( _ChannelState state, int flags, method, host, object deadline, - object metadata, CallCredentials credentials, operationses_and_user_tags, - object context): + object metadata, CallCredentials credentials, operationses_and_user_tags, + object context): cdef _CallState call_state = _CallState() cdef SegregatedCall segregated_call - cdef grpc_completion_queue *c_completion_queue + cdef grpc_completion_queue *c_completion_queue def on_success(started_tags): state.segregated_call_states.add(call_state) - with state.condition: - if state.open: - c_completion_queue = (grpc_completion_queue_create_for_next(NULL)) - else: - raise ValueError('Cannot invoke RPC on closed channel!') - + with state.condition: + if state.open: + c_completion_queue = (grpc_completion_queue_create_for_next(NULL)) + else: + raise ValueError('Cannot invoke RPC on closed channel!') + try: _call( state, call_state, c_completion_queue, on_success, flags, method, host, - deadline, credentials, operationses_and_user_tags, metadata, - context) + deadline, credentials, operationses_and_user_tags, metadata, + context) except: _destroy_c_completion_queue(c_completion_queue) raise @@ -382,7 +382,7 @@ cdef object _watch_connectivity_state( state.c_connectivity_completion_queue, <cpython.PyObject *>tag) state.connectivity_due.add(tag) else: - raise ValueError('Cannot invoke RPC: %s' % state.closed_reason) + raise ValueError('Cannot invoke RPC: %s' % state.closed_reason) completed_tag, event = _latent_event( state.c_connectivity_completion_queue, None) with state.condition: @@ -391,15 +391,15 @@ cdef object _watch_connectivity_state( return event -cdef _close(Channel channel, grpc_status_code code, object details, - drain_calls): - cdef _ChannelState state = channel._state +cdef _close(Channel channel, grpc_status_code code, object details, + drain_calls): + cdef _ChannelState state = channel._state cdef _CallState call_state encoded_details = _encode(details) with state.condition: if state.open: state.open = False - state.closed_reason = details + state.closed_reason = details for call_state in set(state.integrated_call_states.values()): grpc_call_cancel_with_status( call_state.c_call, code, encoded_details, NULL) @@ -409,17 +409,17 @@ cdef _close(Channel channel, grpc_status_code code, object details, # TODO(https://github.com/grpc/grpc/issues/3064): Cancel connectivity # watching. - if drain_calls: - while not _calls_drained(state): - event = channel.next_call_event() - if event.completion_type == CompletionType.queue_timeout: - continue - event.tag(event) - else: - while state.integrated_call_states: - state.condition.wait() - while state.connectivity_due: - state.condition.wait() + if drain_calls: + while not _calls_drained(state): + event = channel.next_call_event() + if event.completion_type == CompletionType.queue_timeout: + continue + event.tag(event) + else: + while state.integrated_call_states: + state.condition.wait() + while state.connectivity_due: + state.condition.wait() _destroy_c_completion_queue(state.c_call_completion_queue) _destroy_c_completion_queue(state.c_connectivity_completion_queue) @@ -434,17 +434,17 @@ cdef _close(Channel channel, grpc_status_code code, object details, state.condition.wait() -cdef _calls_drained(_ChannelState state): - return not (state.integrated_call_states or state.segregated_call_states or - state.connectivity_due) - +cdef _calls_drained(_ChannelState state): + return not (state.integrated_call_states or state.segregated_call_states or + state.connectivity_due) + cdef class Channel: def __cinit__( self, bytes target, object arguments, ChannelCredentials channel_credentials): - arguments = () if arguments is None else tuple(arguments) - fork_handlers_and_grpc_init() + arguments = () if arguments is None else tuple(arguments) + fork_handlers_and_grpc_init() self._state = _ChannelState() self._state.c_call_completion_queue = ( grpc_completion_queue_create_for_next(NULL)) @@ -454,11 +454,11 @@ cdef class Channel: cdef _ChannelArgs channel_args = _ChannelArgs(arguments) if channel_credentials is None: self._state.c_channel = grpc_insecure_channel_create( - <char *>target, channel_args.c_args(), NULL) + <char *>target, channel_args.c_args(), NULL) else: c_channel_credentials = channel_credentials.c() self._state.c_channel = grpc_secure_channel_create( - c_channel_credentials, <char *>target, channel_args.c_args(), NULL) + c_channel_credentials, <char *>target, channel_args.c_args(), NULL) grpc_channel_credentials_release(c_channel_credentials) def target(self): @@ -471,48 +471,48 @@ cdef class Channel: def integrated_call( self, int flags, method, host, object deadline, object metadata, - CallCredentials credentials, operationses_and_tags, - object context = None): + CallCredentials credentials, operationses_and_tags, + object context = None): return _integrated_call( self._state, flags, method, host, deadline, metadata, credentials, - operationses_and_tags, context) + operationses_and_tags, context) def next_call_event(self): def on_success(tag): - if tag is not None: - _process_integrated_call_tag(self._state, tag) - if is_fork_support_enabled(): - queue_deadline = time.time() + 1.0 - else: - queue_deadline = None + if tag is not None: + _process_integrated_call_tag(self._state, tag) + if is_fork_support_enabled(): + queue_deadline = time.time() + 1.0 + else: + queue_deadline = None # NOTE(gnossen): It is acceptable for on_failure to be None here because # failure conditions can only ever happen on the main thread and this # method is only ever invoked on the channel spin thread. - return _next_call_event(self._state, self._state.c_call_completion_queue, + return _next_call_event(self._state, self._state.c_call_completion_queue, on_success, None, queue_deadline) def segregated_call( self, int flags, method, host, object deadline, object metadata, - CallCredentials credentials, operationses_and_tags, - object context = None): + CallCredentials credentials, operationses_and_tags, + object context = None): return _segregated_call( self._state, flags, method, host, deadline, metadata, credentials, - operationses_and_tags, context) + operationses_and_tags, context) def check_connectivity_state(self, bint try_to_connect): with self._state.condition: - if self._state.open: - return grpc_channel_check_connectivity_state( - self._state.c_channel, try_to_connect) - else: - raise ValueError('Cannot invoke RPC: %s' % self._state.closed_reason) + if self._state.open: + return grpc_channel_check_connectivity_state( + self._state.c_channel, try_to_connect) + else: + raise ValueError('Cannot invoke RPC: %s' % self._state.closed_reason) def watch_connectivity_state( self, grpc_connectivity_state last_observed_state, object deadline): return _watch_connectivity_state(self._state, last_observed_state, deadline) def close(self, code, details): - _close(self, code, details, False) - - def close_on_fork(self, code, details): - _close(self, code, details, True) + _close(self, code, details, False) + + def close_on_fork(self, code, details): + _close(self, code, details, True) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channelz.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channelz.pyx.pxi index 36c8cd121c..50f5408c56 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channelz.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/channelz.pyx.pxi @@ -1,71 +1,71 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -def channelz_get_top_channels(start_channel_id): - cdef char *c_returned_str = grpc_channelz_get_top_channels( - start_channel_id, - ) - if c_returned_str == NULL: - raise ValueError('Failed to get top channels, please ensure your' \ - ' start_channel_id==%s is valid' % start_channel_id) - return c_returned_str - -def channelz_get_servers(start_server_id): - cdef char *c_returned_str = grpc_channelz_get_servers(start_server_id) - if c_returned_str == NULL: - raise ValueError('Failed to get servers, please ensure your' \ - ' start_server_id==%s is valid' % start_server_id) - return c_returned_str - -def channelz_get_server(server_id): - cdef char *c_returned_str = grpc_channelz_get_server(server_id) - if c_returned_str == NULL: - raise ValueError('Failed to get the server, please ensure your' \ - ' server_id==%s is valid' % server_id) - return c_returned_str - -def channelz_get_server_sockets(server_id, start_socket_id, max_results): - cdef char *c_returned_str = grpc_channelz_get_server_sockets( - server_id, - start_socket_id, - max_results, - ) - if c_returned_str == NULL: - raise ValueError('Failed to get server sockets, please ensure your' \ - ' server_id==%s and start_socket_id==%s and' \ - ' max_results==%s is valid' % - (server_id, start_socket_id, max_results)) - return c_returned_str - -def channelz_get_channel(channel_id): - cdef char *c_returned_str = grpc_channelz_get_channel(channel_id) - if c_returned_str == NULL: - raise ValueError('Failed to get the channel, please ensure your' \ - ' channel_id==%s is valid' % (channel_id)) - return c_returned_str - -def channelz_get_subchannel(subchannel_id): - cdef char *c_returned_str = grpc_channelz_get_subchannel(subchannel_id) - if c_returned_str == NULL: - raise ValueError('Failed to get the subchannel, please ensure your' \ - ' subchannel_id==%s is valid' % (subchannel_id)) - return c_returned_str - -def channelz_get_socket(socket_id): - cdef char *c_returned_str = grpc_channelz_get_socket(socket_id) - if c_returned_str == NULL: - raise ValueError('Failed to get the socket, please ensure your' \ - ' socket_id==%s is valid' % (socket_id)) - return c_returned_str +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +def channelz_get_top_channels(start_channel_id): + cdef char *c_returned_str = grpc_channelz_get_top_channels( + start_channel_id, + ) + if c_returned_str == NULL: + raise ValueError('Failed to get top channels, please ensure your' \ + ' start_channel_id==%s is valid' % start_channel_id) + return c_returned_str + +def channelz_get_servers(start_server_id): + cdef char *c_returned_str = grpc_channelz_get_servers(start_server_id) + if c_returned_str == NULL: + raise ValueError('Failed to get servers, please ensure your' \ + ' start_server_id==%s is valid' % start_server_id) + return c_returned_str + +def channelz_get_server(server_id): + cdef char *c_returned_str = grpc_channelz_get_server(server_id) + if c_returned_str == NULL: + raise ValueError('Failed to get the server, please ensure your' \ + ' server_id==%s is valid' % server_id) + return c_returned_str + +def channelz_get_server_sockets(server_id, start_socket_id, max_results): + cdef char *c_returned_str = grpc_channelz_get_server_sockets( + server_id, + start_socket_id, + max_results, + ) + if c_returned_str == NULL: + raise ValueError('Failed to get server sockets, please ensure your' \ + ' server_id==%s and start_socket_id==%s and' \ + ' max_results==%s is valid' % + (server_id, start_socket_id, max_results)) + return c_returned_str + +def channelz_get_channel(channel_id): + cdef char *c_returned_str = grpc_channelz_get_channel(channel_id) + if c_returned_str == NULL: + raise ValueError('Failed to get the channel, please ensure your' \ + ' channel_id==%s is valid' % (channel_id)) + return c_returned_str + +def channelz_get_subchannel(subchannel_id): + cdef char *c_returned_str = grpc_channelz_get_subchannel(subchannel_id) + if c_returned_str == NULL: + raise ValueError('Failed to get the subchannel, please ensure your' \ + ' subchannel_id==%s is valid' % (subchannel_id)) + return c_returned_str + +def channelz_get_socket(socket_id): + cdef char *c_returned_str = grpc_channelz_get_socket(socket_id) + if c_returned_str == NULL: + raise ValueError('Failed to get the socket, please ensure your' \ + ' socket_id==%s is valid' % (socket_id)) + return c_returned_str diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi index a47403ac51..a39c023534 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/completion_queue.pyx.pxi @@ -46,7 +46,7 @@ cdef grpc_event _next(grpc_completion_queue *c_completion_queue, deadline) excep cdef _interpret_event(grpc_event c_event): cdef _Tag tag if c_event.type == GRPC_QUEUE_TIMEOUT: - # TODO(ericgribkoff) Do not coopt ConnectivityEvent here. + # TODO(ericgribkoff) Do not coopt ConnectivityEvent here. return None, ConnectivityEvent(GRPC_QUEUE_TIMEOUT, False, None) elif c_event.type == GRPC_QUEUE_SHUTDOWN: # NOTE(nathaniel): For now we coopt ConnectivityEvent here. @@ -68,7 +68,7 @@ cdef class CompletionQueue: def __cinit__(self, shutdown_cq=False): cdef grpc_completion_queue_attributes c_attrs - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() if shutdown_cq: c_attrs.version = 1 c_attrs.cq_completion_type = GRPC_CQ_NEXT diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi index ddaedb30bd..23642cfaeb 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pxd.pxi @@ -15,7 +15,7 @@ cdef class CallCredentials: - cdef grpc_call_credentials *c(self) except * + cdef grpc_call_credentials *c(self) except * # TODO(https://github.com/grpc/grpc/issues/12531): remove. cdef grpc_call_credentials *c_credentials @@ -36,7 +36,7 @@ cdef class MetadataPluginCallCredentials(CallCredentials): cdef readonly object _metadata_plugin cdef readonly bytes _name - cdef grpc_call_credentials *c(self) except * + cdef grpc_call_credentials *c(self) except * cdef grpc_call_credentials *_composition(call_credentialses) @@ -46,26 +46,26 @@ cdef class CompositeCallCredentials(CallCredentials): cdef readonly tuple _call_credentialses - cdef grpc_call_credentials *c(self) except * + cdef grpc_call_credentials *c(self) except * cdef class ChannelCredentials: - cdef grpc_channel_credentials *c(self) except * - - -cdef class SSLSessionCacheLRU: - - cdef grpc_ssl_session_cache *_cache + cdef grpc_channel_credentials *c(self) except * +cdef class SSLSessionCacheLRU: + + cdef grpc_ssl_session_cache *_cache + + cdef class SSLChannelCredentials(ChannelCredentials): cdef readonly object _pem_root_certificates cdef readonly object _private_key cdef readonly object _certificate_chain - cdef grpc_channel_credentials *c(self) except * + cdef grpc_channel_credentials *c(self) except * cdef class CompositeChannelCredentials(ChannelCredentials): @@ -73,7 +73,7 @@ cdef class CompositeChannelCredentials(ChannelCredentials): cdef readonly tuple _call_credentialses cdef readonly ChannelCredentials _channel_credentials - cdef grpc_channel_credentials *c(self) except * + cdef grpc_channel_credentials *c(self) except * cdef class ServerCertificateConfig: diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi index c75579cc04..b802058736 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/credentials.pyx.pxi @@ -13,24 +13,24 @@ # limitations under the License. -def _spawn_callback_in_thread(cb_func, args): +def _spawn_callback_in_thread(cb_func, args): t = ForkManagedThread(target=cb_func, args=args) t.setDaemon(True) t.start() - -async_callback_func = _spawn_callback_in_thread - -def set_async_callback_func(callback_func): - global async_callback_func - async_callback_func = callback_func - -def _spawn_callback_async(callback, args): - async_callback_func(callback, args) - - + +async_callback_func = _spawn_callback_in_thread + +def set_async_callback_func(callback_func): + global async_callback_func + async_callback_func = callback_func + +def _spawn_callback_async(callback, args): + async_callback_func(callback, args) + + cdef class CallCredentials: - cdef grpc_call_credentials *c(self) except *: + cdef grpc_call_credentials *c(self) except *: raise NotImplementedError() @@ -45,14 +45,14 @@ cdef int _get_metadata(void *state, cdef size_t metadata_count cdef grpc_metadata *c_metadata def callback(metadata, grpc_status_code status, bytes error_details): - if status == StatusCode.ok: + if status == StatusCode.ok: _store_c_metadata(metadata, &c_metadata, &metadata_count) cb(user_data, c_metadata, metadata_count, status, NULL) _release_c_metadata(c_metadata, metadata_count) else: cb(user_data, NULL, 0, status, error_details) args = context.service_url, context.method_name, callback, - _spawn_callback_async(<object>state, args) + _spawn_callback_async(<object>state, args) return 0 # Asynchronous return @@ -67,14 +67,14 @@ cdef class MetadataPluginCallCredentials(CallCredentials): self._metadata_plugin = metadata_plugin self._name = name - cdef grpc_call_credentials *c(self) except *: + cdef grpc_call_credentials *c(self) except *: cdef grpc_metadata_credentials_plugin c_metadata_plugin c_metadata_plugin.get_metadata = _get_metadata c_metadata_plugin.destroy = _destroy c_metadata_plugin.state = <void *>self._metadata_plugin c_metadata_plugin.type = self._name cpython.Py_INCREF(self._metadata_plugin) - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() # TODO(yihuazhang): Expose min_security_level via the Python API so that # applications can decide what minimum security level their plugins require. return grpc_metadata_credentials_create_from_plugin(c_metadata_plugin, GRPC_PRIVACY_AND_INTEGRITY, NULL) @@ -102,41 +102,41 @@ cdef class CompositeCallCredentials(CallCredentials): def __cinit__(self, call_credentialses): self._call_credentialses = call_credentialses - cdef grpc_call_credentials *c(self) except *: + cdef grpc_call_credentials *c(self) except *: return _composition(self._call_credentialses) cdef class ChannelCredentials: - cdef grpc_channel_credentials *c(self) except *: + cdef grpc_channel_credentials *c(self) except *: raise NotImplementedError() -cdef class SSLSessionCacheLRU: - - def __cinit__(self, capacity): - fork_handlers_and_grpc_init() - self._cache = grpc_ssl_session_cache_create_lru(capacity) - - def __int__(self): - return <uintptr_t>self._cache - - def __dealloc__(self): - if self._cache != NULL: - grpc_ssl_session_cache_destroy(self._cache) +cdef class SSLSessionCacheLRU: + + def __cinit__(self, capacity): + fork_handlers_and_grpc_init() + self._cache = grpc_ssl_session_cache_create_lru(capacity) + + def __int__(self): + return <uintptr_t>self._cache + + def __dealloc__(self): + if self._cache != NULL: + grpc_ssl_session_cache_destroy(self._cache) grpc_shutdown_blocking() - - + + cdef class SSLChannelCredentials(ChannelCredentials): def __cinit__(self, pem_root_certificates, private_key, certificate_chain): - if pem_root_certificates is not None and not isinstance(pem_root_certificates, bytes): - raise TypeError('expected certificate to be bytes, got %s' % (type(pem_root_certificates))) + if pem_root_certificates is not None and not isinstance(pem_root_certificates, bytes): + raise TypeError('expected certificate to be bytes, got %s' % (type(pem_root_certificates))) self._pem_root_certificates = pem_root_certificates self._private_key = private_key self._certificate_chain = certificate_chain - cdef grpc_channel_credentials *c(self) except *: + cdef grpc_channel_credentials *c(self) except *: cdef const char *c_pem_root_certificates cdef grpc_ssl_pem_key_cert_pair c_pem_key_certificate_pair if self._pem_root_certificates is None: @@ -145,18 +145,18 @@ cdef class SSLChannelCredentials(ChannelCredentials): c_pem_root_certificates = self._pem_root_certificates if self._private_key is None and self._certificate_chain is None: return grpc_ssl_credentials_create( - c_pem_root_certificates, NULL, NULL, NULL) + c_pem_root_certificates, NULL, NULL, NULL) else: - if self._private_key: - c_pem_key_certificate_pair.private_key = self._private_key - else: - c_pem_key_certificate_pair.private_key = NULL - if self._certificate_chain: - c_pem_key_certificate_pair.certificate_chain = self._certificate_chain - else: - c_pem_key_certificate_pair.certificate_chain = NULL + if self._private_key: + c_pem_key_certificate_pair.private_key = self._private_key + else: + c_pem_key_certificate_pair.private_key = NULL + if self._certificate_chain: + c_pem_key_certificate_pair.certificate_chain = self._certificate_chain + else: + c_pem_key_certificate_pair.certificate_chain = NULL return grpc_ssl_credentials_create( - c_pem_root_certificates, &c_pem_key_certificate_pair, NULL, NULL) + c_pem_root_certificates, &c_pem_key_certificate_pair, NULL, NULL) cdef class CompositeChannelCredentials(ChannelCredentials): @@ -165,7 +165,7 @@ cdef class CompositeChannelCredentials(ChannelCredentials): self._call_credentialses = call_credentialses self._channel_credentials = channel_credentials - cdef grpc_channel_credentials *c(self) except *: + cdef grpc_channel_credentials *c(self) except *: cdef grpc_channel_credentials *c_channel_credentials c_channel_credentials = self._channel_credentials.c() cdef grpc_call_credentials *c_call_credentials_composition = _composition( @@ -181,7 +181,7 @@ cdef class CompositeChannelCredentials(ChannelCredentials): cdef class ServerCertificateConfig: def __cinit__(self): - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() self.c_cert_config = NULL self.c_pem_root_certs = NULL self.c_ssl_pem_key_cert_pairs = NULL @@ -196,7 +196,7 @@ cdef class ServerCertificateConfig: cdef class ServerCredentials: def __cinit__(self): - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() self.c_credentials = NULL self.references = [] self.initial_cert_config = None @@ -291,44 +291,44 @@ def server_credentials_ssl_dynamic_cert_config(initial_cert_config, # C-core assumes ownership of c_options credentials.c_credentials = grpc_ssl_server_credentials_create_with_options(c_options) return credentials - -cdef grpc_ssl_certificate_config_reload_status _server_cert_config_fetcher_wrapper( - void* user_data, grpc_ssl_server_certificate_config **config) with gil: - # This is a credentials.ServerCertificateConfig - cdef ServerCertificateConfig cert_config = None - if not user_data: - raise ValueError('internal error: user_data must be specified') - credentials = <ServerCredentials>user_data - if not credentials.initial_cert_config_fetched: - # C-core is asking for the initial cert config - credentials.initial_cert_config_fetched = True - cert_config = credentials.initial_cert_config._certificate_configuration - else: - user_cb = credentials.cert_config_fetcher - try: - cert_config_wrapper = user_cb() - except Exception: - _LOGGER.exception('Error fetching certificate config') - return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL - if cert_config_wrapper is None: - return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED - elif not isinstance( - cert_config_wrapper, grpc.ServerCertificateConfiguration): - _LOGGER.error( - 'Error fetching certificate configuration: certificate ' - 'configuration must be of type grpc.ServerCertificateConfiguration, ' - 'not %s' % type(cert_config_wrapper).__name__) - return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL - else: - cert_config = cert_config_wrapper._certificate_configuration - config[0] = <grpc_ssl_server_certificate_config*>cert_config.c_cert_config - # our caller will assume ownership of memory, so we have to recreate - # a copy of c_cert_config here - cert_config.c_cert_config = grpc_ssl_server_certificate_config_create( - cert_config.c_pem_root_certs, cert_config.c_ssl_pem_key_cert_pairs, - cert_config.c_ssl_pem_key_cert_pairs_count) - return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW - + +cdef grpc_ssl_certificate_config_reload_status _server_cert_config_fetcher_wrapper( + void* user_data, grpc_ssl_server_certificate_config **config) with gil: + # This is a credentials.ServerCertificateConfig + cdef ServerCertificateConfig cert_config = None + if not user_data: + raise ValueError('internal error: user_data must be specified') + credentials = <ServerCredentials>user_data + if not credentials.initial_cert_config_fetched: + # C-core is asking for the initial cert config + credentials.initial_cert_config_fetched = True + cert_config = credentials.initial_cert_config._certificate_configuration + else: + user_cb = credentials.cert_config_fetcher + try: + cert_config_wrapper = user_cb() + except Exception: + _LOGGER.exception('Error fetching certificate config') + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL + if cert_config_wrapper is None: + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_UNCHANGED + elif not isinstance( + cert_config_wrapper, grpc.ServerCertificateConfiguration): + _LOGGER.error( + 'Error fetching certificate configuration: certificate ' + 'configuration must be of type grpc.ServerCertificateConfiguration, ' + 'not %s' % type(cert_config_wrapper).__name__) + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_FAIL + else: + cert_config = cert_config_wrapper._certificate_configuration + config[0] = <grpc_ssl_server_certificate_config*>cert_config.c_cert_config + # our caller will assume ownership of memory, so we have to recreate + # a copy of c_cert_config here + cert_config.c_cert_config = grpc_ssl_server_certificate_config_create( + cert_config.c_pem_root_certs, cert_config.c_ssl_pem_key_cert_pairs, + cert_config.c_ssl_pem_key_cert_pairs_count) + return GRPC_SSL_CERTIFICATE_CONFIG_RELOAD_NEW + class LocalConnectionType: uds = UDS diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pxd.pxi index a925bdd2e6..e9fd362e01 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pxd.pxi @@ -1,29 +1,29 @@ -# Copyright 2018 gRPC authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -cdef extern from "pthread.h" nogil: - int pthread_atfork( - void (*prepare)() nogil, - void (*parent)() nogil, - void (*child)() nogil) - - -cdef void __prefork() nogil - - -cdef void __postfork_parent() nogil - - -cdef void __postfork_child() nogil
\ No newline at end of file +# Copyright 2018 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +cdef extern from "pthread.h" nogil: + int pthread_atfork( + void (*prepare)() nogil, + void (*parent)() nogil, + void (*child)() nogil) + + +cdef void __prefork() nogil + + +cdef void __postfork_parent() nogil + + +cdef void __postfork_child() nogil
\ No newline at end of file diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi index 53657e8b1a..495692b210 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_posix.pyx.pxi @@ -1,62 +1,62 @@ -# Copyright 2018 gRPC authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -_AWAIT_THREADS_TIMEOUT_SECONDS = 5 - -_TRUE_VALUES = ['yes', 'Yes', 'YES', 'true', 'True', 'TRUE', '1'] - -# This flag enables experimental support within gRPC Python for applications -# that will fork() without exec(). When enabled, gRPC Python will attempt to -# pause all of its internally created threads before the fork syscall proceeds. -# -# For this to be successful, the application must not have multiple threads of -# its own calling into gRPC when fork is invoked. Any callbacks from gRPC -# Python-spawned threads into user code (e.g., callbacks for asynchronous RPCs) -# must not block and should execute quickly. -# -# This flag is not supported on Windows. +# Copyright 2018 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +_AWAIT_THREADS_TIMEOUT_SECONDS = 5 + +_TRUE_VALUES = ['yes', 'Yes', 'YES', 'true', 'True', 'TRUE', '1'] + +# This flag enables experimental support within gRPC Python for applications +# that will fork() without exec(). When enabled, gRPC Python will attempt to +# pause all of its internally created threads before the fork syscall proceeds. +# +# For this to be successful, the application must not have multiple threads of +# its own calling into gRPC when fork is invoked. Any callbacks from gRPC +# Python-spawned threads into user code (e.g., callbacks for asynchronous RPCs) +# must not block and should execute quickly. +# +# This flag is not supported on Windows. # This flag is also not supported for non-native IO manager. -_GRPC_ENABLE_FORK_SUPPORT = ( - os.environ.get('GRPC_ENABLE_FORK_SUPPORT', '0') - .lower() in _TRUE_VALUES) - +_GRPC_ENABLE_FORK_SUPPORT = ( + os.environ.get('GRPC_ENABLE_FORK_SUPPORT', '0') + .lower() in _TRUE_VALUES) + _fork_handler_failed = False -cdef void __prefork() nogil: - with gil: +cdef void __prefork() nogil: + with gil: global _fork_handler_failed _fork_handler_failed = False - with _fork_state.fork_in_progress_condition: - _fork_state.fork_in_progress = True - if not _fork_state.active_thread_count.await_zero_threads( - _AWAIT_THREADS_TIMEOUT_SECONDS): - _LOGGER.error( - 'Failed to shutdown gRPC Python threads prior to fork. ' - 'Behavior after fork will be undefined.') + with _fork_state.fork_in_progress_condition: + _fork_state.fork_in_progress = True + if not _fork_state.active_thread_count.await_zero_threads( + _AWAIT_THREADS_TIMEOUT_SECONDS): + _LOGGER.error( + 'Failed to shutdown gRPC Python threads prior to fork. ' + 'Behavior after fork will be undefined.') _fork_handler_failed = True - - -cdef void __postfork_parent() nogil: - with gil: - with _fork_state.fork_in_progress_condition: - _fork_state.fork_in_progress = False - _fork_state.fork_in_progress_condition.notify_all() - - -cdef void __postfork_child() nogil: - with gil: + + +cdef void __postfork_parent() nogil: + with gil: + with _fork_state.fork_in_progress_condition: + _fork_state.fork_in_progress = False + _fork_state.fork_in_progress_condition.notify_all() + + +cdef void __postfork_child() nogil: + with gil: try: if _fork_handler_failed: return @@ -79,130 +79,130 @@ cdef void __postfork_child() nogil: _LOGGER.error(sys.exc_info()[0]) os._exit(os.EX_USAGE) - if grpc_is_initialized() > 0: - with gil: - _LOGGER.error('Failed to shutdown gRPC Core after fork()') - os._exit(os.EX_USAGE) - - -def fork_handlers_and_grpc_init(): - grpc_init() - if _GRPC_ENABLE_FORK_SUPPORT: - with _fork_state.fork_handler_registered_lock: - if not _fork_state.fork_handler_registered: - pthread_atfork(&__prefork, &__postfork_parent, &__postfork_child) - _fork_state.fork_handler_registered = True - - - - -class ForkManagedThread(object): - def __init__(self, target, args=()): - if _GRPC_ENABLE_FORK_SUPPORT: - def managed_target(*args): - try: - target(*args) - finally: - _fork_state.active_thread_count.decrement() + if grpc_is_initialized() > 0: + with gil: + _LOGGER.error('Failed to shutdown gRPC Core after fork()') + os._exit(os.EX_USAGE) + + +def fork_handlers_and_grpc_init(): + grpc_init() + if _GRPC_ENABLE_FORK_SUPPORT: + with _fork_state.fork_handler_registered_lock: + if not _fork_state.fork_handler_registered: + pthread_atfork(&__prefork, &__postfork_parent, &__postfork_child) + _fork_state.fork_handler_registered = True + + + + +class ForkManagedThread(object): + def __init__(self, target, args=()): + if _GRPC_ENABLE_FORK_SUPPORT: + def managed_target(*args): + try: + target(*args) + finally: + _fork_state.active_thread_count.decrement() self._thread = threading.Thread(target=_run_with_context(managed_target), args=args) - else: + else: self._thread = threading.Thread(target=_run_with_context(target), args=args) - - def setDaemon(self, daemonic): - self._thread.daemon = daemonic - - def start(self): - if _GRPC_ENABLE_FORK_SUPPORT: - _fork_state.active_thread_count.increment() - self._thread.start() - - def join(self): - self._thread.join() - - -def block_if_fork_in_progress(postfork_state_to_reset=None): - if _GRPC_ENABLE_FORK_SUPPORT: - with _fork_state.fork_in_progress_condition: - if not _fork_state.fork_in_progress: - return - if postfork_state_to_reset is not None: - _fork_state.postfork_states_to_reset.append(postfork_state_to_reset) - _fork_state.active_thread_count.decrement() - _fork_state.fork_in_progress_condition.wait() - _fork_state.active_thread_count.increment() - - -def enter_user_request_generator(): - if _GRPC_ENABLE_FORK_SUPPORT: - _fork_state.active_thread_count.decrement() - - -def return_from_user_request_generator(): - if _GRPC_ENABLE_FORK_SUPPORT: - _fork_state.active_thread_count.increment() - block_if_fork_in_progress() - - -def get_fork_epoch(): - return _fork_state.fork_epoch - - -def is_fork_support_enabled(): - return _GRPC_ENABLE_FORK_SUPPORT - - -def fork_register_channel(channel): - if _GRPC_ENABLE_FORK_SUPPORT: - _fork_state.channels.add(channel) - - -def fork_unregister_channel(channel): - if _GRPC_ENABLE_FORK_SUPPORT: + + def setDaemon(self, daemonic): + self._thread.daemon = daemonic + + def start(self): + if _GRPC_ENABLE_FORK_SUPPORT: + _fork_state.active_thread_count.increment() + self._thread.start() + + def join(self): + self._thread.join() + + +def block_if_fork_in_progress(postfork_state_to_reset=None): + if _GRPC_ENABLE_FORK_SUPPORT: + with _fork_state.fork_in_progress_condition: + if not _fork_state.fork_in_progress: + return + if postfork_state_to_reset is not None: + _fork_state.postfork_states_to_reset.append(postfork_state_to_reset) + _fork_state.active_thread_count.decrement() + _fork_state.fork_in_progress_condition.wait() + _fork_state.active_thread_count.increment() + + +def enter_user_request_generator(): + if _GRPC_ENABLE_FORK_SUPPORT: + _fork_state.active_thread_count.decrement() + + +def return_from_user_request_generator(): + if _GRPC_ENABLE_FORK_SUPPORT: + _fork_state.active_thread_count.increment() + block_if_fork_in_progress() + + +def get_fork_epoch(): + return _fork_state.fork_epoch + + +def is_fork_support_enabled(): + return _GRPC_ENABLE_FORK_SUPPORT + + +def fork_register_channel(channel): + if _GRPC_ENABLE_FORK_SUPPORT: + _fork_state.channels.add(channel) + + +def fork_unregister_channel(channel): + if _GRPC_ENABLE_FORK_SUPPORT: _fork_state.channels.discard(channel) - - -class _ActiveThreadCount(object): - def __init__(self): - self._num_active_threads = 0 - self._condition = threading.Condition() - - def increment(self): - with self._condition: - self._num_active_threads += 1 - - def decrement(self): - with self._condition: - self._num_active_threads -= 1 - if self._num_active_threads == 0: - self._condition.notify_all() - - def await_zero_threads(self, timeout_secs): - end_time = time.time() + timeout_secs - wait_time = timeout_secs - with self._condition: - while True: - if self._num_active_threads > 0: - self._condition.wait(wait_time) - if self._num_active_threads == 0: - return True - # Thread count may have increased before this re-obtains the - # lock after a notify(). Wait again until timeout_secs has - # elapsed. - wait_time = end_time - time.time() - if wait_time <= 0: - return False - - -class _ForkState(object): - def __init__(self): - self.fork_in_progress_condition = threading.Condition() - self.fork_in_progress = False - self.postfork_states_to_reset = [] - self.fork_handler_registered_lock = threading.Lock() - self.fork_handler_registered = False - self.active_thread_count = _ActiveThreadCount() - self.fork_epoch = 0 - self.channels = set() - - -_fork_state = _ForkState() + + +class _ActiveThreadCount(object): + def __init__(self): + self._num_active_threads = 0 + self._condition = threading.Condition() + + def increment(self): + with self._condition: + self._num_active_threads += 1 + + def decrement(self): + with self._condition: + self._num_active_threads -= 1 + if self._num_active_threads == 0: + self._condition.notify_all() + + def await_zero_threads(self, timeout_secs): + end_time = time.time() + timeout_secs + wait_time = timeout_secs + with self._condition: + while True: + if self._num_active_threads > 0: + self._condition.wait(wait_time) + if self._num_active_threads == 0: + return True + # Thread count may have increased before this re-obtains the + # lock after a notify(). Wait again until timeout_secs has + # elapsed. + wait_time = end_time - time.time() + if wait_time <= 0: + return False + + +class _ForkState(object): + def __init__(self): + self.fork_in_progress_condition = threading.Condition() + self.fork_in_progress = False + self.postfork_states_to_reset = [] + self.fork_handler_registered_lock = threading.Lock() + self.fork_handler_registered = False + self.active_thread_count = _ActiveThreadCount() + self.fork_epoch = 0 + self.channels = set() + + +_fork_state = _ForkState() diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_windows.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_windows.pyx.pxi index 67aaf4d033..189bd7308f 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_windows.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/fork_windows.pyx.pxi @@ -1,61 +1,61 @@ -# Copyright 2018 gRPC authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - - -# No-op implementations for Windows. - -def fork_handlers_and_grpc_init(): - grpc_init() - - -class ForkManagedThread(object): - def __init__(self, target, args=()): +# Copyright 2018 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# No-op implementations for Windows. + +def fork_handlers_and_grpc_init(): + grpc_init() + + +class ForkManagedThread(object): + def __init__(self, target, args=()): self._thread = threading.Thread(target=_run_with_context(target), args=args) - - def setDaemon(self, daemonic): - self._thread.daemon = daemonic - - def start(self): - self._thread.start() - - def join(self): - self._thread.join() - - -def block_if_fork_in_progress(postfork_state_to_reset=None): - pass - - -def enter_user_request_generator(): - pass - - -def return_from_user_request_generator(): - pass - - -def get_fork_epoch(): - return 0 - - -def is_fork_support_enabled(): - return False - - -def fork_register_channel(channel): - pass - - -def fork_unregister_channel(channel): - pass + + def setDaemon(self, daemonic): + self._thread.daemon = daemonic + + def start(self): + self._thread.start() + + def join(self): + self._thread.join() + + +def block_if_fork_in_progress(postfork_state_to_reset=None): + pass + + +def enter_user_request_generator(): + pass + + +def return_from_user_request_generator(): + pass + + +def get_fork_epoch(): + return 0 + + +def is_fork_support_enabled(): + return False + + +def fork_register_channel(channel): + pass + + +def fork_unregister_channel(channel): + pass diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi index 54eb7fdffc..a9743d689e 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc.pxi @@ -144,7 +144,7 @@ cdef extern from "grpc/grpc.h": const char *GRPC_ARG_PRIMARY_USER_AGENT_STRING const char *GRPC_ARG_SECONDARY_USER_AGENT_STRING const char *GRPC_SSL_TARGET_NAME_OVERRIDE_ARG - const char *GRPC_SSL_SESSION_CACHE_ARG + const char *GRPC_SSL_SESSION_CACHE_ARG const char *_GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM \ "GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM" const char *GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL @@ -154,10 +154,10 @@ cdef extern from "grpc/grpc.h": const int GRPC_WRITE_NO_COMPRESS const int GRPC_WRITE_USED_MASK - const int GRPC_INITIAL_METADATA_WAIT_FOR_READY - const int GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET - const int GRPC_INITIAL_METADATA_USED_MASK - + const int GRPC_INITIAL_METADATA_WAIT_FOR_READY + const int GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET + const int GRPC_INITIAL_METADATA_USED_MASK + const int GRPC_MAX_COMPLETION_QUEUE_PLUCKERS ctypedef struct grpc_completion_queue: @@ -304,7 +304,7 @@ cdef extern from "grpc/grpc.h": grpc_metadata_array *trailing_metadata grpc_status_code *status grpc_slice *status_details - char** error_string + char** error_string ctypedef struct grpc_op_data_recv_close_on_server: int *cancelled @@ -336,7 +336,7 @@ cdef extern from "grpc/grpc.h": void grpc_dont_init_openssl() nogil void grpc_init() nogil void grpc_shutdown_blocking() nogil - int grpc_is_initialized() nogil + int grpc_is_initialized() nogil ctypedef struct grpc_completion_queue_factory: pass @@ -405,17 +405,17 @@ cdef extern from "grpc/grpc.h": void grpc_server_cancel_all_calls(grpc_server *server) nogil void grpc_server_destroy(grpc_server *server) nogil - char* grpc_channelz_get_top_channels(intptr_t start_channel_id) - char* grpc_channelz_get_servers(intptr_t start_server_id) - char* grpc_channelz_get_server(intptr_t server_id) - char* grpc_channelz_get_server_sockets(intptr_t server_id, - intptr_t start_socket_id, - intptr_t max_results) - char* grpc_channelz_get_channel(intptr_t channel_id) - char* grpc_channelz_get_subchannel(intptr_t subchannel_id) - char* grpc_channelz_get_socket(intptr_t socket_id) - + char* grpc_channelz_get_top_channels(intptr_t start_channel_id) + char* grpc_channelz_get_servers(intptr_t start_server_id) + char* grpc_channelz_get_server(intptr_t server_id) + char* grpc_channelz_get_server_sockets(intptr_t server_id, + intptr_t start_socket_id, + intptr_t max_results) + char* grpc_channelz_get_channel(intptr_t channel_id) + char* grpc_channelz_get_subchannel(intptr_t subchannel_id) + char* grpc_channelz_get_socket(intptr_t socket_id) + cdef extern from "grpc/grpc_security.h": # Declare this as an enum, this is the only way to make it a const in @@ -489,26 +489,26 @@ cdef extern from "grpc/grpc_security.h": # We don't care about the internals (and in fact don't know them) pass - ctypedef struct grpc_ssl_session_cache: - # We don't care about the internals (and in fact don't know them) - pass - - ctypedef struct verify_peer_options: - # We don't care about the internals (and in fact don't know them) - pass - + ctypedef struct grpc_ssl_session_cache: + # We don't care about the internals (and in fact don't know them) + pass + + ctypedef struct verify_peer_options: + # We don't care about the internals (and in fact don't know them) + pass + ctypedef void (*grpc_ssl_roots_override_callback)(char **pem_root_certs) - grpc_ssl_session_cache *grpc_ssl_session_cache_create_lru(size_t capacity) - void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache) - + grpc_ssl_session_cache *grpc_ssl_session_cache_create_lru(size_t capacity) + void grpc_ssl_session_cache_destroy(grpc_ssl_session_cache* cache) + void grpc_set_ssl_roots_override_callback( grpc_ssl_roots_override_callback cb) nogil grpc_channel_credentials *grpc_google_default_credentials_create(grpc_call_credentials* call_credentials) nogil grpc_channel_credentials *grpc_ssl_credentials_create( const char *pem_root_certs, grpc_ssl_pem_key_cert_pair *pem_key_cert_pair, - verify_peer_options *verify_options, void *reserved) nogil + verify_peer_options *verify_options, void *reserved) nogil grpc_channel_credentials *grpc_composite_channel_credentials_create( grpc_channel_credentials *creds1, grpc_call_credentials *creds2, void *reserved) nogil diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pxd.pxi index bd1d73145b..d68ce8a6e5 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pxd.pxi @@ -1,41 +1,41 @@ -# Copyright 2017 gRPC authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# distutils: language=c++ - -cdef class TimerWrapper: - - cdef grpc_custom_timer *c_timer - cdef object timer - cdef object event - -cdef class SocketWrapper: - cdef object sockopts - cdef object socket - cdef object closed - cdef grpc_custom_socket *c_socket - cdef char* c_buffer - cdef size_t len - cdef grpc_custom_socket *accepting_socket - - cdef grpc_custom_connect_callback connect_cb - cdef grpc_custom_write_callback write_cb - cdef grpc_custom_read_callback read_cb - cdef grpc_custom_accept_callback accept_cb - cdef grpc_custom_close_callback close_cb - - -cdef class ResolveWrapper: - cdef grpc_custom_resolver *c_resolver +# Copyright 2017 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# distutils: language=c++ + +cdef class TimerWrapper: + + cdef grpc_custom_timer *c_timer + cdef object timer + cdef object event + +cdef class SocketWrapper: + cdef object sockopts + cdef object socket + cdef object closed + cdef grpc_custom_socket *c_socket + cdef char* c_buffer + cdef size_t len + cdef grpc_custom_socket *accepting_socket + + cdef grpc_custom_connect_callback connect_cb + cdef grpc_custom_write_callback write_cb + cdef grpc_custom_read_callback read_cb + cdef grpc_custom_accept_callback accept_cb + cdef grpc_custom_close_callback close_cb + + +cdef class ResolveWrapper: + cdef grpc_custom_resolver *c_resolver cdef const char* c_host cdef const char* c_port diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi index 0f693ec691..4b497d861e 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_gevent.pyx.pxi @@ -1,418 +1,418 @@ -# Copyright 2018 gRPC authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# distutils: language=c++ - -from libc cimport string -import errno -gevent_g = None -gevent_socket = None -gevent_hub = None -gevent_event = None -g_event = None -g_pool = None - -def _spawn_greenlet(*args): - greenlet = g_pool.spawn(*args) - -############################### -### socket implementation ### -############################### - -cdef class SocketWrapper: - def __cinit__(self): +# Copyright 2018 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# distutils: language=c++ + +from libc cimport string +import errno +gevent_g = None +gevent_socket = None +gevent_hub = None +gevent_event = None +g_event = None +g_pool = None + +def _spawn_greenlet(*args): + greenlet = g_pool.spawn(*args) + +############################### +### socket implementation ### +############################### + +cdef class SocketWrapper: + def __cinit__(self): fork_handlers_and_grpc_init() - self.sockopts = [] - self.socket = None - self.c_socket = NULL - self.c_buffer = NULL - self.len = 0 - + self.sockopts = [] + self.socket = None + self.c_socket = NULL + self.c_buffer = NULL + self.len = 0 + def __dealloc__(self): grpc_shutdown_blocking() -cdef grpc_error* socket_init(grpc_custom_socket* socket, int domain) with gil: - sw = SocketWrapper() - sw.c_socket = socket - sw.sockopts = [] - cpython.Py_INCREF(sw) - # Python doesn't support AF_UNSPEC sockets, so we defer creation until - # bind/connect when we know what type of socket we need - sw.socket = None - sw.closed = False - sw.accepting_socket = NULL - socket.impl = <void*>sw - return grpc_error_none() - -cdef socket_connect_async_cython(SocketWrapper socket_wrapper, addr_tuple): - try: - socket_wrapper.socket.connect(addr_tuple) - socket_wrapper.connect_cb(<grpc_custom_socket*>socket_wrapper.c_socket, - grpc_error_none()) - except IOError as io_error: - socket_wrapper.connect_cb(<grpc_custom_socket*>socket_wrapper.c_socket, - socket_error("connect", str(io_error))) - g_event.set() - -def socket_connect_async(socket_wrapper, addr_tuple): - socket_connect_async_cython(socket_wrapper, addr_tuple) - -cdef void socket_connect(grpc_custom_socket* socket, const grpc_sockaddr* addr, - size_t addr_len, - grpc_custom_connect_callback cb) with gil: - py_socket = None - socket_wrapper = <SocketWrapper>socket.impl - socket_wrapper.connect_cb = cb - addr_tuple = sockaddr_to_tuple(addr, addr_len) - if sockaddr_is_ipv4(addr, addr_len): - py_socket = gevent_socket.socket(gevent_socket.AF_INET) - else: - py_socket = gevent_socket.socket(gevent_socket.AF_INET6) - applysockopts(py_socket) - socket_wrapper.socket = py_socket - _spawn_greenlet(socket_connect_async, socket_wrapper, addr_tuple) - -cdef void socket_destroy(grpc_custom_socket* socket) with gil: - cpython.Py_DECREF(<SocketWrapper>socket.impl) - -cdef void socket_shutdown(grpc_custom_socket* socket) with gil: - try: - (<SocketWrapper>socket.impl).socket.shutdown(gevent_socket.SHUT_RDWR) - except IOError as io_error: - if io_error.errno != errno.ENOTCONN: - raise io_error - -cdef void socket_close(grpc_custom_socket* socket, - grpc_custom_close_callback cb) with gil: - socket_wrapper = (<SocketWrapper>socket.impl) - if socket_wrapper.socket is not None: - socket_wrapper.socket.close() - socket_wrapper.closed = True - socket_wrapper.close_cb = cb - # Delay the close callback until the accept() call has picked it up - if socket_wrapper.accepting_socket != NULL: - return - socket_wrapper.close_cb(socket) - -def socket_sendmsg(socket, write_bytes): - try: - return socket.sendmsg(write_bytes) - except AttributeError: - # sendmsg not available on all Pythons/Platforms - return socket.send(b''.join(write_bytes)) - -cdef socket_write_async_cython(SocketWrapper socket_wrapper, write_bytes): - try: - while write_bytes: - sent_byte_count = socket_sendmsg(socket_wrapper.socket, write_bytes) - while sent_byte_count > 0: - if sent_byte_count < len(write_bytes[0]): - write_bytes[0] = write_bytes[0][sent_byte_count:] - sent_byte_count = 0 - else: - sent_byte_count -= len(write_bytes[0]) - write_bytes = write_bytes[1:] - socket_wrapper.write_cb(<grpc_custom_socket*>socket_wrapper.c_socket, - grpc_error_none()) - except IOError as io_error: - socket_wrapper.write_cb(<grpc_custom_socket*>socket_wrapper.c_socket, - socket_error("send", str(io_error))) - g_event.set() - -def socket_write_async(socket_wrapper, write_bytes): - socket_write_async_cython(socket_wrapper, write_bytes) - -cdef void socket_write(grpc_custom_socket* socket, grpc_slice_buffer* buffer, - grpc_custom_write_callback cb) with gil: - cdef char* start - sw = <SocketWrapper>socket.impl - sw.write_cb = cb - write_bytes = [] - for i in range(buffer.count): - start = grpc_slice_buffer_start(buffer, i) - length = grpc_slice_buffer_length(buffer, i) - write_bytes.append(<bytes>start[:length]) - _spawn_greenlet(socket_write_async, <SocketWrapper>socket.impl, write_bytes) - -cdef socket_read_async_cython(SocketWrapper socket_wrapper): - cdef char* buff_char_arr - try: - buff_str = socket_wrapper.socket.recv(socket_wrapper.len) - buff_char_arr = buff_str - string.memcpy(<void*>socket_wrapper.c_buffer, buff_char_arr, len(buff_str)) - socket_wrapper.read_cb(<grpc_custom_socket*>socket_wrapper.c_socket, - len(buff_str), grpc_error_none()) - except IOError as io_error: - socket_wrapper.read_cb(<grpc_custom_socket*>socket_wrapper.c_socket, - -1, socket_error("recv", str(io_error))) - g_event.set() - -def socket_read_async(socket_wrapper): - socket_read_async_cython(socket_wrapper) - -cdef void socket_read(grpc_custom_socket* socket, char* buffer, - size_t length, grpc_custom_read_callback cb) with gil: - sw = <SocketWrapper>socket.impl - sw.read_cb = cb - sw.c_buffer = buffer - sw.len = length - _spawn_greenlet(socket_read_async, sw) - -cdef grpc_error* socket_getpeername(grpc_custom_socket* socket, - const grpc_sockaddr* addr, - int* length) with gil: - cdef char* src_buf - peer = (<SocketWrapper>socket.impl).socket.getpeername() - - cdef grpc_resolved_address c_addr - hostname = str_to_bytes(peer[0]) - grpc_string_to_sockaddr(&c_addr, hostname, peer[1]) - string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len) - length[0] = c_addr.len - return grpc_error_none() - -cdef grpc_error* socket_getsockname(grpc_custom_socket* socket, - const grpc_sockaddr* addr, - int* length) with gil: - cdef char* src_buf - cdef grpc_resolved_address c_addr - if (<SocketWrapper>socket.impl).socket is None: - peer = ('0.0.0.0', 0) - else: - peer = (<SocketWrapper>socket.impl).socket.getsockname() - hostname = str_to_bytes(peer[0]) - grpc_string_to_sockaddr(&c_addr, hostname, peer[1]) - string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len) - length[0] = c_addr.len - return grpc_error_none() - -def applysockopts(s): - s.setsockopt(gevent_socket.SOL_SOCKET, gevent_socket.SO_REUSEADDR, 1) - s.setsockopt(gevent_socket.IPPROTO_TCP, gevent_socket.TCP_NODELAY, True) - -cdef grpc_error* socket_bind(grpc_custom_socket* socket, - const grpc_sockaddr* addr, - size_t len, int flags) with gil: - addr_tuple = sockaddr_to_tuple(addr, len) - try: - try: - py_socket = gevent_socket.socket(gevent_socket.AF_INET) - applysockopts(py_socket) - py_socket.bind(addr_tuple) - except gevent_socket.gaierror as e: - py_socket = gevent_socket.socket(gevent_socket.AF_INET6) - applysockopts(py_socket) - py_socket.bind(addr_tuple) - (<SocketWrapper>socket.impl).socket = py_socket - except IOError as io_error: - return socket_error("bind", str(io_error)) - else: - return grpc_error_none() - -cdef grpc_error* socket_listen(grpc_custom_socket* socket) with gil: - (<SocketWrapper>socket.impl).socket.listen(50) - return grpc_error_none() - -cdef void accept_callback_cython(SocketWrapper s) except *: - try: - conn, address = s.socket.accept() - sw = SocketWrapper() - sw.closed = False - sw.c_socket = s.accepting_socket - sw.sockopts = [] - sw.socket = conn - sw.c_socket.impl = <void*>sw - sw.accepting_socket = NULL - cpython.Py_INCREF(sw) - s.accepting_socket = NULL - s.accept_cb(<grpc_custom_socket*>s.c_socket, sw.c_socket, grpc_error_none()) - except IOError as io_error: - #TODO actual error - s.accepting_socket = NULL - s.accept_cb(<grpc_custom_socket*>s.c_socket, s.accepting_socket, - socket_error("accept", str(io_error))) - if s.closed: - s.close_cb(<grpc_custom_socket*>s.c_socket) - g_event.set() - -def socket_accept_async(s): - accept_callback_cython(s) - -cdef void socket_accept(grpc_custom_socket* socket, grpc_custom_socket* client, - grpc_custom_accept_callback cb) with gil: - sw = <SocketWrapper>socket.impl - sw.accepting_socket = client - sw.accept_cb = cb - _spawn_greenlet(socket_accept_async, sw) - -##################################### -######Resolver implementation ####### -##################################### - -cdef class ResolveWrapper: - def __cinit__(self): +cdef grpc_error* socket_init(grpc_custom_socket* socket, int domain) with gil: + sw = SocketWrapper() + sw.c_socket = socket + sw.sockopts = [] + cpython.Py_INCREF(sw) + # Python doesn't support AF_UNSPEC sockets, so we defer creation until + # bind/connect when we know what type of socket we need + sw.socket = None + sw.closed = False + sw.accepting_socket = NULL + socket.impl = <void*>sw + return grpc_error_none() + +cdef socket_connect_async_cython(SocketWrapper socket_wrapper, addr_tuple): + try: + socket_wrapper.socket.connect(addr_tuple) + socket_wrapper.connect_cb(<grpc_custom_socket*>socket_wrapper.c_socket, + grpc_error_none()) + except IOError as io_error: + socket_wrapper.connect_cb(<grpc_custom_socket*>socket_wrapper.c_socket, + socket_error("connect", str(io_error))) + g_event.set() + +def socket_connect_async(socket_wrapper, addr_tuple): + socket_connect_async_cython(socket_wrapper, addr_tuple) + +cdef void socket_connect(grpc_custom_socket* socket, const grpc_sockaddr* addr, + size_t addr_len, + grpc_custom_connect_callback cb) with gil: + py_socket = None + socket_wrapper = <SocketWrapper>socket.impl + socket_wrapper.connect_cb = cb + addr_tuple = sockaddr_to_tuple(addr, addr_len) + if sockaddr_is_ipv4(addr, addr_len): + py_socket = gevent_socket.socket(gevent_socket.AF_INET) + else: + py_socket = gevent_socket.socket(gevent_socket.AF_INET6) + applysockopts(py_socket) + socket_wrapper.socket = py_socket + _spawn_greenlet(socket_connect_async, socket_wrapper, addr_tuple) + +cdef void socket_destroy(grpc_custom_socket* socket) with gil: + cpython.Py_DECREF(<SocketWrapper>socket.impl) + +cdef void socket_shutdown(grpc_custom_socket* socket) with gil: + try: + (<SocketWrapper>socket.impl).socket.shutdown(gevent_socket.SHUT_RDWR) + except IOError as io_error: + if io_error.errno != errno.ENOTCONN: + raise io_error + +cdef void socket_close(grpc_custom_socket* socket, + grpc_custom_close_callback cb) with gil: + socket_wrapper = (<SocketWrapper>socket.impl) + if socket_wrapper.socket is not None: + socket_wrapper.socket.close() + socket_wrapper.closed = True + socket_wrapper.close_cb = cb + # Delay the close callback until the accept() call has picked it up + if socket_wrapper.accepting_socket != NULL: + return + socket_wrapper.close_cb(socket) + +def socket_sendmsg(socket, write_bytes): + try: + return socket.sendmsg(write_bytes) + except AttributeError: + # sendmsg not available on all Pythons/Platforms + return socket.send(b''.join(write_bytes)) + +cdef socket_write_async_cython(SocketWrapper socket_wrapper, write_bytes): + try: + while write_bytes: + sent_byte_count = socket_sendmsg(socket_wrapper.socket, write_bytes) + while sent_byte_count > 0: + if sent_byte_count < len(write_bytes[0]): + write_bytes[0] = write_bytes[0][sent_byte_count:] + sent_byte_count = 0 + else: + sent_byte_count -= len(write_bytes[0]) + write_bytes = write_bytes[1:] + socket_wrapper.write_cb(<grpc_custom_socket*>socket_wrapper.c_socket, + grpc_error_none()) + except IOError as io_error: + socket_wrapper.write_cb(<grpc_custom_socket*>socket_wrapper.c_socket, + socket_error("send", str(io_error))) + g_event.set() + +def socket_write_async(socket_wrapper, write_bytes): + socket_write_async_cython(socket_wrapper, write_bytes) + +cdef void socket_write(grpc_custom_socket* socket, grpc_slice_buffer* buffer, + grpc_custom_write_callback cb) with gil: + cdef char* start + sw = <SocketWrapper>socket.impl + sw.write_cb = cb + write_bytes = [] + for i in range(buffer.count): + start = grpc_slice_buffer_start(buffer, i) + length = grpc_slice_buffer_length(buffer, i) + write_bytes.append(<bytes>start[:length]) + _spawn_greenlet(socket_write_async, <SocketWrapper>socket.impl, write_bytes) + +cdef socket_read_async_cython(SocketWrapper socket_wrapper): + cdef char* buff_char_arr + try: + buff_str = socket_wrapper.socket.recv(socket_wrapper.len) + buff_char_arr = buff_str + string.memcpy(<void*>socket_wrapper.c_buffer, buff_char_arr, len(buff_str)) + socket_wrapper.read_cb(<grpc_custom_socket*>socket_wrapper.c_socket, + len(buff_str), grpc_error_none()) + except IOError as io_error: + socket_wrapper.read_cb(<grpc_custom_socket*>socket_wrapper.c_socket, + -1, socket_error("recv", str(io_error))) + g_event.set() + +def socket_read_async(socket_wrapper): + socket_read_async_cython(socket_wrapper) + +cdef void socket_read(grpc_custom_socket* socket, char* buffer, + size_t length, grpc_custom_read_callback cb) with gil: + sw = <SocketWrapper>socket.impl + sw.read_cb = cb + sw.c_buffer = buffer + sw.len = length + _spawn_greenlet(socket_read_async, sw) + +cdef grpc_error* socket_getpeername(grpc_custom_socket* socket, + const grpc_sockaddr* addr, + int* length) with gil: + cdef char* src_buf + peer = (<SocketWrapper>socket.impl).socket.getpeername() + + cdef grpc_resolved_address c_addr + hostname = str_to_bytes(peer[0]) + grpc_string_to_sockaddr(&c_addr, hostname, peer[1]) + string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len) + length[0] = c_addr.len + return grpc_error_none() + +cdef grpc_error* socket_getsockname(grpc_custom_socket* socket, + const grpc_sockaddr* addr, + int* length) with gil: + cdef char* src_buf + cdef grpc_resolved_address c_addr + if (<SocketWrapper>socket.impl).socket is None: + peer = ('0.0.0.0', 0) + else: + peer = (<SocketWrapper>socket.impl).socket.getsockname() + hostname = str_to_bytes(peer[0]) + grpc_string_to_sockaddr(&c_addr, hostname, peer[1]) + string.memcpy(<void*>addr, <void*>c_addr.addr, c_addr.len) + length[0] = c_addr.len + return grpc_error_none() + +def applysockopts(s): + s.setsockopt(gevent_socket.SOL_SOCKET, gevent_socket.SO_REUSEADDR, 1) + s.setsockopt(gevent_socket.IPPROTO_TCP, gevent_socket.TCP_NODELAY, True) + +cdef grpc_error* socket_bind(grpc_custom_socket* socket, + const grpc_sockaddr* addr, + size_t len, int flags) with gil: + addr_tuple = sockaddr_to_tuple(addr, len) + try: + try: + py_socket = gevent_socket.socket(gevent_socket.AF_INET) + applysockopts(py_socket) + py_socket.bind(addr_tuple) + except gevent_socket.gaierror as e: + py_socket = gevent_socket.socket(gevent_socket.AF_INET6) + applysockopts(py_socket) + py_socket.bind(addr_tuple) + (<SocketWrapper>socket.impl).socket = py_socket + except IOError as io_error: + return socket_error("bind", str(io_error)) + else: + return grpc_error_none() + +cdef grpc_error* socket_listen(grpc_custom_socket* socket) with gil: + (<SocketWrapper>socket.impl).socket.listen(50) + return grpc_error_none() + +cdef void accept_callback_cython(SocketWrapper s) except *: + try: + conn, address = s.socket.accept() + sw = SocketWrapper() + sw.closed = False + sw.c_socket = s.accepting_socket + sw.sockopts = [] + sw.socket = conn + sw.c_socket.impl = <void*>sw + sw.accepting_socket = NULL + cpython.Py_INCREF(sw) + s.accepting_socket = NULL + s.accept_cb(<grpc_custom_socket*>s.c_socket, sw.c_socket, grpc_error_none()) + except IOError as io_error: + #TODO actual error + s.accepting_socket = NULL + s.accept_cb(<grpc_custom_socket*>s.c_socket, s.accepting_socket, + socket_error("accept", str(io_error))) + if s.closed: + s.close_cb(<grpc_custom_socket*>s.c_socket) + g_event.set() + +def socket_accept_async(s): + accept_callback_cython(s) + +cdef void socket_accept(grpc_custom_socket* socket, grpc_custom_socket* client, + grpc_custom_accept_callback cb) with gil: + sw = <SocketWrapper>socket.impl + sw.accepting_socket = client + sw.accept_cb = cb + _spawn_greenlet(socket_accept_async, sw) + +##################################### +######Resolver implementation ####### +##################################### + +cdef class ResolveWrapper: + def __cinit__(self): fork_handlers_and_grpc_init() - self.c_resolver = NULL - self.c_host = NULL - self.c_port = NULL - + self.c_resolver = NULL + self.c_host = NULL + self.c_port = NULL + def __dealloc__(self): grpc_shutdown_blocking() -cdef socket_resolve_async_cython(ResolveWrapper resolve_wrapper): - try: - res = gevent_socket.getaddrinfo(resolve_wrapper.c_host, resolve_wrapper.c_port) - grpc_custom_resolve_callback(<grpc_custom_resolver*>resolve_wrapper.c_resolver, - tuples_to_resolvaddr(res), grpc_error_none()) - except IOError as io_error: - grpc_custom_resolve_callback(<grpc_custom_resolver*>resolve_wrapper.c_resolver, - <grpc_resolved_addresses*>0, - socket_error("getaddrinfo", str(io_error))) - g_event.set() - -def socket_resolve_async_python(resolve_wrapper): - socket_resolve_async_cython(resolve_wrapper) - +cdef socket_resolve_async_cython(ResolveWrapper resolve_wrapper): + try: + res = gevent_socket.getaddrinfo(resolve_wrapper.c_host, resolve_wrapper.c_port) + grpc_custom_resolve_callback(<grpc_custom_resolver*>resolve_wrapper.c_resolver, + tuples_to_resolvaddr(res), grpc_error_none()) + except IOError as io_error: + grpc_custom_resolve_callback(<grpc_custom_resolver*>resolve_wrapper.c_resolver, + <grpc_resolved_addresses*>0, + socket_error("getaddrinfo", str(io_error))) + g_event.set() + +def socket_resolve_async_python(resolve_wrapper): + socket_resolve_async_cython(resolve_wrapper) + cdef void socket_resolve_async(grpc_custom_resolver* r, const char* host, const char* port) with gil: - rw = ResolveWrapper() - rw.c_resolver = r - rw.c_host = host - rw.c_port = port - _spawn_greenlet(socket_resolve_async_python, rw) - + rw = ResolveWrapper() + rw.c_resolver = r + rw.c_host = host + rw.c_port = port + _spawn_greenlet(socket_resolve_async_python, rw) + cdef grpc_error* socket_resolve(const char* host, const char* port, - grpc_resolved_addresses** res) with gil: - try: - result = gevent_socket.getaddrinfo(host, port) - res[0] = tuples_to_resolvaddr(result) - return grpc_error_none() - except IOError as io_error: - return socket_error("getaddrinfo", str(io_error)) - -############################### -### timer implementation ###### -############################### - -cdef class TimerWrapper: - def __cinit__(self, deadline): + grpc_resolved_addresses** res) with gil: + try: + result = gevent_socket.getaddrinfo(host, port) + res[0] = tuples_to_resolvaddr(result) + return grpc_error_none() + except IOError as io_error: + return socket_error("getaddrinfo", str(io_error)) + +############################### +### timer implementation ###### +############################### + +cdef class TimerWrapper: + def __cinit__(self, deadline): fork_handlers_and_grpc_init() - self.timer = gevent_hub.get_hub().loop.timer(deadline) - self.event = None - - def start(self): - self.event = gevent_event.Event() - self.timer.start(self.on_finish) - - def on_finish(self): - grpc_custom_timer_callback(self.c_timer, grpc_error_none()) - self.timer.stop() - g_event.set() - - def stop(self): - self.event.set() - self.timer.stop() - + self.timer = gevent_hub.get_hub().loop.timer(deadline) + self.event = None + + def start(self): + self.event = gevent_event.Event() + self.timer.start(self.on_finish) + + def on_finish(self): + grpc_custom_timer_callback(self.c_timer, grpc_error_none()) + self.timer.stop() + g_event.set() + + def stop(self): + self.event.set() + self.timer.stop() + def __dealloc__(self): grpc_shutdown_blocking() -cdef void timer_start(grpc_custom_timer* t) with gil: - timer = TimerWrapper(t.timeout_ms / 1000.0) - timer.c_timer = t - t.timer = <void*>timer - timer.start() - -cdef void timer_stop(grpc_custom_timer* t) with gil: - time_wrapper = <object>t.timer - time_wrapper.stop() - -############################### -### pollset implementation ### -############################### - -cdef void init_loop() with gil: - pass - -cdef void destroy_loop() with gil: - g_pool.join() - -cdef void kick_loop() with gil: - g_event.set() - -cdef void run_loop(size_t timeout_ms) with gil: - timeout = timeout_ms / 1000.0 - if timeout_ms > 0: - g_event.wait(timeout) - g_event.clear() - -############################### -### Initializer ############### -############################### - -cdef grpc_socket_vtable gevent_socket_vtable -cdef grpc_custom_resolver_vtable gevent_resolver_vtable -cdef grpc_custom_timer_vtable gevent_timer_vtable -cdef grpc_custom_poller_vtable gevent_pollset_vtable - -def init_grpc_gevent(): - # Lazily import gevent - global gevent_socket - global gevent_g - global gevent_hub - global gevent_event - global g_event - global g_pool - import gevent - gevent_g = gevent - import gevent.socket - gevent_socket = gevent.socket - import gevent.hub - gevent_hub = gevent.hub - import gevent.event - gevent_event = gevent.event - import gevent.pool - - g_event = gevent.event.Event() - g_pool = gevent.pool.Group() - - def cb_func(cb, args): - _spawn_greenlet(cb, *args) - set_async_callback_func(cb_func) - - gevent_resolver_vtable.resolve = socket_resolve - gevent_resolver_vtable.resolve_async = socket_resolve_async - - gevent_socket_vtable.init = socket_init - gevent_socket_vtable.connect = socket_connect - gevent_socket_vtable.destroy = socket_destroy - gevent_socket_vtable.shutdown = socket_shutdown - gevent_socket_vtable.close = socket_close - gevent_socket_vtable.write = socket_write - gevent_socket_vtable.read = socket_read - gevent_socket_vtable.getpeername = socket_getpeername - gevent_socket_vtable.getsockname = socket_getsockname - gevent_socket_vtable.bind = socket_bind - gevent_socket_vtable.listen = socket_listen - gevent_socket_vtable.accept = socket_accept - - gevent_timer_vtable.start = timer_start - gevent_timer_vtable.stop = timer_stop - - gevent_pollset_vtable.init = init_loop - gevent_pollset_vtable.poll = run_loop - gevent_pollset_vtable.kick = kick_loop - gevent_pollset_vtable.shutdown = destroy_loop - - grpc_custom_iomgr_init(&gevent_socket_vtable, - &gevent_resolver_vtable, - &gevent_timer_vtable, - &gevent_pollset_vtable) +cdef void timer_start(grpc_custom_timer* t) with gil: + timer = TimerWrapper(t.timeout_ms / 1000.0) + timer.c_timer = t + t.timer = <void*>timer + timer.start() + +cdef void timer_stop(grpc_custom_timer* t) with gil: + time_wrapper = <object>t.timer + time_wrapper.stop() + +############################### +### pollset implementation ### +############################### + +cdef void init_loop() with gil: + pass + +cdef void destroy_loop() with gil: + g_pool.join() + +cdef void kick_loop() with gil: + g_event.set() + +cdef void run_loop(size_t timeout_ms) with gil: + timeout = timeout_ms / 1000.0 + if timeout_ms > 0: + g_event.wait(timeout) + g_event.clear() + +############################### +### Initializer ############### +############################### + +cdef grpc_socket_vtable gevent_socket_vtable +cdef grpc_custom_resolver_vtable gevent_resolver_vtable +cdef grpc_custom_timer_vtable gevent_timer_vtable +cdef grpc_custom_poller_vtable gevent_pollset_vtable + +def init_grpc_gevent(): + # Lazily import gevent + global gevent_socket + global gevent_g + global gevent_hub + global gevent_event + global g_event + global g_pool + import gevent + gevent_g = gevent + import gevent.socket + gevent_socket = gevent.socket + import gevent.hub + gevent_hub = gevent.hub + import gevent.event + gevent_event = gevent.event + import gevent.pool + + g_event = gevent.event.Event() + g_pool = gevent.pool.Group() + + def cb_func(cb, args): + _spawn_greenlet(cb, *args) + set_async_callback_func(cb_func) + + gevent_resolver_vtable.resolve = socket_resolve + gevent_resolver_vtable.resolve_async = socket_resolve_async + + gevent_socket_vtable.init = socket_init + gevent_socket_vtable.connect = socket_connect + gevent_socket_vtable.destroy = socket_destroy + gevent_socket_vtable.shutdown = socket_shutdown + gevent_socket_vtable.close = socket_close + gevent_socket_vtable.write = socket_write + gevent_socket_vtable.read = socket_read + gevent_socket_vtable.getpeername = socket_getpeername + gevent_socket_vtable.getsockname = socket_getsockname + gevent_socket_vtable.bind = socket_bind + gevent_socket_vtable.listen = socket_listen + gevent_socket_vtable.accept = socket_accept + + gevent_timer_vtable.start = timer_start + gevent_timer_vtable.stop = timer_stop + + gevent_pollset_vtable.init = init_loop + gevent_pollset_vtable.poll = run_loop + gevent_pollset_vtable.kick = kick_loop + gevent_pollset_vtable.shutdown = destroy_loop + + grpc_custom_iomgr_init(&gevent_socket_vtable, + &gevent_resolver_vtable, + &gevent_timer_vtable, + &gevent_pollset_vtable) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi index 5c1e0679a9..d7fd61ecd2 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/grpc_string.pyx.pxi @@ -47,5 +47,5 @@ cdef str _decode(bytes bytestring): try: return bytestring.decode('utf8') except UnicodeDecodeError: - _LOGGER.exception('Invalid encoding on %s', bytestring) + _LOGGER.exception('Invalid encoding on %s', bytestring) return bytestring.decode('latin1') diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi index fc72ac1576..2b915b00fd 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pxd.pxi @@ -14,10 +14,10 @@ cdef void _store_c_metadata( - metadata, grpc_metadata **c_metadata, size_t *c_count) except * + metadata, grpc_metadata **c_metadata, size_t *c_count) except * -cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except * +cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except * cdef tuple _metadatum(grpc_slice key_slice, grpc_slice value_slice) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi index b2dd1e3380..04aa9cccb3 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/metadata.pyx.pxi @@ -15,17 +15,17 @@ import collections -class InitialMetadataFlags: - used_mask = GRPC_INITIAL_METADATA_USED_MASK - wait_for_ready = GRPC_INITIAL_METADATA_WAIT_FOR_READY - wait_for_ready_explicitly_set = GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET - - +class InitialMetadataFlags: + used_mask = GRPC_INITIAL_METADATA_USED_MASK + wait_for_ready = GRPC_INITIAL_METADATA_WAIT_FOR_READY + wait_for_ready_explicitly_set = GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET + + _Metadatum = collections.namedtuple('_Metadatum', ('key', 'value',)) cdef void _store_c_metadata( - metadata, grpc_metadata **c_metadata, size_t *c_count) except *: + metadata, grpc_metadata **c_metadata, size_t *c_count) except *: if metadata is None: c_count[0] = 0 c_metadata[0] = NULL @@ -50,7 +50,7 @@ cdef void _store_c_metadata( c_metadata[0][index].value = _slice_from_bytes(encoded_value) -cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except *: +cdef void _release_c_metadata(grpc_metadata *c_metadata, int count) except *: if 0 < count: for index in range(count): grpc_slice_unref(c_metadata[index].key) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi index c9df32dadf..7b0843f173 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pxd.pxi @@ -15,8 +15,8 @@ cdef class Operation: - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * # TODO(https://github.com/grpc/grpc/issues/7950): Eliminate this! cdef grpc_op c_op @@ -29,8 +29,8 @@ cdef class SendInitialMetadataOperation(Operation): cdef grpc_metadata *_c_initial_metadata cdef size_t _c_initial_metadata_count - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class SendMessageOperation(Operation): @@ -39,16 +39,16 @@ cdef class SendMessageOperation(Operation): cdef readonly int _flags cdef grpc_byte_buffer *_c_message_byte_buffer - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class SendCloseFromClientOperation(Operation): cdef readonly int _flags - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class SendStatusFromServerOperation(Operation): @@ -61,8 +61,8 @@ cdef class SendStatusFromServerOperation(Operation): cdef size_t _c_trailing_metadata_count cdef grpc_slice _c_details - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class ReceiveInitialMetadataOperation(Operation): @@ -71,8 +71,8 @@ cdef class ReceiveInitialMetadataOperation(Operation): cdef tuple _initial_metadata cdef grpc_metadata_array _c_initial_metadata - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class ReceiveMessageOperation(Operation): @@ -81,8 +81,8 @@ cdef class ReceiveMessageOperation(Operation): cdef grpc_byte_buffer *_c_message_byte_buffer cdef bytes _message - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class ReceiveStatusOnClientOperation(Operation): @@ -91,14 +91,14 @@ cdef class ReceiveStatusOnClientOperation(Operation): cdef grpc_metadata_array _c_trailing_metadata cdef grpc_status_code _c_code cdef grpc_slice _c_details - cdef const char* _c_error_string + cdef const char* _c_error_string cdef tuple _trailing_metadata cdef object _code cdef str _details - cdef str _error_string + cdef str _error_string - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * cdef class ReceiveCloseOnServerOperation(Operation): @@ -107,5 +107,5 @@ cdef class ReceiveCloseOnServerOperation(Operation): cdef object _cancelled cdef int _c_cancelled - cdef void c(self) except * - cdef void un_c(self) except * + cdef void c(self) except * + cdef void un_c(self) except * diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi index 3f3fd75407..d5e6ad7c81 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/operation.pyx.pxi @@ -15,10 +15,10 @@ cdef class Operation: - cdef void c(self) except *: + cdef void c(self) except *: raise NotImplementedError() - cdef void un_c(self) except *: + cdef void un_c(self) except *: raise NotImplementedError() @@ -31,7 +31,7 @@ cdef class SendInitialMetadataOperation(Operation): def type(self): return GRPC_OP_SEND_INITIAL_METADATA - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_SEND_INITIAL_METADATA self.c_op.flags = self._flags _store_c_metadata( @@ -41,7 +41,7 @@ cdef class SendInitialMetadataOperation(Operation): self.c_op.data.send_initial_metadata.count = self._c_initial_metadata_count self.c_op.data.send_initial_metadata.maybe_compression_level.is_set = 0 - cdef void un_c(self) except *: + cdef void un_c(self) except *: _release_c_metadata( self._c_initial_metadata, self._c_initial_metadata_count) @@ -58,7 +58,7 @@ cdef class SendMessageOperation(Operation): def type(self): return GRPC_OP_SEND_MESSAGE - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_SEND_MESSAGE self.c_op.flags = self._flags cdef grpc_slice message_slice = grpc_slice_from_copied_buffer( @@ -68,7 +68,7 @@ cdef class SendMessageOperation(Operation): grpc_slice_unref(message_slice) self.c_op.data.send_message.send_message = self._c_message_byte_buffer - cdef void un_c(self) except *: + cdef void un_c(self) except *: grpc_byte_buffer_destroy(self._c_message_byte_buffer) @@ -80,11 +80,11 @@ cdef class SendCloseFromClientOperation(Operation): def type(self): return GRPC_OP_SEND_CLOSE_FROM_CLIENT - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_SEND_CLOSE_FROM_CLIENT self.c_op.flags = self._flags - cdef void un_c(self) except *: + cdef void un_c(self) except *: pass @@ -99,7 +99,7 @@ cdef class SendStatusFromServerOperation(Operation): def type(self): return GRPC_OP_SEND_STATUS_FROM_SERVER - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_SEND_STATUS_FROM_SERVER self.c_op.flags = self._flags _store_c_metadata( @@ -113,7 +113,7 @@ cdef class SendStatusFromServerOperation(Operation): self._c_details = _slice_from_bytes(_encode(self._details)) self.c_op.data.send_status_from_server.status_details = &self._c_details - cdef void un_c(self) except *: + cdef void un_c(self) except *: grpc_slice_unref(self._c_details) _release_c_metadata( self._c_trailing_metadata, self._c_trailing_metadata_count) @@ -127,14 +127,14 @@ cdef class ReceiveInitialMetadataOperation(Operation): def type(self): return GRPC_OP_RECV_INITIAL_METADATA - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_RECV_INITIAL_METADATA self.c_op.flags = self._flags grpc_metadata_array_init(&self._c_initial_metadata) self.c_op.data.receive_initial_metadata.receive_initial_metadata = ( &self._c_initial_metadata) - cdef void un_c(self) except *: + cdef void un_c(self) except *: self._initial_metadata = _metadata(&self._c_initial_metadata) grpc_metadata_array_destroy(&self._c_initial_metadata) @@ -150,13 +150,13 @@ cdef class ReceiveMessageOperation(Operation): def type(self): return GRPC_OP_RECV_MESSAGE - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_RECV_MESSAGE self.c_op.flags = self._flags self.c_op.data.receive_message.receive_message = ( &self._c_message_byte_buffer) - cdef void un_c(self) except *: + cdef void un_c(self) except *: cdef grpc_byte_buffer_reader message_reader cdef bint message_reader_status cdef grpc_slice message_slice @@ -192,7 +192,7 @@ cdef class ReceiveStatusOnClientOperation(Operation): def type(self): return GRPC_OP_RECV_STATUS_ON_CLIENT - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_RECV_STATUS_ON_CLIENT self.c_op.flags = self._flags grpc_metadata_array_init(&self._c_trailing_metadata) @@ -202,20 +202,20 @@ cdef class ReceiveStatusOnClientOperation(Operation): &self._c_code) self.c_op.data.receive_status_on_client.status_details = ( &self._c_details) - self.c_op.data.receive_status_on_client.error_string = ( - &self._c_error_string) + self.c_op.data.receive_status_on_client.error_string = ( + &self._c_error_string) - cdef void un_c(self) except *: + cdef void un_c(self) except *: self._trailing_metadata = _metadata(&self._c_trailing_metadata) grpc_metadata_array_destroy(&self._c_trailing_metadata) self._code = self._c_code self._details = _decode(_slice_bytes(self._c_details)) grpc_slice_unref(self._c_details) - if self._c_error_string != NULL: - self._error_string = _decode(self._c_error_string) - gpr_free(<void*>self._c_error_string) - else: - self._error_string = "" + if self._c_error_string != NULL: + self._error_string = _decode(self._c_error_string) + gpr_free(<void*>self._c_error_string) + else: + self._error_string = "" def trailing_metadata(self): return self._trailing_metadata @@ -226,10 +226,10 @@ cdef class ReceiveStatusOnClientOperation(Operation): def details(self): return self._details - def error_string(self): - return self._error_string - + def error_string(self): + return self._error_string + cdef class ReceiveCloseOnServerOperation(Operation): def __cinit__(self, flags): @@ -238,12 +238,12 @@ cdef class ReceiveCloseOnServerOperation(Operation): def type(self): return GRPC_OP_RECV_CLOSE_ON_SERVER - cdef void c(self) except *: + cdef void c(self) except *: self.c_op.type = GRPC_OP_RECV_CLOSE_ON_SERVER self.c_op.flags = self._flags self.c_op.data.receive_close_on_server.cancelled = &self._c_cancelled - cdef void un_c(self) except *: + cdef void un_c(self) except *: self._cancelled = bool(self._c_cancelled) def cancelled(self): diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pxd.pxi index cd6e94c816..afa97eed23 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pxd.pxi @@ -1,20 +1,20 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -cdef extern from "grpc/impl/codegen/propagation_bits.h": - cdef int _GRPC_PROPAGATE_DEADLINE "GRPC_PROPAGATE_DEADLINE" - cdef int _GRPC_PROPAGATE_CENSUS_STATS_CONTEXT "GRPC_PROPAGATE_CENSUS_STATS_CONTEXT" - cdef int _GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT "GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT" - cdef int _GRPC_PROPAGATE_CANCELLATION "GRPC_PROPAGATE_CANCELLATION" - cdef int _GRPC_PROPAGATE_DEFAULTS "GRPC_PROPAGATE_DEFAULTS" +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +cdef extern from "grpc/impl/codegen/propagation_bits.h": + cdef int _GRPC_PROPAGATE_DEADLINE "GRPC_PROPAGATE_DEADLINE" + cdef int _GRPC_PROPAGATE_CENSUS_STATS_CONTEXT "GRPC_PROPAGATE_CENSUS_STATS_CONTEXT" + cdef int _GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT "GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT" + cdef int _GRPC_PROPAGATE_CANCELLATION "GRPC_PROPAGATE_CANCELLATION" + cdef int _GRPC_PROPAGATE_DEFAULTS "GRPC_PROPAGATE_DEFAULTS" diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pyx.pxi index 2dcc76a2db..85e5183ab6 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/propagation_bits.pyx.pxi @@ -1,20 +1,20 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -class PropagationConstants: - GRPC_PROPAGATE_DEADLINE = _GRPC_PROPAGATE_DEADLINE - GRPC_PROPAGATE_CENSUS_STATS_CONTEXT = _GRPC_PROPAGATE_CENSUS_STATS_CONTEXT - GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT = _GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT - GRPC_PROPAGATE_CANCELLATION = _GRPC_PROPAGATE_CANCELLATION - GRPC_PROPAGATE_DEFAULTS = _GRPC_PROPAGATE_DEFAULTS +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +class PropagationConstants: + GRPC_PROPAGATE_DEADLINE = _GRPC_PROPAGATE_DEADLINE + GRPC_PROPAGATE_CENSUS_STATS_CONTEXT = _GRPC_PROPAGATE_CENSUS_STATS_CONTEXT + GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT = _GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT + GRPC_PROPAGATE_CANCELLATION = _GRPC_PROPAGATE_CANCELLATION + GRPC_PROPAGATE_DEFAULTS = _GRPC_PROPAGATE_DEFAULTS diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi index 308d677695..17d5e5429b 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/records.pyx.pxi @@ -49,7 +49,7 @@ class ChannelArgKey: default_authority = GRPC_ARG_DEFAULT_AUTHORITY primary_user_agent_string = GRPC_ARG_PRIMARY_USER_AGENT_STRING secondary_user_agent_string = GRPC_ARG_SECONDARY_USER_AGENT_STRING - ssl_session_cache = GRPC_SSL_SESSION_CACHE_ARG + ssl_session_cache = GRPC_SSL_SESSION_CACHE_ARG ssl_target_name_override = GRPC_SSL_TARGET_NAME_OVERRIDE_ARG @@ -130,7 +130,7 @@ class CompressionLevel: cdef class CallDetails: def __cinit__(self): - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() with nogil: grpc_call_details_init(&self.c_details) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi index b89ed99d97..078d6e2f40 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pxd.pxi @@ -21,7 +21,7 @@ cdef class Server: cdef bint is_shutdown # notification of complete shutdown received # used at dealloc when user forgets to shutdown cdef CompletionQueue backup_shutdown_queue - # TODO(https://github.com/grpc/grpc/issues/15662): Elide this. + # TODO(https://github.com/grpc/grpc/issues/15662): Elide this. cdef list references cdef list registered_completion_queues diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi index eff95c4f29..4779464e3b 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/server.pyx.pxi @@ -16,7 +16,7 @@ cdef class Server: def __cinit__(self, object arguments): - fork_handlers_and_grpc_init() + fork_handlers_and_grpc_init() self.references = [] self.registered_completion_queues = [] self.is_started = False @@ -125,10 +125,10 @@ cdef class Server: with nogil: grpc_server_cancel_all_calls(self.c_server) - # TODO(https://github.com/grpc/grpc/issues/17515) Determine what, if any, - # portion of this is safe to call from __dealloc__, and potentially remove - # backup_shutdown_queue. - def destroy(self): + # TODO(https://github.com/grpc/grpc/issues/17515) Determine what, if any, + # portion of this is safe to call from __dealloc__, and potentially remove + # backup_shutdown_queue. + def destroy(self): if self.c_server != NULL: if not self.is_started: pass @@ -151,7 +151,7 @@ cdef class Server: with nogil: grpc_server_destroy(self.c_server) self.c_server = NULL - - def __dealloc__(self): - if self.c_server == NULL: + + def __dealloc__(self): + if self.c_server == NULL: grpc_shutdown_blocking() diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi index d8ba1ea9bd..9a5d3a9a8e 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pxd.pxi @@ -32,7 +32,7 @@ cdef class _RequestCallTag(_Tag): cdef CallDetails call_details cdef grpc_metadata_array c_invocation_metadata - cdef void prepare(self) except * + cdef void prepare(self) except * cdef RequestCallEvent event(self, grpc_event c_event) @@ -44,7 +44,7 @@ cdef class _BatchOperationTag(_Tag): cdef grpc_op *c_ops cdef size_t c_nops - cdef void prepare(self) except * + cdef void prepare(self) except * cdef BatchOperationEvent event(self, grpc_event c_event) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi index e80dc88767..366a2bbd2a 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/tag.pyx.pxi @@ -35,7 +35,7 @@ cdef class _RequestCallTag(_Tag): self.call = None self.call_details = None - cdef void prepare(self) except *: + cdef void prepare(self) except *: self.call = Call() self.call_details = CallDetails() grpc_metadata_array_init(&self.c_invocation_metadata) @@ -55,7 +55,7 @@ cdef class _BatchOperationTag: self._operations = operations self._retained_call = call - cdef void prepare(self) except *: + cdef void prepare(self) except *: cdef Operation operation self.c_nops = 0 if self._operations is None else len(self._operations) if 0 < self.c_nops: diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi index c46e8a98b0..2156cfa93d 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pxd.pxi @@ -16,4 +16,4 @@ cdef gpr_timespec _timespec_from_time(object time) except * -cdef double _time_from_timespec(gpr_timespec timespec) except * +cdef double _time_from_timespec(gpr_timespec timespec) except * diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi index 6d181bb1d6..7a5ef2ebab 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/_cygrpc/time.pyx.pxi @@ -23,7 +23,7 @@ cdef gpr_timespec _timespec_from_time(object time) except *: ) -cdef double _time_from_timespec(gpr_timespec timespec) except *: +cdef double _time_from_timespec(gpr_timespec timespec) except *: cdef gpr_timespec real_timespec = gpr_convert_clock_type( timespec, GPR_CLOCK_REALTIME) return gpr_timespec_to_micros(real_timespec) / GPR_US_PER_SEC diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd index 166be37022..4663ee9eb6 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pxd @@ -32,14 +32,14 @@ include "_cygrpc/server.pxd.pxi" include "_cygrpc/tag.pxd.pxi" include "_cygrpc/time.pxd.pxi" include "_cygrpc/vtable.pxd.pxi" -include "_cygrpc/_hooks.pxd.pxi" +include "_cygrpc/_hooks.pxd.pxi" include "_cygrpc/iomgr.pxd.pxi" -include "_cygrpc/grpc_gevent.pxd.pxi" - -IF UNAME_SYSNAME != "Windows": - include "_cygrpc/fork_posix.pxd.pxi" +include "_cygrpc/grpc_gevent.pxd.pxi" + +IF UNAME_SYSNAME != "Windows": + include "_cygrpc/fork_posix.pxd.pxi" # Following pxi files are part of the Aio module include "_cygrpc/aio/iomgr/socket.pxd.pxi" diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx index 8d355c6fbb..e9fbfd1f0d 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_cython/cygrpc.pyx @@ -53,19 +53,19 @@ include "_cygrpc/server.pyx.pxi" include "_cygrpc/tag.pyx.pxi" include "_cygrpc/time.pyx.pxi" include "_cygrpc/vtable.pyx.pxi" -include "_cygrpc/_hooks.pyx.pxi" +include "_cygrpc/_hooks.pyx.pxi" include "_cygrpc/iomgr.pyx.pxi" -include "_cygrpc/grpc_gevent.pyx.pxi" +include "_cygrpc/grpc_gevent.pyx.pxi" include "_cygrpc/thread.pyx.pxi" -IF UNAME_SYSNAME == "Windows": - include "_cygrpc/fork_windows.pyx.pxi" -ELSE: - include "_cygrpc/fork_posix.pyx.pxi" - +IF UNAME_SYSNAME == "Windows": + include "_cygrpc/fork_windows.pyx.pxi" +ELSE: + include "_cygrpc/fork_posix.pyx.pxi" + # Following pxi files are part of the Aio module include "_cygrpc/aio/iomgr/iomgr.pyx.pxi" include "_cygrpc/aio/iomgr/socket.pyx.pxi" diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py b/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py index ee63cb3145..a3d3ca8555 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_interceptor.py @@ -72,10 +72,10 @@ def _unwrap_client_call_details(call_details, default_details): except AttributeError: credentials = default_details.credentials - try: - wait_for_ready = call_details.wait_for_ready - except AttributeError: - wait_for_ready = default_details.wait_for_ready + try: + wait_for_ready = call_details.wait_for_ready + except AttributeError: + wait_for_ready = default_details.wait_for_ready try: compression = call_details.compression @@ -84,11 +84,11 @@ def _unwrap_client_call_details(call_details, default_details): return method, timeout, metadata, credentials, wait_for_ready, compression - + class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable=too-many-ancestors def __init__(self, exception, traceback): - super(_FailureOutcome, self).__init__() + super(_FailureOutcome, self).__init__() self._exception = exception self._traceback = traceback @@ -110,12 +110,12 @@ class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable def cancelled(self): return False - def is_active(self): - return False - - def time_remaining(self): - return None - + def is_active(self): + return False + + def time_remaining(self): + return None + def running(self): return False @@ -132,73 +132,73 @@ class _FailureOutcome(grpc.RpcError, grpc.Future, grpc.Call): # pylint: disable return self._traceback def add_callback(self, unused_callback): - return False - + return False + def add_done_callback(self, fn): fn(self) def __iter__(self): return self - def __next__(self): + def __next__(self): raise self._exception - def next(self): - return self.__next__() - - -class _UnaryOutcome(grpc.Call, grpc.Future): - - def __init__(self, response, call): - self._response = response - self._call = call - - def initial_metadata(self): - return self._call.initial_metadata() - - def trailing_metadata(self): - return self._call.trailing_metadata() - - def code(self): - return self._call.code() - - def details(self): - return self._call.details() - - def is_active(self): - return self._call.is_active() - - def time_remaining(self): - return self._call.time_remaining() - - def cancel(self): - return self._call.cancel() - - def add_callback(self, callback): - return self._call.add_callback(callback) - - def cancelled(self): - return False - - def running(self): - return False - - def done(self): - return True - - def result(self, ignored_timeout=None): - return self._response - - def exception(self, ignored_timeout=None): - return None - - def traceback(self, ignored_timeout=None): - return None - - def add_done_callback(self, fn): - fn(self) - - + def next(self): + return self.__next__() + + +class _UnaryOutcome(grpc.Call, grpc.Future): + + def __init__(self, response, call): + self._response = response + self._call = call + + def initial_metadata(self): + return self._call.initial_metadata() + + def trailing_metadata(self): + return self._call.trailing_metadata() + + def code(self): + return self._call.code() + + def details(self): + return self._call.details() + + def is_active(self): + return self._call.is_active() + + def time_remaining(self): + return self._call.time_remaining() + + def cancel(self): + return self._call.cancel() + + def add_callback(self, callback): + return self._call.add_callback(callback) + + def cancelled(self): + return False + + def running(self): + return False + + def done(self): + return True + + def result(self, ignored_timeout=None): + return self._response + + def exception(self, ignored_timeout=None): + return None + + def traceback(self, ignored_timeout=None): + return None + + def add_done_callback(self, fn): + fn(self) + + class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): def __init__(self, thunk, method, interceptor): @@ -206,11 +206,11 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): self._method = method self._interceptor = interceptor - def __call__(self, - request, - timeout=None, - metadata=None, - credentials=None, + def __call__(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): response, ignored_call = self._with_call(request, @@ -219,48 +219,48 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): credentials=credentials, wait_for_ready=wait_for_ready, compression=compression) - return response + return response - def _with_call(self, - request, - timeout=None, - metadata=None, - credentials=None, + def _with_call(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): client_call_details = _ClientCallDetails(self._method, timeout, metadata, credentials, wait_for_ready, compression) - - def continuation(new_details, request): + + def continuation(new_details, request): (new_method, new_timeout, new_metadata, new_credentials, new_wait_for_ready, new_compression) = (_unwrap_client_call_details( new_details, client_call_details)) - try: - response, call = self._thunk(new_method).with_call( - request, - timeout=new_timeout, - metadata=new_metadata, - credentials=new_credentials, + try: + response, call = self._thunk(new_method).with_call( + request, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, wait_for_ready=new_wait_for_ready, compression=new_compression) - return _UnaryOutcome(response, call) - except grpc.RpcError as rpc_error: - return rpc_error - except Exception as exception: # pylint:disable=broad-except - return _FailureOutcome(exception, sys.exc_info()[2]) - + return _UnaryOutcome(response, call) + except grpc.RpcError as rpc_error: + return rpc_error + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + call = self._interceptor.intercept_unary_unary(continuation, client_call_details, request) - return call.result(), call - - def with_call(self, - request, - timeout=None, - metadata=None, - credentials=None, + return call.result(), call + + def with_call(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): return self._with_call(request, @@ -270,11 +270,11 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): wait_for_ready=wait_for_ready, compression=compression) - def future(self, - request, - timeout=None, - metadata=None, - credentials=None, + def future(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): client_call_details = _ClientCallDetails(self._method, timeout, @@ -290,7 +290,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): request, timeout=new_timeout, metadata=new_metadata, - credentials=new_credentials, + credentials=new_credentials, wait_for_ready=new_wait_for_ready, compression=new_compression) @@ -298,7 +298,7 @@ class _UnaryUnaryMultiCallable(grpc.UnaryUnaryMultiCallable): return self._interceptor.intercept_unary_unary( continuation, client_call_details, request) except Exception as exception: # pylint:disable=broad-except - return _FailureOutcome(exception, sys.exc_info()[2]) + return _FailureOutcome(exception, sys.exc_info()[2]) class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): @@ -308,11 +308,11 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): self._method = method self._interceptor = interceptor - def __call__(self, - request, - timeout=None, - metadata=None, - credentials=None, + def __call__(self, + request, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): client_call_details = _ClientCallDetails(self._method, timeout, @@ -335,7 +335,7 @@ class _UnaryStreamMultiCallable(grpc.UnaryStreamMultiCallable): return self._interceptor.intercept_unary_stream( continuation, client_call_details, request) except Exception as exception: # pylint:disable=broad-except - return _FailureOutcome(exception, sys.exc_info()[2]) + return _FailureOutcome(exception, sys.exc_info()[2]) class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): @@ -349,7 +349,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): response, ignored_call = self._with_call(request_iterator, @@ -358,48 +358,48 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): credentials=credentials, wait_for_ready=wait_for_ready, compression=compression) - return response + return response - def _with_call(self, - request_iterator, - timeout=None, - metadata=None, - credentials=None, + def _with_call(self, + request_iterator, + timeout=None, + metadata=None, + credentials=None, wait_for_ready=None, compression=None): client_call_details = _ClientCallDetails(self._method, timeout, metadata, credentials, wait_for_ready, compression) - - def continuation(new_details, request_iterator): + + def continuation(new_details, request_iterator): (new_method, new_timeout, new_metadata, new_credentials, new_wait_for_ready, new_compression) = (_unwrap_client_call_details( new_details, client_call_details)) - try: - response, call = self._thunk(new_method).with_call( - request_iterator, - timeout=new_timeout, - metadata=new_metadata, - credentials=new_credentials, + try: + response, call = self._thunk(new_method).with_call( + request_iterator, + timeout=new_timeout, + metadata=new_metadata, + credentials=new_credentials, wait_for_ready=new_wait_for_ready, compression=new_compression) - return _UnaryOutcome(response, call) - except grpc.RpcError as rpc_error: - return rpc_error - except Exception as exception: # pylint:disable=broad-except - return _FailureOutcome(exception, sys.exc_info()[2]) - + return _UnaryOutcome(response, call) + except grpc.RpcError as rpc_error: + return rpc_error + except Exception as exception: # pylint:disable=broad-except + return _FailureOutcome(exception, sys.exc_info()[2]) + call = self._interceptor.intercept_stream_unary(continuation, client_call_details, request_iterator) - return call.result(), call - + return call.result(), call + def with_call(self, request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): return self._with_call(request_iterator, @@ -413,7 +413,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): client_call_details = _ClientCallDetails(self._method, timeout, @@ -429,7 +429,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): request_iterator, timeout=new_timeout, metadata=new_metadata, - credentials=new_credentials, + credentials=new_credentials, wait_for_ready=new_wait_for_ready, compression=new_compression) @@ -437,7 +437,7 @@ class _StreamUnaryMultiCallable(grpc.StreamUnaryMultiCallable): return self._interceptor.intercept_stream_unary( continuation, client_call_details, request_iterator) except Exception as exception: # pylint:disable=broad-except - return _FailureOutcome(exception, sys.exc_info()[2]) + return _FailureOutcome(exception, sys.exc_info()[2]) class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): @@ -451,7 +451,7 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): request_iterator, timeout=None, metadata=None, - credentials=None, + credentials=None, wait_for_ready=None, compression=None): client_call_details = _ClientCallDetails(self._method, timeout, @@ -474,7 +474,7 @@ class _StreamStreamMultiCallable(grpc.StreamStreamMultiCallable): return self._interceptor.intercept_stream_stream( continuation, client_call_details, request_iterator) except Exception as exception: # pylint:disable=broad-except - return _FailureOutcome(exception, sys.exc_info()[2]) + return _FailureOutcome(exception, sys.exc_info()[2]) class _Channel(grpc.Channel): @@ -483,11 +483,11 @@ class _Channel(grpc.Channel): self._channel = channel self._interceptor = interceptor - def subscribe(self, callback, try_to_connect=False): - self._channel.subscribe(callback, try_to_connect=try_to_connect) + def subscribe(self, callback, try_to_connect=False): + self._channel.subscribe(callback, try_to_connect=try_to_connect) - def unsubscribe(self, callback): - self._channel.unsubscribe(callback) + def unsubscribe(self, callback): + self._channel.unsubscribe(callback) def unary_unary(self, method, diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py b/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py index e3bfa90916..8b4aeb3d38 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_plugin_wrapping.py @@ -20,9 +20,9 @@ import grpc from grpc import _common from grpc._cython import cygrpc -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + class _AuthMetadataContext( collections.namedtuple('AuthMetadataContext', ( 'service_url', @@ -77,7 +77,7 @@ class _Plugin(object): self._metadata_plugin( context, _AuthMetadataPluginCallback(callback_state, callback)) except Exception as exception: # pylint: disable=broad-except - _LOGGER.exception( + _LOGGER.exception( 'AuthMetadataPluginCallback "%s" raised exception!', self._metadata_plugin) with callback_state.lock: diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_server.py b/contrib/libs/grpc/src/python/grpcio/grpc/_server.py index 48ff743995..ee10f8d67c 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_server.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_server.py @@ -28,8 +28,8 @@ from grpc import _compression from grpc import _interceptor from grpc._cython import cygrpc -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + _SHUTDOWN_TAG = 'shutdown' _REQUEST_CALL_TAG = 'request_call' @@ -49,7 +49,7 @@ _CANCELLED = 'cancelled' _EMPTY_FLAGS = 0 -_DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0 +_DEALLOCATED_SERVER_CHECK_PERIOD_S = 1.0 _INF_TIMEOUT = 1e9 @@ -104,7 +104,7 @@ class _RPCState(object): self.statused = False self.rpc_errors = [] self.callbacks = [] - self.aborted = False + self.aborted = False def _raise_rpc_error(state): @@ -308,20 +308,20 @@ class _Context(grpc.ServicerContext): def abort(self, code, details): # treat OK like other invalid arguments: fail the RPC if code == grpc.StatusCode.OK: - _LOGGER.error( + _LOGGER.error( 'abort() called with StatusCode.OK; returning UNKNOWN') code = grpc.StatusCode.UNKNOWN details = '' with self._state.condition: self._state.code = code self._state.details = _common.encode(details) - self._state.aborted = True - raise Exception() - - def abort_with_status(self, status): - self._state.trailing_metadata = status.trailing_metadata - self.abort(status.code, status.details) + self._state.aborted = True + raise Exception() + def abort_with_status(self, status): + self._state.trailing_metadata = status.trailing_metadata + self.abort(status.code, status.details) + def set_code(self, code): with self._state.condition: self._state.code = code @@ -364,8 +364,8 @@ class _RequestIterator(object): self._state.request = None return request - raise AssertionError() # should never run - + raise AssertionError() # should never run + def _next(self): with self._state.condition: self._raise_or_start_receive_message() @@ -455,12 +455,12 @@ def _take_response_from_response_iterator(rpc_event, state, response_iterator): return None, True except Exception as exception: # pylint: disable=broad-except with state.condition: - if state.aborted: + if state.aborted: _abort(state, rpc_event.call, cygrpc.StatusCode.unknown, b'RPC Aborted') elif exception not in state.rpc_errors: details = 'Exception iterating responses: {}'.format(exception) - _LOGGER.exception(details) + _LOGGER.exception(details) _abort(state, rpc_event.call, cygrpc.StatusCode.unknown, _common.encode(details)) return None, False @@ -546,18 +546,18 @@ def _status(rpc_event, state, serialized_response): def _unary_response_in_pool(rpc_event, state, behavior, argument_thunk, request_deserializer, response_serializer): cygrpc.install_context_from_request_call_event(rpc_event) - try: - argument = argument_thunk() - if argument is not None: - response, proceed = _call_behavior(rpc_event, state, behavior, - argument, request_deserializer) - if proceed: - serialized_response = _serialize_response( - rpc_event, state, response, response_serializer) - if serialized_response is not None: - _status(rpc_event, state, serialized_response) - finally: - cygrpc.uninstall_context() + try: + argument = argument_thunk() + if argument is not None: + response, proceed = _call_behavior(rpc_event, state, behavior, + argument, request_deserializer) + if proceed: + serialized_response = _serialize_response( + rpc_event, state, response, response_serializer) + if serialized_response is not None: + _status(rpc_event, state, serialized_response) + finally: + cygrpc.uninstall_context() def _stream_response_in_pool(rpc_event, state, behavior, argument_thunk, @@ -574,9 +574,9 @@ def _stream_response_in_pool(rpc_event, state, behavior, argument_thunk, if serialized_response is not None: _send_response(rpc_event, state, serialized_response) - try: - argument = argument_thunk() - if argument is not None: + try: + argument = argument_thunk() + if argument is not None: if hasattr(behavior, 'experimental_non_blocking' ) and behavior.experimental_non_blocking: _call_behavior(rpc_event, @@ -591,8 +591,8 @@ def _stream_response_in_pool(rpc_event, state, behavior, argument_thunk, if proceed: _send_message_callback_to_blocking_iterator_adapter( rpc_event, state, send_response, response_iterator) - finally: - cygrpc.uninstall_context() + finally: + cygrpc.uninstall_context() def _is_rpc_state_active(state): @@ -736,7 +736,7 @@ def _handle_call(rpc_event, generic_handlers, interceptor_pipeline, thread_pool, interceptor_pipeline) except Exception as exception: # pylint: disable=broad-except details = 'Exception servicing handler: {}'.format(exception) - _LOGGER.exception(details) + _LOGGER.exception(details) return _reject_rpc(rpc_event, cygrpc.StatusCode.unknown, b'Error in service handler!'), None if method_handler is None: @@ -780,10 +780,10 @@ class _ServerState(object): self.rpc_states = set() self.due = set() - # A "volatile" flag to interrupt the daemon serving thread - self.server_deallocated = False - + # A "volatile" flag to interrupt the daemon serving thread + self.server_deallocated = False + def _add_generic_handlers(state, generic_handlers): with state.lock: state.generic_handlers.extend(generic_handlers) @@ -809,7 +809,7 @@ def _request_call(state): # TODO(https://github.com/grpc/grpc/issues/6597): delete this function. def _stop_serving(state): if not state.rpc_states and not state.due: - state.server.destroy() + state.server.destroy() for shutdown_event in state.shutdown_events: shutdown_event.set() state.stage = _ServerStage.STOPPED @@ -823,71 +823,71 @@ def _on_call_completed(state): state.active_rpc_count -= 1 -def _process_event_and_continue(state, event): - should_continue = True - if event.tag is _SHUTDOWN_TAG: - with state.lock: - state.due.remove(_SHUTDOWN_TAG) - if _stop_serving(state): - should_continue = False - elif event.tag is _REQUEST_CALL_TAG: - with state.lock: - state.due.remove(_REQUEST_CALL_TAG) - concurrency_exceeded = ( - state.maximum_concurrent_rpcs is not None and - state.active_rpc_count >= state.maximum_concurrent_rpcs) +def _process_event_and_continue(state, event): + should_continue = True + if event.tag is _SHUTDOWN_TAG: + with state.lock: + state.due.remove(_SHUTDOWN_TAG) + if _stop_serving(state): + should_continue = False + elif event.tag is _REQUEST_CALL_TAG: + with state.lock: + state.due.remove(_REQUEST_CALL_TAG) + concurrency_exceeded = ( + state.maximum_concurrent_rpcs is not None and + state.active_rpc_count >= state.maximum_concurrent_rpcs) rpc_state, rpc_future = _handle_call(event, state.generic_handlers, state.interceptor_pipeline, state.thread_pool, concurrency_exceeded) - if rpc_state is not None: - state.rpc_states.add(rpc_state) - if rpc_future is not None: - state.active_rpc_count += 1 - rpc_future.add_done_callback( - lambda unused_future: _on_call_completed(state)) - if state.stage is _ServerStage.STARTED: - _request_call(state) - elif _stop_serving(state): - should_continue = False - else: - rpc_state, callbacks = event.tag(event) - for callback in callbacks: - try: - callback() - except Exception: # pylint: disable=broad-except - _LOGGER.exception('Exception calling callback!') - if rpc_state is not None: - with state.lock: - state.rpc_states.remove(rpc_state) - if _stop_serving(state): - should_continue = False - return should_continue - - + if rpc_state is not None: + state.rpc_states.add(rpc_state) + if rpc_future is not None: + state.active_rpc_count += 1 + rpc_future.add_done_callback( + lambda unused_future: _on_call_completed(state)) + if state.stage is _ServerStage.STARTED: + _request_call(state) + elif _stop_serving(state): + should_continue = False + else: + rpc_state, callbacks = event.tag(event) + for callback in callbacks: + try: + callback() + except Exception: # pylint: disable=broad-except + _LOGGER.exception('Exception calling callback!') + if rpc_state is not None: + with state.lock: + state.rpc_states.remove(rpc_state) + if _stop_serving(state): + should_continue = False + return should_continue + + def _serve(state): while True: - timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S - event = state.completion_queue.poll(timeout) - if state.server_deallocated: - _begin_shutdown_once(state) - if event.completion_type != cygrpc.CompletionType.queue_timeout: - if not _process_event_and_continue(state, event): - return + timeout = time.time() + _DEALLOCATED_SERVER_CHECK_PERIOD_S + event = state.completion_queue.poll(timeout) + if state.server_deallocated: + _begin_shutdown_once(state) + if event.completion_type != cygrpc.CompletionType.queue_timeout: + if not _process_event_and_continue(state, event): + return # We want to force the deletion of the previous event # ~before~ we poll again; if the event has a reference # to a shutdown Call object, this can induce spinlock. event = None -def _begin_shutdown_once(state): - with state.lock: - if state.stage is _ServerStage.STARTED: - state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG) - state.stage = _ServerStage.GRACE - state.due.add(_SHUTDOWN_TAG) - - +def _begin_shutdown_once(state): + with state.lock: + if state.stage is _ServerStage.STARTED: + state.server.shutdown(state.completion_queue, _SHUTDOWN_TAG) + state.stage = _ServerStage.GRACE + state.due.add(_SHUTDOWN_TAG) + + def _stop(state, grace): with state.lock: if state.stage is _ServerStage.STOPPED: @@ -895,7 +895,7 @@ def _stop(state, grace): shutdown_event.set() return shutdown_event else: - _begin_shutdown_once(state) + _begin_shutdown_once(state) shutdown_event = threading.Event() state.shutdown_events.append(shutdown_event) if grace is None: @@ -922,27 +922,27 @@ def _start(state): state.stage = _ServerStage.STARTED _request_call(state) - thread = threading.Thread(target=_serve, args=(state,)) - thread.daemon = True + thread = threading.Thread(target=_serve, args=(state,)) + thread.daemon = True thread.start() -def _validate_generic_rpc_handlers(generic_rpc_handlers): - for generic_rpc_handler in generic_rpc_handlers: - service_attribute = getattr(generic_rpc_handler, 'service', None) - if service_attribute is None: - raise AttributeError( - '"{}" must conform to grpc.GenericRpcHandler type but does ' - 'not have "service" method!'.format(generic_rpc_handler)) - +def _validate_generic_rpc_handlers(generic_rpc_handlers): + for generic_rpc_handler in generic_rpc_handlers: + service_attribute = getattr(generic_rpc_handler, 'service', None) + if service_attribute is None: + raise AttributeError( + '"{}" must conform to grpc.GenericRpcHandler type but does ' + 'not have "service" method!'.format(generic_rpc_handler)) + def _augment_options(base_options, compression): compression_option = _compression.create_channel_option(compression) return tuple(base_options) + compression_option -class _Server(grpc.Server): - +class _Server(grpc.Server): + # pylint: disable=too-many-arguments def __init__(self, thread_pool, generic_handlers, interceptors, options, maximum_concurrent_rpcs, compression): @@ -954,7 +954,7 @@ class _Server(grpc.Server): thread_pool, maximum_concurrent_rpcs) def add_generic_rpc_handlers(self, generic_rpc_handlers): - _validate_generic_rpc_handlers(generic_rpc_handlers) + _validate_generic_rpc_handlers(generic_rpc_handlers) _add_generic_handlers(self._state, generic_rpc_handlers) def add_insecure_port(self, address): @@ -982,14 +982,14 @@ class _Server(grpc.Server): return _stop(self._state, grace) def __del__(self): - if hasattr(self, '_state'): - # We can not grab a lock in __del__(), so set a flag to signal the - # serving daemon thread (if it exists) to initiate shutdown. - self._state.server_deallocated = True - - -def create_server(thread_pool, generic_rpc_handlers, interceptors, options, + if hasattr(self, '_state'): + # We can not grab a lock in __del__(), so set a flag to signal the + # serving daemon thread (if it exists) to initiate shutdown. + self._state.server_deallocated = True + + +def create_server(thread_pool, generic_rpc_handlers, interceptors, options, maximum_concurrent_rpcs, compression): - _validate_generic_rpc_handlers(generic_rpc_handlers) - return _Server(thread_pool, generic_rpc_handlers, interceptors, options, + _validate_generic_rpc_handlers(generic_rpc_handlers) + return _Server(thread_pool, generic_rpc_handlers, interceptors, options, maximum_concurrent_rpcs, compression) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py b/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py index c48aaf60a2..b1996711db 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/_utilities.py @@ -16,15 +16,15 @@ import collections import threading import time -import logging +import logging import six import grpc from grpc import _common -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + _DONE_CALLBACK_EXCEPTION_LOG_MESSAGE = ( 'Exception calling connectivity future "done" callback!') @@ -100,10 +100,10 @@ class _ChannelReadyFuture(grpc.Future): return for done_callback in done_callbacks: - try: - done_callback(self) - except Exception: # pylint: disable=broad-except - _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE) + try: + done_callback(self) + except Exception: # pylint: disable=broad-except + _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE) def cancel(self): with self._condition: @@ -117,13 +117,13 @@ class _ChannelReadyFuture(grpc.Future): return False for done_callback in done_callbacks: - try: - done_callback(self) - except Exception: # pylint: disable=broad-except - _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE) - - return True + try: + done_callback(self) + except Exception: # pylint: disable=broad-except + _LOGGER.exception(_DONE_CALLBACK_EXCEPTION_LOG_MESSAGE) + return True + def cancelled(self): with self._condition: return self._cancelled diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py index 8843a3c550..65be79e985 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/_server_adaptations.py @@ -168,8 +168,8 @@ def _run_request_pipe_thread(request_iterator, request_consumer, return request_consumer.terminate() - request_pipe_thread = threading.Thread(target=pipe_requests) - request_pipe_thread.daemon = True + request_pipe_thread = threading.Thread(target=pipe_requests) + request_pipe_thread.daemon = True request_pipe_thread.start() @@ -301,7 +301,7 @@ def _simple_method_handler(implementation, request_deserializer, True, True, request_deserializer, response_serializer, None, None, None, _adapt_stream_stream_event(implementation.stream_stream_event)) - raise ValueError() + raise ValueError() def _flatten_method_pair_map(method_pair_map): diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py b/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py index fe3ce606c9..58d523f909 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/beta/utilities.py @@ -85,8 +85,8 @@ class _ChannelReadyFuture(future.Future): callable_util.call_logging_exceptions( done_callback, _DONE_CALLBACK_EXCEPTION_LOG_MESSAGE, self) - return True - + return True + def cancelled(self): with self._condition: return self._cancelled diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/session_cache.py b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/session_cache.py index 5c55f7c327..28747ba568 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/experimental/session_cache.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/experimental/session_cache.py @@ -1,45 +1,45 @@ -# Copyright 2018 gRPC authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""gRPC's APIs for TLS Session Resumption support""" - -from grpc._cython import cygrpc as _cygrpc - - -def ssl_session_cache_lru(capacity): - """Creates an SSLSessionCache with LRU replacement policy - - Args: - capacity: Size of the cache - - Returns: - An SSLSessionCache with LRU replacement policy that can be passed as a value for - the grpc.ssl_session_cache option to a grpc.Channel. SSL session caches are used - to store session tickets, which clients can present to resume previous TLS sessions - with a server. - """ - return SSLSessionCache(_cygrpc.SSLSessionCacheLRU(capacity)) - - -class SSLSessionCache(object): - """An encapsulation of a session cache used for TLS session resumption. - - Instances of this class can be passed to a Channel as values for the - grpc.ssl_session_cache option - """ - - def __init__(self, cache): - self._cache = cache - - def __int__(self): - return int(self._cache) +# Copyright 2018 gRPC authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""gRPC's APIs for TLS Session Resumption support""" + +from grpc._cython import cygrpc as _cygrpc + + +def ssl_session_cache_lru(capacity): + """Creates an SSLSessionCache with LRU replacement policy + + Args: + capacity: Size of the cache + + Returns: + An SSLSessionCache with LRU replacement policy that can be passed as a value for + the grpc.ssl_session_cache option to a grpc.Channel. SSL session caches are used + to store session tickets, which clients can present to resume previous TLS sessions + with a server. + """ + return SSLSessionCache(_cygrpc.SSLSessionCacheLRU(capacity)) + + +class SSLSessionCache(object): + """An encapsulation of a session cache used for TLS session resumption. + + Instances of this class can be passed to a Channel as values for the + grpc.ssl_session_cache option + """ + + def __init__(self, cache): + self._cache = cache + + def __int__(self): + return int(self._cache) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py index 24daf3406f..b9b36b3c46 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/callable_util.py @@ -21,9 +21,9 @@ import logging import six -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + class Outcome(six.with_metaclass(abc.ABCMeta)): """A sum type describing the outcome of some call. @@ -55,7 +55,7 @@ def _call_logging_exceptions(behavior, message, *args, **kwargs): return _EasyOutcome(Outcome.Kind.RETURNED, behavior(*args, **kwargs), None) except Exception as e: # pylint: disable=broad-except - _LOGGER.exception(message) + _LOGGER.exception(message) return _EasyOutcome(Outcome.Kind.RAISED, None, e) diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py index 421999fb1c..8a3b71f0bb 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/logging_pool.py @@ -17,9 +17,9 @@ import logging from concurrent import futures -_LOGGER = logging.getLogger(__name__) - +_LOGGER = logging.getLogger(__name__) + def _wrap(behavior): """Wraps an arbitrary callable behavior in exception-logging.""" @@ -27,7 +27,7 @@ def _wrap(behavior): try: return behavior(*args, **kwargs) except Exception: - _LOGGER.exception( + _LOGGER.exception( 'Unexpected exception from %s executed in logging pool!', behavior) raise diff --git a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py index 1faaf29bd7..35be07b076 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc/framework/foundation/stream_util.py @@ -19,7 +19,7 @@ import threading from grpc.framework.foundation import stream _NO_VALUE = object() -_LOGGER = logging.getLogger(__name__) +_LOGGER = logging.getLogger(__name__) class TransformingConsumer(stream.Consumer): @@ -47,10 +47,10 @@ class IterableConsumer(stream.Consumer): self._values = [] self._active = True - def consume(self, value): + def consume(self, value): with self._condition: if self._active: - self._values.append(value) + self._values.append(value) self._condition.notify() def terminate(self): @@ -58,10 +58,10 @@ class IterableConsumer(stream.Consumer): self._active = False self._condition.notify() - def consume_and_terminate(self, value): + def consume_and_terminate(self, value): with self._condition: if self._active: - self._values.append(value) + self._values.append(value) self._active = False self._condition.notify() @@ -104,7 +104,7 @@ class ThreadSwitchingConsumer(stream.Consumer): else: sink.consume(value) except Exception as e: # pylint:disable=broad-except - _LOGGER.exception(e) + _LOGGER.exception(e) with self._lock: if terminate: diff --git a/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py b/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py index 67f985e1f4..8201883389 100644 --- a/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py +++ b/contrib/libs/grpc/src/python/grpcio/grpc_core_dependencies.py @@ -269,7 +269,7 @@ CORE_SOURCE_FILES = [ 'src/core/lib/gpr/tmpfile_windows.cc', 'src/core/lib/gpr/wrap_memcpy.cc', 'src/core/lib/gprpp/arena.cc', - 'src/core/lib/gprpp/fork.cc', + 'src/core/lib/gprpp/fork.cc', 'src/core/lib/gprpp/global_config_env.cc', 'src/core/lib/gprpp/host_port.cc', 'src/core/lib/gprpp/mpscq.cc', @@ -279,7 +279,7 @@ CORE_SOURCE_FILES = [ 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/httpcli_security_connector.cc', 'src/core/lib/http/parser.cc', - 'src/core/lib/iomgr/buffer_list.cc', + 'src/core/lib/iomgr/buffer_list.cc', 'src/core/lib/iomgr/call_combiner.cc', 'src/core/lib/iomgr/cfstream_handle.cc', 'src/core/lib/iomgr/combiner.cc', @@ -306,9 +306,9 @@ CORE_SOURCE_FILES = [ 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', - 'src/core/lib/iomgr/grpc_if_nametoindex_posix.cc', - 'src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc', - 'src/core/lib/iomgr/internal_errqueue.cc', + 'src/core/lib/iomgr/grpc_if_nametoindex_posix.cc', + 'src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc', + 'src/core/lib/iomgr/internal_errqueue.cc', 'src/core/lib/iomgr/iocp_windows.cc', 'src/core/lib/iomgr/iomgr.cc', 'src/core/lib/iomgr/iomgr_custom.cc', @@ -465,7 +465,7 @@ CORE_SOURCE_FILES = [ 'src/core/lib/transport/timeout_encoding.cc', 'src/core/lib/transport/transport.cc', 'src/core/lib/transport/transport_op_string.cc', - 'src/core/lib/uri/uri_parser.cc', + 'src/core/lib/uri/uri_parser.cc', 'src/core/plugin_registry/grpc_plugin_registry.cc', 'src/core/tsi/alts/crypt/aes_gcm.cc', 'src/core/tsi/alts/crypt/gsec.cc', @@ -477,7 +477,7 @@ CORE_SOURCE_FILES = [ 'src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc', 'src/core/tsi/alts/frame_protector/frame_handler.cc', 'src/core/tsi/alts/handshaker/alts_handshaker_client.cc', - 'src/core/tsi/alts/handshaker/alts_shared_resource.cc', + 'src/core/tsi/alts/handshaker/alts_shared_resource.cc', 'src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc', 'src/core/tsi/alts/handshaker/alts_tsi_utils.cc', 'src/core/tsi/alts/handshaker/transport_security_common_api.cc', @@ -487,7 +487,7 @@ CORE_SOURCE_FILES = [ 'src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc', 'src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc', 'src/core/tsi/fake_transport_security.cc', - 'src/core/tsi/local_transport_security.cc', + 'src/core/tsi/local_transport_security.cc', 'src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc', 'src/core/tsi/ssl/session_cache/ssl_session_cache.cc', 'src/core/tsi/ssl/session_cache/ssl_session_openssl.cc', diff --git a/contrib/libs/grpc/src/python/grpcio/ya.make b/contrib/libs/grpc/src/python/grpcio/ya.make index 5cdb0230c4..870239eb3f 100644 --- a/contrib/libs/grpc/src/python/grpcio/ya.make +++ b/contrib/libs/grpc/src/python/grpcio/ya.make @@ -62,7 +62,7 @@ PY_SRCS( grpc/beta/utilities.py grpc/experimental/__init__.py grpc/experimental/gevent.py - grpc/experimental/session_cache.py + grpc/experimental/session_cache.py grpc/framework/__init__.py grpc/framework/common/__init__.py grpc/framework/common/cardinality.py diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/channelz_commands.py b/contrib/libs/grpc/src/python/grpcio_channelz/channelz_commands.py index dbbce2fda5..bee44b06a9 100644 --- a/contrib/libs/grpc/src/python/grpcio_channelz/channelz_commands.py +++ b/contrib/libs/grpc/src/python/grpcio_channelz/channelz_commands.py @@ -1,67 +1,67 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""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__))) -CHANNELZ_PROTO = os.path.join(ROOT_DIR, - '../../proto/grpc/channelz/channelz.proto') -LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') - - -class Preprocess(setuptools.Command): - """Command to copy proto modules from grpc/src/proto and LICENSE from - the root directory""" - - description = '' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - if os.path.isfile(CHANNELZ_PROTO): +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""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__))) +CHANNELZ_PROTO = os.path.join(ROOT_DIR, + '../../proto/grpc/channelz/channelz.proto') +LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') + + +class Preprocess(setuptools.Command): + """Command to copy proto modules from grpc/src/proto and LICENSE from + the root directory""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + if os.path.isfile(CHANNELZ_PROTO): shutil.copyfile( CHANNELZ_PROTO, os.path.join(ROOT_DIR, 'grpc_channelz/v1/channelz.proto')) - if os.path.isfile(LICENSE): - shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) - - -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['']) + if os.path.isfile(LICENSE): + shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) + + +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/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/__init__.py b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/__init__.py index 38fdfc9c5c..10b401503b 100644 --- a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/__init__.py +++ b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/__init__.py @@ -1,13 +1,13 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/__init__.py b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/__init__.py index 38fdfc9c5c..10b401503b 100644 --- a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/__init__.py +++ b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/__init__.py @@ -1,13 +1,13 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/channelz.py b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/channelz.py index 508fad5397..bd4733bc4a 100644 --- a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/channelz.py +++ b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_channelz/v1/channelz.py @@ -1,72 +1,72 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Channelz debug service implementation in gRPC Python.""" - +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Channelz debug service implementation in gRPC Python.""" + import sys -import grpc - -import grpc_channelz.v1.channelz_pb2_grpc as _channelz_pb2_grpc +import grpc + +import grpc_channelz.v1.channelz_pb2_grpc as _channelz_pb2_grpc from grpc_channelz.v1._servicer import ChannelzServicer - + _add_channelz_servicer_doc = """Add Channelz servicer to a server. - + Channelz servicer is in charge of pulling information from C-Core for entire process. It will allow the server to response to Channelz queries. - + The Channelz statistic is enabled by default inside C-Core. Whether the statistic is enabled or not is isolated from adding Channelz servicer. That means you can query Channelz info with a Channelz-disabled channel, and you can add Channelz servicer to a Channelz-disabled server. - + The Channelz statistic can be enabled or disabled by channel option 'grpc.enable_channelz'. Set to 1 to enable, set to 0 to disable. - + This is an EXPERIMENTAL API. - + Args: server: A gRPC server to which Channelz service will be added. """ - + if sys.version_info[0] >= 3 and sys.version_info[1] >= 6: from grpc_channelz.v1 import _async as aio - + def add_channelz_servicer(server): - + if isinstance(server, grpc.experimental.aio.Server): _channelz_pb2_grpc.add_ChannelzServicer_to_server( aio.ChannelzServicer(), server) else: _channelz_pb2_grpc.add_ChannelzServicer_to_server( ChannelzServicer(), server) - + add_channelz_servicer.__doc__ = _add_channelz_servicer_doc - + __all__ = [ "aio", "add_channelz_servicer", "ChannelzServicer", ] - + else: - + def add_channelz_servicer(server): _channelz_pb2_grpc.add_ChannelzServicer_to_server( ChannelzServicer(), server) - + add_channelz_servicer.__doc__ = _add_channelz_servicer_doc - + __all__ = [ "add_channelz_servicer", "ChannelzServicer", diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_version.py b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_version.py index 52cb1a9d3b..86908b1331 100644 --- a/contrib/libs/grpc/src/python/grpcio_channelz/grpc_version.py +++ b/contrib/libs/grpc/src/python/grpcio_channelz/grpc_version.py @@ -1,17 +1,17 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_channelz/grpc_version.py.template`!!! - +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_channelz/grpc_version.py.template`!!! + VERSION = '1.33.2' diff --git a/contrib/libs/grpc/src/python/grpcio_channelz/setup.py b/contrib/libs/grpc/src/python/grpcio_channelz/setup.py index 678b5ef13f..d61ad7594e 100644 --- a/contrib/libs/grpc/src/python/grpcio_channelz/setup.py +++ b/contrib/libs/grpc/src/python/grpcio_channelz/setup.py @@ -1,103 +1,103 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Setup module for the GRPC Python package's Channelz.""" - -import os -import sys - -import setuptools - +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Setup module for the GRPC Python package's Channelz.""" + +import os +import sys + +import setuptools + _PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__)) _README_PATH = os.path.join(_PACKAGE_PATH, '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__))) - -# Break import-style to ensure we can actually find our local modules. -import grpc_version - - -class _NoOpCommand(setuptools.Command): - """No-op command.""" - - description = '' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - pass - - -CLASSIFIERS = [ - 'Development Status :: 5 - Production/Stable', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', +# 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 local modules. +import grpc_version + + +class _NoOpCommand(setuptools.Command): + """No-op command.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + pass + + +CLASSIFIERS = [ + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', - 'License :: OSI Approved :: Apache Software License', -] - -PACKAGE_DIRECTORIES = { - '': '.', -} - -INSTALL_REQUIRES = ( - 'protobuf>=3.6.0', - 'grpcio>={version}'.format(version=grpc_version.VERSION), -) - -try: - import channelz_commands as _channelz_commands - # we are in the build environment, otherwise the above import fails + 'License :: OSI Approved :: Apache Software License', +] + +PACKAGE_DIRECTORIES = { + '': '.', +} + +INSTALL_REQUIRES = ( + 'protobuf>=3.6.0', + 'grpcio>={version}'.format(version=grpc_version.VERSION), +) + +try: + import channelz_commands as _channelz_commands + # we are in the build environment, otherwise the above import fails SETUP_REQUIRES = ('grpcio-tools=={version}'.format( version=grpc_version.VERSION),) - COMMAND_CLASS = { - # Run preprocess from the repository *before* doing any packaging! - 'preprocess': _channelz_commands.Preprocess, - 'build_package_protos': _channelz_commands.BuildPackageProtos, - } -except ImportError: - SETUP_REQUIRES = () - COMMAND_CLASS = { - # wire up commands to no-op not to break the external dependencies - 'preprocess': _NoOpCommand, - 'build_package_protos': _NoOpCommand, - } - -setuptools.setup( - name='grpcio-channelz', - version=grpc_version.VERSION, - license='Apache License 2.0', - description='Channel Level Live Debug Information Service for gRPC', + COMMAND_CLASS = { + # Run preprocess from the repository *before* doing any packaging! + 'preprocess': _channelz_commands.Preprocess, + 'build_package_protos': _channelz_commands.BuildPackageProtos, + } +except ImportError: + SETUP_REQUIRES = () + COMMAND_CLASS = { + # wire up commands to no-op not to break the external dependencies + 'preprocess': _NoOpCommand, + 'build_package_protos': _NoOpCommand, + } + +setuptools.setup( + name='grpcio-channelz', + version=grpc_version.VERSION, + license='Apache License 2.0', + description='Channel Level Live Debug Information Service for gRPC', long_description=open(_README_PATH, 'r').read(), - author='The gRPC Authors', - author_email='grpc-io@googlegroups.com', - classifiers=CLASSIFIERS, - url='https://grpc.io', - package_dir=PACKAGE_DIRECTORIES, - packages=setuptools.find_packages('.'), - install_requires=INSTALL_REQUIRES, - setup_requires=SETUP_REQUIRES, - cmdclass=COMMAND_CLASS) + author='The gRPC Authors', + author_email='grpc-io@googlegroups.com', + classifiers=CLASSIFIERS, + url='https://grpc.io', + package_dir=PACKAGE_DIRECTORIES, + packages=setuptools.find_packages('.'), + install_requires=INSTALL_REQUIRES, + setup_requires=SETUP_REQUIRES, + cmdclass=COMMAND_CLASS) diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py index f7ee639ec8..b0d8d1d620 100644 --- a/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py +++ b/contrib/libs/grpc/src/python/grpcio_health_checking/grpc_health/v1/health.py @@ -18,55 +18,55 @@ import threading import sys import grpc -from grpc_health.v1 import health_pb2 as _health_pb2 -from grpc_health.v1 import health_pb2_grpc as _health_pb2_grpc +from grpc_health.v1 import health_pb2 as _health_pb2 +from grpc_health.v1 import health_pb2_grpc as _health_pb2_grpc if sys.version_info[0] >= 3 and sys.version_info[1] >= 6: # Exposes AsyncHealthServicer as public API. from . import _async as aio # pylint: disable=unused-import # The service name of the health checking servicer. -SERVICE_NAME = _health_pb2.DESCRIPTOR.services_by_name['Health'].full_name +SERVICE_NAME = _health_pb2.DESCRIPTOR.services_by_name['Health'].full_name # The entry of overall health for the entire server. OVERALL_HEALTH = '' - -class _Watcher(): - - def __init__(self): - self._condition = threading.Condition() + +class _Watcher(): + + def __init__(self): + self._condition = threading.Condition() self._responses = collections.deque() - self._open = True - - def __iter__(self): - return self - - def _next(self): - with self._condition: - while not self._responses and self._open: - self._condition.wait() - if self._responses: + self._open = True + + def __iter__(self): + return self + + def _next(self): + with self._condition: + while not self._responses and self._open: + self._condition.wait() + if self._responses: return self._responses.popleft() - else: - raise StopIteration() - - def next(self): - return self._next() - - def __next__(self): - return self._next() - - def add(self, response): - with self._condition: - self._responses.append(response) - self._condition.notify() - - def close(self): - with self._condition: - self._open = False - self._condition.notify() - - + else: + raise StopIteration() + + def next(self): + return self._next() + + def __next__(self): + return self._next() + + def add(self, response): + with self._condition: + self._responses.append(response) + self._condition.notify() + + def close(self): + with self._condition: + self._open = False + self._condition.notify() + + def _watcher_to_send_response_callback_adapter(watcher): def send_response_callback(response): @@ -78,13 +78,13 @@ def _watcher_to_send_response_callback_adapter(watcher): return send_response_callback -class HealthServicer(_health_pb2_grpc.HealthServicer): +class HealthServicer(_health_pb2_grpc.HealthServicer): """Servicer handling RPCs for service statuses.""" def __init__(self, experimental_non_blocking=True, experimental_thread_pool=None): - self._lock = threading.RLock() + self._lock = threading.RLock() self._server_status = {"": _health_pb2.HealthCheckResponse.SERVING} self._send_response_callbacks = {} self.Watch.__func__.experimental_non_blocking = experimental_non_blocking @@ -92,23 +92,23 @@ class HealthServicer(_health_pb2_grpc.HealthServicer): self._gracefully_shutting_down = False def _on_close_callback(self, send_response_callback, service): - - def callback(): - with self._lock: + + def callback(): + with self._lock: self._send_response_callbacks[service].remove( send_response_callback) send_response_callback(None) - - return callback - + + return callback + def Check(self, request, context): - with self._lock: + with self._lock: status = self._server_status.get(request.service) if status is None: context.set_code(grpc.StatusCode.NOT_FOUND) - return _health_pb2.HealthCheckResponse() + return _health_pb2.HealthCheckResponse() else: - return _health_pb2.HealthCheckResponse(status=status) + return _health_pb2.HealthCheckResponse(status=status) # pylint: disable=arguments-differ def Watch(self, request, context, send_response_callback=None): @@ -120,11 +120,11 @@ class HealthServicer(_health_pb2_grpc.HealthServicer): blocking_watcher = _Watcher() send_response_callback = _watcher_to_send_response_callback_adapter( blocking_watcher) - service = request.service - with self._lock: - status = self._server_status.get(service) - if status is None: - status = _health_pb2.HealthCheckResponse.SERVICE_UNKNOWN # pylint: disable=no-member + service = request.service + with self._lock: + status = self._server_status.get(service) + if status is None: + status = _health_pb2.HealthCheckResponse.SERVICE_UNKNOWN # pylint: disable=no-member send_response_callback( _health_pb2.HealthCheckResponse(status=status)) if service not in self._send_response_callbacks: @@ -133,16 +133,16 @@ class HealthServicer(_health_pb2_grpc.HealthServicer): context.add_callback( self._on_close_callback(send_response_callback, service)) return blocking_watcher - + def set(self, service, status): """Sets the status of a service. - Args: + Args: service: string, the name of the service. - status: HealthCheckResponse.status enum value indicating the status of - the service - """ - with self._lock: + status: HealthCheckResponse.status enum value indicating the status of + the service + """ + with self._lock: if self._gracefully_shutting_down: return else: diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py b/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py index 874dec7343..bb8985a1fd 100644 --- a/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py +++ b/contrib/libs/grpc/src/python/grpcio_health_checking/health_commands.py @@ -20,12 +20,12 @@ import setuptools ROOT_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) HEALTH_PROTO = os.path.join(ROOT_DIR, '../../proto/grpc/health/v1/health.proto') -LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') +LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') -class Preprocess(setuptools.Command): - """Command to copy proto modules from grpc/src/proto and LICENSE from - the root directory""" +class Preprocess(setuptools.Command): + """Command to copy proto modules from grpc/src/proto and LICENSE from + the root directory""" description = '' user_options = [] @@ -41,8 +41,8 @@ class Preprocess(setuptools.Command): shutil.copyfile( HEALTH_PROTO, os.path.join(ROOT_DIR, 'grpc_health/v1/health.proto')) - if os.path.isfile(LICENSE): - shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) + if os.path.isfile(LICENSE): + shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) class BuildPackageProtos(setuptools.Command): diff --git a/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py b/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py index fa1fbbd55a..cf5ab50317 100644 --- a/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py +++ b/contrib/libs/grpc/src/python/grpcio_health_checking/setup.py @@ -63,7 +63,7 @@ PACKAGE_DIRECTORIES = { } INSTALL_REQUIRES = ( - 'protobuf>=3.6.0', + 'protobuf>=3.6.0', 'grpcio>={version}'.format(version=grpc_version.VERSION), ) @@ -74,7 +74,7 @@ try: version=grpc_version.VERSION),) COMMAND_CLASS = { # Run preprocess from the repository *before* doing any packaging! - 'preprocess': _health_commands.Preprocess, + 'preprocess': _health_commands.Preprocess, 'build_package_protos': _health_commands.BuildPackageProtos, } except ImportError: diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py index b302cea241..b5f0d91d5d 100644 --- a/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py +++ b/contrib/libs/grpc/src/python/grpcio_reflection/grpc_reflection/v1alpha/reflection.py @@ -21,8 +21,8 @@ from src.proto.grpc.reflection.v1alpha import reflection_pb2_grpc as _reflection from grpc_reflection.v1alpha._base import BaseReflectionServicer -SERVICE_NAME = _reflection_pb2.DESCRIPTOR.services_by_name[ - 'ServerReflection'].full_name +SERVICE_NAME = _reflection_pb2.DESCRIPTOR.services_by_name[ + 'ServerReflection'].full_name class ReflectionServicer(BaseReflectionServicer): @@ -46,8 +46,8 @@ class ReflectionServicer(BaseReflectionServicer): elif request.HasField('list_services'): yield self._list_services() else: - yield _reflection_pb2.ServerReflectionResponse( - error_response=_reflection_pb2.ErrorResponse( + 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/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py b/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py index 311ca4c4db..2e9c174748 100644 --- a/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py +++ b/contrib/libs/grpc/src/python/grpcio_reflection/reflection_commands.py @@ -21,12 +21,12 @@ import setuptools ROOT_DIR = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) REFLECTION_PROTO = os.path.join( ROOT_DIR, '../../proto/grpc/reflection/v1alpha/reflection.proto') -LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') +LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') -class Preprocess(setuptools.Command): - """Command to copy proto modules from grpc/src/proto and LICENSE from - the root directory""" +class Preprocess(setuptools.Command): + """Command to copy proto modules from grpc/src/proto and LICENSE from + the root directory""" description = '' user_options = [] @@ -43,8 +43,8 @@ class Preprocess(setuptools.Command): REFLECTION_PROTO, os.path.join(ROOT_DIR, 'grpc_reflection/v1alpha/reflection.proto')) - if os.path.isfile(LICENSE): - shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) + if os.path.isfile(LICENSE): + shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) class BuildPackageProtos(setuptools.Command): diff --git a/contrib/libs/grpc/src/python/grpcio_reflection/setup.py b/contrib/libs/grpc/src/python/grpcio_reflection/setup.py index 2d0a3fcdaa..9a714d03ef 100644 --- a/contrib/libs/grpc/src/python/grpcio_reflection/setup.py +++ b/contrib/libs/grpc/src/python/grpcio_reflection/setup.py @@ -64,7 +64,7 @@ PACKAGE_DIRECTORIES = { } INSTALL_REQUIRES = ( - 'protobuf>=3.6.0', + 'protobuf>=3.6.0', 'grpcio>={version}'.format(version=grpc_version.VERSION), ) @@ -75,7 +75,7 @@ try: version=grpc_version.VERSION),) COMMAND_CLASS = { # Run preprocess from the repository *before* doing any packaging! - 'preprocess': _reflection_commands.Preprocess, + 'preprocess': _reflection_commands.Preprocess, 'build_package_protos': _reflection_commands.BuildPackageProtos, } except ImportError: diff --git a/contrib/libs/grpc/src/python/grpcio_status/grpc_status/__init__.py b/contrib/libs/grpc/src/python/grpcio_status/grpc_status/__init__.py index 38fdfc9c5c..10b401503b 100644 --- a/contrib/libs/grpc/src/python/grpcio_status/grpc_status/__init__.py +++ b/contrib/libs/grpc/src/python/grpcio_status/grpc_status/__init__.py @@ -1,13 +1,13 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py b/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py index d0ec08e3a5..3d4fcfd9b6 100644 --- a/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py +++ b/contrib/libs/grpc/src/python/grpcio_status/grpc_status/rpc_status.py @@ -1,78 +1,78 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Reference implementation for status mapping in gRPC Python.""" - -import collections +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Reference implementation for status mapping in gRPC Python.""" + +import collections import sys - -import grpc - -from google.rpc import status_pb2 + +import grpc + +from google.rpc import status_pb2 from ._common import code_to_grpc_status_code, GRPC_DETAILS_METADATA_KEY - - -class _Status( + + +class _Status( collections.namedtuple('_Status', ('code', 'details', 'trailing_metadata')), grpc.Status): - pass - - -def from_call(call): - """Returns a google.rpc.status.Status message corresponding to a given grpc.Call. - - This is an EXPERIMENTAL API. - - Args: - call: A grpc.Call instance. - - Returns: - A google.rpc.status.Status message representing the status of the RPC. - - Raises: - ValueError: If the gRPC call's code or details are inconsistent with the - status code and message inside of the google.rpc.status.Status. - """ + pass + + +def from_call(call): + """Returns a google.rpc.status.Status message corresponding to a given grpc.Call. + + This is an EXPERIMENTAL API. + + Args: + call: A grpc.Call instance. + + Returns: + A google.rpc.status.Status message representing the status of the RPC. + + Raises: + ValueError: If the gRPC call's code or details are inconsistent with the + status code and message inside of the google.rpc.status.Status. + """ if call.trailing_metadata() is None: return None - for key, value in call.trailing_metadata(): + for key, value in call.trailing_metadata(): if key == GRPC_DETAILS_METADATA_KEY: - rich_status = status_pb2.Status.FromString(value) - if call.code().value[0] != rich_status.code: - raise ValueError( - 'Code in Status proto (%s) doesn\'t match status code (%s)' + rich_status = status_pb2.Status.FromString(value) + if call.code().value[0] != rich_status.code: + raise ValueError( + 'Code in Status proto (%s) doesn\'t match status code (%s)' % (code_to_grpc_status_code(rich_status.code), call.code())) - if call.details() != rich_status.message: - raise ValueError( - 'Message in Status proto (%s) doesn\'t match status details (%s)' - % (rich_status.message, call.details())) - return rich_status - return None - - -def to_status(status): - """Convert a google.rpc.status.Status message to grpc.Status. - - This is an EXPERIMENTAL API. - - Args: - status: a google.rpc.status.Status message representing the non-OK status - to terminate the RPC with and communicate it to the client. - - Returns: - A grpc.Status instance representing the input google.rpc.status.Status message. - """ + if call.details() != rich_status.message: + raise ValueError( + 'Message in Status proto (%s) doesn\'t match status details (%s)' + % (rich_status.message, call.details())) + return rich_status + return None + + +def to_status(status): + """Convert a google.rpc.status.Status message to grpc.Status. + + This is an EXPERIMENTAL API. + + Args: + status: a google.rpc.status.Status message representing the non-OK status + to terminate the RPC with and communicate it to the client. + + Returns: + A grpc.Status instance representing the input google.rpc.status.Status message. + """ return _Status(code=code_to_grpc_status_code(status.code), details=status.message, trailing_metadata=((GRPC_DETAILS_METADATA_KEY, diff --git a/contrib/libs/grpc/src/python/grpcio_status/grpc_version.py b/contrib/libs/grpc/src/python/grpcio_status/grpc_version.py index 2b6ec9c659..4f586aee97 100644 --- a/contrib/libs/grpc/src/python/grpcio_status/grpc_version.py +++ b/contrib/libs/grpc/src/python/grpcio_status/grpc_version.py @@ -1,17 +1,17 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_status/grpc_version.py.template`!!! - +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio_status/grpc_version.py.template`!!! + VERSION = '1.33.2' diff --git a/contrib/libs/grpc/src/python/grpcio_status/setup.py b/contrib/libs/grpc/src/python/grpcio_status/setup.py index eb49069c34..052b470a3f 100644 --- a/contrib/libs/grpc/src/python/grpcio_status/setup.py +++ b/contrib/libs/grpc/src/python/grpcio_status/setup.py @@ -1,88 +1,88 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""Setup module for the GRPC Python package's status mapping.""" - -import os - -import setuptools - +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Setup module for the GRPC Python package's status mapping.""" + +import os + +import setuptools + _PACKAGE_PATH = os.path.realpath(os.path.dirname(__file__)) _README_PATH = os.path.join(_PACKAGE_PATH, '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__))) - -# Break import-style to ensure we can actually find our local modules. -import grpc_version - - -class _NoOpCommand(setuptools.Command): - """No-op command.""" - - description = '' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - pass - - -CLASSIFIERS = [ - 'Development Status :: 5 - Production/Stable', - 'Programming Language :: Python', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Programming Language :: Python :: 3.7', +# 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 local modules. +import grpc_version + + +class _NoOpCommand(setuptools.Command): + """No-op command.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + pass + + +CLASSIFIERS = [ + 'Development Status :: 5 - Production/Stable', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', - 'License :: OSI Approved :: Apache Software License', -] - -PACKAGE_DIRECTORIES = { - '': '.', -} - -INSTALL_REQUIRES = ( - 'protobuf>=3.6.0', - 'grpcio>={version}'.format(version=grpc_version.VERSION), - 'googleapis-common-protos>=1.5.5', -) - -try: - import status_commands as _status_commands - # we are in the build environment, otherwise the above import fails - COMMAND_CLASS = { - # Run preprocess from the repository *before* doing any packaging! - 'preprocess': _status_commands.Preprocess, - 'build_package_protos': _NoOpCommand, - } -except ImportError: - COMMAND_CLASS = { - # wire up commands to no-op not to break the external dependencies - 'preprocess': _NoOpCommand, - 'build_package_protos': _NoOpCommand, - } - + 'License :: OSI Approved :: Apache Software License', +] + +PACKAGE_DIRECTORIES = { + '': '.', +} + +INSTALL_REQUIRES = ( + 'protobuf>=3.6.0', + 'grpcio>={version}'.format(version=grpc_version.VERSION), + 'googleapis-common-protos>=1.5.5', +) + +try: + import status_commands as _status_commands + # we are in the build environment, otherwise the above import fails + COMMAND_CLASS = { + # Run preprocess from the repository *before* doing any packaging! + 'preprocess': _status_commands.Preprocess, + 'build_package_protos': _NoOpCommand, + } +except ImportError: + COMMAND_CLASS = { + # wire up commands to no-op not to break the external dependencies + 'preprocess': _NoOpCommand, + 'build_package_protos': _NoOpCommand, + } + setuptools.setup(name='grpcio-status', version=grpc_version.VERSION, description='Status proto mapping for gRPC', diff --git a/contrib/libs/grpc/src/python/grpcio_status/status_commands.py b/contrib/libs/grpc/src/python/grpcio_status/status_commands.py index 8306f3c027..fe2e36a1e5 100644 --- a/contrib/libs/grpc/src/python/grpcio_status/status_commands.py +++ b/contrib/libs/grpc/src/python/grpcio_status/status_commands.py @@ -1,43 +1,43 @@ -# Copyright 2018 The gRPC Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""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__))) +# Copyright 2018 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""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__))) STATUS_PROTO = os.path.join( ROOT_DIR, '../../../third_party/googleapis/google/rpc/status.proto') PACKAGE_STATUS_PROTO_PATH = 'grpc_status/google/rpc' -LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') - - -class Preprocess(setuptools.Command): - """Command to copy LICENSE from root directory.""" - - description = '' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): +LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') + + +class Preprocess(setuptools.Command): + """Command to copy LICENSE from root directory.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): if os.path.isfile(STATUS_PROTO): if not os.path.isdir(PACKAGE_STATUS_PROTO_PATH): os.makedirs(PACKAGE_STATUS_PROTO_PATH) @@ -45,5 +45,5 @@ class Preprocess(setuptools.Command): STATUS_PROTO, os.path.join(ROOT_DIR, PACKAGE_STATUS_PROTO_PATH, 'status.proto')) - if os.path.isfile(LICENSE): - shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) + if os.path.isfile(LICENSE): + shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) diff --git a/contrib/libs/grpc/src/python/grpcio_testing/README.rst b/contrib/libs/grpc/src/python/grpcio_testing/README.rst index 968dec8507..1b7eaa9b66 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/README.rst +++ b/contrib/libs/grpc/src/python/grpcio_testing/README.rst @@ -1,8 +1,8 @@ -gRPC Python Testing Package -=========================== - -Testing utilities for gRPC Python - +gRPC Python Testing Package +=========================== + +Testing utilities for gRPC Python + Supported Python Versions ------------------------- Python >= 3.5 @@ -11,8 +11,8 @@ Deprecated Python Versions -------------------------- Python == 2.7. Python 2.7 support will be removed on January 1, 2020. -Dependencies ------------- - -Depends on the `grpcio` package, available from PyPI via `pip install grpcio`. - +Dependencies +------------ + +Depends on the `grpcio` package, available from PyPI via `pip install grpcio`. + diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py index 65fdd1b8ca..02c71d2cb8 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/__init__.py @@ -14,7 +14,7 @@ """Objects for use in testing gRPC Python-using application code.""" import abc -import six +import six from google.protobuf import descriptor diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py index d7205ca579..56a3d881b7 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_channel/_invocation.py @@ -18,8 +18,8 @@ import threading import grpc _NOT_YET_OBSERVED = object() -logging.basicConfig() -_LOGGER = logging.getLogger(__name__) +logging.basicConfig() +_LOGGER = logging.getLogger(__name__) def _cancel(handler): @@ -250,7 +250,7 @@ def consume_requests(request_iterator, handler): break except Exception: # pylint: disable=broad-except details = 'Exception iterating requests!' - _LOGGER.exception(details) + _LOGGER.exception(details) handler.cancel(grpc.StatusCode.UNKNOWN, details) consumption = threading.Thread(target=_consume) diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py index 100d8195f6..10e11e1e0e 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_handler.py @@ -105,10 +105,10 @@ class _Handler(Handler): self._expiration_future.cancel() self._condition.notify_all() - def add_termination_callback(self, callback): + def add_termination_callback(self, callback): with self._condition: if self._code is None: - self._termination_callbacks.append(callback) + self._termination_callbacks.append(callback) return True else: return False @@ -185,7 +185,7 @@ class _Handler(Handler): elif self._code is None: self._condition.wait() else: - return self._trailing_metadata, self._code, self._details + return self._trailing_metadata, self._code, self._details def expire(self): with self._condition: diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py index 736b714dc6..41b58a54f0 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_rpc.py @@ -18,10 +18,10 @@ import threading import grpc from grpc_testing import _common -logging.basicConfig() -_LOGGER = logging.getLogger(__name__) - +logging.basicConfig() +_LOGGER = logging.getLogger(__name__) + class Rpc(object): def __init__(self, handler, invocation_metadata): @@ -50,7 +50,7 @@ class Rpc(object): try: callback() except Exception: # pylint: disable=broad-except - _LOGGER.exception('Exception calling server-side callback!') + _LOGGER.exception('Exception calling server-side callback!') callback_calling_thread = threading.Thread(target=call_back) callback_calling_thread.start() @@ -89,7 +89,7 @@ class Rpc(object): def application_exception_abort(self, exception): with self._condition: if exception not in self._rpc_errors: - _LOGGER.exception('Exception calling application!') + _LOGGER.exception('Exception calling application!') self._abort( grpc.StatusCode.UNKNOWN, 'Exception calling application: {}'.format(exception)) diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py index c63750f978..03c6890014 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_server/_servicer_context.py @@ -78,9 +78,9 @@ class ServicerContext(grpc.ServicerContext): self._rpc._abort(code, details) raise Exception() - def abort_with_status(self, status): - raise NotImplementedError() - + def abort_with_status(self, status): + raise NotImplementedError() + def set_code(self, code): self._rpc.set_code(code) diff --git a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py index 9692c34e6f..6cbc4c164f 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/grpc_testing/_time.py @@ -21,16 +21,16 @@ import time as _time import grpc import grpc_testing -logging.basicConfig() -_LOGGER = logging.getLogger(__name__) - +logging.basicConfig() +_LOGGER = logging.getLogger(__name__) + def _call(behaviors): for behavior in behaviors: try: behavior() except Exception: # pylint: disable=broad-except - _LOGGER.exception('Exception calling behavior "%r"!', behavior) + _LOGGER.exception('Exception calling behavior "%r"!', behavior) def _call_in_thread(behaviors): diff --git a/contrib/libs/grpc/src/python/grpcio_testing/setup.py b/contrib/libs/grpc/src/python/grpcio_testing/setup.py index 1946793fe6..10d725ff2a 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/setup.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/setup.py @@ -27,45 +27,45 @@ os.chdir(os.path.dirname(os.path.abspath(__file__))) # Break import style to ensure that we can find same-directory modules. import grpc_version - -class _NoOpCommand(setuptools.Command): - """No-op command.""" - - description = '' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - pass - - + +class _NoOpCommand(setuptools.Command): + """No-op command.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + pass + + PACKAGE_DIRECTORIES = { '': '.', } INSTALL_REQUIRES = ( - 'protobuf>=3.6.0', + 'protobuf>=3.6.0', 'grpcio>={version}'.format(version=grpc_version.VERSION), ) -try: - import testing_commands as _testing_commands - # we are in the build environment, otherwise the above import fails - COMMAND_CLASS = { - # Run preprocess from the repository *before* doing any packaging! - 'preprocess': _testing_commands.Preprocess, - } -except ImportError: - COMMAND_CLASS = { - # wire up commands to no-op not to break the external dependencies - 'preprocess': _NoOpCommand, - } - +try: + import testing_commands as _testing_commands + # we are in the build environment, otherwise the above import fails + COMMAND_CLASS = { + # Run preprocess from the repository *before* doing any packaging! + 'preprocess': _testing_commands.Preprocess, + } +except ImportError: + COMMAND_CLASS = { + # wire up commands to no-op not to break the external dependencies + 'preprocess': _NoOpCommand, + } + setuptools.setup(name='grpcio-testing', version=grpc_version.VERSION, license='Apache License 2.0', diff --git a/contrib/libs/grpc/src/python/grpcio_testing/testing_commands.py b/contrib/libs/grpc/src/python/grpcio_testing/testing_commands.py index fb40d37efb..4d51085999 100644 --- a/contrib/libs/grpc/src/python/grpcio_testing/testing_commands.py +++ b/contrib/libs/grpc/src/python/grpcio_testing/testing_commands.py @@ -1,39 +1,39 @@ -# Copyright 2018 gRPC Authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -"""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__))) -LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') - - -class Preprocess(setuptools.Command): - """Command to copy LICENSE from root directory.""" - - description = '' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - if os.path.isfile(LICENSE): - shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) +# Copyright 2018 gRPC Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""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__))) +LICENSE = os.path.join(ROOT_DIR, '../../../LICENSE') + + +class Preprocess(setuptools.Command): + """Command to copy LICENSE from root directory.""" + + description = '' + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + def run(self): + if os.path.isfile(LICENSE): + shutil.copyfile(LICENSE, os.path.join(ROOT_DIR, 'LICENSE')) diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc index 5971b53075..f81103bb94 100644 --- a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc +++ b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.cc @@ -40,18 +40,18 @@ std::unique_ptr<ByteBuffer> SerializeToByteBuffer( return std::unique_ptr<ByteBuffer>(new ByteBuffer(&slice, 1)); } -bool SerializeToByteBufferInPlace(grpc::protobuf::Message* message, - ByteBuffer* buffer) { +bool SerializeToByteBufferInPlace(grpc::protobuf::Message* message, + ByteBuffer* buffer) { TString buf; - if (!message->SerializeToString(&buf)) { - return false; - } - buffer->Clear(); - Slice slice(buf); - ByteBuffer tmp(&slice, 1); - buffer->Swap(&tmp); - return true; -} - + if (!message->SerializeToString(&buf)) { + return false; + } + buffer->Clear(); + Slice slice(buf); + ByteBuffer tmp(&slice, 1); + buffer->Swap(&tmp); + return true; +} + } // namespace testing } // namespace grpc diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h index 3d01fb2468..00b5fc7252 100644 --- a/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h +++ b/contrib/libs/grpc/test/cpp/util/byte_buffer_proto_helper.h @@ -27,15 +27,15 @@ namespace grpc { namespace testing { -bool ParseFromByteBuffer(ByteBuffer* buffer, - ::grpc::protobuf::Message* message); +bool ParseFromByteBuffer(ByteBuffer* buffer, + ::grpc::protobuf::Message* message); std::unique_ptr<ByteBuffer> SerializeToByteBuffer( - ::grpc::protobuf::Message* message); - -bool SerializeToByteBufferInPlace(::grpc::protobuf::Message* message, - ByteBuffer* buffer); + ::grpc::protobuf::Message* message); +bool SerializeToByteBufferInPlace(::grpc::protobuf::Message* message, + ByteBuffer* buffer); + } // namespace testing } // namespace grpc diff --git a/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc b/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc index c63f351a8f..3c4b73e267 100644 --- a/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc +++ b/contrib/libs/grpc/test/cpp/util/byte_buffer_test.cc @@ -45,13 +45,13 @@ class ByteBufferTest : public ::testing::Test { static void TearDownTestCase() { grpc_shutdown(); } }; -TEST_F(ByteBufferTest, CopyCtor) { - ByteBuffer buffer1; - EXPECT_FALSE(buffer1.Valid()); - const ByteBuffer& buffer2 = buffer1; - EXPECT_FALSE(buffer2.Valid()); -} - +TEST_F(ByteBufferTest, CopyCtor) { + ByteBuffer buffer1; + EXPECT_FALSE(buffer1.Valid()); + const ByteBuffer& buffer2 = buffer1; + EXPECT_FALSE(buffer2.Valid()); +} + TEST_F(ByteBufferTest, CreateFromSingleSlice) { Slice s(kContent1); ByteBuffer buffer(&s, 1); diff --git a/contrib/libs/grpc/test/cpp/util/channel_trace_proto_helper.cc b/contrib/libs/grpc/test/cpp/util/channel_trace_proto_helper.cc index d4b4026774..97d20abf64 100644 --- a/contrib/libs/grpc/test/cpp/util/channel_trace_proto_helper.cc +++ b/contrib/libs/grpc/test/cpp/util/channel_trace_proto_helper.cc @@ -16,14 +16,14 @@ * */ -#include <grpc/support/port_platform.h> - +#include <grpc/support/port_platform.h> + #include "test/cpp/util/channel_trace_proto_helper.h" #include <grpc/grpc.h> #include <grpc/support/log.h> -#include <grpcpp/impl/codegen/config.h> -#include <grpcpp/impl/codegen/config_protobuf.h> +#include <grpcpp/impl/codegen/config.h> +#include <grpcpp/impl/codegen/config_protobuf.h> #include <gtest/gtest.h> #include "src/core/lib/iomgr/error.h" @@ -32,30 +32,30 @@ namespace grpc { -namespace { - -// Generic helper that takes in a json string, converts it to a proto, and -// then back to json. This ensures that the json string was correctly formatted -// according to https://developers.google.com/protocol-buffers/docs/proto3#json -template <typename Message> +namespace { + +// Generic helper that takes in a json string, converts it to a proto, and +// then back to json. This ensures that the json string was correctly formatted +// according to https://developers.google.com/protocol-buffers/docs/proto3#json +template <typename Message> void VaidateProtoJsonTranslation(const TString& json_str) { - Message msg; - grpc::protobuf::json::JsonParseOptions parse_options; + Message msg; + grpc::protobuf::json::JsonParseOptions parse_options; // If the following line is failing, then uncomment the last line of the // comment, and uncomment the lines that print the two strings. You can // then compare the output, and determine what fields are missing. // - // parse_options.ignore_unknown_fields = true; - grpc::protobuf::util::Status s = - grpc::protobuf::json::JsonStringToMessage(json_str, &msg, parse_options); - EXPECT_TRUE(s.ok()); + // parse_options.ignore_unknown_fields = true; + grpc::protobuf::util::Status s = + grpc::protobuf::json::JsonStringToMessage(json_str, &msg, parse_options); + EXPECT_TRUE(s.ok()); TString proto_json_str; - grpc::protobuf::json::JsonPrintOptions print_options; - // We usually do not want this to be true, however it can be helpful to - // uncomment and see the output produced then all fields are printed. - // print_options.always_print_primitive_fields = true; - s = grpc::protobuf::json::MessageToJsonString(msg, &proto_json_str); - EXPECT_TRUE(s.ok()); + grpc::protobuf::json::JsonPrintOptions print_options; + // We usually do not want this to be true, however it can be helpful to + // uncomment and see the output produced then all fields are printed. + // print_options.always_print_primitive_fields = true; + s = grpc::protobuf::json::MessageToJsonString(msg, &proto_json_str); + EXPECT_TRUE(s.ok()); // Parse JSON and re-dump to string, to make sure formatting is the // same as what would be generated by our JSON library. grpc_error* error = GRPC_ERROR_NONE; @@ -64,52 +64,52 @@ void VaidateProtoJsonTranslation(const TString& json_str) { ASSERT_EQ(error, GRPC_ERROR_NONE) << grpc_error_string(error); ASSERT_EQ(parsed_json.type(), grpc_core::Json::Type::OBJECT); proto_json_str = parsed_json.Dump(); - // uncomment these to compare the json strings. - // gpr_log(GPR_ERROR, "tracer json: %s", json_str.c_str()); + // uncomment these to compare the json strings. + // gpr_log(GPR_ERROR, "tracer json: %s", json_str.c_str()); // gpr_log(GPR_ERROR, "proto json: %s", proto_json_str.c_str()); - EXPECT_EQ(json_str, proto_json_str); + EXPECT_EQ(json_str, proto_json_str); } -} // namespace - -namespace testing { - +} // namespace + +namespace testing { + void ValidateChannelTraceProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::ChannelTrace>(json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::ChannelTrace>(json_c_str); +} + void ValidateChannelProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::Channel>(json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::Channel>(json_c_str); +} + void ValidateGetTopChannelsResponseProtoJsonTranslation( const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::GetTopChannelsResponse>( - json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::GetTopChannelsResponse>( + json_c_str); +} + void ValidateGetChannelResponseProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::GetChannelResponse>( - json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::GetChannelResponse>( + json_c_str); +} + void ValidateGetServerResponseProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::GetServerResponse>( - json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::GetServerResponse>( + json_c_str); +} + void ValidateSubchannelProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::Subchannel>(json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::Subchannel>(json_c_str); +} + void ValidateServerProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::Server>(json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::Server>(json_c_str); +} + void ValidateGetServersResponseProtoJsonTranslation(const char* json_c_str) { - VaidateProtoJsonTranslation<grpc::channelz::v1::GetServersResponse>( - json_c_str); -} - + VaidateProtoJsonTranslation<grpc::channelz::v1::GetServersResponse>( + json_c_str); +} + } // namespace testing } // namespace grpc diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.cc b/contrib/libs/grpc/test/cpp/util/cli_call.cc index 5b3631667f..8bc3c16e96 100644 --- a/contrib/libs/grpc/test/cpp/util/cli_call.cc +++ b/contrib/libs/grpc/test/cpp/util/cli_call.cc @@ -50,7 +50,7 @@ Status CliCall::Call(const std::shared_ptr<grpc::Channel>& channel, return call.Finish(server_trailing_metadata); } -CliCall::CliCall(const std::shared_ptr<grpc::Channel>& channel, +CliCall::CliCall(const std::shared_ptr<grpc::Channel>& channel, const TString& method, const OutgoingMetadataContainer& metadata, CliArgs args) : stub_(new grpc::GenericStub(channel)) { diff --git a/contrib/libs/grpc/test/cpp/util/cli_call.h b/contrib/libs/grpc/test/cpp/util/cli_call.h index 79d00d99f4..cb1c1bb869 100644 --- a/contrib/libs/grpc/test/cpp/util/cli_call.h +++ b/contrib/libs/grpc/test/cpp/util/cli_call.h @@ -46,7 +46,7 @@ class CliCall final { typedef std::multimap<grpc::string_ref, grpc::string_ref> IncomingMetadataContainer; - CliCall(const std::shared_ptr<grpc::Channel>& channel, + CliCall(const std::shared_ptr<grpc::Channel>& channel, const TString& method, const OutgoingMetadataContainer& metadata, CliArgs args); CliCall(const std::shared_ptr<grpc::Channel>& channel, diff --git a/contrib/libs/grpc/test/cpp/util/cli_call_test.cc b/contrib/libs/grpc/test/cpp/util/cli_call_test.cc index 4f0544b2e5..ac3f287061 100644 --- a/contrib/libs/grpc/test/cpp/util/cli_call_test.cc +++ b/contrib/libs/grpc/test/cpp/util/cli_call_test.cc @@ -122,7 +122,7 @@ TEST_F(CliCallTest, SimpleRpc) { } // namespace grpc int main(int argc, char** argv) { - grpc::testing::TestEnvironment env(argc, argv); + grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc b/contrib/libs/grpc/test/cpp/util/cli_credentials.cc index efd548eb9b..33502efb07 100644 --- a/contrib/libs/grpc/test/cpp/util/cli_credentials.cc +++ b/contrib/libs/grpc/test/cpp/util/cli_credentials.cc @@ -19,129 +19,129 @@ #include "test/cpp/util/cli_credentials.h" #include <gflags/gflags.h> -#include <grpc/slice.h> -#include <grpc/support/log.h> -#include <grpcpp/impl/codegen/slice.h> - -#include "src/core/lib/iomgr/load_file.h" - -DEFINE_bool( - enable_ssl, false, - "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); -DEFINE_bool(use_auth, false, - "Whether to create default google credentials. Deprecated. Use " - "--channel_creds_type=gdc."); +#include <grpc/slice.h> +#include <grpc/support/log.h> +#include <grpcpp/impl/codegen/slice.h> + +#include "src/core/lib/iomgr/load_file.h" + +DEFINE_bool( + enable_ssl, false, + "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); +DEFINE_bool(use_auth, false, + "Whether to create default google credentials. Deprecated. Use " + "--channel_creds_type=gdc."); DEFINE_string( access_token, "", - "The access token that will be sent to the server to authenticate RPCs. " - "Deprecated. Use --call_creds=access_token=<token>."); -DEFINE_string( - ssl_target, "", - "If not empty, treat the server host name as this for ssl/tls certificate " - "validation."); -DEFINE_string( - ssl_client_cert, "", + "The access token that will be sent to the server to authenticate RPCs. " + "Deprecated. Use --call_creds=access_token=<token>."); +DEFINE_string( + ssl_target, "", + "If not empty, treat the server host name as this for ssl/tls certificate " + "validation."); +DEFINE_string( + ssl_client_cert, "", "If not empty, load this PEM formatted client certificate file. Requires " - "use of --ssl_client_key."); -DEFINE_string( - ssl_client_key, "", + "use of --ssl_client_key."); +DEFINE_string( + ssl_client_key, "", "If not empty, load this PEM formatted private key. Requires use of " - "--ssl_client_cert"); -DEFINE_string( + "--ssl_client_cert"); +DEFINE_string( local_connect_type, "local_tcp", "The type of local connections for which local channel credentials will " "be applied. Should be local_tcp or uds."); DEFINE_string( - channel_creds_type, "", + channel_creds_type, "", "The channel creds type: insecure, ssl, gdc (Google Default Credentials), " "alts, or local."); -DEFINE_string( - call_creds, "", - "Call credentials to use: none (default), or access_token=<token>. If " - "provided, the call creds are composited on top of channel creds."); +DEFINE_string( + call_creds, "", + "Call credentials to use: none (default), or access_token=<token>. If " + "provided, the call creds are composited on top of channel creds."); namespace grpc { namespace testing { -namespace { - -const char ACCESS_TOKEN_PREFIX[] = "access_token="; -constexpr int ACCESS_TOKEN_PREFIX_LEN = - sizeof(ACCESS_TOKEN_PREFIX) / sizeof(*ACCESS_TOKEN_PREFIX) - 1; +namespace { +const char ACCESS_TOKEN_PREFIX[] = "access_token="; +constexpr int ACCESS_TOKEN_PREFIX_LEN = + sizeof(ACCESS_TOKEN_PREFIX) / sizeof(*ACCESS_TOKEN_PREFIX) - 1; + bool IsAccessToken(const TString& auth) { - return auth.length() > ACCESS_TOKEN_PREFIX_LEN && - auth.compare(0, ACCESS_TOKEN_PREFIX_LEN, ACCESS_TOKEN_PREFIX) == 0; -} - + return auth.length() > ACCESS_TOKEN_PREFIX_LEN && + auth.compare(0, ACCESS_TOKEN_PREFIX_LEN, ACCESS_TOKEN_PREFIX) == 0; +} + TString AccessToken(const TString& auth) { - if (!IsAccessToken(auth)) { - return ""; + if (!IsAccessToken(auth)) { + return ""; } return TString(auth.c_str(), ACCESS_TOKEN_PREFIX_LEN); -} - -} // namespace +} +} // namespace + TString CliCredentials::GetDefaultChannelCredsType() const { - // Compatibility logic for --enable_ssl. - if (FLAGS_enable_ssl) { - fprintf(stderr, - "warning: --enable_ssl is deprecated. Use " - "--channel_creds_type=ssl.\n"); - return "ssl"; - } - // Compatibility logic for --use_auth. - if (FLAGS_access_token.empty() && FLAGS_use_auth) { - fprintf(stderr, - "warning: --use_auth is deprecated. Use " - "--channel_creds_type=gdc.\n"); - return "gdc"; - } - return "insecure"; -} - + // Compatibility logic for --enable_ssl. + if (FLAGS_enable_ssl) { + fprintf(stderr, + "warning: --enable_ssl is deprecated. Use " + "--channel_creds_type=ssl.\n"); + return "ssl"; + } + // Compatibility logic for --use_auth. + if (FLAGS_access_token.empty() && FLAGS_use_auth) { + fprintf(stderr, + "warning: --use_auth is deprecated. Use " + "--channel_creds_type=gdc.\n"); + return "gdc"; + } + return "insecure"; +} + TString CliCredentials::GetDefaultCallCreds() const { - if (!FLAGS_access_token.empty()) { - fprintf(stderr, - "warning: --access_token is deprecated. Use " - "--call_creds=access_token=<token>.\n"); + if (!FLAGS_access_token.empty()) { + fprintf(stderr, + "warning: --access_token is deprecated. Use " + "--call_creds=access_token=<token>.\n"); return TString("access_token=") + FLAGS_access_token; - } - return "none"; -} - -std::shared_ptr<grpc::ChannelCredentials> -CliCredentials::GetChannelCredentials() const { - if (FLAGS_channel_creds_type.compare("insecure") == 0) { - return grpc::InsecureChannelCredentials(); - } else if (FLAGS_channel_creds_type.compare("ssl") == 0) { - grpc::SslCredentialsOptions ssl_creds_options; - // TODO(@Capstan): This won't affect Google Default Credentials using SSL. - if (!FLAGS_ssl_client_cert.empty()) { - grpc_slice cert_slice = grpc_empty_slice(); - GRPC_LOG_IF_ERROR( - "load_file", - grpc_load_file(FLAGS_ssl_client_cert.c_str(), 1, &cert_slice)); - ssl_creds_options.pem_cert_chain = - grpc::StringFromCopiedSlice(cert_slice); - grpc_slice_unref(cert_slice); - } - if (!FLAGS_ssl_client_key.empty()) { - grpc_slice key_slice = grpc_empty_slice(); - GRPC_LOG_IF_ERROR( - "load_file", - grpc_load_file(FLAGS_ssl_client_key.c_str(), 1, &key_slice)); - ssl_creds_options.pem_private_key = - grpc::StringFromCopiedSlice(key_slice); - grpc_slice_unref(key_slice); - } - return grpc::SslCredentials(ssl_creds_options); - } else if (FLAGS_channel_creds_type.compare("gdc") == 0) { + } + return "none"; +} + +std::shared_ptr<grpc::ChannelCredentials> +CliCredentials::GetChannelCredentials() const { + if (FLAGS_channel_creds_type.compare("insecure") == 0) { + return grpc::InsecureChannelCredentials(); + } else if (FLAGS_channel_creds_type.compare("ssl") == 0) { + grpc::SslCredentialsOptions ssl_creds_options; + // TODO(@Capstan): This won't affect Google Default Credentials using SSL. + if (!FLAGS_ssl_client_cert.empty()) { + grpc_slice cert_slice = grpc_empty_slice(); + GRPC_LOG_IF_ERROR( + "load_file", + grpc_load_file(FLAGS_ssl_client_cert.c_str(), 1, &cert_slice)); + ssl_creds_options.pem_cert_chain = + grpc::StringFromCopiedSlice(cert_slice); + grpc_slice_unref(cert_slice); + } + if (!FLAGS_ssl_client_key.empty()) { + grpc_slice key_slice = grpc_empty_slice(); + GRPC_LOG_IF_ERROR( + "load_file", + grpc_load_file(FLAGS_ssl_client_key.c_str(), 1, &key_slice)); + ssl_creds_options.pem_private_key = + grpc::StringFromCopiedSlice(key_slice); + grpc_slice_unref(key_slice); + } + return grpc::SslCredentials(ssl_creds_options); + } else if (FLAGS_channel_creds_type.compare("gdc") == 0) { return grpc::GoogleDefaultCredentials(); - } else if (FLAGS_channel_creds_type.compare("alts") == 0) { - return grpc::experimental::AltsCredentials( - grpc::experimental::AltsCredentialsOptions()); + } else if (FLAGS_channel_creds_type.compare("alts") == 0) { + return grpc::experimental::AltsCredentials( + grpc::experimental::AltsCredentialsOptions()); } else if (FLAGS_channel_creds_type.compare("local") == 0) { if (FLAGS_local_connect_type.compare("local_tcp") == 0) { return grpc::experimental::LocalCredentials(LOCAL_TCP); @@ -153,67 +153,67 @@ CliCredentials::GetChannelCredentials() const { FLAGS_local_connect_type.c_str()); } } - fprintf(stderr, + fprintf(stderr, "--channel_creds_type=%s invalid; must be insecure, ssl, gdc, " "alts, or local.\n", - FLAGS_channel_creds_type.c_str()); - return std::shared_ptr<grpc::ChannelCredentials>(); -} + FLAGS_channel_creds_type.c_str()); + return std::shared_ptr<grpc::ChannelCredentials>(); +} -std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials() - const { +std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials() + const { if (IsAccessToken(FLAGS_call_creds.c_str())) { return grpc::AccessTokenCredentials(AccessToken(FLAGS_call_creds.c_str())); } - if (FLAGS_call_creds.compare("none") == 0) { - // Nothing to do; creds, if any, are baked into the channel. - return std::shared_ptr<grpc::CallCredentials>(); - } - fprintf(stderr, - "--call_creds=%s invalid; must be none " - "or access_token=<token>.\n", - FLAGS_call_creds.c_str()); - return std::shared_ptr<grpc::CallCredentials>(); -} - -std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials() - const { - if (FLAGS_call_creds.empty()) { - FLAGS_call_creds = GetDefaultCallCreds(); + if (FLAGS_call_creds.compare("none") == 0) { + // Nothing to do; creds, if any, are baked into the channel. + return std::shared_ptr<grpc::CallCredentials>(); + } + fprintf(stderr, + "--call_creds=%s invalid; must be none " + "or access_token=<token>.\n", + FLAGS_call_creds.c_str()); + return std::shared_ptr<grpc::CallCredentials>(); +} + +std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials() + const { + if (FLAGS_call_creds.empty()) { + FLAGS_call_creds = GetDefaultCallCreds(); } else if (!FLAGS_access_token.empty() && !IsAccessToken(FLAGS_call_creds.c_str())) { - fprintf(stderr, - "warning: ignoring --access_token because --call_creds " - "already set to %s.\n", - FLAGS_call_creds.c_str()); - } - if (FLAGS_channel_creds_type.empty()) { - FLAGS_channel_creds_type = GetDefaultChannelCredsType(); - } else if (FLAGS_enable_ssl && FLAGS_channel_creds_type.compare("ssl") != 0) { - fprintf(stderr, - "warning: ignoring --enable_ssl because " - "--channel_creds_type already set to %s.\n", - FLAGS_channel_creds_type.c_str()); - } else if (FLAGS_use_auth && FLAGS_channel_creds_type.compare("gdc") != 0) { - fprintf(stderr, - "warning: ignoring --use_auth because " - "--channel_creds_type already set to %s.\n", - FLAGS_channel_creds_type.c_str()); - } - // Legacy transport upgrade logic for insecure requests. + fprintf(stderr, + "warning: ignoring --access_token because --call_creds " + "already set to %s.\n", + FLAGS_call_creds.c_str()); + } + if (FLAGS_channel_creds_type.empty()) { + FLAGS_channel_creds_type = GetDefaultChannelCredsType(); + } else if (FLAGS_enable_ssl && FLAGS_channel_creds_type.compare("ssl") != 0) { + fprintf(stderr, + "warning: ignoring --enable_ssl because " + "--channel_creds_type already set to %s.\n", + FLAGS_channel_creds_type.c_str()); + } else if (FLAGS_use_auth && FLAGS_channel_creds_type.compare("gdc") != 0) { + fprintf(stderr, + "warning: ignoring --use_auth because " + "--channel_creds_type already set to %s.\n", + FLAGS_channel_creds_type.c_str()); + } + // Legacy transport upgrade logic for insecure requests. if (IsAccessToken(FLAGS_call_creds.c_str()) && - FLAGS_channel_creds_type.compare("insecure") == 0) { - fprintf(stderr, - "warning: --channel_creds_type=insecure upgraded to ssl because " - "an access token was provided.\n"); - FLAGS_channel_creds_type = "ssl"; - } - std::shared_ptr<grpc::ChannelCredentials> channel_creds = - GetChannelCredentials(); - // Composite any call-type credentials on top of the base channel. - std::shared_ptr<grpc::CallCredentials> call_creds = GetCallCredentials(); - return (channel_creds == nullptr || call_creds == nullptr) - ? channel_creds - : grpc::CompositeChannelCredentials(channel_creds, call_creds); + FLAGS_channel_creds_type.compare("insecure") == 0) { + fprintf(stderr, + "warning: --channel_creds_type=insecure upgraded to ssl because " + "an access token was provided.\n"); + FLAGS_channel_creds_type = "ssl"; + } + std::shared_ptr<grpc::ChannelCredentials> channel_creds = + GetChannelCredentials(); + // Composite any call-type credentials on top of the base channel. + std::shared_ptr<grpc::CallCredentials> call_creds = GetCallCredentials(); + return (channel_creds == nullptr || call_creds == nullptr) + ? channel_creds + : grpc::CompositeChannelCredentials(channel_creds, call_creds); } const TString CliCredentials::GetCredentialUsage() const { @@ -221,25 +221,25 @@ const TString CliCredentials::GetCredentialUsage() const { "(deprecated)\n" " --use_auth ; Set whether to create default google" " credentials\n" - " ; (deprecated)\n" + " ; (deprecated)\n" " --access_token ; Set the access token in metadata," - " overrides --use_auth\n" - " ; (deprecated)\n" - " --ssl_target ; Set server host for ssl validation\n" - " --ssl_client_cert ; Client cert for ssl\n" - " --ssl_client_key ; Client private key for ssl\n" + " overrides --use_auth\n" + " ; (deprecated)\n" + " --ssl_target ; Set server host for ssl validation\n" + " --ssl_client_cert ; Client cert for ssl\n" + " --ssl_client_key ; Client private key for ssl\n" " --local_connect_type ; Set to local_tcp or uds\n" " --channel_creds_type ; Set to insecure, ssl, gdc, alts, or " "local\n" - " --call_creds ; Set to none, or" - " access_token=<token>\n"; + " --call_creds ; Set to none, or" + " access_token=<token>\n"; } - + const TString CliCredentials::GetSslTargetNameOverride() const { - bool use_ssl = FLAGS_channel_creds_type.compare("ssl") == 0 || - FLAGS_channel_creds_type.compare("gdc") == 0; - return use_ssl ? FLAGS_ssl_target : ""; -} - + bool use_ssl = FLAGS_channel_creds_type.compare("ssl") == 0 || + FLAGS_channel_creds_type.compare("gdc") == 0; + return use_ssl ? FLAGS_ssl_target : ""; +} + } // namespace testing } // namespace grpc diff --git a/contrib/libs/grpc/test/cpp/util/cli_credentials.h b/contrib/libs/grpc/test/cpp/util/cli_credentials.h index 3e695692fa..7a1435600c 100644 --- a/contrib/libs/grpc/test/cpp/util/cli_credentials.h +++ b/contrib/libs/grpc/test/cpp/util/cli_credentials.h @@ -28,25 +28,25 @@ namespace testing { class CliCredentials { public: virtual ~CliCredentials() {} - std::shared_ptr<grpc::ChannelCredentials> GetCredentials() const; + std::shared_ptr<grpc::ChannelCredentials> GetCredentials() const; virtual const TString GetCredentialUsage() const; virtual const TString GetSslTargetNameOverride() const; - - protected: - // Returns the appropriate channel_creds_type value for the set of legacy - // flag arguments. + + protected: + // Returns the appropriate channel_creds_type value for the set of legacy + // flag arguments. virtual TString GetDefaultChannelCredsType() const; - // Returns the appropriate call_creds value for the set of legacy flag - // arguments. + // Returns the appropriate call_creds value for the set of legacy flag + // arguments. virtual TString GetDefaultCallCreds() const; - // Returns the base transport channel credentials. Child classes can override - // to support additional channel_creds_types unknown to this base class. - virtual std::shared_ptr<grpc::ChannelCredentials> GetChannelCredentials() - const; - // Returns call credentials to composite onto the base transport channel - // credentials. Child classes can override to support additional - // authentication flags unknown to this base class. - virtual std::shared_ptr<grpc::CallCredentials> GetCallCredentials() const; + // Returns the base transport channel credentials. Child classes can override + // to support additional channel_creds_types unknown to this base class. + virtual std::shared_ptr<grpc::ChannelCredentials> GetChannelCredentials() + const; + // Returns call credentials to composite onto the base transport channel + // credentials. Child classes can override to support additional + // authentication flags unknown to this base class. + virtual std::shared_ptr<grpc::CallCredentials> GetCallCredentials() const; }; } // namespace testing diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc b/contrib/libs/grpc/test/cpp/util/grpc_tool.cc index 30f3024e25..019e5e40f1 100644 --- a/contrib/libs/grpc/test/cpp/util/grpc_tool.cc +++ b/contrib/libs/grpc/test/cpp/util/grpc_tool.cc @@ -66,8 +66,8 @@ DEFINE_bool( display_peer_address, false, "Log the peer socket address of the connection that each RPC is made " "on to stderr."); -DEFINE_bool(json_input, false, "Input in json format"); -DEFINE_bool(json_output, false, "Output in json format"); +DEFINE_bool(json_input, false, "Input in json format"); +DEFINE_bool(json_output, false, "Output in json format"); DEFINE_string(infile, "", "Input file (default is stdin)"); DEFINE_bool(batch, false, "Input contains multiple requests. Please do not use this to send " @@ -102,8 +102,8 @@ class GrpcTool { GrpcToolOutputCallback callback); bool ToText(int argc, const char** argv, const CliCredentials& cred, GrpcToolOutputCallback callback); - bool ToJson(int argc, const char** argv, const CliCredentials& cred, - GrpcToolOutputCallback callback); + bool ToJson(int argc, const char** argv, const CliCredentials& cred, + GrpcToolOutputCallback callback); bool ToBinary(int argc, const char** argv, const CliCredentials& cred, GrpcToolOutputCallback callback); @@ -205,9 +205,9 @@ void ReadResponse(CliCall* call, const TString& method_name, fprintf(stderr, "got response.\n"); if (!FLAGS_binary_output) { gpr_mu_lock(parser_mu); - serialized_response_proto = parser->GetFormattedStringFromMethod( - method_name, serialized_response_proto, false /* is_request */, - FLAGS_json_output); + serialized_response_proto = parser->GetFormattedStringFromMethod( + method_name, serialized_response_proto, false /* is_request */, + FLAGS_json_output); if (parser->HasError() && print_mode) { fprintf(stderr, "Failed to parse response.\n"); } @@ -223,20 +223,20 @@ void ReadResponse(CliCall* call, const TString& method_name, } } -std::shared_ptr<grpc::Channel> CreateCliChannel( +std::shared_ptr<grpc::Channel> CreateCliChannel( const TString& server_address, const CliCredentials& cred) { - grpc::ChannelArguments args; - if (!cred.GetSslTargetNameOverride().empty()) { - args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride()); - } + grpc::ChannelArguments args; + if (!cred.GetSslTargetNameOverride().empty()) { + args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride()); + } if (!FLAGS_default_service_config.empty()) { args.SetString(GRPC_ARG_SERVICE_CONFIG, FLAGS_default_service_config.c_str()); } return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(), args); -} - +} + struct Command { const char* command; std::function<bool(GrpcTool*, int, const char**, const CliCredentials&, @@ -255,7 +255,7 @@ const Command ops[] = { {"parse", BindWith5Args(&GrpcTool::ParseMessage), 2, 3}, {"totext", BindWith5Args(&GrpcTool::ToText), 2, 3}, {"tobinary", BindWith5Args(&GrpcTool::ToBinary), 2, 3}, - {"tojson", BindWith5Args(&GrpcTool::ToJson), 2, 3}, + {"tojson", BindWith5Args(&GrpcTool::ToJson), 2, 3}, }; void Usage(const TString& msg) { @@ -267,7 +267,7 @@ void Usage(const TString& msg) { " grpc_cli type ... ; Print type\n" " grpc_cli parse ... ; Parse message\n" " grpc_cli totext ... ; Convert binary message to text\n" - " grpc_cli tojson ... ; Convert binary message to json\n" + " grpc_cli tojson ... ; Convert binary message to json\n" " grpc_cli tobinary ... ; Convert text message to binary\n" " grpc_cli help ... ; Print this message, or per-command usage\n" "\n", @@ -357,7 +357,7 @@ bool GrpcTool::ListServices(int argc, const char** argv, TString server_address(argv[0]); std::shared_ptr<grpc::Channel> channel = - CreateCliChannel(server_address, cred); + CreateCliChannel(server_address, cred); grpc::ProtoReflectionDescriptorDatabase desc_db(channel); grpc::protobuf::DescriptorPool desc_pool(&desc_db); @@ -455,7 +455,7 @@ bool GrpcTool::PrintType(int /*argc*/, const char** argv, TString server_address(argv[0]); std::shared_ptr<grpc::Channel> channel = - CreateCliChannel(server_address, cred); + CreateCliChannel(server_address, cred); grpc::ProtoReflectionDescriptorDatabase desc_db(channel); grpc::protobuf::DescriptorPool desc_pool(&desc_db); @@ -491,8 +491,8 @@ bool GrpcTool::CallMethod(int argc, const char** argv, " --infile ; Input filename (defaults to stdin)\n" " --outfile ; Output filename (defaults to stdout)\n" " --binary_input ; Input in binary format\n" - " --binary_output ; Output in binary format\n" - " --json_input ; Input in json format\n" + " --binary_output ; Output in binary format\n" + " --json_input ; Input in json format\n" " --json_output ; Output in json format\n" " --timeout ; Specify timeout (in seconds), used to " "set the deadline for RPCs. The default value of -1 means no " @@ -511,28 +511,28 @@ bool GrpcTool::CallMethod(int argc, const char** argv, bool print_mode = false; std::shared_ptr<grpc::Channel> channel = - CreateCliChannel(server_address, cred); + CreateCliChannel(server_address, cred); - if (!FLAGS_binary_input || !FLAGS_binary_output) { - parser.reset( - new grpc::testing::ProtoFileParser(FLAGS_remotedb ? channel : nullptr, + if (!FLAGS_binary_input || !FLAGS_binary_output) { + parser.reset( + new grpc::testing::ProtoFileParser(FLAGS_remotedb ? channel : nullptr, FLAGS_proto_path.c_str(), FLAGS_protofiles.c_str())); - if (parser->HasError()) { - fprintf( - stderr, - "Failed to find remote reflection service and local proto files.\n"); - return false; - } - } + if (parser->HasError()) { + fprintf( + stderr, + "Failed to find remote reflection service and local proto files.\n"); + return false; + } + } if (FLAGS_binary_input) { formatted_method_name = method_name; } else { formatted_method_name = parser->GetFormattedMethodName(method_name); - if (parser->HasError()) { - fprintf(stderr, "Failed to find method %s in proto files.\n", - method_name.c_str()); - } + if (parser->HasError()) { + fprintf(stderr, "Failed to find method %s in proto files.\n", + method_name.c_str()); + } } if (argc == 3) { @@ -585,8 +585,8 @@ bool GrpcTool::CallMethod(int argc, const char** argv, } else { gpr_mu_lock(&parser_mu); serialized_request_proto = parser->GetSerializedProtoFromMethod( - method_name, request_text, true /* is_request */, - FLAGS_json_input); + method_name, request_text, true /* is_request */, + FLAGS_json_input); request_text.clear(); if (parser->HasError()) { if (print_mode) { @@ -671,8 +671,8 @@ bool GrpcTool::CallMethod(int argc, const char** argv, request_text.clear(); } else { serialized_request_proto = parser->GetSerializedProtoFromMethod( - method_name, request_text, true /* is_request */, - FLAGS_json_input); + method_name, request_text, true /* is_request */, + FLAGS_json_input); request_text.clear(); if (parser->HasError()) { if (print_mode) { @@ -716,8 +716,8 @@ bool GrpcTool::CallMethod(int argc, const char** argv, } else { TString response_text = parser->GetFormattedStringFromMethod( method_name, serialized_response_proto, - false /* is_request */, FLAGS_json_output); - + false /* is_request */, FLAGS_json_output); + if (parser->HasError() && print_mode) { fprintf(stderr, "Failed to parse response.\n"); } else { @@ -774,9 +774,9 @@ bool GrpcTool::CallMethod(int argc, const char** argv, serialized_request_proto = request_text; } else { serialized_request_proto = parser->GetSerializedProtoFromMethod( - method_name, request_text, true /* is_request */, FLAGS_json_input); + method_name, request_text, true /* is_request */, FLAGS_json_input); if (parser->HasError()) { - fprintf(stderr, "Failed to parse request.\n"); + fprintf(stderr, "Failed to parse request.\n"); return false; } } @@ -802,15 +802,15 @@ bool GrpcTool::CallMethod(int argc, const char** argv, receive_initial_metadata ? &server_initial_metadata : nullptr); receive_initial_metadata = false) { if (!FLAGS_binary_output) { - serialized_response_proto = parser->GetFormattedStringFromMethod( - method_name, serialized_response_proto, false /* is_request */, - FLAGS_json_output); + serialized_response_proto = parser->GetFormattedStringFromMethod( + method_name, serialized_response_proto, false /* is_request */, + FLAGS_json_output); if (parser->HasError()) { - fprintf(stderr, "Failed to parse response.\n"); + fprintf(stderr, "Failed to parse response.\n"); return false; } } - + if (receive_initial_metadata) { PrintMetadata(server_initial_metadata, "Received initial metadata from server:"); @@ -852,9 +852,9 @@ bool GrpcTool::ParseMessage(int argc, const char** argv, " --infile ; Input filename (defaults to stdin)\n" " --outfile ; Output filename (defaults to stdout)\n" " --binary_input ; Input in binary format\n" - " --binary_output ; Output in binary format\n" - " --json_input ; Input in json format\n" - " --json_output ; Output in json format\n" + + " --binary_output ; Output in binary format\n" + " --json_input ; Input in json format\n" + " --json_output ; Output in json format\n" + cred.GetCredentialUsage()); std::stringstream output_ss; @@ -886,14 +886,14 @@ bool GrpcTool::ParseMessage(int argc, const char** argv, if (!FLAGS_binary_input || !FLAGS_binary_output) { std::shared_ptr<grpc::Channel> channel = - CreateCliChannel(server_address, cred); + CreateCliChannel(server_address, cred); parser.reset( new grpc::testing::ProtoFileParser(FLAGS_remotedb ? channel : nullptr, FLAGS_proto_path.c_str(), FLAGS_protofiles.c_str())); if (parser->HasError()) { - fprintf( - stderr, - "Failed to find remote reflection service and local proto files.\n"); + fprintf( + stderr, + "Failed to find remote reflection service and local proto files.\n"); return false; } } @@ -901,10 +901,10 @@ bool GrpcTool::ParseMessage(int argc, const char** argv, if (FLAGS_binary_input) { serialized_request_proto = message_text; } else { - serialized_request_proto = parser->GetSerializedProtoFromMessageType( - type_name, message_text, FLAGS_json_input); + serialized_request_proto = parser->GetSerializedProtoFromMessageType( + type_name, message_text, FLAGS_json_input); if (parser->HasError()) { - fprintf(stderr, "Failed to serialize the message.\n"); + fprintf(stderr, "Failed to serialize the message.\n"); return false; } } @@ -913,13 +913,13 @@ bool GrpcTool::ParseMessage(int argc, const char** argv, output_ss << serialized_request_proto; } else { TString output_text; - output_text = parser->GetFormattedStringFromMessageType( - type_name, serialized_request_proto, FLAGS_json_output); + output_text = parser->GetFormattedStringFromMessageType( + type_name, serialized_request_proto, FLAGS_json_output); if (parser->HasError()) { - fprintf(stderr, "Failed to deserialize the message.\n"); + fprintf(stderr, "Failed to deserialize the message.\n"); return false; } - + output_ss << output_text << std::endl; } @@ -944,25 +944,25 @@ bool GrpcTool::ToText(int argc, const char** argv, const CliCredentials& cred, return ParseMessage(argc, argv, cred, callback); } -bool GrpcTool::ToJson(int argc, const char** argv, const CliCredentials& cred, - GrpcToolOutputCallback callback) { - CommandUsage( - "Convert binary message to json\n" - " grpc_cli tojson <protofiles> <type>\n" - " <protofiles> ; Comma separated list of proto files\n" - " <type> ; Protocol buffer type name\n" - " --proto_path ; The search path of proto files\n" - " --infile ; Input filename (defaults to stdin)\n" - " --outfile ; Output filename (defaults to stdout)\n"); - - FLAGS_protofiles = argv[0]; - FLAGS_remotedb = false; - FLAGS_binary_input = true; - FLAGS_binary_output = false; - FLAGS_json_output = true; - return ParseMessage(argc, argv, cred, callback); -} - +bool GrpcTool::ToJson(int argc, const char** argv, const CliCredentials& cred, + GrpcToolOutputCallback callback) { + CommandUsage( + "Convert binary message to json\n" + " grpc_cli tojson <protofiles> <type>\n" + " <protofiles> ; Comma separated list of proto files\n" + " <type> ; Protocol buffer type name\n" + " --proto_path ; The search path of proto files\n" + " --infile ; Input filename (defaults to stdin)\n" + " --outfile ; Output filename (defaults to stdout)\n"); + + FLAGS_protofiles = argv[0]; + FLAGS_remotedb = false; + FLAGS_binary_input = true; + FLAGS_binary_output = false; + FLAGS_json_output = true; + return ParseMessage(argc, argv, cred, callback); +} + bool GrpcTool::ToBinary(int argc, const char** argv, const CliCredentials& cred, GrpcToolOutputCallback callback) { CommandUsage( diff --git a/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc b/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc index ff610daadd..1b217226cd 100644 --- a/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc +++ b/contrib/libs/grpc/test/cpp/util/grpc_tool_test.cc @@ -57,7 +57,7 @@ using grpc::testing::EchoResponse; "Echo2\n" \ "CheckDeadlineUpperBound\n" \ "CheckDeadlineSet\n" \ - "CheckClientInitialMetadata\n" \ + "CheckClientInitialMetadata\n" \ "RequestStream\n" \ "ResponseStream\n" \ "BidiStream\n" \ @@ -94,32 +94,32 @@ using grpc::testing::EchoResponse; " rpc Echo(grpc.testing.EchoRequest) returns (grpc.testing.EchoResponse) " \ "{}\n" -#define ECHO_RESPONSE_MESSAGE_TEXT_FORMAT \ - "message: \"echo\"\n" \ - "param {\n" \ - " host: \"localhost\"\n" \ - " peer: \"peer\"\n" \ +#define ECHO_RESPONSE_MESSAGE_TEXT_FORMAT \ + "message: \"echo\"\n" \ + "param {\n" \ + " host: \"localhost\"\n" \ + " peer: \"peer\"\n" \ "}\n\n" -#define ECHO_RESPONSE_MESSAGE_JSON_FORMAT \ - "{\n" \ - " \"message\": \"echo\",\n" \ - " \"param\": {\n" \ - " \"host\": \"localhost\",\n" \ - " \"peer\": \"peer\"\n" \ - " }\n" \ - "}\n\n" - -DECLARE_string(channel_creds_type); -DECLARE_string(ssl_target); - +#define ECHO_RESPONSE_MESSAGE_JSON_FORMAT \ + "{\n" \ + " \"message\": \"echo\",\n" \ + " \"param\": {\n" \ + " \"host\": \"localhost\",\n" \ + " \"peer\": \"peer\"\n" \ + " }\n" \ + "}\n\n" + +DECLARE_string(channel_creds_type); +DECLARE_string(ssl_target); + namespace grpc { namespace testing { DECLARE_bool(binary_input); DECLARE_bool(binary_output); -DECLARE_bool(json_input); -DECLARE_bool(json_output); +DECLARE_bool(json_input); +DECLARE_bool(json_output); DECLARE_bool(l); DECLARE_bool(batch); DECLARE_string(metadata); @@ -134,27 +134,27 @@ const int kServerDefaultResponseStreamsToSend = 3; class TestCliCredentials final : public grpc::testing::CliCredentials { public: - TestCliCredentials(bool secure = false) : secure_(secure) {} - std::shared_ptr<grpc::ChannelCredentials> GetChannelCredentials() - const override { - if (!secure_) { - return InsecureChannelCredentials(); - } + TestCliCredentials(bool secure = false) : secure_(secure) {} + std::shared_ptr<grpc::ChannelCredentials> GetChannelCredentials() + const override { + if (!secure_) { + return InsecureChannelCredentials(); + } grpc_slice ca_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", grpc_load_file(CA_CERT_PATH, 1, &ca_slice))); const char* test_root_cert = reinterpret_cast<const char*> GRPC_SLICE_START_PTR(ca_slice); - SslCredentialsOptions ssl_opts = {test_root_cert, "", ""}; + SslCredentialsOptions ssl_opts = {test_root_cert, "", ""}; std::shared_ptr<grpc::ChannelCredentials> credential_ptr = grpc::SslCredentials(grpc::SslCredentialsOptions(ssl_opts)); grpc_slice_unref(ca_slice); return credential_ptr; } const TString GetCredentialUsage() const override { return ""; } - - private: - const bool secure_; + + private: + const bool secure_; }; bool PrintStream(std::stringstream* ss, const TString& output) { @@ -289,7 +289,7 @@ class GrpcToolTest : public ::testing::Test { server_address << "localhost:" << port; // Setup server ServerBuilder builder; - std::shared_ptr<grpc::ServerCredentials> creds; + std::shared_ptr<grpc::ServerCredentials> creds; grpc_slice cert_slice, key_slice; GPR_ASSERT(GRPC_LOG_IF_ERROR( "load_file", grpc_load_file(SERVER_CERT_PATH, 1, &cert_slice))); @@ -301,15 +301,15 @@ class GrpcToolTest : public ::testing::Test { reinterpret_cast<const char*> GRPC_SLICE_START_PTR(key_slice); SslServerCredentialsOptions::PemKeyCertPair pkcp = {server_key, server_cert}; - if (secure) { - SslServerCredentialsOptions ssl_opts; - ssl_opts.pem_root_certs = ""; - ssl_opts.pem_key_cert_pairs.push_back(pkcp); - creds = SslServerCredentials(ssl_opts); - } else { - creds = InsecureServerCredentials(); - } - builder.AddListeningPort(server_address.str(), creds); + if (secure) { + SslServerCredentialsOptions ssl_opts; + ssl_opts.pem_root_certs = ""; + ssl_opts.pem_key_cert_pairs.push_back(pkcp); + creds = SslServerCredentials(ssl_opts); + } else { + creds = InsecureServerCredentials(); + } + builder.AddListeningPort(server_address.str(), creds); builder.RegisterService(&service_); server_ = builder.BuildAndStart(); grpc_slice_unref(cert_slice); @@ -491,64 +491,64 @@ TEST_F(GrpcToolTest, CallCommand) { // Expected output: "message: \"Hello\"" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), "message: \"Hello\"")); - - // with json_output + + // with json_output output_stream.str(TString()); - output_stream.clear(); - - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - - // Expected output: - // { - // "message": "Hello" - // } - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "{\n \"message\": \"Hello\"\n}")); - + output_stream.clear(); + + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + + // Expected output: + // { + // "message": "Hello" + // } + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "{\n \"message\": \"Hello\"\n}")); + ShutdownServer(); } -TEST_F(GrpcToolTest, CallCommandJsonInput) { - // Test input "grpc_cli call localhost:<port> Echo "{ \"message\": \"Hello\"}" - std::stringstream output_stream; - +TEST_F(GrpcToolTest, CallCommandJsonInput) { + // Test input "grpc_cli call localhost:<port> Echo "{ \"message\": \"Hello\"}" + std::stringstream output_stream; + const TString server_address = SetUpServer(); - const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", - "{ \"message\": \"Hello\"}"}; - - FLAGS_json_input = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - // Expected output: "message: \"Hello\"" - EXPECT_TRUE(nullptr != - strstr(output_stream.str().c_str(), "message: \"Hello\"")); - - // with json_output + const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", + "{ \"message\": \"Hello\"}"}; + + FLAGS_json_input = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + // Expected output: "message: \"Hello\"" + EXPECT_TRUE(nullptr != + strstr(output_stream.str().c_str(), "message: \"Hello\"")); + + // with json_output output_stream.str(TString()); - output_stream.clear(); - - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_json_input = false; - - // Expected output: - // { - // "message": "Hello" - // } - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "{\n \"message\": \"Hello\"\n}")); - - ShutdownServer(); -} - + output_stream.clear(); + + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + FLAGS_json_input = false; + + // Expected output: + // { + // "message": "Hello" + // } + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "{\n \"message\": \"Hello\"\n}")); + + ShutdownServer(); +} + TEST_F(GrpcToolTest, CallCommandBatch) { // Test input "grpc_cli call Echo" std::stringstream output_stream; @@ -573,105 +573,105 @@ TEST_F(GrpcToolTest, CallCommandBatch) { EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), "message: \"Hello0\"\nmessage: " "\"Hello1\"\nmessage: \"Hello2\"\n")); - // with json_output + // with json_output output_stream.str(TString()); - output_stream.clear(); - ss.clear(); - ss.seekg(0); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_batch = true; - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_batch = false; - - // Expected output: - // { - // "message": "Hello0" - // } - // { - // "message": "Hello1" - // } - // { - // "message": "Hello2" - // } - // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: - // "Hello2"\n" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "{\n \"message\": \"Hello0\"\n}\n" - "{\n \"message\": \"Hello1\"\n}\n" - "{\n \"message\": \"Hello2\"\n}\n")); - + output_stream.clear(); + ss.clear(); + ss.seekg(0); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_batch = true; + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + FLAGS_batch = false; + + // Expected output: + // { + // "message": "Hello0" + // } + // { + // "message": "Hello1" + // } + // { + // "message": "Hello2" + // } + // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: + // "Hello2"\n" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "{\n \"message\": \"Hello0\"\n}\n" + "{\n \"message\": \"Hello1\"\n}\n" + "{\n \"message\": \"Hello2\"\n}\n")); + std::cin.rdbuf(orig); ShutdownServer(); } -TEST_F(GrpcToolTest, CallCommandBatchJsonInput) { - // Test input "grpc_cli call Echo" - std::stringstream output_stream; - +TEST_F(GrpcToolTest, CallCommandBatchJsonInput) { + // Test input "grpc_cli call Echo" + std::stringstream output_stream; + const TString server_address = SetUpServer(); - const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", - "{\"message\": \"Hello0\"}"}; - - // Mock std::cin input "message: 'Hello1'\n\n message: 'Hello2'\n\n" - std::streambuf* orig = std::cin.rdbuf(); - std::istringstream ss( - "{\"message\": \"Hello1\"}\n\n{\"message\": \"Hello2\" }\n\n"); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_json_input = true; - FLAGS_batch = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_batch = false; - - // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: - // "Hello2"\n" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "message: \"Hello0\"\nmessage: " - "\"Hello1\"\nmessage: \"Hello2\"\n")); - // with json_output + const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", + "{\"message\": \"Hello0\"}"}; + + // Mock std::cin input "message: 'Hello1'\n\n message: 'Hello2'\n\n" + std::streambuf* orig = std::cin.rdbuf(); + std::istringstream ss( + "{\"message\": \"Hello1\"}\n\n{\"message\": \"Hello2\" }\n\n"); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_json_input = true; + FLAGS_batch = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_batch = false; + + // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: + // "Hello2"\n" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "message: \"Hello0\"\nmessage: " + "\"Hello1\"\nmessage: \"Hello2\"\n")); + // with json_output output_stream.str(TString()); - output_stream.clear(); - ss.clear(); - ss.seekg(0); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_batch = true; - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_batch = false; - FLAGS_json_input = false; - - // Expected output: - // { - // "message": "Hello0" - // } - // { - // "message": "Hello1" - // } - // { - // "message": "Hello2" - // } - // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: - // "Hello2"\n" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "{\n \"message\": \"Hello0\"\n}\n" - "{\n \"message\": \"Hello1\"\n}\n" - "{\n \"message\": \"Hello2\"\n}\n")); - - std::cin.rdbuf(orig); - ShutdownServer(); -} - + output_stream.clear(); + ss.clear(); + ss.seekg(0); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_batch = true; + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + FLAGS_batch = false; + FLAGS_json_input = false; + + // Expected output: + // { + // "message": "Hello0" + // } + // { + // "message": "Hello1" + // } + // { + // "message": "Hello2" + // } + // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: + // "Hello2"\n" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "{\n \"message\": \"Hello0\"\n}\n" + "{\n \"message\": \"Hello1\"\n}\n" + "{\n \"message\": \"Hello2\"\n}\n")); + + std::cin.rdbuf(orig); + ShutdownServer(); +} + TEST_F(GrpcToolTest, CallCommandBatchWithBadRequest) { // Test input "grpc_cli call Echo" std::stringstream output_stream; @@ -694,99 +694,99 @@ TEST_F(GrpcToolTest, CallCommandBatchWithBadRequest) { // Expected output: "message: "Hello0"\nmessage: "Hello2"\n" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), "message: \"Hello0\"\nmessage: \"Hello2\"\n")); - - // with json_output + + // with json_output output_stream.str(TString()); - output_stream.clear(); - ss.clear(); - ss.seekg(0); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_batch = true; - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_batch = false; - - // Expected output: - // { - // "message": "Hello0" - // } - // { - // "message": "Hello2" - // } - // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: - // "Hello2"\n" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "{\n \"message\": \"Hello0\"\n}\n" - "{\n \"message\": \"Hello2\"\n}\n")); - + output_stream.clear(); + ss.clear(); + ss.seekg(0); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_batch = true; + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + FLAGS_batch = false; + + // Expected output: + // { + // "message": "Hello0" + // } + // { + // "message": "Hello2" + // } + // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: + // "Hello2"\n" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "{\n \"message\": \"Hello0\"\n}\n" + "{\n \"message\": \"Hello2\"\n}\n")); + std::cin.rdbuf(orig); ShutdownServer(); } -TEST_F(GrpcToolTest, CallCommandBatchJsonInputWithBadRequest) { - // Test input "grpc_cli call Echo" - std::stringstream output_stream; - +TEST_F(GrpcToolTest, CallCommandBatchJsonInputWithBadRequest) { + // Test input "grpc_cli call Echo" + std::stringstream output_stream; + const TString server_address = SetUpServer(); - const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", - "{ \"message\": \"Hello0\"}"}; - - // Mock std::cin input "message: 1\n\n message: 'Hello2'\n\n" - std::streambuf* orig = std::cin.rdbuf(); - std::istringstream ss( - "{ \"message\": 1 }\n\n { \"message\": \"Hello2\" }\n\n"); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_batch = true; - FLAGS_json_input = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_input = false; - FLAGS_batch = false; - - // Expected output: "message: "Hello0"\nmessage: "Hello2"\n" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "message: \"Hello0\"\nmessage: \"Hello2\"\n")); - - // with json_output + const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", + "{ \"message\": \"Hello0\"}"}; + + // Mock std::cin input "message: 1\n\n message: 'Hello2'\n\n" + std::streambuf* orig = std::cin.rdbuf(); + std::istringstream ss( + "{ \"message\": 1 }\n\n { \"message\": \"Hello2\" }\n\n"); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_batch = true; + FLAGS_json_input = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_input = false; + FLAGS_batch = false; + + // Expected output: "message: "Hello0"\nmessage: "Hello2"\n" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "message: \"Hello0\"\nmessage: \"Hello2\"\n")); + + // with json_output output_stream.str(TString()); - output_stream.clear(); - ss.clear(); - ss.seekg(0); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_batch = true; - FLAGS_json_input = true; - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_json_input = false; - FLAGS_batch = false; - - // Expected output: - // { - // "message": "Hello0" - // } - // { - // "message": "Hello2" - // } - // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: - // "Hello2"\n" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "{\n \"message\": \"Hello0\"\n}\n" - "{\n \"message\": \"Hello2\"\n}\n")); - - std::cin.rdbuf(orig); - ShutdownServer(); -} - + output_stream.clear(); + ss.clear(); + ss.seekg(0); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_batch = true; + FLAGS_json_input = true; + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + FLAGS_json_input = false; + FLAGS_batch = false; + + // Expected output: + // { + // "message": "Hello0" + // } + // { + // "message": "Hello2" + // } + // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: + // "Hello2"\n" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "{\n \"message\": \"Hello0\"\n}\n" + "{\n \"message\": \"Hello2\"\n}\n")); + + std::cin.rdbuf(orig); + ShutdownServer(); +} + TEST_F(GrpcToolTest, CallCommandRequestStream) { // Test input: grpc_cli call localhost:<port> RequestStream "message: // 'Hello0'" @@ -812,34 +812,34 @@ TEST_F(GrpcToolTest, CallCommandRequestStream) { ShutdownServer(); } -TEST_F(GrpcToolTest, CallCommandRequestStreamJsonInput) { - // Test input: grpc_cli call localhost:<port> RequestStream "{ \"message\": - // \"Hello0\"}" - std::stringstream output_stream; - +TEST_F(GrpcToolTest, CallCommandRequestStreamJsonInput) { + // Test input: grpc_cli call localhost:<port> RequestStream "{ \"message\": + // \"Hello0\"}" + std::stringstream output_stream; + const TString server_address = SetUpServer(); - const char* argv[] = {"grpc_cli", "call", server_address.c_str(), - "RequestStream", "{ \"message\": \"Hello0\" }"}; - - // Mock std::cin input "message: 'Hello1'\n\n message: 'Hello2'\n\n" - std::streambuf* orig = std::cin.rdbuf(); - std::istringstream ss( - "{ \"message\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_json_input = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_input = false; - - // Expected output: "message: \"Hello0Hello1Hello2\"" - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - "message: \"Hello0Hello1Hello2\"")); - std::cin.rdbuf(orig); - ShutdownServer(); -} - + const char* argv[] = {"grpc_cli", "call", server_address.c_str(), + "RequestStream", "{ \"message\": \"Hello0\" }"}; + + // Mock std::cin input "message: 'Hello1'\n\n message: 'Hello2'\n\n" + std::streambuf* orig = std::cin.rdbuf(); + std::istringstream ss( + "{ \"message\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_json_input = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_input = false; + + // Expected output: "message: \"Hello0Hello1Hello2\"" + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + "message: \"Hello0Hello1Hello2\"")); + std::cin.rdbuf(orig); + ShutdownServer(); +} + TEST_F(GrpcToolTest, CallCommandRequestStreamWithBadRequest) { // Test input: grpc_cli call localhost:<port> RequestStream "message: // 'Hello0'" @@ -865,34 +865,34 @@ TEST_F(GrpcToolTest, CallCommandRequestStreamWithBadRequest) { ShutdownServer(); } -TEST_F(GrpcToolTest, CallCommandRequestStreamWithBadRequestJsonInput) { - // Test input: grpc_cli call localhost:<port> RequestStream "message: - // 'Hello0'" - std::stringstream output_stream; - +TEST_F(GrpcToolTest, CallCommandRequestStreamWithBadRequestJsonInput) { + // Test input: grpc_cli call localhost:<port> RequestStream "message: + // 'Hello0'" + std::stringstream output_stream; + const TString server_address = SetUpServer(); - const char* argv[] = {"grpc_cli", "call", server_address.c_str(), - "RequestStream", "{ \"message\": \"Hello0\" }"}; - - // Mock std::cin input "bad_field: 'Hello1'\n\n message: 'Hello2'\n\n" - std::streambuf* orig = std::cin.rdbuf(); - std::istringstream ss( - "{ \"bad_field\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); - std::cin.rdbuf(ss.rdbuf()); - - FLAGS_json_input = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_input = false; - - // Expected output: "message: \"Hello0Hello2\"" - EXPECT_TRUE(nullptr != - strstr(output_stream.str().c_str(), "message: \"Hello0Hello2\"")); - std::cin.rdbuf(orig); - ShutdownServer(); -} - + const char* argv[] = {"grpc_cli", "call", server_address.c_str(), + "RequestStream", "{ \"message\": \"Hello0\" }"}; + + // Mock std::cin input "bad_field: 'Hello1'\n\n message: 'Hello2'\n\n" + std::streambuf* orig = std::cin.rdbuf(); + std::istringstream ss( + "{ \"bad_field\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); + std::cin.rdbuf(ss.rdbuf()); + + FLAGS_json_input = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_input = false; + + // Expected output: "message: \"Hello0Hello2\"" + EXPECT_TRUE(nullptr != + strstr(output_stream.str().c_str(), "message: \"Hello0Hello2\"")); + std::cin.rdbuf(orig); + ShutdownServer(); +} + TEST_F(GrpcToolTest, CallCommandWithTimeoutDeadlineSet) { // Test input "grpc_cli call CheckDeadlineSet --timeout=5000.25" std::stringstream output_stream; @@ -1001,24 +1001,24 @@ TEST_F(GrpcToolTest, CallCommandResponseStream) { expected_response_text.c_str())); } - // with json_output + // with json_output output_stream.str(TString()); - output_stream.clear(); - - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - - // Expected output: "{\n \"message\": \"Hello{n}\"\n}\n" - for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) { + output_stream.clear(); + + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + + // Expected output: "{\n \"message\": \"Hello{n}\"\n}\n" + for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) { TString expected_response_text = "{\n \"message\": \"Hello" + ToString(i) + "\"\n}\n"; - EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), - expected_response_text.c_str())); - } - + EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), + expected_response_text.c_str())); + } + ShutdownServer(); } @@ -1082,32 +1082,32 @@ TEST_F(GrpcToolTest, ParseCommand) { const TString server_address = SetUpServer(); const char* argv[] = {"grpc_cli", "parse", server_address.c_str(), - "grpc.testing.EchoResponse", - ECHO_RESPONSE_MESSAGE_TEXT_FORMAT}; + "grpc.testing.EchoResponse", + ECHO_RESPONSE_MESSAGE_TEXT_FORMAT}; FLAGS_binary_input = false; FLAGS_binary_output = false; EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - // Expected output: ECHO_RESPONSE_MESSAGE_TEXT_FORMAT - EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), - ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); + // Expected output: ECHO_RESPONSE_MESSAGE_TEXT_FORMAT + EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), + ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); - // with json_output + // with json_output output_stream.str(TString()); - output_stream.clear(); - - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - - // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT - EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), - ECHO_RESPONSE_MESSAGE_JSON_FORMAT)); - + output_stream.clear(); + + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + + // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT + EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), + ECHO_RESPONSE_MESSAGE_JSON_FORMAT)); + // Parse text message to binary message and then parse it back to text message output_stream.str(TString()); output_stream.clear(); @@ -1126,52 +1126,52 @@ TEST_F(GrpcToolTest, ParseCommand) { std::placeholders::_1))); // Expected output: ECHO_RESPONSE_MESSAGE - EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), - ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); + EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), + ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); FLAGS_binary_input = false; FLAGS_binary_output = false; ShutdownServer(); } -TEST_F(GrpcToolTest, ParseCommandJsonFormat) { - // Test input "grpc_cli parse localhost:<port> grpc.testing.EchoResponse - // ECHO_RESPONSE_MESSAGE_JSON_FORMAT" - std::stringstream output_stream; - std::stringstream binary_output_stream; - +TEST_F(GrpcToolTest, ParseCommandJsonFormat) { + // Test input "grpc_cli parse localhost:<port> grpc.testing.EchoResponse + // ECHO_RESPONSE_MESSAGE_JSON_FORMAT" + std::stringstream output_stream; + std::stringstream binary_output_stream; + const TString server_address = SetUpServer(); - const char* argv[] = {"grpc_cli", "parse", server_address.c_str(), - "grpc.testing.EchoResponse", - ECHO_RESPONSE_MESSAGE_JSON_FORMAT}; - - FLAGS_json_input = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - - // Expected output: ECHO_RESPONSE_MESSAGE_TEXT_FORMAT - EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), - ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); - - // with json_output + const char* argv[] = {"grpc_cli", "parse", server_address.c_str(), + "grpc.testing.EchoResponse", + ECHO_RESPONSE_MESSAGE_JSON_FORMAT}; + + FLAGS_json_input = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + + // Expected output: ECHO_RESPONSE_MESSAGE_TEXT_FORMAT + EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), + ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); + + // with json_output output_stream.str(TString()); - output_stream.clear(); - - FLAGS_json_output = true; - EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), - std::bind(PrintStream, &output_stream, - std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_json_input = false; - - // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT - EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), - ECHO_RESPONSE_MESSAGE_JSON_FORMAT)); - - ShutdownServer(); -} - + output_stream.clear(); + + FLAGS_json_output = true; + EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), + std::bind(PrintStream, &output_stream, + std::placeholders::_1))); + FLAGS_json_output = false; + FLAGS_json_input = false; + + // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT + EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), + ECHO_RESPONSE_MESSAGE_JSON_FORMAT)); + + ShutdownServer(); +} + TEST_F(GrpcToolTest, TooFewArguments) { // Test input "grpc_cli call Echo" std::stringstream output_stream; @@ -1288,29 +1288,29 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) { gpr_free(test_srcdir); } -TEST_F(GrpcToolTest, ListCommand_OverrideSslHostName) { +TEST_F(GrpcToolTest, ListCommand_OverrideSslHostName) { const TString server_address = SetUpServer(true); - - // Test input "grpc_cli ls localhost:<port> --channel_creds_type=ssl - // --ssl_target=z.test.google.fr" - std::stringstream output_stream; - const char* argv[] = {"grpc_cli", "ls", server_address.c_str()}; - FLAGS_l = false; - FLAGS_channel_creds_type = "ssl"; - FLAGS_ssl_target = "z.test.google.fr"; - EXPECT_TRUE( - 0 == GrpcToolMainLib( - ArraySize(argv), argv, TestCliCredentials(true), - std::bind(PrintStream, &output_stream, std::placeholders::_1))); - EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), - "grpc.testing.EchoTestService\n" - "grpc.reflection.v1alpha.ServerReflection\n")); - - FLAGS_channel_creds_type = ""; - FLAGS_ssl_target = ""; - ShutdownServer(); -} - + + // Test input "grpc_cli ls localhost:<port> --channel_creds_type=ssl + // --ssl_target=z.test.google.fr" + std::stringstream output_stream; + const char* argv[] = {"grpc_cli", "ls", server_address.c_str()}; + FLAGS_l = false; + FLAGS_channel_creds_type = "ssl"; + FLAGS_ssl_target = "z.test.google.fr"; + EXPECT_TRUE( + 0 == GrpcToolMainLib( + ArraySize(argv), argv, TestCliCredentials(true), + std::bind(PrintStream, &output_stream, std::placeholders::_1))); + EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), + "grpc.testing.EchoTestService\n" + "grpc.reflection.v1alpha.ServerReflection\n")); + + FLAGS_channel_creds_type = ""; + FLAGS_ssl_target = ""; + ShutdownServer(); +} + TEST_F(GrpcToolTest, ConfiguringDefaultServiceConfig) { // Test input "grpc_cli list localhost:<port> // --default_service_config={\"loadBalancingConfig\":[{\"pick_first\":{}}]}" @@ -1337,7 +1337,7 @@ TEST_F(GrpcToolTest, ConfiguringDefaultServiceConfig) { } // namespace grpc int main(int argc, char** argv) { - grpc::testing::TestEnvironment env(argc, argv); + grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); ::testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc b/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc index b0912a712c..4b10c67e97 100644 --- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc +++ b/contrib/libs/grpc/test/cpp/util/proto_file_parser.cc @@ -63,7 +63,7 @@ class ErrorPrinter : public protobuf::compiler::MultiFileErrorCollector { ProtoFileParser* parser_; // not owned }; -ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel, +ProtoFileParser::ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel, const TString& proto_path, const TString& protofiles) : has_error_(false), @@ -217,31 +217,31 @@ bool ProtoFileParser::IsStreaming(const TString& method, bool is_request) { TString ProtoFileParser::GetSerializedProtoFromMethod( const TString& method, const TString& formatted_proto, - bool is_request, bool is_json_format) { + bool is_request, bool is_json_format) { has_error_ = false; TString message_type_name = GetMessageTypeFromMethod(method, is_request); if (has_error_) { return ""; } - return GetSerializedProtoFromMessageType(message_type_name, formatted_proto, - is_json_format); + return GetSerializedProtoFromMessageType(message_type_name, formatted_proto, + is_json_format); } TString ProtoFileParser::GetFormattedStringFromMethod( const TString& method, const TString& serialized_proto, - bool is_request, bool is_json_format) { + bool is_request, bool is_json_format) { has_error_ = false; TString message_type_name = GetMessageTypeFromMethod(method, is_request); if (has_error_) { return ""; } - return GetFormattedStringFromMessageType(message_type_name, serialized_proto, - is_json_format); + return GetFormattedStringFromMessageType(message_type_name, serialized_proto, + is_json_format); } TString ProtoFileParser::GetSerializedProtoFromMessageType( const TString& message_type_name, const TString& formatted_proto, - bool is_json_format) { + bool is_json_format) { has_error_ = false; google::protobuf::string serialized; const protobuf::Descriptor* desc = @@ -252,22 +252,22 @@ TString ProtoFileParser::GetSerializedProtoFromMessageType( } std::unique_ptr<grpc::protobuf::Message> msg( dynamic_factory_->GetPrototype(desc)->New()); - bool ok; - if (is_json_format) { - ok = grpc::protobuf::json::JsonStringToMessage(google::protobuf::string(formatted_proto), msg.get()) - .ok(); - if (!ok) { - LogError("Failed to convert json format to proto."); - return ""; - } - } else { - ok = protobuf::TextFormat::ParseFromString(google::protobuf::string(formatted_proto), msg.get()); - if (!ok) { - LogError("Failed to convert text format to proto."); - return ""; - } + bool ok; + if (is_json_format) { + ok = grpc::protobuf::json::JsonStringToMessage(google::protobuf::string(formatted_proto), msg.get()) + .ok(); + if (!ok) { + LogError("Failed to convert json format to proto."); + return ""; + } + } else { + ok = protobuf::TextFormat::ParseFromString(google::protobuf::string(formatted_proto), msg.get()); + if (!ok) { + LogError("Failed to convert text format to proto."); + return ""; + } } - + ok = msg->SerializeToString(&serialized); if (!ok) { LogError("Failed to serialize proto."); @@ -278,7 +278,7 @@ TString ProtoFileParser::GetSerializedProtoFromMessageType( TString ProtoFileParser::GetFormattedStringFromMessageType( const TString& message_type_name, const TString& serialized_proto, - bool is_json_format) { + bool is_json_format) { has_error_ = false; const protobuf::Descriptor* desc = desc_pool_->FindMessageTypeByName(google::protobuf::string(message_type_name)); @@ -292,24 +292,24 @@ TString ProtoFileParser::GetFormattedStringFromMessageType( LogError("Failed to deserialize proto."); return ""; } - google::protobuf::string formatted_string; - - if (is_json_format) { - grpc::protobuf::json::JsonPrintOptions jsonPrintOptions; - jsonPrintOptions.add_whitespace = true; - if (!grpc::protobuf::json::MessageToJsonString( - *msg.get(), &formatted_string, jsonPrintOptions) - .ok()) { - LogError("Failed to print proto message to json format"); - return ""; - } - } else { - if (!protobuf::TextFormat::PrintToString(*msg.get(), &formatted_string)) { - LogError("Failed to print proto message to text format"); - return ""; - } + google::protobuf::string formatted_string; + + if (is_json_format) { + grpc::protobuf::json::JsonPrintOptions jsonPrintOptions; + jsonPrintOptions.add_whitespace = true; + if (!grpc::protobuf::json::MessageToJsonString( + *msg.get(), &formatted_string, jsonPrintOptions) + .ok()) { + LogError("Failed to print proto message to json format"); + return ""; + } + } else { + if (!protobuf::TextFormat::PrintToString(*msg.get(), &formatted_string)) { + LogError("Failed to print proto message to text format"); + return ""; + } } - return formatted_string; + return formatted_string; } void ProtoFileParser::LogError(const TString& error_msg) { diff --git a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h b/contrib/libs/grpc/test/cpp/util/proto_file_parser.h index c0445641c7..d482f9c3de 100644 --- a/contrib/libs/grpc/test/cpp/util/proto_file_parser.h +++ b/contrib/libs/grpc/test/cpp/util/proto_file_parser.h @@ -36,7 +36,7 @@ class ProtoFileParser { // The parser will search proto files using the server reflection service // provided on the given channel. The given protofiles in a source tree rooted // from proto_path will also be searched. - ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel, + ProtoFileParser(const std::shared_ptr<grpc::Channel>& channel, const TString& proto_path, const TString& protofiles); ~ProtoFileParser(); @@ -52,47 +52,47 @@ class ProtoFileParser { // used as the argument of Stub::Call() TString GetFormattedMethodName(const TString& method); - /// Converts a text or json string to its binary proto representation for the - /// given method's input or return type. - /// \param method the name of the method (does not need to be fully qualified - /// name) - /// \param formatted_proto the text- or json-formatted proto string - /// \param is_request if \c true the resolved type is that of the input - /// parameter of the method, otherwise it is the output type - /// \param is_json_format if \c true the \c formatted_proto is treated as a - /// json-formatted proto, otherwise it is treated as a text-formatted - /// proto + /// Converts a text or json string to its binary proto representation for the + /// given method's input or return type. + /// \param method the name of the method (does not need to be fully qualified + /// name) + /// \param formatted_proto the text- or json-formatted proto string + /// \param is_request if \c true the resolved type is that of the input + /// parameter of the method, otherwise it is the output type + /// \param is_json_format if \c true the \c formatted_proto is treated as a + /// json-formatted proto, otherwise it is treated as a text-formatted + /// proto /// \return the serialised binary proto representation of \c formatted_proto TString GetSerializedProtoFromMethod(const TString& method, const TString& formatted_proto, bool is_request, bool is_json_format); - /// Converts a text or json string to its proto representation for the given - /// message type. - /// \param formatted_proto the text- or json-formatted proto string + /// Converts a text or json string to its proto representation for the given + /// message type. + /// \param formatted_proto the text- or json-formatted proto string /// \return the serialised binary proto representation of \c formatted_proto TString GetSerializedProtoFromMessageType( const TString& message_type_name, const TString& formatted_proto, bool is_json_format); - /// Converts a binary proto string to its text or json string representation - /// for the given method's input or return type. - /// \param method the name of the method (does not need to be a fully - /// qualified name) - /// \param the serialised binary proto representation of type - /// \c message_type_name - /// \return the text- or json-formatted proto string of \c serialized_proto + /// Converts a binary proto string to its text or json string representation + /// for the given method's input or return type. + /// \param method the name of the method (does not need to be a fully + /// qualified name) + /// \param the serialised binary proto representation of type + /// \c message_type_name + /// \return the text- or json-formatted proto string of \c serialized_proto TString GetFormattedStringFromMethod(const TString& method, const TString& serialized_proto, bool is_request, bool is_json_format); - - /// Converts a binary proto string to its text or json string representation - /// for the given message type. - /// \param the serialised binary proto representation of type - /// \c message_type_name - /// \return the text- or json-formatted proto string of \c serialized_proto + + /// Converts a binary proto string to its text or json string representation + /// for the given message type. + /// \param the serialised binary proto representation of type + /// \c message_type_name + /// \return the text- or json-formatted proto string of \c serialized_proto TString GetFormattedStringFromMessageType( const TString& message_type_name, const TString& serialized_proto, bool is_json_format); diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc index 27a4c1e4cf..0d4e49224f 100644 --- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc +++ b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.cc @@ -35,7 +35,7 @@ ProtoReflectionDescriptorDatabase::ProtoReflectionDescriptorDatabase( : stub_(std::move(stub)) {} ProtoReflectionDescriptorDatabase::ProtoReflectionDescriptorDatabase( - const std::shared_ptr<grpc::Channel>& channel) + const std::shared_ptr<grpc::Channel>& channel) : stub_(ServerReflection::NewStub(channel)) {} ProtoReflectionDescriptorDatabase::~ProtoReflectionDescriptorDatabase() { @@ -82,7 +82,7 @@ bool ProtoReflectionDescriptorDatabase::FindFileByName( AddFileFromResponse(response.file_descriptor_response()); } else if (response.message_response_case() == ServerReflectionResponse::MessageResponseCase::kErrorResponse) { - const ErrorResponse& error = response.error_response(); + const ErrorResponse& error = response.error_response(); if (error.error_code() == StatusCode::NOT_FOUND) { gpr_log(GPR_INFO, "NOT_FOUND from server for FindFileByName(%s)", filename.c_str()); @@ -129,7 +129,7 @@ bool ProtoReflectionDescriptorDatabase::FindFileContainingSymbol( AddFileFromResponse(response.file_descriptor_response()); } else if (response.message_response_case() == ServerReflectionResponse::MessageResponseCase::kErrorResponse) { - const ErrorResponse& error = response.error_response(); + const ErrorResponse& error = response.error_response(); if (error.error_code() == StatusCode::NOT_FOUND) { missing_symbols_.insert(symbol_name); gpr_log(GPR_INFO, @@ -185,7 +185,7 @@ bool ProtoReflectionDescriptorDatabase::FindFileContainingExtension( AddFileFromResponse(response.file_descriptor_response()); } else if (response.message_response_case() == ServerReflectionResponse::MessageResponseCase::kErrorResponse) { - const ErrorResponse& error = response.error_response(); + const ErrorResponse& error = response.error_response(); if (error.error_code() == StatusCode::NOT_FOUND) { if (missing_extensions_.find(containing_type) == missing_extensions_.end()) { @@ -241,7 +241,7 @@ bool ProtoReflectionDescriptorDatabase::FindAllExtensionNumbers( return true; } else if (response.message_response_case() == ServerReflectionResponse::MessageResponseCase::kErrorResponse) { - const ErrorResponse& error = response.error_response(); + const ErrorResponse& error = response.error_response(); if (error.error_code() == StatusCode::NOT_FOUND) { gpr_log(GPR_INFO, "NOT_FOUND from server for FindAllExtensionNumbers(%s)", extendee_type.c_str()); @@ -268,14 +268,14 @@ bool ProtoReflectionDescriptorDatabase::GetServices( if (response.message_response_case() == ServerReflectionResponse::MessageResponseCase::kListServicesResponse) { - const ListServiceResponse& ls_response = response.list_services_response(); + const ListServiceResponse& ls_response = response.list_services_response(); for (int i = 0; i < ls_response.service_size(); ++i) { (*output).push_back(ls_response.service(i).name()); } return true; } else if (response.message_response_case() == ServerReflectionResponse::MessageResponseCase::kErrorResponse) { - const ErrorResponse& error = response.error_response(); + const ErrorResponse& error = response.error_response(); gpr_log(GPR_INFO, "Error on GetServices()\n\tError code: %d\n" "\tError Message: %s", diff --git a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h index cdd6f0cccd..bdc905cbb9 100644 --- a/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h +++ b/contrib/libs/grpc/test/cpp/util/proto_reflection_descriptor_database.h @@ -38,7 +38,7 @@ class ProtoReflectionDescriptorDatabase : public protobuf::DescriptorDatabase { std::unique_ptr<reflection::v1alpha::ServerReflection::Stub> stub); explicit ProtoReflectionDescriptorDatabase( - const std::shared_ptr<grpc::Channel>& channel); + const std::shared_ptr<grpc::Channel>& channel); virtual ~ProtoReflectionDescriptorDatabase(); diff --git a/contrib/libs/grpc/test/cpp/util/string_ref_test.cc b/contrib/libs/grpc/test/cpp/util/string_ref_test.cc index 8e3259b764..cb8b545379 100644 --- a/contrib/libs/grpc/test/cpp/util/string_ref_test.cc +++ b/contrib/libs/grpc/test/cpp/util/string_ref_test.cc @@ -62,7 +62,7 @@ TEST_F(StringRefTest, FromString) { TEST_F(StringRefTest, CopyConstructor) { string_ref s1(kTestString); ; - const string_ref& s2(s1); + const string_ref& s2(s1); EXPECT_EQ(s1.length(), s2.length()); EXPECT_EQ(s1.data(), s2.data()); } diff --git a/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc b/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc index f7134b773f..baac88eb52 100644 --- a/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc +++ b/contrib/libs/grpc/test/cpp/util/test_credentials_provider.cc @@ -93,8 +93,8 @@ class DefaultCredentialsProvider : public CredentialsProvider { SslCredentialsOptions ssl_opts = {test_root_cert, "", ""}; args->SetSslTargetNameOverride("foo.test.google.fr"); return grpc::SslCredentials(ssl_opts); - } else if (type == grpc::testing::kGoogleDefaultCredentialsType) { - return grpc::GoogleDefaultCredentials(); + } else if (type == grpc::testing::kGoogleDefaultCredentialsType) { + return grpc::GoogleDefaultCredentials(); } else { std::unique_lock<std::mutex> lock(mu_); auto it(std::find(added_secure_type_names_.begin(), diff --git a/contrib/libs/grpc/test/cpp/util/test_credentials_provider.h b/contrib/libs/grpc/test/cpp/util/test_credentials_provider.h index acba277ada..d29814f764 100644 --- a/contrib/libs/grpc/test/cpp/util/test_credentials_provider.h +++ b/contrib/libs/grpc/test/cpp/util/test_credentials_provider.h @@ -33,7 +33,7 @@ const char kInsecureCredentialsType[] = "INSECURE_CREDENTIALS"; // property "transport_security_type". const char kTlsCredentialsType[] = "ssl"; const char kAltsCredentialsType[] = "alts"; -const char kGoogleDefaultCredentialsType[] = "google_default_credentials"; +const char kGoogleDefaultCredentialsType[] = "google_default_credentials"; // Provide test credentials of a particular type. class CredentialTypeProvider { |