diff options
author | dvshkurko <dvshkurko@yandex-team.ru> | 2022-02-10 16:45:52 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:52 +0300 |
commit | c768a99151e47c3a4bb7b92c514d256abd301c4d (patch) | |
tree | 1a2c5ffcf89eb53ecd79dbc9bc0a195c27404d0c /contrib/libs/grpc/test/core/util | |
parent | 321ee9bce31ec6e238be26dbcbe539cffa2c3309 (diff) | |
download | ydb-c768a99151e47c3a4bb7b92c514d256abd301c4d.tar.gz |
Restoring authorship annotation for <dvshkurko@yandex-team.ru>. Commit 2 of 2.
Diffstat (limited to 'contrib/libs/grpc/test/core/util')
51 files changed, 4815 insertions, 4815 deletions
diff --git a/contrib/libs/grpc/test/core/util/cmdline.cc b/contrib/libs/grpc/test/core/util/cmdline.cc index 55d801ec7d..62b47f927a 100644 --- a/contrib/libs/grpc/test/core/util/cmdline.cc +++ b/contrib/libs/grpc/test/core/util/cmdline.cc @@ -1,319 +1,319 @@ -/* - * - * 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 "test/core/util/cmdline.h" - -#include <limits.h> -#include <stdio.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 "test/core/util/cmdline.h" + +#include <limits.h> +#include <stdio.h> +#include <string.h> + #include <vector> #include "y_absl/strings/str_cat.h" #include "y_absl/strings/str_format.h" #include "y_absl/strings/str_join.h" -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> -#include "src/core/lib/gpr/string.h" - -typedef enum { ARGTYPE_INT, ARGTYPE_BOOL, ARGTYPE_STRING } argtype; - -typedef struct arg { - const char* name; - const char* help; - argtype type; - void* value; - struct arg* next; -} arg; - -struct gpr_cmdline { - const char* description; - arg* args; - const char* argv0; - - const char* extra_arg_name; - const char* extra_arg_help; - void (*extra_arg)(void* user_data, const char* arg); - void* extra_arg_user_data; - - int (*state)(gpr_cmdline* cl, char* arg); - arg* cur_arg; - - int survive_failure; -}; - -static int normal_state(gpr_cmdline* cl, char* arg); - -gpr_cmdline* gpr_cmdline_create(const char* description) { - gpr_cmdline* cl = static_cast<gpr_cmdline*>(gpr_zalloc(sizeof(gpr_cmdline))); - - cl->description = description; - cl->state = normal_state; - - return cl; -} - -void gpr_cmdline_set_survive_failure(gpr_cmdline* cl) { - cl->survive_failure = 1; -} - -void gpr_cmdline_destroy(gpr_cmdline* cl) { - while (cl->args) { - arg* a = cl->args; - cl->args = a->next; - gpr_free(a); - } - gpr_free(cl); -} - -static void add_arg(gpr_cmdline* cl, const char* name, const char* help, - argtype type, void* value) { - arg* a; - - for (a = cl->args; a; a = a->next) { - GPR_ASSERT(0 != strcmp(a->name, name)); - } - - a = static_cast<arg*>(gpr_zalloc(sizeof(arg))); - a->name = name; - a->help = help; - a->type = type; - a->value = value; - a->next = cl->args; - cl->args = a; -} - -void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help, - int* value) { - add_arg(cl, name, help, ARGTYPE_INT, value); -} - -void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help, - int* value) { - add_arg(cl, name, help, ARGTYPE_BOOL, value); -} - -void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help, - const char** value) { - add_arg(cl, name, help, ARGTYPE_STRING, value); -} - -void gpr_cmdline_on_extra_arg( - gpr_cmdline* cl, const char* name, const char* help, - void (*on_extra_arg)(void* user_data, const char* arg), void* user_data) { - GPR_ASSERT(!cl->extra_arg); - GPR_ASSERT(on_extra_arg); - - cl->extra_arg = on_extra_arg; - cl->extra_arg_user_data = user_data; - cl->extra_arg_name = name; - cl->extra_arg_help = help; -} - -/* recursively descend argument list, adding the last element - to s first - so that arguments are added in the order they were - added to the list by api calls */ +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> +#include "src/core/lib/gpr/string.h" + +typedef enum { ARGTYPE_INT, ARGTYPE_BOOL, ARGTYPE_STRING } argtype; + +typedef struct arg { + const char* name; + const char* help; + argtype type; + void* value; + struct arg* next; +} arg; + +struct gpr_cmdline { + const char* description; + arg* args; + const char* argv0; + + const char* extra_arg_name; + const char* extra_arg_help; + void (*extra_arg)(void* user_data, const char* arg); + void* extra_arg_user_data; + + int (*state)(gpr_cmdline* cl, char* arg); + arg* cur_arg; + + int survive_failure; +}; + +static int normal_state(gpr_cmdline* cl, char* arg); + +gpr_cmdline* gpr_cmdline_create(const char* description) { + gpr_cmdline* cl = static_cast<gpr_cmdline*>(gpr_zalloc(sizeof(gpr_cmdline))); + + cl->description = description; + cl->state = normal_state; + + return cl; +} + +void gpr_cmdline_set_survive_failure(gpr_cmdline* cl) { + cl->survive_failure = 1; +} + +void gpr_cmdline_destroy(gpr_cmdline* cl) { + while (cl->args) { + arg* a = cl->args; + cl->args = a->next; + gpr_free(a); + } + gpr_free(cl); +} + +static void add_arg(gpr_cmdline* cl, const char* name, const char* help, + argtype type, void* value) { + arg* a; + + for (a = cl->args; a; a = a->next) { + GPR_ASSERT(0 != strcmp(a->name, name)); + } + + a = static_cast<arg*>(gpr_zalloc(sizeof(arg))); + a->name = name; + a->help = help; + a->type = type; + a->value = value; + a->next = cl->args; + cl->args = a; +} + +void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help, + int* value) { + add_arg(cl, name, help, ARGTYPE_INT, value); +} + +void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help, + int* value) { + add_arg(cl, name, help, ARGTYPE_BOOL, value); +} + +void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help, + const char** value) { + add_arg(cl, name, help, ARGTYPE_STRING, value); +} + +void gpr_cmdline_on_extra_arg( + gpr_cmdline* cl, const char* name, const char* help, + void (*on_extra_arg)(void* user_data, const char* arg), void* user_data) { + GPR_ASSERT(!cl->extra_arg); + GPR_ASSERT(on_extra_arg); + + cl->extra_arg = on_extra_arg; + cl->extra_arg_user_data = user_data; + cl->extra_arg_name = name; + cl->extra_arg_help = help; +} + +/* recursively descend argument list, adding the last element + to s first - so that arguments are added in the order they were + added to the list by api calls */ static void add_args_to_usage(arg* a, std::vector<TString>* s) { if (a == nullptr) return; add_args_to_usage(a->next, s); - switch (a->type) { - case ARGTYPE_BOOL: + switch (a->type) { + case ARGTYPE_BOOL: s->push_back(y_absl::StrFormat(" [--%s|--no-%s]", a->name, a->name)); - break; - case ARGTYPE_STRING: + break; + case ARGTYPE_STRING: s->push_back(y_absl::StrFormat(" [--%s=string]", a->name)); - break; - case ARGTYPE_INT: + break; + case ARGTYPE_INT: s->push_back(y_absl::StrFormat(" [--%s=int]", a->name)); - break; - } -} - + break; + } +} + TString gpr_cmdline_usage_string(gpr_cmdline* cl, const char* argv0) { - const char* name = strrchr(argv0, '/'); + const char* name = strrchr(argv0, '/'); if (name != nullptr) { - name++; - } else { - name = argv0; - } - + name++; + } else { + name = argv0; + } + std::vector<TString> s; s.push_back(y_absl::StrCat("Usage: ", name)); add_args_to_usage(cl->args, &s); - if (cl->extra_arg) { + if (cl->extra_arg) { s.push_back(y_absl::StrFormat(" [%s...]", cl->extra_arg_name)); - } + } s.push_back("\n"); return y_absl::StrJoin(s, ""); -} - -static int print_usage_and_die(gpr_cmdline* cl) { +} + +static int print_usage_and_die(gpr_cmdline* cl) { fprintf(stderr, "%s", gpr_cmdline_usage_string(cl, cl->argv0).c_str()); - if (!cl->survive_failure) { - exit(1); - } - return 0; -} - -static int extra_state(gpr_cmdline* cl, char* str) { - if (!cl->extra_arg) { - return print_usage_and_die(cl); - } - cl->extra_arg(cl->extra_arg_user_data, str); - return 1; -} - -static arg* find_arg(gpr_cmdline* cl, char* name) { - arg* a; - - for (a = cl->args; a; a = a->next) { - if (0 == strcmp(a->name, name)) { - break; - } - } - - if (!a) { - fprintf(stderr, "Unknown argument: %s\n", name); - return nullptr; - } - - return a; -} - -static int value_state(gpr_cmdline* cl, char* str) { - long intval; - char* end; - - GPR_ASSERT(cl->cur_arg); - - switch (cl->cur_arg->type) { - case ARGTYPE_INT: - intval = strtol(str, &end, 0); - if (*end || intval < INT_MIN || intval > INT_MAX) { - fprintf(stderr, "expected integer, got '%s' for %s\n", str, - cl->cur_arg->name); - return print_usage_and_die(cl); - } - *static_cast<int*>(cl->cur_arg->value) = static_cast<int>(intval); - break; - case ARGTYPE_BOOL: - if (0 == strcmp(str, "1") || 0 == strcmp(str, "true")) { - *static_cast<int*>(cl->cur_arg->value) = 1; - } else if (0 == strcmp(str, "0") || 0 == strcmp(str, "false")) { - *static_cast<int*>(cl->cur_arg->value) = 0; - } else { - fprintf(stderr, "expected boolean, got '%s' for %s\n", str, - cl->cur_arg->name); - return print_usage_and_die(cl); - } - break; - case ARGTYPE_STRING: - *static_cast<char**>(cl->cur_arg->value) = str; - break; - } - - cl->state = normal_state; - return 1; -} - -static int normal_state(gpr_cmdline* cl, char* str) { - char* eq = nullptr; - char* tmp = nullptr; - char* arg_name = nullptr; - int r = 1; - - if (0 == strcmp(str, "-help") || 0 == strcmp(str, "--help") || - 0 == strcmp(str, "-h")) { - return print_usage_and_die(cl); - } - - cl->cur_arg = nullptr; - - if (str[0] == '-') { - if (str[1] == '-') { - if (str[2] == 0) { - /* handle '--' to move to just extra args */ - cl->state = extra_state; - return 1; - } - str += 2; - } else { - str += 1; - } - /* first byte of str is now past the leading '-' or '--' */ - if (str[0] == 'n' && str[1] == 'o' && str[2] == '-') { - /* str is of the form '--no-foo' - it's a flag disable */ - str += 3; - cl->cur_arg = find_arg(cl, str); - if (cl->cur_arg == nullptr) { - return print_usage_and_die(cl); - } - if (cl->cur_arg->type != ARGTYPE_BOOL) { - fprintf(stderr, "%s is not a flag argument\n", str); - return print_usage_and_die(cl); - } - *static_cast<int*>(cl->cur_arg->value) = 0; - return 1; /* early out */ - } - eq = strchr(str, '='); - if (eq != nullptr) { - /* copy the string into a temp buffer and extract the name */ - tmp = arg_name = - static_cast<char*>(gpr_malloc(static_cast<size_t>(eq - str + 1))); - memcpy(arg_name, str, static_cast<size_t>(eq - str)); - arg_name[eq - str] = 0; - } else { - arg_name = str; - } - cl->cur_arg = find_arg(cl, arg_name); - if (cl->cur_arg == nullptr) { - return print_usage_and_die(cl); - } - if (eq != nullptr) { - /* str was of the type --foo=value, parse the value */ - r = value_state(cl, eq + 1); - } else if (cl->cur_arg->type != ARGTYPE_BOOL) { - /* flag types don't have a '--foo value' variant, other types do */ - cl->state = value_state; - } else { - /* flag parameter: just set the value */ - *static_cast<int*>(cl->cur_arg->value) = 1; - } - } else { - r = extra_state(cl, str); - } - - gpr_free(tmp); - return r; -} - -int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv) { - int i; - - GPR_ASSERT(argc >= 1); - cl->argv0 = argv[0]; - - for (i = 1; i < argc; i++) { - if (!cl->state(cl, argv[i])) { - return 0; - } - } - return 1; -} + if (!cl->survive_failure) { + exit(1); + } + return 0; +} + +static int extra_state(gpr_cmdline* cl, char* str) { + if (!cl->extra_arg) { + return print_usage_and_die(cl); + } + cl->extra_arg(cl->extra_arg_user_data, str); + return 1; +} + +static arg* find_arg(gpr_cmdline* cl, char* name) { + arg* a; + + for (a = cl->args; a; a = a->next) { + if (0 == strcmp(a->name, name)) { + break; + } + } + + if (!a) { + fprintf(stderr, "Unknown argument: %s\n", name); + return nullptr; + } + + return a; +} + +static int value_state(gpr_cmdline* cl, char* str) { + long intval; + char* end; + + GPR_ASSERT(cl->cur_arg); + + switch (cl->cur_arg->type) { + case ARGTYPE_INT: + intval = strtol(str, &end, 0); + if (*end || intval < INT_MIN || intval > INT_MAX) { + fprintf(stderr, "expected integer, got '%s' for %s\n", str, + cl->cur_arg->name); + return print_usage_and_die(cl); + } + *static_cast<int*>(cl->cur_arg->value) = static_cast<int>(intval); + break; + case ARGTYPE_BOOL: + if (0 == strcmp(str, "1") || 0 == strcmp(str, "true")) { + *static_cast<int*>(cl->cur_arg->value) = 1; + } else if (0 == strcmp(str, "0") || 0 == strcmp(str, "false")) { + *static_cast<int*>(cl->cur_arg->value) = 0; + } else { + fprintf(stderr, "expected boolean, got '%s' for %s\n", str, + cl->cur_arg->name); + return print_usage_and_die(cl); + } + break; + case ARGTYPE_STRING: + *static_cast<char**>(cl->cur_arg->value) = str; + break; + } + + cl->state = normal_state; + return 1; +} + +static int normal_state(gpr_cmdline* cl, char* str) { + char* eq = nullptr; + char* tmp = nullptr; + char* arg_name = nullptr; + int r = 1; + + if (0 == strcmp(str, "-help") || 0 == strcmp(str, "--help") || + 0 == strcmp(str, "-h")) { + return print_usage_and_die(cl); + } + + cl->cur_arg = nullptr; + + if (str[0] == '-') { + if (str[1] == '-') { + if (str[2] == 0) { + /* handle '--' to move to just extra args */ + cl->state = extra_state; + return 1; + } + str += 2; + } else { + str += 1; + } + /* first byte of str is now past the leading '-' or '--' */ + if (str[0] == 'n' && str[1] == 'o' && str[2] == '-') { + /* str is of the form '--no-foo' - it's a flag disable */ + str += 3; + cl->cur_arg = find_arg(cl, str); + if (cl->cur_arg == nullptr) { + return print_usage_and_die(cl); + } + if (cl->cur_arg->type != ARGTYPE_BOOL) { + fprintf(stderr, "%s is not a flag argument\n", str); + return print_usage_and_die(cl); + } + *static_cast<int*>(cl->cur_arg->value) = 0; + return 1; /* early out */ + } + eq = strchr(str, '='); + if (eq != nullptr) { + /* copy the string into a temp buffer and extract the name */ + tmp = arg_name = + static_cast<char*>(gpr_malloc(static_cast<size_t>(eq - str + 1))); + memcpy(arg_name, str, static_cast<size_t>(eq - str)); + arg_name[eq - str] = 0; + } else { + arg_name = str; + } + cl->cur_arg = find_arg(cl, arg_name); + if (cl->cur_arg == nullptr) { + return print_usage_and_die(cl); + } + if (eq != nullptr) { + /* str was of the type --foo=value, parse the value */ + r = value_state(cl, eq + 1); + } else if (cl->cur_arg->type != ARGTYPE_BOOL) { + /* flag types don't have a '--foo value' variant, other types do */ + cl->state = value_state; + } else { + /* flag parameter: just set the value */ + *static_cast<int*>(cl->cur_arg->value) = 1; + } + } else { + r = extra_state(cl, str); + } + + gpr_free(tmp); + return r; +} + +int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv) { + int i; + + GPR_ASSERT(argc >= 1); + cl->argv0 = argv[0]; + + for (i = 1; i < argc; i++) { + if (!cl->state(cl, argv[i])) { + return 0; + } + } + return 1; +} diff --git a/contrib/libs/grpc/test/core/util/cmdline.h b/contrib/libs/grpc/test/core/util/cmdline.h index 6a06bbfe43..cc75a8974e 100644 --- a/contrib/libs/grpc/test/core/util/cmdline.h +++ b/contrib/libs/grpc/test/core/util/cmdline.h @@ -1,82 +1,82 @@ -/* - * - * 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_TEST_CORE_UTIL_CMDLINE_H -#define GRPC_TEST_CORE_UTIL_CMDLINE_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_TEST_CORE_UTIL_CMDLINE_H +#define GRPC_TEST_CORE_UTIL_CMDLINE_H + +#include <grpc/support/port_platform.h> + #include <util/generic/string.h> -/** Simple command line parser. - - Supports flags that can be specified as -foo, --foo, --no-foo, -no-foo, etc - And integers, strings that can be specified as -foo=4, -foo blah, etc - - No support for short command line options (but we may get that in the - future.) - - Usage (for a program with a single flag argument 'foo'): - - int main(int argc, char **argv) { - gpr_cmdline *cl; - int verbose = 0; - - cl = gpr_cmdline_create("My cool tool"); - gpr_cmdline_add_int(cl, "verbose", "Produce verbose output?", &verbose); - gpr_cmdline_parse(cl, argc, argv); - gpr_cmdline_destroy(cl); - - if (verbose) { - gpr_log(GPR_INFO, "Goodbye cruel world!"); - } - - return 0; - } */ - -typedef struct gpr_cmdline gpr_cmdline; - -/** Construct a command line parser: takes a short description of the tool - doing the parsing */ -gpr_cmdline* gpr_cmdline_create(const char* description); -/** Add an integer parameter, with a name (used on the command line) and some - helpful text (used in the command usage) */ -void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help, - int* value); -/** The same, for a boolean flag */ -void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help, - int* value); -/** And for a string */ -void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help, - const char** value); -/** Set a callback for non-named arguments */ -void gpr_cmdline_on_extra_arg( - gpr_cmdline* cl, const char* name, const char* help, - void (*on_extra_arg)(void* user_data, const char* arg), void* user_data); -/** Enable surviving failure: default behavior is to exit the process */ -void gpr_cmdline_set_survive_failure(gpr_cmdline* cl); -/** Parse the command line; returns 1 on success, on failure either dies - (by default) or returns 0 if gpr_cmdline_set_survive_failure() has been - called */ -int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv); -/** Destroy the parser */ -void gpr_cmdline_destroy(gpr_cmdline* cl); -/** Get a string describing usage */ +/** Simple command line parser. + + Supports flags that can be specified as -foo, --foo, --no-foo, -no-foo, etc + And integers, strings that can be specified as -foo=4, -foo blah, etc + + No support for short command line options (but we may get that in the + future.) + + Usage (for a program with a single flag argument 'foo'): + + int main(int argc, char **argv) { + gpr_cmdline *cl; + int verbose = 0; + + cl = gpr_cmdline_create("My cool tool"); + gpr_cmdline_add_int(cl, "verbose", "Produce verbose output?", &verbose); + gpr_cmdline_parse(cl, argc, argv); + gpr_cmdline_destroy(cl); + + if (verbose) { + gpr_log(GPR_INFO, "Goodbye cruel world!"); + } + + return 0; + } */ + +typedef struct gpr_cmdline gpr_cmdline; + +/** Construct a command line parser: takes a short description of the tool + doing the parsing */ +gpr_cmdline* gpr_cmdline_create(const char* description); +/** Add an integer parameter, with a name (used on the command line) and some + helpful text (used in the command usage) */ +void gpr_cmdline_add_int(gpr_cmdline* cl, const char* name, const char* help, + int* value); +/** The same, for a boolean flag */ +void gpr_cmdline_add_flag(gpr_cmdline* cl, const char* name, const char* help, + int* value); +/** And for a string */ +void gpr_cmdline_add_string(gpr_cmdline* cl, const char* name, const char* help, + const char** value); +/** Set a callback for non-named arguments */ +void gpr_cmdline_on_extra_arg( + gpr_cmdline* cl, const char* name, const char* help, + void (*on_extra_arg)(void* user_data, const char* arg), void* user_data); +/** Enable surviving failure: default behavior is to exit the process */ +void gpr_cmdline_set_survive_failure(gpr_cmdline* cl); +/** Parse the command line; returns 1 on success, on failure either dies + (by default) or returns 0 if gpr_cmdline_set_survive_failure() has been + called */ +int gpr_cmdline_parse(gpr_cmdline* cl, int argc, char** argv); +/** Destroy the parser */ +void gpr_cmdline_destroy(gpr_cmdline* cl); +/** Get a string describing usage */ TString gpr_cmdline_usage_string(gpr_cmdline* cl, const char* argv0); - -#endif /* GRPC_TEST_CORE_UTIL_CMDLINE_H */ + +#endif /* GRPC_TEST_CORE_UTIL_CMDLINE_H */ diff --git a/contrib/libs/grpc/test/core/util/cmdline_test.cc b/contrib/libs/grpc/test/core/util/cmdline_test.cc index 10628d18f0..b1b7da6b17 100644 --- a/contrib/libs/grpc/test/core/util/cmdline_test.cc +++ b/contrib/libs/grpc/test/core/util/cmdline_test.cc @@ -1,488 +1,488 @@ -/* - * - * 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 <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "src/core/lib/gpr/useful.h" -#include "test/core/util/cmdline.h" -#include "test/core/util/test_config.h" - -#define LOG_TEST() gpr_log(GPR_INFO, "test at %s:%d", __FILE__, __LINE__) - -static void test_simple_int(void) { - int x = 1; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"), - const_cast<char*>("3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_int(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 1); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 3); - gpr_cmdline_destroy(cl); -} - -static void test_eq_int(void) { - int x = 1; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_int(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 1); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 3); - gpr_cmdline_destroy(cl); -} - -static void test_2dash_int(void) { - int x = 1; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"), - const_cast<char*>("3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_int(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 1); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 3); - gpr_cmdline_destroy(cl); -} - -static void test_2dash_eq_int(void) { - int x = 1; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_int(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 1); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 3); - gpr_cmdline_destroy(cl); -} - -static void test_simple_string(void) { - const char* x = nullptr; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"), - const_cast<char*>("3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_string(cl, "foo", nullptr, &x); - GPR_ASSERT(x == nullptr); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(0 == strcmp(x, "3")); - gpr_cmdline_destroy(cl); -} - -static void test_eq_string(void) { - const char* x = nullptr; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_string(cl, "foo", nullptr, &x); - GPR_ASSERT(x == nullptr); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(0 == strcmp(x, "3")); - gpr_cmdline_destroy(cl); -} - -static void test_2dash_string(void) { - const char* x = nullptr; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"), - const_cast<char*>("3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_string(cl, "foo", nullptr, &x); - GPR_ASSERT(x == nullptr); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(0 == strcmp(x, "3")); - gpr_cmdline_destroy(cl); -} - -static void test_2dash_eq_string(void) { - const char* x = nullptr; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_string(cl, "foo", nullptr, &x); - GPR_ASSERT(x == nullptr); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(0 == strcmp(x, "3")); - gpr_cmdline_destroy(cl); -} - -static void test_flag_on(void) { - int x = 2; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_flag(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 2); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 1); - gpr_cmdline_destroy(cl); -} - -static void test_flag_no(void) { - int x = 2; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--no-foo")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_flag(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 2); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 0); - gpr_cmdline_destroy(cl); -} - -static void test_flag_val_1(void) { - int x = 2; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=1")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_flag(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 2); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 1); - gpr_cmdline_destroy(cl); -} - -static void test_flag_val_0(void) { - int x = 2; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=0")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_flag(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 2); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 0); - gpr_cmdline_destroy(cl); -} - -static void test_flag_val_true(void) { - int x = 2; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=true")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_flag(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 2); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 1); - gpr_cmdline_destroy(cl); -} - -static void test_flag_val_false(void) { - int x = 2; - gpr_cmdline* cl; - char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=false")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_flag(cl, "foo", nullptr, &x); - GPR_ASSERT(x == 2); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 0); - gpr_cmdline_destroy(cl); -} - -static void test_many(void) { - const char* str = nullptr; - int x = 0; - int flag = 2; - gpr_cmdline* cl; - - char* args[] = {(char*)__FILE__, const_cast<char*>("--str"), - const_cast<char*>("hello"), const_cast<char*>("-x=4"), - const_cast<char*>("-no-flag")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(x == 4); - GPR_ASSERT(0 == strcmp(str, "hello")); - GPR_ASSERT(flag == 0); - gpr_cmdline_destroy(cl); -} - -static void extra_arg_cb(void* user_data, const char* arg) { - int* count = static_cast<int*>(user_data); - GPR_ASSERT(arg != nullptr); - GPR_ASSERT(strlen(arg) == 1); - GPR_ASSERT(arg[0] == 'a' + *count); - ++*count; -} - -static void test_extra(void) { - gpr_cmdline* cl; - int count = 0; - char* args[] = {(char*)__FILE__, const_cast<char*>("a"), - const_cast<char*>("b"), const_cast<char*>("c")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - &count); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(count == 3); - gpr_cmdline_destroy(cl); -} - -static void test_extra_dashdash(void) { - gpr_cmdline* cl; - int count = 0; - char* args[] = {(char*)__FILE__, const_cast<char*>("--"), - const_cast<char*>("a"), const_cast<char*>("b"), - const_cast<char*>("c")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - &count); - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); - GPR_ASSERT(count == 3); - gpr_cmdline_destroy(cl); -} - -static void test_usage(void) { - gpr_cmdline* cl; - - const char* str = nullptr; - int x = 0; - int flag = 2; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - nullptr); - +/* + * + * 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 <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/lib/gpr/useful.h" +#include "test/core/util/cmdline.h" +#include "test/core/util/test_config.h" + +#define LOG_TEST() gpr_log(GPR_INFO, "test at %s:%d", __FILE__, __LINE__) + +static void test_simple_int(void) { + int x = 1; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"), + const_cast<char*>("3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_int(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 1); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 3); + gpr_cmdline_destroy(cl); +} + +static void test_eq_int(void) { + int x = 1; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_int(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 1); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 3); + gpr_cmdline_destroy(cl); +} + +static void test_2dash_int(void) { + int x = 1; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"), + const_cast<char*>("3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_int(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 1); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 3); + gpr_cmdline_destroy(cl); +} + +static void test_2dash_eq_int(void) { + int x = 1; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_int(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 1); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 3); + gpr_cmdline_destroy(cl); +} + +static void test_simple_string(void) { + const char* x = nullptr; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("-foo"), + const_cast<char*>("3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_string(cl, "foo", nullptr, &x); + GPR_ASSERT(x == nullptr); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(0 == strcmp(x, "3")); + gpr_cmdline_destroy(cl); +} + +static void test_eq_string(void) { + const char* x = nullptr; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("-foo=3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_string(cl, "foo", nullptr, &x); + GPR_ASSERT(x == nullptr); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(0 == strcmp(x, "3")); + gpr_cmdline_destroy(cl); +} + +static void test_2dash_string(void) { + const char* x = nullptr; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo"), + const_cast<char*>("3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_string(cl, "foo", nullptr, &x); + GPR_ASSERT(x == nullptr); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(0 == strcmp(x, "3")); + gpr_cmdline_destroy(cl); +} + +static void test_2dash_eq_string(void) { + const char* x = nullptr; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=3")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_string(cl, "foo", nullptr, &x); + GPR_ASSERT(x == nullptr); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(0 == strcmp(x, "3")); + gpr_cmdline_destroy(cl); +} + +static void test_flag_on(void) { + int x = 2; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_flag(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 2); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 1); + gpr_cmdline_destroy(cl); +} + +static void test_flag_no(void) { + int x = 2; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--no-foo")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_flag(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 2); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 0); + gpr_cmdline_destroy(cl); +} + +static void test_flag_val_1(void) { + int x = 2; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=1")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_flag(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 2); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 1); + gpr_cmdline_destroy(cl); +} + +static void test_flag_val_0(void) { + int x = 2; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=0")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_flag(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 2); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 0); + gpr_cmdline_destroy(cl); +} + +static void test_flag_val_true(void) { + int x = 2; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=true")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_flag(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 2); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 1); + gpr_cmdline_destroy(cl); +} + +static void test_flag_val_false(void) { + int x = 2; + gpr_cmdline* cl; + char* args[] = {(char*)__FILE__, const_cast<char*>("--foo=false")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_flag(cl, "foo", nullptr, &x); + GPR_ASSERT(x == 2); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 0); + gpr_cmdline_destroy(cl); +} + +static void test_many(void) { + const char* str = nullptr; + int x = 0; + int flag = 2; + gpr_cmdline* cl; + + char* args[] = {(char*)__FILE__, const_cast<char*>("--str"), + const_cast<char*>("hello"), const_cast<char*>("-x=4"), + const_cast<char*>("-no-flag")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(x == 4); + GPR_ASSERT(0 == strcmp(str, "hello")); + GPR_ASSERT(flag == 0); + gpr_cmdline_destroy(cl); +} + +static void extra_arg_cb(void* user_data, const char* arg) { + int* count = static_cast<int*>(user_data); + GPR_ASSERT(arg != nullptr); + GPR_ASSERT(strlen(arg) == 1); + GPR_ASSERT(arg[0] == 'a' + *count); + ++*count; +} + +static void test_extra(void) { + gpr_cmdline* cl; + int count = 0; + char* args[] = {(char*)__FILE__, const_cast<char*>("a"), + const_cast<char*>("b"), const_cast<char*>("c")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + &count); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(count == 3); + gpr_cmdline_destroy(cl); +} + +static void test_extra_dashdash(void) { + gpr_cmdline* cl; + int count = 0; + char* args[] = {(char*)__FILE__, const_cast<char*>("--"), + const_cast<char*>("a"), const_cast<char*>("b"), + const_cast<char*>("c")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + &count); + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(args), args); + GPR_ASSERT(count == 3); + gpr_cmdline_destroy(cl); +} + +static void test_usage(void) { + gpr_cmdline* cl; + + const char* str = nullptr; + int x = 0; + int flag = 2; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + nullptr); + TString usage = gpr_cmdline_usage_string(cl, "test"); GPR_ASSERT(usage == "Usage: test [--str=string] [--x=int] " "[--flag|--no-flag] [file...]\n"); - - usage = gpr_cmdline_usage_string(cl, "/foo/test"); + + usage = gpr_cmdline_usage_string(cl, "/foo/test"); GPR_ASSERT(usage == "Usage: test [--str=string] [--x=int] " "[--flag|--no-flag] [file...]\n"); - - gpr_cmdline_destroy(cl); -} - -static void test_help(void) { - gpr_cmdline* cl; - - const char* str = nullptr; - int x = 0; - int flag = 2; - - char* help[] = {(char*)__FILE__, const_cast<char*>("-h")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_set_survive_failure(cl); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - nullptr); - - GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(help), help)); - - gpr_cmdline_destroy(cl); -} - -static void test_badargs1(void) { - gpr_cmdline* cl; - - const char* str = nullptr; - int x = 0; - int flag = 2; - - char* bad_arg_name[] = {(char*)__FILE__, const_cast<char*>("--y")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_set_survive_failure(cl); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - nullptr); - - GPR_ASSERT(0 == - gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_arg_name), bad_arg_name)); - - gpr_cmdline_destroy(cl); -} - -static void test_badargs2(void) { - gpr_cmdline* cl; - - const char* str = nullptr; - int x = 0; - int flag = 2; - - char* bad_int_value[] = {(char*)__FILE__, const_cast<char*>("--x"), - const_cast<char*>("henry")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_set_survive_failure(cl); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - nullptr); - - GPR_ASSERT( - 0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_int_value), bad_int_value)); - - gpr_cmdline_destroy(cl); -} - -static void test_badargs3(void) { - gpr_cmdline* cl; - - const char* str = nullptr; - int x = 0; - int flag = 2; - - char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--flag=henry")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_set_survive_failure(cl); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - nullptr); - - GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value), - bad_bool_value)); - - gpr_cmdline_destroy(cl); -} - -static void test_badargs4(void) { - gpr_cmdline* cl; - - const char* str = nullptr; - int x = 0; - int flag = 2; - - char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--no-str")}; - - LOG_TEST(); - - cl = gpr_cmdline_create(nullptr); - gpr_cmdline_set_survive_failure(cl); - gpr_cmdline_add_string(cl, "str", nullptr, &str); - gpr_cmdline_add_int(cl, "x", nullptr, &x); - gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); - gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, - nullptr); - - GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value), - bad_bool_value)); - - gpr_cmdline_destroy(cl); -} - -int main(int argc, char** argv) { - grpc::testing::TestEnvironment env(argc, argv); - test_simple_int(); - test_eq_int(); - test_2dash_int(); - test_2dash_eq_int(); - test_simple_string(); - test_eq_string(); - test_2dash_string(); - test_2dash_eq_string(); - test_flag_on(); - test_flag_no(); - test_flag_val_1(); - test_flag_val_0(); - test_flag_val_true(); - test_flag_val_false(); - test_many(); - test_extra(); - test_extra_dashdash(); - test_usage(); - test_help(); - test_badargs1(); - test_badargs2(); - test_badargs3(); - test_badargs4(); - return 0; -} + + gpr_cmdline_destroy(cl); +} + +static void test_help(void) { + gpr_cmdline* cl; + + const char* str = nullptr; + int x = 0; + int flag = 2; + + char* help[] = {(char*)__FILE__, const_cast<char*>("-h")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_set_survive_failure(cl); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + nullptr); + + GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(help), help)); + + gpr_cmdline_destroy(cl); +} + +static void test_badargs1(void) { + gpr_cmdline* cl; + + const char* str = nullptr; + int x = 0; + int flag = 2; + + char* bad_arg_name[] = {(char*)__FILE__, const_cast<char*>("--y")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_set_survive_failure(cl); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + nullptr); + + GPR_ASSERT(0 == + gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_arg_name), bad_arg_name)); + + gpr_cmdline_destroy(cl); +} + +static void test_badargs2(void) { + gpr_cmdline* cl; + + const char* str = nullptr; + int x = 0; + int flag = 2; + + char* bad_int_value[] = {(char*)__FILE__, const_cast<char*>("--x"), + const_cast<char*>("henry")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_set_survive_failure(cl); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + nullptr); + + GPR_ASSERT( + 0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_int_value), bad_int_value)); + + gpr_cmdline_destroy(cl); +} + +static void test_badargs3(void) { + gpr_cmdline* cl; + + const char* str = nullptr; + int x = 0; + int flag = 2; + + char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--flag=henry")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_set_survive_failure(cl); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + nullptr); + + GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value), + bad_bool_value)); + + gpr_cmdline_destroy(cl); +} + +static void test_badargs4(void) { + gpr_cmdline* cl; + + const char* str = nullptr; + int x = 0; + int flag = 2; + + char* bad_bool_value[] = {(char*)__FILE__, const_cast<char*>("--no-str")}; + + LOG_TEST(); + + cl = gpr_cmdline_create(nullptr); + gpr_cmdline_set_survive_failure(cl); + gpr_cmdline_add_string(cl, "str", nullptr, &str); + gpr_cmdline_add_int(cl, "x", nullptr, &x); + gpr_cmdline_add_flag(cl, "flag", nullptr, &flag); + gpr_cmdline_on_extra_arg(cl, "file", "filenames to process", extra_arg_cb, + nullptr); + + GPR_ASSERT(0 == gpr_cmdline_parse(cl, GPR_ARRAY_SIZE(bad_bool_value), + bad_bool_value)); + + gpr_cmdline_destroy(cl); +} + +int main(int argc, char** argv) { + grpc::testing::TestEnvironment env(argc, argv); + test_simple_int(); + test_eq_int(); + test_2dash_int(); + test_2dash_eq_int(); + test_simple_string(); + test_eq_string(); + test_2dash_string(); + test_2dash_eq_string(); + test_flag_on(); + test_flag_no(); + test_flag_val_1(); + test_flag_val_0(); + test_flag_val_true(); + test_flag_val_false(); + test_many(); + test_extra(); + test_extra_dashdash(); + test_usage(); + test_help(); + test_badargs1(); + test_badargs2(); + test_badargs3(); + test_badargs4(); + return 0; +} diff --git a/contrib/libs/grpc/test/core/util/debugger_macros.cc b/contrib/libs/grpc/test/core/util/debugger_macros.cc index b866cfd647..fde68f3217 100644 --- a/contrib/libs/grpc/test/core/util/debugger_macros.cc +++ b/contrib/libs/grpc/test/core/util/debugger_macros.cc @@ -1,57 +1,57 @@ -/* - * - * 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. - * - */ - -/* - * A collection of 'macros' that help navigating the grpc object hierarchy - * Not intended to be robust for main-line code, often cuts across abstraction - * boundaries. - */ -#include <stdio.h> - -#include "src/core/ext/filters/client_channel/client_channel.h" -#include "src/core/ext/transport/chttp2/transport/internal.h" -#include "src/core/lib/channel/connected_channel.h" -#include "src/core/lib/surface/call.h" - -grpc_stream* grpc_transport_stream_from_call(grpc_call* call) { - grpc_call_stack* cs = grpc_call_get_call_stack(call); - for (;;) { - grpc_call_element* el = grpc_call_stack_element(cs, cs->count - 1); - if (el->filter == &grpc_client_channel_filter) { - grpc_core::RefCountedPtr<grpc_core::SubchannelCall> scc = - grpc_client_channel_get_subchannel_call(el); - if (scc == nullptr) { - fprintf(stderr, "No subchannel-call"); - fflush(stderr); - return nullptr; - } - cs = scc->GetCallStack(); - } else if (el->filter == &grpc_connected_filter) { - return grpc_connected_channel_get_stream(el); - } else { - fprintf(stderr, "Unrecognized filter: %s", el->filter->name); - fflush(stderr); - return nullptr; - } - } -} - -grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call) { - return reinterpret_cast<grpc_chttp2_stream*>( - grpc_transport_stream_from_call(call)); -} +/* + * + * 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. + * + */ + +/* + * A collection of 'macros' that help navigating the grpc object hierarchy + * Not intended to be robust for main-line code, often cuts across abstraction + * boundaries. + */ +#include <stdio.h> + +#include "src/core/ext/filters/client_channel/client_channel.h" +#include "src/core/ext/transport/chttp2/transport/internal.h" +#include "src/core/lib/channel/connected_channel.h" +#include "src/core/lib/surface/call.h" + +grpc_stream* grpc_transport_stream_from_call(grpc_call* call) { + grpc_call_stack* cs = grpc_call_get_call_stack(call); + for (;;) { + grpc_call_element* el = grpc_call_stack_element(cs, cs->count - 1); + if (el->filter == &grpc_client_channel_filter) { + grpc_core::RefCountedPtr<grpc_core::SubchannelCall> scc = + grpc_client_channel_get_subchannel_call(el); + if (scc == nullptr) { + fprintf(stderr, "No subchannel-call"); + fflush(stderr); + return nullptr; + } + cs = scc->GetCallStack(); + } else if (el->filter == &grpc_connected_filter) { + return grpc_connected_channel_get_stream(el); + } else { + fprintf(stderr, "Unrecognized filter: %s", el->filter->name); + fflush(stderr); + return nullptr; + } + } +} + +grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call) { + return reinterpret_cast<grpc_chttp2_stream*>( + grpc_transport_stream_from_call(call)); +} diff --git a/contrib/libs/grpc/test/core/util/debugger_macros.h b/contrib/libs/grpc/test/core/util/debugger_macros.h index a5a603661b..71228c6e87 100644 --- a/contrib/libs/grpc/test/core/util/debugger_macros.h +++ b/contrib/libs/grpc/test/core/util/debugger_macros.h @@ -1,27 +1,27 @@ -/* - * - * 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. - * - */ - -#ifndef GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H -#define GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H - -#include "src/core/ext/transport/chttp2/transport/internal.h" -#include "src/core/lib/surface/call.h" - -grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call); - -#endif /* GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_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. + * + */ + +#ifndef GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H +#define GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H + +#include "src/core/ext/transport/chttp2/transport/internal.h" +#include "src/core/lib/surface/call.h" + +grpc_chttp2_stream* grpc_chttp2_stream_from_call(grpc_call* call); + +#endif /* GRPC_TEST_CORE_UTIL_DEBUGGER_MACROS_H */ diff --git a/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc b/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc index ad7bad6fe5..99ab45120d 100644 --- a/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc +++ b/contrib/libs/grpc/test/core/util/fuzzer_corpus_test.cc @@ -1,169 +1,169 @@ -/* - * - * 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 <stdbool.h> - -#include <dirent.h> -#include <gflags/gflags.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <gtest/gtest.h> -#include <stdio.h> -#include <sys/types.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 <stdbool.h> + +#include <dirent.h> +#include <gflags/gflags.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <gtest/gtest.h> +#include <stdio.h> +#include <sys/types.h> + #include <grpc/grpc.h> -#include "src/core/lib/gpr/env.h" -#include "src/core/lib/iomgr/load_file.h" -#include "test/core/util/test_config.h" -#include "test/cpp/util/test_config.h" - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); -extern bool squelch; -extern bool leak_check; - -// In some distros, gflags is in the namespace google, and in some others, -// in gflags. This hack is enabling us to find both. -namespace google {} -namespace gflags {} -using namespace google; -using namespace gflags; - -DEFINE_string(file, "", "Use this file as test data"); -DEFINE_string(directory, "", "Use this directory as test data"); - +#include "src/core/lib/gpr/env.h" +#include "src/core/lib/iomgr/load_file.h" +#include "test/core/util/test_config.h" +#include "test/cpp/util/test_config.h" + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); +extern bool squelch; +extern bool leak_check; + +// In some distros, gflags is in the namespace google, and in some others, +// in gflags. This hack is enabling us to find both. +namespace google {} +namespace gflags {} +using namespace google; +using namespace gflags; + +DEFINE_string(file, "", "Use this file as test data"); +DEFINE_string(directory, "", "Use this directory as test data"); + class FuzzerCorpusTest : public ::testing::TestWithParam<TString> {}; - -TEST_P(FuzzerCorpusTest, RunOneExample) { + +TEST_P(FuzzerCorpusTest, RunOneExample) { // Need to call grpc_init() here to use a slice, but need to shut it // down before calling LLVMFuzzerTestOneInput(), because most // implementations of that function will initialize and shutdown gRPC // internally. grpc_init(); - gpr_log(GPR_DEBUG, "Example file: %s", GetParam().c_str()); - grpc_slice buffer; - squelch = false; - leak_check = false; - GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", - grpc_load_file(GetParam().c_str(), 0, &buffer))); + gpr_log(GPR_DEBUG, "Example file: %s", GetParam().c_str()); + grpc_slice buffer; + squelch = false; + leak_check = false; + GPR_ASSERT(GRPC_LOG_IF_ERROR("load_file", + grpc_load_file(GetParam().c_str(), 0, &buffer))); size_t length = GRPC_SLICE_LENGTH(buffer); void* data = gpr_malloc(length); memcpy(data, GPR_SLICE_START_PTR(buffer), length); - grpc_slice_unref(buffer); + grpc_slice_unref(buffer); grpc_shutdown_blocking(); LLVMFuzzerTestOneInput(static_cast<uint8_t*>(data), length); gpr_free(data); -} - -class ExampleGenerator +} + +class ExampleGenerator : public ::testing::internal::ParamGeneratorInterface<TString> { - public: + public: virtual ::testing::internal::ParamIteratorInterface<TString>* Begin() - const; + const; virtual ::testing::internal::ParamIteratorInterface<TString>* End() const; - - private: - void Materialize() const { - if (examples_.empty()) { - if (!FLAGS_file.empty()) examples_.push_back(FLAGS_file); - if (!FLAGS_directory.empty()) { - char* test_srcdir = gpr_getenv("TEST_SRCDIR"); + + private: + void Materialize() const { + if (examples_.empty()) { + if (!FLAGS_file.empty()) examples_.push_back(FLAGS_file); + if (!FLAGS_directory.empty()) { + char* test_srcdir = gpr_getenv("TEST_SRCDIR"); gpr_log(GPR_DEBUG, "test_srcdir=\"%s\"", test_srcdir); TString directory = FLAGS_directory; - if (test_srcdir != nullptr) { + if (test_srcdir != nullptr) { directory = test_srcdir + TString("/com_github_grpc_grpc/") + directory; - } + } gpr_log(GPR_DEBUG, "Using corpus directory: %s", directory.c_str()); - DIR* dp; - struct dirent* ep; + DIR* dp; + struct dirent* ep; dp = opendir(directory.c_str()); - - if (dp != nullptr) { - while ((ep = readdir(dp)) != nullptr) { + + if (dp != nullptr) { + while ((ep = readdir(dp)) != nullptr) { if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0) { examples_.push_back(directory + "/" + ep->d_name); - } - } - - (void)closedir(dp); - } else { - perror("Couldn't open the directory"); - abort(); - } - gpr_free(test_srcdir); - } - } + } + } + + (void)closedir(dp); + } else { + perror("Couldn't open the directory"); + abort(); + } + gpr_free(test_srcdir); + } + } // Make sure we don't succeed without doing anything, which caused // us to be blind to our fuzzers not running for 9 months. GPR_ASSERT(!examples_.empty()); - } - + } + mutable std::vector<TString> examples_; -}; - -class ExampleIterator +}; + +class ExampleIterator : public ::testing::internal::ParamIteratorInterface<TString> { - public: - ExampleIterator(const ExampleGenerator& base_, + public: + ExampleIterator(const ExampleGenerator& base_, std::vector<TString>::const_iterator begin) - : base_(base_), begin_(begin), current_(begin) {} - - virtual const ExampleGenerator* BaseGenerator() const { return &base_; } - - virtual void Advance() { current_++; } - virtual ExampleIterator* Clone() const { return new ExampleIterator(*this); } + : base_(base_), begin_(begin), current_(begin) {} + + virtual const ExampleGenerator* BaseGenerator() const { return &base_; } + + virtual void Advance() { current_++; } + virtual ExampleIterator* Clone() const { return new ExampleIterator(*this); } virtual const TString* Current() const { return &*current_; } - + virtual bool Equals(const ParamIteratorInterface<TString>& other) const { - return &base_ == other.BaseGenerator() && - current_ == dynamic_cast<const ExampleIterator*>(&other)->current_; - } - - private: - ExampleIterator(const ExampleIterator& other) - : base_(other.base_), begin_(other.begin_), current_(other.current_) {} - - const ExampleGenerator& base_; + return &base_ == other.BaseGenerator() && + current_ == dynamic_cast<const ExampleIterator*>(&other)->current_; + } + + private: + ExampleIterator(const ExampleIterator& other) + : base_(other.base_), begin_(other.begin_), current_(other.current_) {} + + const ExampleGenerator& base_; const std::vector<TString>::const_iterator begin_; std::vector<TString>::const_iterator current_; -}; - +}; + ::testing::internal::ParamIteratorInterface<TString>* -ExampleGenerator::Begin() const { - Materialize(); - return new ExampleIterator(*this, examples_.begin()); -} - +ExampleGenerator::Begin() const { + Materialize(); + return new ExampleIterator(*this, examples_.begin()); +} + ::testing::internal::ParamIteratorInterface<TString>* -ExampleGenerator::End() const { - Materialize(); - return new ExampleIterator(*this, examples_.end()); -} - -INSTANTIATE_TEST_SUITE_P( - CorpusExamples, FuzzerCorpusTest, +ExampleGenerator::End() const { + Materialize(); + return new ExampleIterator(*this, examples_.end()); +} + +INSTANTIATE_TEST_SUITE_P( + CorpusExamples, FuzzerCorpusTest, ::testing::internal::ParamGenerator<TString>(new ExampleGenerator)); - -int main(int argc, char** argv) { - grpc::testing::TestEnvironment env(argc, argv); + +int main(int argc, char** argv) { + grpc::testing::TestEnvironment env(argc, argv); grpc::testing::InitTest(&argc, &argv, true); - ::testing::InitGoogleTest(&argc, argv); - - return RUN_ALL_TESTS(); -} + ::testing::InitGoogleTest(&argc, argv); + + return RUN_ALL_TESTS(); +} diff --git a/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh b/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh index 7ffd96f006..7c471afcc2 100755 --- a/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh +++ b/contrib/libs/grpc/test/core/util/fuzzer_one_entry_runner.sh @@ -1,18 +1,18 @@ -#!/bin/sh - -# Test runner for fuzzer tests from bazel - -# 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. -"$1" "$2" +#!/bin/sh + +# Test runner for fuzzer tests from bazel + +# 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. +"$1" "$2" diff --git a/contrib/libs/grpc/test/core/util/fuzzer_util.cc b/contrib/libs/grpc/test/core/util/fuzzer_util.cc index 0601ae9356..29c9b8875f 100644 --- a/contrib/libs/grpc/test/core/util/fuzzer_util.cc +++ b/contrib/libs/grpc/test/core/util/fuzzer_util.cc @@ -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. - * - */ - -#include "test/core/util/fuzzer_util.h" - -#include <grpc/support/alloc.h> - -#include "src/core/lib/gpr/useful.h" - -namespace grpc_core { -namespace testing { - -uint8_t grpc_fuzzer_get_next_byte(input_stream* inp) { - if (inp->cur == inp->end) { - return 0; - } - return *inp->cur++; -} - -char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special) { - char* str = nullptr; - size_t cap = 0; - size_t sz = 0; - char c; - do { - if (cap == sz) { - cap = GPR_MAX(3 * cap / 2, cap + 8); - str = static_cast<char*>(gpr_realloc(str, cap)); - } - c = static_cast<char>(grpc_fuzzer_get_next_byte(inp)); - str[sz++] = c; - } while (c != 0 && c != 1); - if (special != nullptr) { - *special = (c == 1); - } - if (c == 1) { - str[sz - 1] = 0; - } - return str; -} - -uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp) { - uint8_t b = grpc_fuzzer_get_next_byte(inp); - uint32_t x = b & 0x7f; - if (b & 0x80) { - x <<= 7; - b = grpc_fuzzer_get_next_byte(inp); - x |= b & 0x7f; - if (b & 0x80) { - x <<= 7; - b = grpc_fuzzer_get_next_byte(inp); - x |= b & 0x7f; - if (b & 0x80) { - x <<= 7; - b = grpc_fuzzer_get_next_byte(inp); - x |= b & 0x7f; - if (b & 0x80) { - x = (x << 4) | (grpc_fuzzer_get_next_byte(inp) & 0x0f); - } - } - } - } - return x; -} - -} // namespace testing -} // 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 "test/core/util/fuzzer_util.h" + +#include <grpc/support/alloc.h> + +#include "src/core/lib/gpr/useful.h" + +namespace grpc_core { +namespace testing { + +uint8_t grpc_fuzzer_get_next_byte(input_stream* inp) { + if (inp->cur == inp->end) { + return 0; + } + return *inp->cur++; +} + +char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special) { + char* str = nullptr; + size_t cap = 0; + size_t sz = 0; + char c; + do { + if (cap == sz) { + cap = GPR_MAX(3 * cap / 2, cap + 8); + str = static_cast<char*>(gpr_realloc(str, cap)); + } + c = static_cast<char>(grpc_fuzzer_get_next_byte(inp)); + str[sz++] = c; + } while (c != 0 && c != 1); + if (special != nullptr) { + *special = (c == 1); + } + if (c == 1) { + str[sz - 1] = 0; + } + return str; +} + +uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp) { + uint8_t b = grpc_fuzzer_get_next_byte(inp); + uint32_t x = b & 0x7f; + if (b & 0x80) { + x <<= 7; + b = grpc_fuzzer_get_next_byte(inp); + x |= b & 0x7f; + if (b & 0x80) { + x <<= 7; + b = grpc_fuzzer_get_next_byte(inp); + x |= b & 0x7f; + if (b & 0x80) { + x <<= 7; + b = grpc_fuzzer_get_next_byte(inp); + x |= b & 0x7f; + if (b & 0x80) { + x = (x << 4) | (grpc_fuzzer_get_next_byte(inp) & 0x0f); + } + } + } + } + return x; +} + +} // namespace testing +} // namespace grpc_core diff --git a/contrib/libs/grpc/test/core/util/fuzzer_util.h b/contrib/libs/grpc/test/core/util/fuzzer_util.h index 7e2d74831c..0e938399a1 100644 --- a/contrib/libs/grpc/test/core/util/fuzzer_util.h +++ b/contrib/libs/grpc/test/core/util/fuzzer_util.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_TEST_CORE_UTIL_FUZZER_UTIL_H -#define GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H - -#include <stdint.h> - -namespace grpc_core { - -namespace testing { - -// Main struct for input_stream. It allows easy access to input -// bytes, and allows reading a little past the end(avoiding -// needing to check everywhere). -typedef struct { - const uint8_t* cur; - const uint8_t* end; -} input_stream; - -// get a byte from an input stream. -uint8_t grpc_fuzzer_get_next_byte(input_stream* inp); - -// get a string and boolean values (if special is not null) from an input -// stream. -char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special); - -// get a uint32 value from an input stream. -uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp); - -} // namespace testing -} // namespace grpc_core - -#endif /* GRPC_TEST_CORE_UTIL_FUZZER_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_TEST_CORE_UTIL_FUZZER_UTIL_H +#define GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H + +#include <stdint.h> + +namespace grpc_core { + +namespace testing { + +// Main struct for input_stream. It allows easy access to input +// bytes, and allows reading a little past the end(avoiding +// needing to check everywhere). +typedef struct { + const uint8_t* cur; + const uint8_t* end; +} input_stream; + +// get a byte from an input stream. +uint8_t grpc_fuzzer_get_next_byte(input_stream* inp); + +// get a string and boolean values (if special is not null) from an input +// stream. +char* grpc_fuzzer_get_next_string(input_stream* inp, bool* special); + +// get a uint32 value from an input stream. +uint32_t grpc_fuzzer_get_next_uint32(input_stream* inp); + +} // namespace testing +} // namespace grpc_core + +#endif /* GRPC_TEST_CORE_UTIL_FUZZER_UTIL_H */ diff --git a/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl b/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl index e6d7053374..99594b29e1 100644 --- a/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl +++ b/contrib/libs/grpc/test/core/util/grpc_fuzzer.bzl @@ -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. - -load("//bazel:grpc_build_system.bzl", "grpc_cc_test") - +# 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. + +load("//bazel:grpc_build_system.bzl", "grpc_cc_test") + def grpc_fuzzer(name, corpus, srcs = [], deps = [], data = [], size = "large", **kwargs): - grpc_cc_test( - name = name, - srcs = srcs, - deps = deps + ["//test/core/util:fuzzer_corpus_test"], + grpc_cc_test( + name = name, + srcs = srcs, + deps = deps + ["//test/core/util:fuzzer_corpus_test"], data = data + native.glob([corpus + "/**"]), - external_deps = [ - "gtest", - ], - size = size, - args = ["--directory=" + native.package_name() + "/" + corpus], - **kwargs - ) + external_deps = [ + "gtest", + ], + size = size, + args = ["--directory=" + native.package_name() + "/" + corpus], + **kwargs + ) diff --git a/contrib/libs/grpc/test/core/util/grpc_profiler.cc b/contrib/libs/grpc/test/core/util/grpc_profiler.cc index 6ed0d14c9f..88f233598b 100644 --- a/contrib/libs/grpc/test/core/util/grpc_profiler.cc +++ b/contrib/libs/grpc/test/core/util/grpc_profiler.cc @@ -1,45 +1,45 @@ -/* - * - * 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 "test/core/util/grpc_profiler.h" - -#if GRPC_HAVE_PERFTOOLS -#include <gperftools/profiler.h> - -void grpc_profiler_start(const char* filename) { ProfilerStart(filename); } - -void grpc_profiler_stop() { ProfilerStop(); } -#else -#include <grpc/support/log.h> - -void grpc_profiler_start(const char* filename) { - static int printed_warning = 0; - if (!printed_warning) { - gpr_log(GPR_DEBUG, - "You do not have google-perftools installed, profiling is disabled " - "[for %s]", - filename); - gpr_log(GPR_DEBUG, - "To install on ubuntu: sudo apt-get install google-perftools " - "libgoogle-perftools-dev"); - printed_warning = 1; - } -} - -void grpc_profiler_stop(void) {} -#endif +/* + * + * 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 "test/core/util/grpc_profiler.h" + +#if GRPC_HAVE_PERFTOOLS +#include <gperftools/profiler.h> + +void grpc_profiler_start(const char* filename) { ProfilerStart(filename); } + +void grpc_profiler_stop() { ProfilerStop(); } +#else +#include <grpc/support/log.h> + +void grpc_profiler_start(const char* filename) { + static int printed_warning = 0; + if (!printed_warning) { + gpr_log(GPR_DEBUG, + "You do not have google-perftools installed, profiling is disabled " + "[for %s]", + filename); + gpr_log(GPR_DEBUG, + "To install on ubuntu: sudo apt-get install google-perftools " + "libgoogle-perftools-dev"); + printed_warning = 1; + } +} + +void grpc_profiler_stop(void) {} +#endif diff --git a/contrib/libs/grpc/test/core/util/grpc_profiler.h b/contrib/libs/grpc/test/core/util/grpc_profiler.h index ca715c22bc..f9ddd2242e 100644 --- a/contrib/libs/grpc/test/core/util/grpc_profiler.h +++ b/contrib/libs/grpc/test/core/util/grpc_profiler.h @@ -1,25 +1,25 @@ -/* - * - * 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_TEST_CORE_UTIL_GRPC_PROFILER_H -#define GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H - -void grpc_profiler_start(const char* filename); -void grpc_profiler_stop(); - -#endif /* GRPC_TEST_CORE_UTIL_GRPC_PROFILER_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_TEST_CORE_UTIL_GRPC_PROFILER_H +#define GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H + +void grpc_profiler_start(const char* filename); +void grpc_profiler_stop(); + +#endif /* GRPC_TEST_CORE_UTIL_GRPC_PROFILER_H */ diff --git a/contrib/libs/grpc/test/core/util/histogram.cc b/contrib/libs/grpc/test/core/util/histogram.cc index 3b17818873..f028ac404e 100644 --- a/contrib/libs/grpc/test/core/util/histogram.cc +++ b/contrib/libs/grpc/test/core/util/histogram.cc @@ -1,230 +1,230 @@ -/* - * - * 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 "test/core/util/histogram.h" - -#include <math.h> -#include <stddef.h> -#include <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/port_platform.h> - -#include "src/core/lib/gpr/useful.h" - -/* Histograms are stored with exponentially increasing bucket sizes. - The first bucket is [0, m) where m = 1 + resolution - Bucket n (n>=1) contains [m**n, m**(n+1)) - There are sufficient buckets to reach max_bucket_start */ - -struct grpc_histogram { - /* Sum of all values seen so far */ - double sum; - /* Sum of squares of all values seen so far */ - double sum_of_squares; - /* number of values seen so far */ - double count; - /* m in the description */ - double multiplier; - double one_on_log_multiplier; - /* minimum value seen */ - double min_seen; - /* maximum value seen */ - double max_seen; - /* maximum representable value */ - double max_possible; - /* number of buckets */ - size_t num_buckets; - /* the buckets themselves */ - uint32_t* buckets; -}; - -/* determine a bucket index given a value - does no bounds checking */ -static size_t bucket_for_unchecked(grpc_histogram* h, double x) { - return static_cast<size_t>(log(x) * h->one_on_log_multiplier); -} - -/* bounds checked version of the above */ -static size_t bucket_for(grpc_histogram* h, double x) { - size_t bucket = bucket_for_unchecked(h, GPR_CLAMP(x, 1.0, h->max_possible)); - GPR_ASSERT(bucket < h->num_buckets); - return bucket; -} - -/* at what value does a bucket start? */ -static double bucket_start(grpc_histogram* h, double x) { - return pow(h->multiplier, x); -} - -grpc_histogram* grpc_histogram_create(double resolution, - double max_bucket_start) { - grpc_histogram* h = - static_cast<grpc_histogram*>(gpr_malloc(sizeof(grpc_histogram))); - GPR_ASSERT(resolution > 0.0); - GPR_ASSERT(max_bucket_start > resolution); - h->sum = 0.0; - h->sum_of_squares = 0.0; - h->multiplier = 1.0 + resolution; - h->one_on_log_multiplier = 1.0 / log(1.0 + resolution); - h->max_possible = max_bucket_start; - h->count = 0.0; - h->min_seen = max_bucket_start; - h->max_seen = 0.0; - h->num_buckets = bucket_for_unchecked(h, max_bucket_start) + 1; - GPR_ASSERT(h->num_buckets > 1); - GPR_ASSERT(h->num_buckets < 100000000); - h->buckets = - static_cast<uint32_t*>(gpr_zalloc(sizeof(uint32_t) * h->num_buckets)); - return h; -} - -void grpc_histogram_destroy(grpc_histogram* h) { - gpr_free(h->buckets); - gpr_free(h); -} - -void grpc_histogram_add(grpc_histogram* h, double x) { - h->sum += x; - h->sum_of_squares += x * x; - h->count++; - if (x < h->min_seen) { - h->min_seen = x; - } - if (x > h->max_seen) { - h->max_seen = x; - } - h->buckets[bucket_for(h, x)]++; -} - -int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src) { - if ((dst->num_buckets != src->num_buckets) || - (dst->multiplier != src->multiplier)) { - /* Fail because these histograms don't match */ - return 0; - } - grpc_histogram_merge_contents(dst, src->buckets, src->num_buckets, - src->min_seen, src->max_seen, src->sum, - src->sum_of_squares, src->count); - return 1; -} - -void grpc_histogram_merge_contents(grpc_histogram* dst, const uint32_t* data, - size_t data_count, double min_seen, - double max_seen, double sum, - double sum_of_squares, double count) { - size_t i; - GPR_ASSERT(dst->num_buckets == data_count); - dst->sum += sum; - dst->sum_of_squares += sum_of_squares; - dst->count += count; - if (min_seen < dst->min_seen) { - dst->min_seen = min_seen; - } - if (max_seen > dst->max_seen) { - dst->max_seen = max_seen; - } - for (i = 0; i < dst->num_buckets; i++) { - dst->buckets[i] += data[i]; - } -} - -static double threshold_for_count_below(grpc_histogram* h, double count_below) { - double count_so_far; - double lower_bound; - double upper_bound; - size_t lower_idx; - size_t upper_idx; - - if (h->count == 0) { - return 0.0; - } - - if (count_below <= 0) { - return h->min_seen; - } - if (count_below >= h->count) { - return h->max_seen; - } - - /* find the lowest bucket that gets us above count_below */ - count_so_far = 0.0; - for (lower_idx = 0; lower_idx < h->num_buckets; lower_idx++) { - count_so_far += h->buckets[lower_idx]; - if (count_so_far >= count_below) { - break; - } - } - if (count_so_far == count_below) { - /* this bucket hits the threshold exactly... we should be midway through - any run of zero values following the bucket */ - for (upper_idx = lower_idx + 1; upper_idx < h->num_buckets; upper_idx++) { - if (h->buckets[upper_idx]) { - break; - } - } - return (bucket_start(h, static_cast<double>(lower_idx)) + - bucket_start(h, static_cast<double>(upper_idx))) / - 2.0; - } else { - /* treat values as uniform throughout the bucket, and find where this value - should lie */ - lower_bound = bucket_start(h, static_cast<double>(lower_idx)); - upper_bound = bucket_start(h, static_cast<double>(lower_idx + 1)); - return GPR_CLAMP(upper_bound - (upper_bound - lower_bound) * - (count_so_far - count_below) / - h->buckets[lower_idx], - h->min_seen, h->max_seen); - } -} - -double grpc_histogram_percentile(grpc_histogram* h, double percentile) { - return threshold_for_count_below(h, h->count * percentile / 100.0); -} - -double grpc_histogram_mean(grpc_histogram* h) { - GPR_ASSERT(h->count != 0); - return h->sum / h->count; -} - -double grpc_histogram_stddev(grpc_histogram* h) { - return sqrt(grpc_histogram_variance(h)); -} - -double grpc_histogram_variance(grpc_histogram* h) { - if (h->count == 0) return 0.0; - return (h->sum_of_squares * h->count - h->sum * h->sum) / - (h->count * h->count); -} - -double grpc_histogram_maximum(grpc_histogram* h) { return h->max_seen; } - -double grpc_histogram_minimum(grpc_histogram* h) { return h->min_seen; } - -double grpc_histogram_count(grpc_histogram* h) { return h->count; } - -double grpc_histogram_sum(grpc_histogram* h) { return h->sum; } - -double grpc_histogram_sum_of_squares(grpc_histogram* h) { - return h->sum_of_squares; -} - -const uint32_t* grpc_histogram_get_contents(grpc_histogram* h, size_t* size) { - *size = h->num_buckets; - return h->buckets; -} +/* + * + * 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 "test/core/util/histogram.h" + +#include <math.h> +#include <stddef.h> +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/port_platform.h> + +#include "src/core/lib/gpr/useful.h" + +/* Histograms are stored with exponentially increasing bucket sizes. + The first bucket is [0, m) where m = 1 + resolution + Bucket n (n>=1) contains [m**n, m**(n+1)) + There are sufficient buckets to reach max_bucket_start */ + +struct grpc_histogram { + /* Sum of all values seen so far */ + double sum; + /* Sum of squares of all values seen so far */ + double sum_of_squares; + /* number of values seen so far */ + double count; + /* m in the description */ + double multiplier; + double one_on_log_multiplier; + /* minimum value seen */ + double min_seen; + /* maximum value seen */ + double max_seen; + /* maximum representable value */ + double max_possible; + /* number of buckets */ + size_t num_buckets; + /* the buckets themselves */ + uint32_t* buckets; +}; + +/* determine a bucket index given a value - does no bounds checking */ +static size_t bucket_for_unchecked(grpc_histogram* h, double x) { + return static_cast<size_t>(log(x) * h->one_on_log_multiplier); +} + +/* bounds checked version of the above */ +static size_t bucket_for(grpc_histogram* h, double x) { + size_t bucket = bucket_for_unchecked(h, GPR_CLAMP(x, 1.0, h->max_possible)); + GPR_ASSERT(bucket < h->num_buckets); + return bucket; +} + +/* at what value does a bucket start? */ +static double bucket_start(grpc_histogram* h, double x) { + return pow(h->multiplier, x); +} + +grpc_histogram* grpc_histogram_create(double resolution, + double max_bucket_start) { + grpc_histogram* h = + static_cast<grpc_histogram*>(gpr_malloc(sizeof(grpc_histogram))); + GPR_ASSERT(resolution > 0.0); + GPR_ASSERT(max_bucket_start > resolution); + h->sum = 0.0; + h->sum_of_squares = 0.0; + h->multiplier = 1.0 + resolution; + h->one_on_log_multiplier = 1.0 / log(1.0 + resolution); + h->max_possible = max_bucket_start; + h->count = 0.0; + h->min_seen = max_bucket_start; + h->max_seen = 0.0; + h->num_buckets = bucket_for_unchecked(h, max_bucket_start) + 1; + GPR_ASSERT(h->num_buckets > 1); + GPR_ASSERT(h->num_buckets < 100000000); + h->buckets = + static_cast<uint32_t*>(gpr_zalloc(sizeof(uint32_t) * h->num_buckets)); + return h; +} + +void grpc_histogram_destroy(grpc_histogram* h) { + gpr_free(h->buckets); + gpr_free(h); +} + +void grpc_histogram_add(grpc_histogram* h, double x) { + h->sum += x; + h->sum_of_squares += x * x; + h->count++; + if (x < h->min_seen) { + h->min_seen = x; + } + if (x > h->max_seen) { + h->max_seen = x; + } + h->buckets[bucket_for(h, x)]++; +} + +int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src) { + if ((dst->num_buckets != src->num_buckets) || + (dst->multiplier != src->multiplier)) { + /* Fail because these histograms don't match */ + return 0; + } + grpc_histogram_merge_contents(dst, src->buckets, src->num_buckets, + src->min_seen, src->max_seen, src->sum, + src->sum_of_squares, src->count); + return 1; +} + +void grpc_histogram_merge_contents(grpc_histogram* dst, const uint32_t* data, + size_t data_count, double min_seen, + double max_seen, double sum, + double sum_of_squares, double count) { + size_t i; + GPR_ASSERT(dst->num_buckets == data_count); + dst->sum += sum; + dst->sum_of_squares += sum_of_squares; + dst->count += count; + if (min_seen < dst->min_seen) { + dst->min_seen = min_seen; + } + if (max_seen > dst->max_seen) { + dst->max_seen = max_seen; + } + for (i = 0; i < dst->num_buckets; i++) { + dst->buckets[i] += data[i]; + } +} + +static double threshold_for_count_below(grpc_histogram* h, double count_below) { + double count_so_far; + double lower_bound; + double upper_bound; + size_t lower_idx; + size_t upper_idx; + + if (h->count == 0) { + return 0.0; + } + + if (count_below <= 0) { + return h->min_seen; + } + if (count_below >= h->count) { + return h->max_seen; + } + + /* find the lowest bucket that gets us above count_below */ + count_so_far = 0.0; + for (lower_idx = 0; lower_idx < h->num_buckets; lower_idx++) { + count_so_far += h->buckets[lower_idx]; + if (count_so_far >= count_below) { + break; + } + } + if (count_so_far == count_below) { + /* this bucket hits the threshold exactly... we should be midway through + any run of zero values following the bucket */ + for (upper_idx = lower_idx + 1; upper_idx < h->num_buckets; upper_idx++) { + if (h->buckets[upper_idx]) { + break; + } + } + return (bucket_start(h, static_cast<double>(lower_idx)) + + bucket_start(h, static_cast<double>(upper_idx))) / + 2.0; + } else { + /* treat values as uniform throughout the bucket, and find where this value + should lie */ + lower_bound = bucket_start(h, static_cast<double>(lower_idx)); + upper_bound = bucket_start(h, static_cast<double>(lower_idx + 1)); + return GPR_CLAMP(upper_bound - (upper_bound - lower_bound) * + (count_so_far - count_below) / + h->buckets[lower_idx], + h->min_seen, h->max_seen); + } +} + +double grpc_histogram_percentile(grpc_histogram* h, double percentile) { + return threshold_for_count_below(h, h->count * percentile / 100.0); +} + +double grpc_histogram_mean(grpc_histogram* h) { + GPR_ASSERT(h->count != 0); + return h->sum / h->count; +} + +double grpc_histogram_stddev(grpc_histogram* h) { + return sqrt(grpc_histogram_variance(h)); +} + +double grpc_histogram_variance(grpc_histogram* h) { + if (h->count == 0) return 0.0; + return (h->sum_of_squares * h->count - h->sum * h->sum) / + (h->count * h->count); +} + +double grpc_histogram_maximum(grpc_histogram* h) { return h->max_seen; } + +double grpc_histogram_minimum(grpc_histogram* h) { return h->min_seen; } + +double grpc_histogram_count(grpc_histogram* h) { return h->count; } + +double grpc_histogram_sum(grpc_histogram* h) { return h->sum; } + +double grpc_histogram_sum_of_squares(grpc_histogram* h) { + return h->sum_of_squares; +} + +const uint32_t* grpc_histogram_get_contents(grpc_histogram* h, size_t* size) { + *size = h->num_buckets; + return h->buckets; +} diff --git a/contrib/libs/grpc/test/core/util/histogram.h b/contrib/libs/grpc/test/core/util/histogram.h index eeeb06352c..9d4985e64f 100644 --- a/contrib/libs/grpc/test/core/util/histogram.h +++ b/contrib/libs/grpc/test/core/util/histogram.h @@ -1,62 +1,62 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#ifndef GRPC_SUPPORT_HISTOGRAM_H -#define GRPC_SUPPORT_HISTOGRAM_H - -#include <grpc/support/port_platform.h> -#include <stddef.h> - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct grpc_histogram grpc_histogram; - -grpc_histogram* grpc_histogram_create(double resolution, - double max_bucket_start); -void grpc_histogram_destroy(grpc_histogram* h); -void grpc_histogram_add(grpc_histogram* h, double x); - -/** The following merges the second histogram into the first. It only works - if they have the same buckets and resolution. Returns 0 on failure, 1 - on success */ -int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src); - -double grpc_histogram_percentile(grpc_histogram* histogram, double percentile); -double grpc_histogram_mean(grpc_histogram* histogram); -double grpc_histogram_stddev(grpc_histogram* histogram); -double grpc_histogram_variance(grpc_histogram* histogram); -double grpc_histogram_maximum(grpc_histogram* histogram); -double grpc_histogram_minimum(grpc_histogram* histogram); -double grpc_histogram_count(grpc_histogram* histogram); -double grpc_histogram_sum(grpc_histogram* histogram); -double grpc_histogram_sum_of_squares(grpc_histogram* histogram); - -const uint32_t* grpc_histogram_get_contents(grpc_histogram* histogram, - size_t* count); -void grpc_histogram_merge_contents(grpc_histogram* histogram, - const uint32_t* data, size_t data_count, - double min_seen, double max_seen, double sum, - double sum_of_squares, double count); - -#ifdef __cplusplus -} -#endif - -#endif /* GRPC_SUPPORT_HISTOGRAM_H */ +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#ifndef GRPC_SUPPORT_HISTOGRAM_H +#define GRPC_SUPPORT_HISTOGRAM_H + +#include <grpc/support/port_platform.h> +#include <stddef.h> + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct grpc_histogram grpc_histogram; + +grpc_histogram* grpc_histogram_create(double resolution, + double max_bucket_start); +void grpc_histogram_destroy(grpc_histogram* h); +void grpc_histogram_add(grpc_histogram* h, double x); + +/** The following merges the second histogram into the first. It only works + if they have the same buckets and resolution. Returns 0 on failure, 1 + on success */ +int grpc_histogram_merge(grpc_histogram* dst, const grpc_histogram* src); + +double grpc_histogram_percentile(grpc_histogram* histogram, double percentile); +double grpc_histogram_mean(grpc_histogram* histogram); +double grpc_histogram_stddev(grpc_histogram* histogram); +double grpc_histogram_variance(grpc_histogram* histogram); +double grpc_histogram_maximum(grpc_histogram* histogram); +double grpc_histogram_minimum(grpc_histogram* histogram); +double grpc_histogram_count(grpc_histogram* histogram); +double grpc_histogram_sum(grpc_histogram* histogram); +double grpc_histogram_sum_of_squares(grpc_histogram* histogram); + +const uint32_t* grpc_histogram_get_contents(grpc_histogram* histogram, + size_t* count); +void grpc_histogram_merge_contents(grpc_histogram* histogram, + const uint32_t* data, size_t data_count, + double min_seen, double max_seen, double sum, + double sum_of_squares, double count); + +#ifdef __cplusplus +} +#endif + +#endif /* GRPC_SUPPORT_HISTOGRAM_H */ diff --git a/contrib/libs/grpc/test/core/util/histogram_test.cc b/contrib/libs/grpc/test/core/util/histogram_test.cc index 44c0084185..b96ac7d841 100644 --- a/contrib/libs/grpc/test/core/util/histogram_test.cc +++ b/contrib/libs/grpc/test/core/util/histogram_test.cc @@ -1,163 +1,163 @@ -/* - * - * 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 "test/core/util/histogram.h" -#include <grpc/support/log.h> - -#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", x); - -static void test_no_op(void) { - grpc_histogram_destroy(grpc_histogram_create(0.01, 60e9)); -} - -static void expect_percentile(grpc_histogram* h, double percentile, - double min_expect, double max_expect) { - double got = grpc_histogram_percentile(h, percentile); - gpr_log(GPR_INFO, "@%f%%, expect %f <= %f <= %f", percentile, min_expect, got, - max_expect); - GPR_ASSERT(min_expect <= got); - GPR_ASSERT(got <= max_expect); -} - -static void test_simple(void) { - grpc_histogram* h; - - LOG_TEST("test_simple"); - - h = grpc_histogram_create(0.01, 60e9); - grpc_histogram_add(h, 10000); - grpc_histogram_add(h, 10000); - grpc_histogram_add(h, 11000); - grpc_histogram_add(h, 11000); - - expect_percentile(h, 50, 10001, 10999); - GPR_ASSERT(grpc_histogram_mean(h) == 10500); - - grpc_histogram_destroy(h); -} - -static void test_percentile(void) { - grpc_histogram* h; - double last; - double i; - double cur; - - LOG_TEST("test_percentile"); - - h = grpc_histogram_create(0.05, 1e9); - grpc_histogram_add(h, 2.5); - grpc_histogram_add(h, 2.5); - grpc_histogram_add(h, 8); - grpc_histogram_add(h, 4); - - GPR_ASSERT(grpc_histogram_count(h) == 4); - GPR_ASSERT(grpc_histogram_minimum(h) == 2.5); - GPR_ASSERT(grpc_histogram_maximum(h) == 8); - GPR_ASSERT(grpc_histogram_sum(h) == 17); - GPR_ASSERT(grpc_histogram_sum_of_squares(h) == 92.5); - GPR_ASSERT(grpc_histogram_mean(h) == 4.25); - GPR_ASSERT(grpc_histogram_variance(h) == 5.0625); - GPR_ASSERT(grpc_histogram_stddev(h) == 2.25); - - expect_percentile(h, -10, 2.5, 2.5); - expect_percentile(h, 0, 2.5, 2.5); - expect_percentile(h, 12.5, 2.5, 2.5); - expect_percentile(h, 25, 2.5, 2.5); - expect_percentile(h, 37.5, 2.5, 2.8); - expect_percentile(h, 50, 3.0, 3.5); - expect_percentile(h, 62.5, 3.5, 4.5); - expect_percentile(h, 75, 5, 7.9); - expect_percentile(h, 100, 8, 8); - expect_percentile(h, 110, 8, 8); - - /* test monotonicity */ - last = 0.0; - for (i = 0; i < 100.0; i += 0.01) { - cur = grpc_histogram_percentile(h, i); - GPR_ASSERT(cur >= last); - last = cur; - } - - grpc_histogram_destroy(h); -} - -static void test_merge(void) { - grpc_histogram *h1, *h2; - double last; - double i; - double cur; - - LOG_TEST("test_merge"); - - h1 = grpc_histogram_create(0.05, 1e9); - grpc_histogram_add(h1, 2.5); - grpc_histogram_add(h1, 2.5); - grpc_histogram_add(h1, 8); - grpc_histogram_add(h1, 4); - - h2 = grpc_histogram_create(0.01, 1e9); - GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0); - grpc_histogram_destroy(h2); - - h2 = grpc_histogram_create(0.05, 1e10); - GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0); - grpc_histogram_destroy(h2); - - h2 = grpc_histogram_create(0.05, 1e9); - GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1); - GPR_ASSERT(grpc_histogram_count(h1) == 4); - GPR_ASSERT(grpc_histogram_minimum(h1) == 2.5); - GPR_ASSERT(grpc_histogram_maximum(h1) == 8); - GPR_ASSERT(grpc_histogram_sum(h1) == 17); - GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 92.5); - GPR_ASSERT(grpc_histogram_mean(h1) == 4.25); - GPR_ASSERT(grpc_histogram_variance(h1) == 5.0625); - GPR_ASSERT(grpc_histogram_stddev(h1) == 2.25); - grpc_histogram_destroy(h2); - - h2 = grpc_histogram_create(0.05, 1e9); - grpc_histogram_add(h2, 7.0); - grpc_histogram_add(h2, 17.0); - grpc_histogram_add(h2, 1.0); - GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1); - GPR_ASSERT(grpc_histogram_count(h1) == 7); - GPR_ASSERT(grpc_histogram_minimum(h1) == 1.0); - GPR_ASSERT(grpc_histogram_maximum(h1) == 17.0); - GPR_ASSERT(grpc_histogram_sum(h1) == 42.0); - GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 431.5); - GPR_ASSERT(grpc_histogram_mean(h1) == 6.0); - - /* test monotonicity */ - last = 0.0; - for (i = 0; i < 100.0; i += 0.01) { - cur = grpc_histogram_percentile(h1, i); - GPR_ASSERT(cur >= last); - last = cur; - } - - grpc_histogram_destroy(h1); - grpc_histogram_destroy(h2); -} - -int main(void) { - test_no_op(); - test_simple(); - test_percentile(); - test_merge(); - return 0; -} +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "test/core/util/histogram.h" +#include <grpc/support/log.h> + +#define LOG_TEST(x) gpr_log(GPR_INFO, "%s", x); + +static void test_no_op(void) { + grpc_histogram_destroy(grpc_histogram_create(0.01, 60e9)); +} + +static void expect_percentile(grpc_histogram* h, double percentile, + double min_expect, double max_expect) { + double got = grpc_histogram_percentile(h, percentile); + gpr_log(GPR_INFO, "@%f%%, expect %f <= %f <= %f", percentile, min_expect, got, + max_expect); + GPR_ASSERT(min_expect <= got); + GPR_ASSERT(got <= max_expect); +} + +static void test_simple(void) { + grpc_histogram* h; + + LOG_TEST("test_simple"); + + h = grpc_histogram_create(0.01, 60e9); + grpc_histogram_add(h, 10000); + grpc_histogram_add(h, 10000); + grpc_histogram_add(h, 11000); + grpc_histogram_add(h, 11000); + + expect_percentile(h, 50, 10001, 10999); + GPR_ASSERT(grpc_histogram_mean(h) == 10500); + + grpc_histogram_destroy(h); +} + +static void test_percentile(void) { + grpc_histogram* h; + double last; + double i; + double cur; + + LOG_TEST("test_percentile"); + + h = grpc_histogram_create(0.05, 1e9); + grpc_histogram_add(h, 2.5); + grpc_histogram_add(h, 2.5); + grpc_histogram_add(h, 8); + grpc_histogram_add(h, 4); + + GPR_ASSERT(grpc_histogram_count(h) == 4); + GPR_ASSERT(grpc_histogram_minimum(h) == 2.5); + GPR_ASSERT(grpc_histogram_maximum(h) == 8); + GPR_ASSERT(grpc_histogram_sum(h) == 17); + GPR_ASSERT(grpc_histogram_sum_of_squares(h) == 92.5); + GPR_ASSERT(grpc_histogram_mean(h) == 4.25); + GPR_ASSERT(grpc_histogram_variance(h) == 5.0625); + GPR_ASSERT(grpc_histogram_stddev(h) == 2.25); + + expect_percentile(h, -10, 2.5, 2.5); + expect_percentile(h, 0, 2.5, 2.5); + expect_percentile(h, 12.5, 2.5, 2.5); + expect_percentile(h, 25, 2.5, 2.5); + expect_percentile(h, 37.5, 2.5, 2.8); + expect_percentile(h, 50, 3.0, 3.5); + expect_percentile(h, 62.5, 3.5, 4.5); + expect_percentile(h, 75, 5, 7.9); + expect_percentile(h, 100, 8, 8); + expect_percentile(h, 110, 8, 8); + + /* test monotonicity */ + last = 0.0; + for (i = 0; i < 100.0; i += 0.01) { + cur = grpc_histogram_percentile(h, i); + GPR_ASSERT(cur >= last); + last = cur; + } + + grpc_histogram_destroy(h); +} + +static void test_merge(void) { + grpc_histogram *h1, *h2; + double last; + double i; + double cur; + + LOG_TEST("test_merge"); + + h1 = grpc_histogram_create(0.05, 1e9); + grpc_histogram_add(h1, 2.5); + grpc_histogram_add(h1, 2.5); + grpc_histogram_add(h1, 8); + grpc_histogram_add(h1, 4); + + h2 = grpc_histogram_create(0.01, 1e9); + GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0); + grpc_histogram_destroy(h2); + + h2 = grpc_histogram_create(0.05, 1e10); + GPR_ASSERT(grpc_histogram_merge(h1, h2) == 0); + grpc_histogram_destroy(h2); + + h2 = grpc_histogram_create(0.05, 1e9); + GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1); + GPR_ASSERT(grpc_histogram_count(h1) == 4); + GPR_ASSERT(grpc_histogram_minimum(h1) == 2.5); + GPR_ASSERT(grpc_histogram_maximum(h1) == 8); + GPR_ASSERT(grpc_histogram_sum(h1) == 17); + GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 92.5); + GPR_ASSERT(grpc_histogram_mean(h1) == 4.25); + GPR_ASSERT(grpc_histogram_variance(h1) == 5.0625); + GPR_ASSERT(grpc_histogram_stddev(h1) == 2.25); + grpc_histogram_destroy(h2); + + h2 = grpc_histogram_create(0.05, 1e9); + grpc_histogram_add(h2, 7.0); + grpc_histogram_add(h2, 17.0); + grpc_histogram_add(h2, 1.0); + GPR_ASSERT(grpc_histogram_merge(h1, h2) == 1); + GPR_ASSERT(grpc_histogram_count(h1) == 7); + GPR_ASSERT(grpc_histogram_minimum(h1) == 1.0); + GPR_ASSERT(grpc_histogram_maximum(h1) == 17.0); + GPR_ASSERT(grpc_histogram_sum(h1) == 42.0); + GPR_ASSERT(grpc_histogram_sum_of_squares(h1) == 431.5); + GPR_ASSERT(grpc_histogram_mean(h1) == 6.0); + + /* test monotonicity */ + last = 0.0; + for (i = 0; i < 100.0; i += 0.01) { + cur = grpc_histogram_percentile(h1, i); + GPR_ASSERT(cur >= last); + last = cur; + } + + grpc_histogram_destroy(h1); + grpc_histogram_destroy(h2); +} + +int main(void) { + test_no_op(); + test_simple(); + test_percentile(); + test_merge(); + return 0; +} diff --git a/contrib/libs/grpc/test/core/util/lsan_suppressions.txt b/contrib/libs/grpc/test/core/util/lsan_suppressions.txt index 4ab9d9978b..204ddbef5e 100644 --- a/contrib/libs/grpc/test/core/util/lsan_suppressions.txt +++ b/contrib/libs/grpc/test/core/util/lsan_suppressions.txt @@ -1,6 +1,6 @@ -# this is busted in BoringSSL -leak:CRYPTO_set_thread_local -leak:err_get_state -leak:ERR_add_error_dataf -leak:err_add_error_vdata -leak:RAND_bytes_with_additional_data +# this is busted in BoringSSL +leak:CRYPTO_set_thread_local +leak:err_get_state +leak:ERR_add_error_dataf +leak:err_add_error_vdata +leak:RAND_bytes_with_additional_data diff --git a/contrib/libs/grpc/test/core/util/memory_counters.cc b/contrib/libs/grpc/test/core/util/memory_counters.cc index 62cfc9b4c3..ddd8d2f283 100644 --- a/contrib/libs/grpc/test/core/util/memory_counters.cc +++ b/contrib/libs/grpc/test/core/util/memory_counters.cc @@ -1,169 +1,169 @@ -/* - * - * 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 <inttypes.h> -#include <stdint.h> -#include <string.h> - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/sync.h> -#include <grpc/support/time.h> - -#include "src/core/lib/gpr/alloc.h" -#include "src/core/lib/surface/init.h" -#include "test/core/util/memory_counters.h" - -#include <stdio.h> - -static struct grpc_memory_counters g_memory_counters; -static bool g_memory_counter_enabled; - -#ifdef GPR_LOW_LEVEL_COUNTERS -/* hide these from the microbenchmark atomic stats */ -#define NO_BARRIER_FETCH_ADD(x, sz) \ - __atomic_fetch_add((x), (sz), __ATOMIC_RELAXED) -#define NO_BARRIER_LOAD(x) __atomic_load_n((x), __ATOMIC_RELAXED) -#else -#define NO_BARRIER_FETCH_ADD(x, sz) gpr_atm_no_barrier_fetch_add(x, sz) -#define NO_BARRIER_LOAD(x) gpr_atm_no_barrier_load(x) -#endif - -// Memory counter uses --wrap=symbol feature from ld. To use this, -// `GPR_WRAP_MEMORY_COUNTER` needs to be defined. following options should be -// passed to the compiler. -// -Wl,--wrap=malloc -Wl,--wrap=calloc -Wl,--wrap=realloc -Wl,--wrap=free -// * Reference: https://linux.die.net/man/1/ld) -#if GPR_WRAP_MEMORY_COUNTER - -extern "C" { -void* __real_malloc(size_t size); -void* __real_calloc(size_t size); -void* __real_realloc(void* ptr, size_t size); -void __real_free(void* ptr); - -void* __wrap_malloc(size_t size); -void* __wrap_calloc(size_t size); -void* __wrap_realloc(void* ptr, size_t size); -void __wrap_free(void* ptr); -} - -void* __wrap_malloc(size_t size) { - if (!size) return nullptr; - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1); - void* ptr = - __real_malloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size); - *static_cast<size_t*>(ptr) = size; - return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); -} - -void* __wrap_calloc(size_t size) { - if (!size) return nullptr; - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1); - void* ptr = - __real_calloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size); - *static_cast<size_t*>(ptr) = size; - return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); -} - -void* __wrap_realloc(void* ptr, size_t size) { - if (ptr == nullptr) { - return __wrap_malloc(size); - } - if (size == 0) { - __wrap_free(ptr); - return nullptr; - } - void* rptr = - static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, - -*static_cast<gpr_atm*>(rptr)); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1); - void* new_ptr = - __real_realloc(rptr, GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size); - *static_cast<size_t*>(new_ptr) = size; - return static_cast<char*>(new_ptr) + - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); -} - -void __wrap_free(void* ptr) { - if (ptr == nullptr) return; - void* rptr = - static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size_t)); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, - -*static_cast<gpr_atm*>(rptr)); - NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, -(gpr_atm)1); - __real_free(rptr); -} - -#endif // GPR_WRAP_MEMORY_COUNTER - -void grpc_memory_counters_init() { - memset(&g_memory_counters, 0, sizeof(g_memory_counters)); - g_memory_counter_enabled = true; -} - -void grpc_memory_counters_destroy() { g_memory_counter_enabled = false; } - -struct grpc_memory_counters grpc_memory_counters_snapshot() { - struct grpc_memory_counters counters; - counters.total_size_relative = - NO_BARRIER_LOAD(&g_memory_counters.total_size_relative); - counters.total_size_absolute = - NO_BARRIER_LOAD(&g_memory_counters.total_size_absolute); - counters.total_allocs_relative = - NO_BARRIER_LOAD(&g_memory_counters.total_allocs_relative); - counters.total_allocs_absolute = - NO_BARRIER_LOAD(&g_memory_counters.total_allocs_absolute); - return counters; -} - -namespace grpc_core { -namespace testing { - -LeakDetector::LeakDetector(bool enable) : enabled_(enable) { - if (enabled_) { - grpc_memory_counters_init(); - } -} - -LeakDetector::~LeakDetector() { - // Wait for grpc_shutdown() to finish its async work. - grpc_maybe_wait_for_async_shutdown(); - if (enabled_) { - struct grpc_memory_counters counters = grpc_memory_counters_snapshot(); - if (counters.total_size_relative != 0) { - gpr_log(GPR_ERROR, "Leaking %" PRIuPTR " bytes", - static_cast<uintptr_t>(counters.total_size_relative)); - GPR_ASSERT(0); - } - grpc_memory_counters_destroy(); - } -} - -} // namespace testing -} // namespace grpc_core +/* + * + * 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 <inttypes.h> +#include <stdint.h> +#include <string.h> + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/sync.h> +#include <grpc/support/time.h> + +#include "src/core/lib/gpr/alloc.h" +#include "src/core/lib/surface/init.h" +#include "test/core/util/memory_counters.h" + +#include <stdio.h> + +static struct grpc_memory_counters g_memory_counters; +static bool g_memory_counter_enabled; + +#ifdef GPR_LOW_LEVEL_COUNTERS +/* hide these from the microbenchmark atomic stats */ +#define NO_BARRIER_FETCH_ADD(x, sz) \ + __atomic_fetch_add((x), (sz), __ATOMIC_RELAXED) +#define NO_BARRIER_LOAD(x) __atomic_load_n((x), __ATOMIC_RELAXED) +#else +#define NO_BARRIER_FETCH_ADD(x, sz) gpr_atm_no_barrier_fetch_add(x, sz) +#define NO_BARRIER_LOAD(x) gpr_atm_no_barrier_load(x) +#endif + +// Memory counter uses --wrap=symbol feature from ld. To use this, +// `GPR_WRAP_MEMORY_COUNTER` needs to be defined. following options should be +// passed to the compiler. +// -Wl,--wrap=malloc -Wl,--wrap=calloc -Wl,--wrap=realloc -Wl,--wrap=free +// * Reference: https://linux.die.net/man/1/ld) +#if GPR_WRAP_MEMORY_COUNTER + +extern "C" { +void* __real_malloc(size_t size); +void* __real_calloc(size_t size); +void* __real_realloc(void* ptr, size_t size); +void __real_free(void* ptr); + +void* __wrap_malloc(size_t size); +void* __wrap_calloc(size_t size); +void* __wrap_realloc(void* ptr, size_t size); +void __wrap_free(void* ptr); +} + +void* __wrap_malloc(size_t size) { + if (!size) return nullptr; + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1); + void* ptr = + __real_malloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size); + *static_cast<size_t*>(ptr) = size; + return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); +} + +void* __wrap_calloc(size_t size) { + if (!size) return nullptr; + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, (gpr_atm)1); + void* ptr = + __real_calloc(GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size); + *static_cast<size_t*>(ptr) = size; + return static_cast<char*>(ptr) + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); +} + +void* __wrap_realloc(void* ptr, size_t size) { + if (ptr == nullptr) { + return __wrap_malloc(size); + } + if (size == 0) { + __wrap_free(ptr); + return nullptr; + } + void* rptr = + static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_absolute, (gpr_atm)size); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, + -*static_cast<gpr_atm*>(rptr)); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, (gpr_atm)size); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_absolute, (gpr_atm)1); + void* new_ptr = + __real_realloc(rptr, GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)) + size); + *static_cast<size_t*>(new_ptr) = size; + return static_cast<char*>(new_ptr) + + GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size)); +} + +void __wrap_free(void* ptr) { + if (ptr == nullptr) return; + void* rptr = + static_cast<char*>(ptr) - GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(size_t)); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_size_relative, + -*static_cast<gpr_atm*>(rptr)); + NO_BARRIER_FETCH_ADD(&g_memory_counters.total_allocs_relative, -(gpr_atm)1); + __real_free(rptr); +} + +#endif // GPR_WRAP_MEMORY_COUNTER + +void grpc_memory_counters_init() { + memset(&g_memory_counters, 0, sizeof(g_memory_counters)); + g_memory_counter_enabled = true; +} + +void grpc_memory_counters_destroy() { g_memory_counter_enabled = false; } + +struct grpc_memory_counters grpc_memory_counters_snapshot() { + struct grpc_memory_counters counters; + counters.total_size_relative = + NO_BARRIER_LOAD(&g_memory_counters.total_size_relative); + counters.total_size_absolute = + NO_BARRIER_LOAD(&g_memory_counters.total_size_absolute); + counters.total_allocs_relative = + NO_BARRIER_LOAD(&g_memory_counters.total_allocs_relative); + counters.total_allocs_absolute = + NO_BARRIER_LOAD(&g_memory_counters.total_allocs_absolute); + return counters; +} + +namespace grpc_core { +namespace testing { + +LeakDetector::LeakDetector(bool enable) : enabled_(enable) { + if (enabled_) { + grpc_memory_counters_init(); + } +} + +LeakDetector::~LeakDetector() { + // Wait for grpc_shutdown() to finish its async work. + grpc_maybe_wait_for_async_shutdown(); + if (enabled_) { + struct grpc_memory_counters counters = grpc_memory_counters_snapshot(); + if (counters.total_size_relative != 0) { + gpr_log(GPR_ERROR, "Leaking %" PRIuPTR " bytes", + static_cast<uintptr_t>(counters.total_size_relative)); + GPR_ASSERT(0); + } + grpc_memory_counters_destroy(); + } +} + +} // namespace testing +} // namespace grpc_core diff --git a/contrib/libs/grpc/test/core/util/memory_counters.h b/contrib/libs/grpc/test/core/util/memory_counters.h index bb4100032d..c92a001ff1 100644 --- a/contrib/libs/grpc/test/core/util/memory_counters.h +++ b/contrib/libs/grpc/test/core/util/memory_counters.h @@ -1,53 +1,53 @@ -/* - * - * 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. - * - */ - -#ifndef GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H -#define GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H - -#include <grpc/support/atm.h> - -struct grpc_memory_counters { - gpr_atm total_size_relative; - gpr_atm total_size_absolute; - gpr_atm total_allocs_relative; - gpr_atm total_allocs_absolute; -}; - -void grpc_memory_counters_init(); -void grpc_memory_counters_destroy(); -struct grpc_memory_counters grpc_memory_counters_snapshot(); - -namespace grpc_core { -namespace testing { - -// At destruction time, it will check there is no memory leak. -// The object should be created before grpc_init() is called and destroyed after -// grpc_shutdown() is returned. -class LeakDetector { - public: - explicit LeakDetector(bool enable); - ~LeakDetector(); - - private: - const bool enabled_; -}; - -} // namespace testing -} // namespace grpc_core - -#endif +/* + * + * 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. + * + */ + +#ifndef GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H +#define GRPC_TEST_CORE_UTIL_MEMORY_COUNTERS_H + +#include <grpc/support/atm.h> + +struct grpc_memory_counters { + gpr_atm total_size_relative; + gpr_atm total_size_absolute; + gpr_atm total_allocs_relative; + gpr_atm total_allocs_absolute; +}; + +void grpc_memory_counters_init(); +void grpc_memory_counters_destroy(); +struct grpc_memory_counters grpc_memory_counters_snapshot(); + +namespace grpc_core { +namespace testing { + +// At destruction time, it will check there is no memory leak. +// The object should be created before grpc_init() is called and destroyed after +// grpc_shutdown() is returned. +class LeakDetector { + public: + explicit LeakDetector(bool enable); + ~LeakDetector(); + + private: + const bool enabled_; +}; + +} // namespace testing +} // namespace grpc_core + +#endif diff --git a/contrib/libs/grpc/test/core/util/mock_endpoint.cc b/contrib/libs/grpc/test/core/util/mock_endpoint.cc index 6191adee89..3c2d6a3f8b 100644 --- a/contrib/libs/grpc/test/core/util/mock_endpoint.cc +++ b/contrib/libs/grpc/test/core/util/mock_endpoint.cc @@ -1,155 +1,155 @@ -/* - * - * 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. - * - */ - -/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when - using that endpoint. Because of various transitive includes in uv.h, - including windows.h on Windows, uv.h must be included before other system - headers. Therefore, sockaddr.h must always be included first */ -#include "src/core/lib/iomgr/sockaddr.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. + * + */ + +/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when + using that endpoint. Because of various transitive includes in uv.h, + including windows.h on Windows, uv.h must be included before other system + headers. Therefore, sockaddr.h must always be included first */ +#include "src/core/lib/iomgr/sockaddr.h" + #include <inttypes.h> #include <util/generic/string.h> #include "y_absl/strings/str_format.h" -#include "test/core/util/mock_endpoint.h" - -#include <grpc/support/alloc.h> -#include <grpc/support/string_util.h> -#include "src/core/lib/iomgr/sockaddr.h" - -typedef struct mock_endpoint { - grpc_endpoint base; - gpr_mu mu; - void (*on_write)(grpc_slice slice); - grpc_slice_buffer read_buffer; - grpc_slice_buffer* on_read_out; - grpc_closure* on_read; - grpc_resource_user* resource_user; -} mock_endpoint; - -static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, bool /*urgent*/) { - mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); - gpr_mu_lock(&m->mu); - if (m->read_buffer.count > 0) { - grpc_slice_buffer_swap(&m->read_buffer, slices); - grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE); - } else { - m->on_read = cb; - m->on_read_out = slices; - } - gpr_mu_unlock(&m->mu); -} - -static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* /*arg*/) { - mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); - for (size_t i = 0; i < slices->count; i++) { - m->on_write(slices->slices[i]); - } - grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE); -} - -static void me_add_to_pollset(grpc_endpoint* /*ep*/, - grpc_pollset* /*pollset*/) {} - -static void me_add_to_pollset_set(grpc_endpoint* /*ep*/, - grpc_pollset_set* /*pollset*/) {} - -static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/, - grpc_pollset_set* /*pollset*/) {} - -static void me_shutdown(grpc_endpoint* ep, grpc_error* why) { - mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); - gpr_mu_lock(&m->mu); - if (m->on_read) { - grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, - GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( - "Endpoint Shutdown", &why, 1)); - m->on_read = nullptr; - } - gpr_mu_unlock(&m->mu); - grpc_resource_user_shutdown(m->resource_user); - GRPC_ERROR_UNREF(why); -} - -static void me_destroy(grpc_endpoint* ep) { - mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); - grpc_slice_buffer_destroy(&m->read_buffer); - grpc_resource_user_unref(m->resource_user); - gpr_mu_destroy(&m->mu); - gpr_free(m); -} - +#include "test/core/util/mock_endpoint.h" + +#include <grpc/support/alloc.h> +#include <grpc/support/string_util.h> +#include "src/core/lib/iomgr/sockaddr.h" + +typedef struct mock_endpoint { + grpc_endpoint base; + gpr_mu mu; + void (*on_write)(grpc_slice slice); + grpc_slice_buffer read_buffer; + grpc_slice_buffer* on_read_out; + grpc_closure* on_read; + grpc_resource_user* resource_user; +} mock_endpoint; + +static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, bool /*urgent*/) { + mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); + gpr_mu_lock(&m->mu); + if (m->read_buffer.count > 0) { + grpc_slice_buffer_swap(&m->read_buffer, slices); + grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE); + } else { + m->on_read = cb; + m->on_read_out = slices; + } + gpr_mu_unlock(&m->mu); +} + +static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, void* /*arg*/) { + mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); + for (size_t i = 0; i < slices->count; i++) { + m->on_write(slices->slices[i]); + } + grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE); +} + +static void me_add_to_pollset(grpc_endpoint* /*ep*/, + grpc_pollset* /*pollset*/) {} + +static void me_add_to_pollset_set(grpc_endpoint* /*ep*/, + grpc_pollset_set* /*pollset*/) {} + +static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/, + grpc_pollset_set* /*pollset*/) {} + +static void me_shutdown(grpc_endpoint* ep, grpc_error* why) { + mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); + gpr_mu_lock(&m->mu); + if (m->on_read) { + grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, + GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING( + "Endpoint Shutdown", &why, 1)); + m->on_read = nullptr; + } + gpr_mu_unlock(&m->mu); + grpc_resource_user_shutdown(m->resource_user); + GRPC_ERROR_UNREF(why); +} + +static void me_destroy(grpc_endpoint* ep) { + mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); + grpc_slice_buffer_destroy(&m->read_buffer); + grpc_resource_user_unref(m->resource_user); + gpr_mu_destroy(&m->mu); + gpr_free(m); +} + static y_absl::string_view me_get_peer(grpc_endpoint* /*ep*/) { return "fake:mock_endpoint"; -} - +} + static y_absl::string_view me_get_local_address(grpc_endpoint* /*ep*/) { return "fake:mock_endpoint"; } -static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) { - mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); - return m->resource_user; -} - -static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; } - -static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; } - -static const grpc_endpoint_vtable vtable = {me_read, - me_write, - me_add_to_pollset, - me_add_to_pollset_set, - me_delete_from_pollset_set, - me_shutdown, - me_destroy, - me_get_resource_user, - me_get_peer, +static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) { + mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); + return m->resource_user; +} + +static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; } + +static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; } + +static const grpc_endpoint_vtable vtable = {me_read, + me_write, + me_add_to_pollset, + me_add_to_pollset_set, + me_delete_from_pollset_set, + me_shutdown, + me_destroy, + me_get_resource_user, + me_get_peer, me_get_local_address, - me_get_fd, - me_can_track_err}; - -grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice), - grpc_resource_quota* resource_quota) { - mock_endpoint* m = static_cast<mock_endpoint*>(gpr_malloc(sizeof(*m))); - m->base.vtable = &vtable; + me_get_fd, + me_can_track_err}; + +grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice), + grpc_resource_quota* resource_quota) { + mock_endpoint* m = static_cast<mock_endpoint*>(gpr_malloc(sizeof(*m))); + m->base.vtable = &vtable; TString name = y_absl::StrFormat("mock_endpoint_%" PRIxPTR, (intptr_t)m); m->resource_user = grpc_resource_user_create(resource_quota, name.c_str()); - grpc_slice_buffer_init(&m->read_buffer); - gpr_mu_init(&m->mu); - m->on_write = on_write; - m->on_read = nullptr; - return &m->base; -} - -void grpc_mock_endpoint_put_read(grpc_endpoint* ep, grpc_slice slice) { - mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); - gpr_mu_lock(&m->mu); - if (m->on_read != nullptr) { - grpc_slice_buffer_add(m->on_read_out, slice); - grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE); - m->on_read = nullptr; - } else { - grpc_slice_buffer_add(&m->read_buffer, slice); - } - gpr_mu_unlock(&m->mu); -} + grpc_slice_buffer_init(&m->read_buffer); + gpr_mu_init(&m->mu); + m->on_write = on_write; + m->on_read = nullptr; + return &m->base; +} + +void grpc_mock_endpoint_put_read(grpc_endpoint* ep, grpc_slice slice) { + mock_endpoint* m = reinterpret_cast<mock_endpoint*>(ep); + gpr_mu_lock(&m->mu); + if (m->on_read != nullptr) { + grpc_slice_buffer_add(m->on_read_out, slice); + grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE); + m->on_read = nullptr; + } else { + grpc_slice_buffer_add(&m->read_buffer, slice); + } + gpr_mu_unlock(&m->mu); +} diff --git a/contrib/libs/grpc/test/core/util/mock_endpoint.h b/contrib/libs/grpc/test/core/util/mock_endpoint.h index 1d63c36256..6521d3e8e8 100644 --- a/contrib/libs/grpc/test/core/util/mock_endpoint.h +++ b/contrib/libs/grpc/test/core/util/mock_endpoint.h @@ -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. - * - */ - -#ifndef MOCK_ENDPOINT_H -#define MOCK_ENDPOINT_H - -#include "src/core/lib/iomgr/endpoint.h" - -grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice), - grpc_resource_quota* resource_quota); -void grpc_mock_endpoint_put_read(grpc_endpoint* mock_endpoint, - grpc_slice slice); - -#endif +/* + * + * 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. + * + */ + +#ifndef MOCK_ENDPOINT_H +#define MOCK_ENDPOINT_H + +#include "src/core/lib/iomgr/endpoint.h" + +grpc_endpoint* grpc_mock_endpoint_create(void (*on_write)(grpc_slice slice), + grpc_resource_quota* resource_quota); +void grpc_mock_endpoint_put_read(grpc_endpoint* mock_endpoint, + grpc_slice slice); + +#endif diff --git a/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc b/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc index 564dacad9a..2f376d6853 100644 --- a/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc +++ b/contrib/libs/grpc/test/core/util/one_corpus_entry_fuzzer.cc @@ -1,48 +1,48 @@ -/* - * - * 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 <stdbool.h> - -#include <grpc/grpc.h> - -#include <grpc/support/log.h> -#include "src/core/lib/iomgr/exec_ctx.h" -#include "src/core/lib/iomgr/load_file.h" - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); - -extern bool squelch; -extern bool leak_check; - -int main(int argc, char** argv) { - grpc_slice buffer; - squelch = false; - leak_check = false; - /* TODO(yashkt) Calling grpc_init breaks tests. Fix the tests and replace - * grpc_core::ExecCtx::GlobalInit with grpc_init and GlobalShutdown with - * grpc_shutdown */ - GPR_ASSERT(argc > 1); /* Make sure that we have a filename argument */ - GPR_ASSERT( - GRPC_LOG_IF_ERROR("load_file", grpc_load_file(argv[1], 0, &buffer))); - LLVMFuzzerTestOneInput(GRPC_SLICE_START_PTR(buffer), - GRPC_SLICE_LENGTH(buffer)); - grpc_core::ExecCtx::GlobalInit(); - grpc_slice_unref(buffer); - grpc_core::ExecCtx::GlobalShutdown(); - return 0; -} +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include <stdbool.h> + +#include <grpc/grpc.h> + +#include <grpc/support/log.h> +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/iomgr/load_file.h" + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); + +extern bool squelch; +extern bool leak_check; + +int main(int argc, char** argv) { + grpc_slice buffer; + squelch = false; + leak_check = false; + /* TODO(yashkt) Calling grpc_init breaks tests. Fix the tests and replace + * grpc_core::ExecCtx::GlobalInit with grpc_init and GlobalShutdown with + * grpc_shutdown */ + GPR_ASSERT(argc > 1); /* Make sure that we have a filename argument */ + GPR_ASSERT( + GRPC_LOG_IF_ERROR("load_file", grpc_load_file(argv[1], 0, &buffer))); + LLVMFuzzerTestOneInput(GRPC_SLICE_START_PTR(buffer), + GRPC_SLICE_LENGTH(buffer)); + grpc_core::ExecCtx::GlobalInit(); + grpc_slice_unref(buffer); + grpc_core::ExecCtx::GlobalShutdown(); + return 0; +} diff --git a/contrib/libs/grpc/test/core/util/parse_hexstring.cc b/contrib/libs/grpc/test/core/util/parse_hexstring.cc index a4830e87fc..cd64843bd3 100644 --- a/contrib/libs/grpc/test/core/util/parse_hexstring.cc +++ b/contrib/libs/grpc/test/core/util/parse_hexstring.cc @@ -1,56 +1,56 @@ -/* - * - * 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 "test/core/util/parse_hexstring.h" -#include <grpc/support/log.h> - -grpc_slice parse_hexstring(const char* hexstring) { - size_t nibbles = 0; - const char* p = nullptr; - uint8_t* out; - uint8_t temp; - grpc_slice slice; - - for (p = hexstring; *p; p++) { - nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f'); - } - - GPR_ASSERT((nibbles & 1) == 0); - - slice = grpc_slice_malloc(nibbles / 2); - out = GRPC_SLICE_START_PTR(slice); - - nibbles = 0; - temp = 0; - for (p = hexstring; *p; p++) { - if (*p >= '0' && *p <= '9') { - temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0'); - nibbles++; - } else if (*p >= 'a' && *p <= 'f') { - temp = - static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10); - nibbles++; - } - if (nibbles == 2) { - *out++ = temp; - nibbles = 0; - } - } - - return slice; -} +/* + * + * 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 "test/core/util/parse_hexstring.h" +#include <grpc/support/log.h> + +grpc_slice parse_hexstring(const char* hexstring) { + size_t nibbles = 0; + const char* p = nullptr; + uint8_t* out; + uint8_t temp; + grpc_slice slice; + + for (p = hexstring; *p; p++) { + nibbles += (*p >= '0' && *p <= '9') || (*p >= 'a' && *p <= 'f'); + } + + GPR_ASSERT((nibbles & 1) == 0); + + slice = grpc_slice_malloc(nibbles / 2); + out = GRPC_SLICE_START_PTR(slice); + + nibbles = 0; + temp = 0; + for (p = hexstring; *p; p++) { + if (*p >= '0' && *p <= '9') { + temp = static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - '0'); + nibbles++; + } else if (*p >= 'a' && *p <= 'f') { + temp = + static_cast<uint8_t>(temp << 4) | static_cast<uint8_t>(*p - 'a' + 10); + nibbles++; + } + if (nibbles == 2) { + *out++ = temp; + nibbles = 0; + } + } + + return slice; +} diff --git a/contrib/libs/grpc/test/core/util/parse_hexstring.h b/contrib/libs/grpc/test/core/util/parse_hexstring.h index 0c0419461e..b7d54c1711 100644 --- a/contrib/libs/grpc/test/core/util/parse_hexstring.h +++ b/contrib/libs/grpc/test/core/util/parse_hexstring.h @@ -1,26 +1,26 @@ -/* - * - * 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_TEST_CORE_UTIL_PARSE_HEXSTRING_H -#define GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H - -#include <grpc/slice.h> - -grpc_slice parse_hexstring(const char* hexstring); - -#endif /* GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_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_TEST_CORE_UTIL_PARSE_HEXSTRING_H +#define GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H + +#include <grpc/slice.h> + +grpc_slice parse_hexstring(const char* hexstring); + +#endif /* GRPC_TEST_CORE_UTIL_PARSE_HEXSTRING_H */ diff --git a/contrib/libs/grpc/test/core/util/passthru_endpoint.cc b/contrib/libs/grpc/test/core/util/passthru_endpoint.cc index f2224260af..a5baafad02 100644 --- a/contrib/libs/grpc/test/core/util/passthru_endpoint.cc +++ b/contrib/libs/grpc/test/core/util/passthru_endpoint.cc @@ -1,164 +1,164 @@ -/* - * - * 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. - * - */ - -/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when - using that endpoint. Because of various transitive includes in uv.h, - including windows.h on Windows, uv.h must be included before other system - headers. Therefore, sockaddr.h must always be included first */ -#include "src/core/lib/iomgr/sockaddr.h" - -#include "test/core/util/passthru_endpoint.h" - -#include <inttypes.h> -#include <string.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. + * + */ + +/* With the addition of a libuv endpoint, sockaddr.h now includes uv.h when + using that endpoint. Because of various transitive includes in uv.h, + including windows.h on Windows, uv.h must be included before other system + headers. Therefore, sockaddr.h must always be included first */ +#include "src/core/lib/iomgr/sockaddr.h" + +#include "test/core/util/passthru_endpoint.h" + +#include <inttypes.h> +#include <string.h> + #include <util/generic/string.h> #include "y_absl/strings/str_format.h" -#include <grpc/support/alloc.h> -#include <grpc/support/string_util.h> -#include "src/core/lib/iomgr/sockaddr.h" - -#include "src/core/lib/slice/slice_internal.h" - -typedef struct passthru_endpoint passthru_endpoint; - -typedef struct { - grpc_endpoint base; - passthru_endpoint* parent; - grpc_slice_buffer read_buffer; - grpc_slice_buffer* on_read_out; - grpc_closure* on_read; - grpc_resource_user* resource_user; -} half; - -struct passthru_endpoint { - gpr_mu mu; - int halves; - grpc_passthru_endpoint_stats* stats; - bool shutdown; - half client; - half server; -}; - -static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, bool /*urgent*/) { - half* m = reinterpret_cast<half*>(ep); - gpr_mu_lock(&m->parent->mu); - if (m->parent->shutdown) { - grpc_core::ExecCtx::Run( - DEBUG_LOCATION, cb, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Already shutdown")); - } else if (m->read_buffer.count > 0) { - grpc_slice_buffer_swap(&m->read_buffer, slices); - grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE); - } else { - m->on_read = cb; - m->on_read_out = slices; - } - gpr_mu_unlock(&m->parent->mu); -} - -static half* other_half(half* h) { - if (h == &h->parent->client) return &h->parent->server; - return &h->parent->client; -} - -static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* /*arg*/) { - half* m = other_half(reinterpret_cast<half*>(ep)); - gpr_mu_lock(&m->parent->mu); - grpc_error* error = GRPC_ERROR_NONE; - gpr_atm_no_barrier_fetch_add(&m->parent->stats->num_writes, (gpr_atm)1); - if (m->parent->shutdown) { - error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown"); - } else if (m->on_read != nullptr) { - for (size_t i = 0; i < slices->count; i++) { - grpc_slice_buffer_add(m->on_read_out, grpc_slice_copy(slices->slices[i])); - } - grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE); - m->on_read = nullptr; - } else { - for (size_t i = 0; i < slices->count; i++) { - grpc_slice_buffer_add(&m->read_buffer, - grpc_slice_copy(slices->slices[i])); - } - } - gpr_mu_unlock(&m->parent->mu); - grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error); -} - -static void me_add_to_pollset(grpc_endpoint* /*ep*/, - grpc_pollset* /*pollset*/) {} - -static void me_add_to_pollset_set(grpc_endpoint* /*ep*/, - grpc_pollset_set* /*pollset*/) {} - -static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/, - grpc_pollset_set* /*pollset*/) {} - -static void me_shutdown(grpc_endpoint* ep, grpc_error* why) { - half* m = reinterpret_cast<half*>(ep); - gpr_mu_lock(&m->parent->mu); - m->parent->shutdown = true; - if (m->on_read) { - grpc_core::ExecCtx::Run( - DEBUG_LOCATION, m->on_read, - GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1)); - m->on_read = nullptr; - } - m = other_half(m); - if (m->on_read) { - grpc_core::ExecCtx::Run( - DEBUG_LOCATION, m->on_read, - GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1)); - m->on_read = nullptr; - } - gpr_mu_unlock(&m->parent->mu); - grpc_resource_user_shutdown(m->resource_user); - GRPC_ERROR_UNREF(why); -} - -static void me_destroy(grpc_endpoint* ep) { - passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent; - gpr_mu_lock(&p->mu); - if (0 == --p->halves) { - gpr_mu_unlock(&p->mu); - gpr_mu_destroy(&p->mu); - grpc_passthru_endpoint_stats_destroy(p->stats); - grpc_slice_buffer_destroy_internal(&p->client.read_buffer); - grpc_slice_buffer_destroy_internal(&p->server.read_buffer); - grpc_resource_user_unref(p->client.resource_user); - grpc_resource_user_unref(p->server.resource_user); - gpr_free(p); - } else { - gpr_mu_unlock(&p->mu); - } -} - +#include <grpc/support/alloc.h> +#include <grpc/support/string_util.h> +#include "src/core/lib/iomgr/sockaddr.h" + +#include "src/core/lib/slice/slice_internal.h" + +typedef struct passthru_endpoint passthru_endpoint; + +typedef struct { + grpc_endpoint base; + passthru_endpoint* parent; + grpc_slice_buffer read_buffer; + grpc_slice_buffer* on_read_out; + grpc_closure* on_read; + grpc_resource_user* resource_user; +} half; + +struct passthru_endpoint { + gpr_mu mu; + int halves; + grpc_passthru_endpoint_stats* stats; + bool shutdown; + half client; + half server; +}; + +static void me_read(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, bool /*urgent*/) { + half* m = reinterpret_cast<half*>(ep); + gpr_mu_lock(&m->parent->mu); + if (m->parent->shutdown) { + grpc_core::ExecCtx::Run( + DEBUG_LOCATION, cb, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Already shutdown")); + } else if (m->read_buffer.count > 0) { + grpc_slice_buffer_swap(&m->read_buffer, slices); + grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, GRPC_ERROR_NONE); + } else { + m->on_read = cb; + m->on_read_out = slices; + } + gpr_mu_unlock(&m->parent->mu); +} + +static half* other_half(half* h) { + if (h == &h->parent->client) return &h->parent->server; + return &h->parent->client; +} + +static void me_write(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, void* /*arg*/) { + half* m = other_half(reinterpret_cast<half*>(ep)); + gpr_mu_lock(&m->parent->mu); + grpc_error* error = GRPC_ERROR_NONE; + gpr_atm_no_barrier_fetch_add(&m->parent->stats->num_writes, (gpr_atm)1); + if (m->parent->shutdown) { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Endpoint already shutdown"); + } else if (m->on_read != nullptr) { + for (size_t i = 0; i < slices->count; i++) { + grpc_slice_buffer_add(m->on_read_out, grpc_slice_copy(slices->slices[i])); + } + grpc_core::ExecCtx::Run(DEBUG_LOCATION, m->on_read, GRPC_ERROR_NONE); + m->on_read = nullptr; + } else { + for (size_t i = 0; i < slices->count; i++) { + grpc_slice_buffer_add(&m->read_buffer, + grpc_slice_copy(slices->slices[i])); + } + } + gpr_mu_unlock(&m->parent->mu); + grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, error); +} + +static void me_add_to_pollset(grpc_endpoint* /*ep*/, + grpc_pollset* /*pollset*/) {} + +static void me_add_to_pollset_set(grpc_endpoint* /*ep*/, + grpc_pollset_set* /*pollset*/) {} + +static void me_delete_from_pollset_set(grpc_endpoint* /*ep*/, + grpc_pollset_set* /*pollset*/) {} + +static void me_shutdown(grpc_endpoint* ep, grpc_error* why) { + half* m = reinterpret_cast<half*>(ep); + gpr_mu_lock(&m->parent->mu); + m->parent->shutdown = true; + if (m->on_read) { + grpc_core::ExecCtx::Run( + DEBUG_LOCATION, m->on_read, + GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1)); + m->on_read = nullptr; + } + m = other_half(m); + if (m->on_read) { + grpc_core::ExecCtx::Run( + DEBUG_LOCATION, m->on_read, + GRPC_ERROR_CREATE_REFERENCING_FROM_STATIC_STRING("Shutdown", &why, 1)); + m->on_read = nullptr; + } + gpr_mu_unlock(&m->parent->mu); + grpc_resource_user_shutdown(m->resource_user); + GRPC_ERROR_UNREF(why); +} + +static void me_destroy(grpc_endpoint* ep) { + passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent; + gpr_mu_lock(&p->mu); + if (0 == --p->halves) { + gpr_mu_unlock(&p->mu); + gpr_mu_destroy(&p->mu); + grpc_passthru_endpoint_stats_destroy(p->stats); + grpc_slice_buffer_destroy_internal(&p->client.read_buffer); + grpc_slice_buffer_destroy_internal(&p->server.read_buffer); + grpc_resource_user_unref(p->client.resource_user); + grpc_resource_user_unref(p->server.resource_user); + gpr_free(p); + } else { + gpr_mu_unlock(&p->mu); + } +} + static y_absl::string_view me_get_peer(grpc_endpoint* ep) { - passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent; - return (reinterpret_cast<half*>(ep)) == &p->client + passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent; + return (reinterpret_cast<half*>(ep)) == &p->client ? "fake:mock_client_endpoint" : "fake:mock_server_endpoint"; -} - +} + static y_absl::string_view me_get_local_address(grpc_endpoint* ep) { passthru_endpoint* p = (reinterpret_cast<half*>(ep))->parent; return (reinterpret_cast<half*>(ep)) == &p->client @@ -166,74 +166,74 @@ static y_absl::string_view me_get_local_address(grpc_endpoint* ep) { : "fake:mock_server_endpoint"; } -static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; } - -static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; } - -static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) { - half* m = reinterpret_cast<half*>(ep); - return m->resource_user; -} - -static const grpc_endpoint_vtable vtable = { - me_read, - me_write, - me_add_to_pollset, - me_add_to_pollset_set, - me_delete_from_pollset_set, - me_shutdown, - me_destroy, - me_get_resource_user, - me_get_peer, +static int me_get_fd(grpc_endpoint* /*ep*/) { return -1; } + +static bool me_can_track_err(grpc_endpoint* /*ep*/) { return false; } + +static grpc_resource_user* me_get_resource_user(grpc_endpoint* ep) { + half* m = reinterpret_cast<half*>(ep); + return m->resource_user; +} + +static const grpc_endpoint_vtable vtable = { + me_read, + me_write, + me_add_to_pollset, + me_add_to_pollset_set, + me_delete_from_pollset_set, + me_shutdown, + me_destroy, + me_get_resource_user, + me_get_peer, me_get_local_address, - me_get_fd, - me_can_track_err, -}; - -static void half_init(half* m, passthru_endpoint* parent, - grpc_resource_quota* resource_quota, - const char* half_name) { - m->base.vtable = &vtable; - m->parent = parent; - grpc_slice_buffer_init(&m->read_buffer); - m->on_read = nullptr; + me_get_fd, + me_can_track_err, +}; + +static void half_init(half* m, passthru_endpoint* parent, + grpc_resource_quota* resource_quota, + const char* half_name) { + m->base.vtable = &vtable; + m->parent = parent; + grpc_slice_buffer_init(&m->read_buffer); + m->on_read = nullptr; TString name = y_absl::StrFormat("passthru_endpoint_%s_%" PRIxPTR, half_name, (intptr_t)parent); m->resource_user = grpc_resource_user_create(resource_quota, name.c_str()); -} - -void grpc_passthru_endpoint_create(grpc_endpoint** client, - grpc_endpoint** server, - grpc_resource_quota* resource_quota, - grpc_passthru_endpoint_stats* stats) { - passthru_endpoint* m = - static_cast<passthru_endpoint*>(gpr_malloc(sizeof(*m))); - m->halves = 2; - m->shutdown = 0; - if (stats == nullptr) { - m->stats = grpc_passthru_endpoint_stats_create(); - } else { - gpr_ref(&stats->refs); - m->stats = stats; - } - half_init(&m->client, m, resource_quota, "client"); - half_init(&m->server, m, resource_quota, "server"); - gpr_mu_init(&m->mu); - *client = &m->client.base; - *server = &m->server.base; -} - -grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create() { - grpc_passthru_endpoint_stats* stats = - static_cast<grpc_passthru_endpoint_stats*>( - gpr_malloc(sizeof(grpc_passthru_endpoint_stats))); - memset(stats, 0, sizeof(*stats)); - gpr_ref_init(&stats->refs, 1); - return stats; -} - -void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats) { - if (gpr_unref(&stats->refs)) { - gpr_free(stats); - } -} +} + +void grpc_passthru_endpoint_create(grpc_endpoint** client, + grpc_endpoint** server, + grpc_resource_quota* resource_quota, + grpc_passthru_endpoint_stats* stats) { + passthru_endpoint* m = + static_cast<passthru_endpoint*>(gpr_malloc(sizeof(*m))); + m->halves = 2; + m->shutdown = 0; + if (stats == nullptr) { + m->stats = grpc_passthru_endpoint_stats_create(); + } else { + gpr_ref(&stats->refs); + m->stats = stats; + } + half_init(&m->client, m, resource_quota, "client"); + half_init(&m->server, m, resource_quota, "server"); + gpr_mu_init(&m->mu); + *client = &m->client.base; + *server = &m->server.base; +} + +grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create() { + grpc_passthru_endpoint_stats* stats = + static_cast<grpc_passthru_endpoint_stats*>( + gpr_malloc(sizeof(grpc_passthru_endpoint_stats))); + memset(stats, 0, sizeof(*stats)); + gpr_ref_init(&stats->refs, 1); + return stats; +} + +void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats) { + if (gpr_unref(&stats->refs)) { + gpr_free(stats); + } +} diff --git a/contrib/libs/grpc/test/core/util/passthru_endpoint.h b/contrib/libs/grpc/test/core/util/passthru_endpoint.h index 039e5e0aa1..a46c775505 100644 --- a/contrib/libs/grpc/test/core/util/passthru_endpoint.h +++ b/contrib/libs/grpc/test/core/util/passthru_endpoint.h @@ -1,43 +1,43 @@ -/* - * - * 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. - * - */ - -#ifndef MOCK_ENDPOINT_H -#define MOCK_ENDPOINT_H - -#include <grpc/support/atm.h> - -#include "src/core/lib/iomgr/endpoint.h" - -/* The struct is refcounted, always use grpc_passthru_endpoint_stats_create and - * grpc_passthru_endpoint_stats_destroy, rather then embedding it in your - * objects by value. */ -typedef struct { - gpr_refcount refs; - gpr_atm num_writes; -} grpc_passthru_endpoint_stats; - -void grpc_passthru_endpoint_create(grpc_endpoint** client, - grpc_endpoint** server, - grpc_resource_quota* resource_quota, - grpc_passthru_endpoint_stats* stats); - -grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create(); - -void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats); - -#endif +/* + * + * 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. + * + */ + +#ifndef MOCK_ENDPOINT_H +#define MOCK_ENDPOINT_H + +#include <grpc/support/atm.h> + +#include "src/core/lib/iomgr/endpoint.h" + +/* The struct is refcounted, always use grpc_passthru_endpoint_stats_create and + * grpc_passthru_endpoint_stats_destroy, rather then embedding it in your + * objects by value. */ +typedef struct { + gpr_refcount refs; + gpr_atm num_writes; +} grpc_passthru_endpoint_stats; + +void grpc_passthru_endpoint_create(grpc_endpoint** client, + grpc_endpoint** server, + grpc_resource_quota* resource_quota, + grpc_passthru_endpoint_stats* stats); + +grpc_passthru_endpoint_stats* grpc_passthru_endpoint_stats_create(); + +void grpc_passthru_endpoint_stats_destroy(grpc_passthru_endpoint_stats* stats); + +#endif diff --git a/contrib/libs/grpc/test/core/util/port.cc b/contrib/libs/grpc/test/core/util/port.cc index 936929fd66..5a34b6026f 100644 --- a/contrib/libs/grpc/test/core/util/port.cc +++ b/contrib/libs/grpc/test/core/util/port.cc @@ -1,143 +1,143 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include "src/core/lib/iomgr/port.h" -#include "test/core/util/test_config.h" -#if defined(GRPC_TEST_PICK_PORT) - -#include "test/core/util/port.h" - -#include <stdbool.h> -#include <stdio.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/http/httpcli.h" -#include "src/core/lib/iomgr/resolve_address.h" -#include "src/core/lib/iomgr/sockaddr_utils.h" -#include "test/core/util/port_server_client.h" - -static int* chosen_ports = nullptr; -static size_t num_chosen_ports = 0; +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "src/core/lib/iomgr/port.h" +#include "test/core/util/test_config.h" +#if defined(GRPC_TEST_PICK_PORT) + +#include "test/core/util/port.h" + +#include <stdbool.h> +#include <stdio.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/http/httpcli.h" +#include "src/core/lib/iomgr/resolve_address.h" +#include "src/core/lib/iomgr/sockaddr_utils.h" +#include "test/core/util/port_server_client.h" + +static int* chosen_ports = nullptr; +static size_t num_chosen_ports = 0; static grpc_core::Mutex* g_default_port_picker_mu; static gpr_once g_default_port_picker_init = GPR_ONCE_INIT; - + static void init_default_port_picker() { g_default_port_picker_mu = new grpc_core::Mutex(); } static int free_chosen_port_locked(int port) { - size_t i; - int found = 0; - size_t found_at = 0; - /* Find the port and erase it from the list, then tell the server it can be - freed. */ - for (i = 0; i < num_chosen_ports; i++) { - if (chosen_ports[i] == port) { - GPR_ASSERT(found == 0); - found = 1; - found_at = i; - } - } - if (found) { - chosen_ports[found_at] = chosen_ports[num_chosen_ports - 1]; - num_chosen_ports--; - grpc_free_port_using_server(port); - } - return found; -} - -static void free_chosen_ports(void) { + size_t i; + int found = 0; + size_t found_at = 0; + /* Find the port and erase it from the list, then tell the server it can be + freed. */ + for (i = 0; i < num_chosen_ports; i++) { + if (chosen_ports[i] == port) { + GPR_ASSERT(found == 0); + found = 1; + found_at = i; + } + } + if (found) { + chosen_ports[found_at] = chosen_ports[num_chosen_ports - 1]; + num_chosen_ports--; + grpc_free_port_using_server(port); + } + return found; +} + +static void free_chosen_ports(void) { grpc_core::MutexLock lock(g_default_port_picker_mu); - size_t i; - grpc_init(); - for (i = 0; i < num_chosen_ports; i++) { - grpc_free_port_using_server(chosen_ports[i]); - } - grpc_shutdown_blocking(); - gpr_free(chosen_ports); -} - + size_t i; + grpc_init(); + for (i = 0; i < num_chosen_ports; i++) { + grpc_free_port_using_server(chosen_ports[i]); + } + grpc_shutdown_blocking(); + gpr_free(chosen_ports); +} + static void chose_port_locked(int port) { - if (chosen_ports == nullptr) { - atexit(free_chosen_ports); - } - num_chosen_ports++; - chosen_ports = static_cast<int*>( - gpr_realloc(chosen_ports, sizeof(int) * num_chosen_ports)); - chosen_ports[num_chosen_ports - 1] = port; -} - -static int grpc_pick_unused_port_impl(void) { + if (chosen_ports == nullptr) { + atexit(free_chosen_ports); + } + num_chosen_ports++; + chosen_ports = static_cast<int*>( + gpr_realloc(chosen_ports, sizeof(int) * num_chosen_ports)); + chosen_ports[num_chosen_ports - 1] = port; +} + +static int grpc_pick_unused_port_impl(void) { gpr_once_init(&g_default_port_picker_init, init_default_port_picker); grpc_core::MutexLock lock(g_default_port_picker_mu); - int port = grpc_pick_port_using_server(); - if (port != 0) { + int port = grpc_pick_port_using_server(); + if (port != 0) { chose_port_locked(port); - } - - return port; -} - -static int grpc_pick_unused_port_or_die_impl(void) { - int port = grpc_pick_unused_port(); - if (port == 0) { - fprintf(stderr, - "gRPC tests require a helper port server to allocate ports used \n" - "during the test.\n\n" - "This server is not currently running.\n\n" - "To start it, run tools/run_tests/start_port_server.py\n\n"); - exit(1); - } - return port; -} - -static void grpc_recycle_unused_port_impl(int port) { + } + + return port; +} + +static int grpc_pick_unused_port_or_die_impl(void) { + int port = grpc_pick_unused_port(); + if (port == 0) { + fprintf(stderr, + "gRPC tests require a helper port server to allocate ports used \n" + "during the test.\n\n" + "This server is not currently running.\n\n" + "To start it, run tools/run_tests/start_port_server.py\n\n"); + exit(1); + } + return port; +} + +static void grpc_recycle_unused_port_impl(int port) { gpr_once_init(&g_default_port_picker_init, init_default_port_picker); grpc_core::MutexLock lock(g_default_port_picker_mu); GPR_ASSERT(free_chosen_port_locked(port)); -} - -static grpc_pick_port_functions g_pick_port_functions = { - grpc_pick_unused_port_impl, grpc_pick_unused_port_or_die_impl, - grpc_recycle_unused_port_impl}; - -int grpc_pick_unused_port(void) { - return g_pick_port_functions.pick_unused_port_fn(); -} - -int grpc_pick_unused_port_or_die(void) { - return g_pick_port_functions.pick_unused_port_or_die_fn(); -} - -void grpc_recycle_unused_port(int port) { - g_pick_port_functions.recycle_unused_port_fn(port); -} - -void grpc_set_pick_port_functions(grpc_pick_port_functions functions) { - GPR_ASSERT(functions.pick_unused_port_fn != nullptr); - GPR_ASSERT(functions.pick_unused_port_or_die_fn != nullptr); - GPR_ASSERT(functions.recycle_unused_port_fn != nullptr); - g_pick_port_functions = functions; -} - -#endif /* GRPC_TEST_PICK_PORT */ +} + +static grpc_pick_port_functions g_pick_port_functions = { + grpc_pick_unused_port_impl, grpc_pick_unused_port_or_die_impl, + grpc_recycle_unused_port_impl}; + +int grpc_pick_unused_port(void) { + return g_pick_port_functions.pick_unused_port_fn(); +} + +int grpc_pick_unused_port_or_die(void) { + return g_pick_port_functions.pick_unused_port_or_die_fn(); +} + +void grpc_recycle_unused_port(int port) { + g_pick_port_functions.recycle_unused_port_fn(port); +} + +void grpc_set_pick_port_functions(grpc_pick_port_functions functions) { + GPR_ASSERT(functions.pick_unused_port_fn != nullptr); + GPR_ASSERT(functions.pick_unused_port_or_die_fn != nullptr); + GPR_ASSERT(functions.recycle_unused_port_fn != nullptr); + g_pick_port_functions = functions; +} + +#endif /* GRPC_TEST_PICK_PORT */ diff --git a/contrib/libs/grpc/test/core/util/port.h b/contrib/libs/grpc/test/core/util/port.h index cf79445537..3a4cf4467a 100644 --- a/contrib/libs/grpc/test/core/util/port.h +++ b/contrib/libs/grpc/test/core/util/port.h @@ -1,44 +1,44 @@ -/* - * - * 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_TEST_CORE_UTIL_PORT_H -#define GRPC_TEST_CORE_UTIL_PORT_H - -typedef struct grpc_pick_port_functions { - int (*pick_unused_port_fn)(void); - int (*pick_unused_port_or_die_fn)(void); - void (*recycle_unused_port_fn)(int port); -} grpc_pick_port_functions; - -/* pick a port number that is currently unused by either tcp or udp. return - 0 on failure. */ -int grpc_pick_unused_port(void); -/* pick a port number that is currently unused by either tcp or udp. abort - on failure. */ -int grpc_pick_unused_port_or_die(void); - -/* Return a port which was previously returned by grpc_pick_unused_port(). - * Implementations of grpc_pick_unused_port() backed by a portserver may limit - * the total number of ports available; this lets a binary return its allocated - * ports back to the server if it is going to allocate a large number. */ -void grpc_recycle_unused_port(int port); - -/** Request the family of pick_port functions in \a functions be used. */ -void grpc_set_pick_port_functions(grpc_pick_port_functions functions); - -#endif /* GRPC_TEST_CORE_UTIL_PORT_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_TEST_CORE_UTIL_PORT_H +#define GRPC_TEST_CORE_UTIL_PORT_H + +typedef struct grpc_pick_port_functions { + int (*pick_unused_port_fn)(void); + int (*pick_unused_port_or_die_fn)(void); + void (*recycle_unused_port_fn)(int port); +} grpc_pick_port_functions; + +/* pick a port number that is currently unused by either tcp or udp. return + 0 on failure. */ +int grpc_pick_unused_port(void); +/* pick a port number that is currently unused by either tcp or udp. abort + on failure. */ +int grpc_pick_unused_port_or_die(void); + +/* Return a port which was previously returned by grpc_pick_unused_port(). + * Implementations of grpc_pick_unused_port() backed by a portserver may limit + * the total number of ports available; this lets a binary return its allocated + * ports back to the server if it is going to allocate a large number. */ +void grpc_recycle_unused_port(int port); + +/** Request the family of pick_port functions in \a functions be used. */ +void grpc_set_pick_port_functions(grpc_pick_port_functions functions); + +#endif /* GRPC_TEST_CORE_UTIL_PORT_H */ diff --git a/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc b/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc index 7d0598cd81..5e043e7f97 100644 --- a/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc +++ b/contrib/libs/grpc/test/core/util/port_isolated_runtime_environment.cc @@ -1,56 +1,56 @@ -/* - * - * 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. - * - */ - -/* When individual tests run in an isolated runtime environment (e.g. each test - * runs in a separate container) the framework takes a round-robin pick of a - * port within certain range. There is no need to recycle ports. - */ -#include <grpc/support/atm.h> -#include <grpc/support/log.h> -#include <grpc/support/time.h> -#include <stdlib.h> -#include "src/core/lib/iomgr/port.h" -#include "test/core/util/test_config.h" -#if defined(GRPC_PORT_ISOLATED_RUNTIME) - -#include "test/core/util/port.h" - -#define MIN_PORT 1025 -#define MAX_PORT 32766 - -static int get_random_port_offset() { - srand(gpr_now(GPR_CLOCK_REALTIME).tv_nsec); - double rnd = static_cast<double>(rand()) / - (static_cast<double>(RAND_MAX) + 1.0); // values from [0,1) - return static_cast<int>(rnd * (MAX_PORT - MIN_PORT + 1)); -} - -static int s_initial_offset = get_random_port_offset(); -static gpr_atm s_pick_counter = 0; - +/* + * + * Copyright 2017 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +/* When individual tests run in an isolated runtime environment (e.g. each test + * runs in a separate container) the framework takes a round-robin pick of a + * port within certain range. There is no need to recycle ports. + */ +#include <grpc/support/atm.h> +#include <grpc/support/log.h> +#include <grpc/support/time.h> +#include <stdlib.h> +#include "src/core/lib/iomgr/port.h" +#include "test/core/util/test_config.h" +#if defined(GRPC_PORT_ISOLATED_RUNTIME) + +#include "test/core/util/port.h" + +#define MIN_PORT 1025 +#define MAX_PORT 32766 + +static int get_random_port_offset() { + srand(gpr_now(GPR_CLOCK_REALTIME).tv_nsec); + double rnd = static_cast<double>(rand()) / + (static_cast<double>(RAND_MAX) + 1.0); // values from [0,1) + return static_cast<int>(rnd * (MAX_PORT - MIN_PORT + 1)); +} + +static int s_initial_offset = get_random_port_offset(); +static gpr_atm s_pick_counter = 0; + static int grpc_pick_unused_port_or_die_impl(void) { - int orig_counter_val = - static_cast<int>(gpr_atm_full_fetch_add(&s_pick_counter, 1)); - GPR_ASSERT(orig_counter_val < (MAX_PORT - MIN_PORT + 1)); - return MIN_PORT + - (s_initial_offset + orig_counter_val) % (MAX_PORT - MIN_PORT + 1); -} - + int orig_counter_val = + static_cast<int>(gpr_atm_full_fetch_add(&s_pick_counter, 1)); + GPR_ASSERT(orig_counter_val < (MAX_PORT - MIN_PORT + 1)); + return MIN_PORT + + (s_initial_offset + orig_counter_val) % (MAX_PORT - MIN_PORT + 1); +} + int grpc_pick_unused_port_or_die(void) { while (true) { int port = grpc_pick_unused_port_or_die_impl(); @@ -64,6 +64,6 @@ int grpc_pick_unused_port_or_die(void) { } } -void grpc_recycle_unused_port(int port) { (void)port; } - -#endif /* GRPC_PORT_ISOLATED_RUNTIME */ +void grpc_recycle_unused_port(int port) { (void)port; } + +#endif /* GRPC_PORT_ISOLATED_RUNTIME */ diff --git a/contrib/libs/grpc/test/core/util/port_server_client.cc b/contrib/libs/grpc/test/core/util/port_server_client.cc index 3f27a1687d..973068dcda 100644 --- a/contrib/libs/grpc/test/core/util/port_server_client.cc +++ b/contrib/libs/grpc/test/core/util/port_server_client.cc @@ -1,89 +1,89 @@ -/* - * - * 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 "test/core/util/test_config.h" - -#ifdef GRPC_TEST_PICK_PORT -#include "test/core/util/port_server_client.h" - -#include <math.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 <grpc/support/sync.h> -#include <grpc/support/time.h> - -#include "src/core/lib/http/httpcli.h" - -typedef struct freereq { - gpr_mu* mu = nullptr; - grpc_polling_entity pops = {}; - int done = 0; -} freereq; - -static void destroy_pops_and_shutdown(void* p, grpc_error* /*error*/) { - grpc_pollset* pollset = - grpc_polling_entity_pollset(static_cast<grpc_polling_entity*>(p)); - grpc_pollset_destroy(pollset); - gpr_free(pollset); -} - -static void freed_port_from_server(void* arg, grpc_error* /*error*/) { - freereq* pr = static_cast<freereq*>(arg); - gpr_mu_lock(pr->mu); - pr->done = 1; - GRPC_LOG_IF_ERROR( - "pollset_kick", - grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr)); - gpr_mu_unlock(pr->mu); -} - -void grpc_free_port_using_server(int port) { - grpc_httpcli_context context; - grpc_httpcli_request req; - grpc_httpcli_response rsp; - freereq pr; - char* path; - grpc_closure* shutdown_closure; - - grpc_init(); +/* + * + * 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 "test/core/util/test_config.h" + +#ifdef GRPC_TEST_PICK_PORT +#include "test/core/util/port_server_client.h" + +#include <math.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 <grpc/support/sync.h> +#include <grpc/support/time.h> + +#include "src/core/lib/http/httpcli.h" + +typedef struct freereq { + gpr_mu* mu = nullptr; + grpc_polling_entity pops = {}; + int done = 0; +} freereq; + +static void destroy_pops_and_shutdown(void* p, grpc_error* /*error*/) { + grpc_pollset* pollset = + grpc_polling_entity_pollset(static_cast<grpc_polling_entity*>(p)); + grpc_pollset_destroy(pollset); + gpr_free(pollset); +} + +static void freed_port_from_server(void* arg, grpc_error* /*error*/) { + freereq* pr = static_cast<freereq*>(arg); + gpr_mu_lock(pr->mu); + pr->done = 1; + GRPC_LOG_IF_ERROR( + "pollset_kick", + grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr)); + gpr_mu_unlock(pr->mu); +} + +void grpc_free_port_using_server(int port) { + grpc_httpcli_context context; + grpc_httpcli_request req; + grpc_httpcli_response rsp; + freereq pr; + char* path; + grpc_closure* shutdown_closure; + + grpc_init(); { grpc_core::ExecCtx exec_ctx; - + pr = {}; memset(&req, 0, sizeof(req)); rsp = {}; - + grpc_pollset* pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); grpc_pollset_init(pollset, &pr.mu); pr.pops = grpc_polling_entity_create_from_pollset(pollset); shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops, grpc_schedule_on_exec_ctx); - + req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS); gpr_asprintf(&path, "/drop/%d", port); req.http.path = path; - + grpc_httpcli_context_init(&context); grpc_resource_quota* resource_quota = grpc_resource_quota_create("port_server_client/free"); @@ -104,153 +104,153 @@ void grpc_free_port_using_server(int port) { grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) { pr.done = 1; } - } + } gpr_mu_unlock(pr.mu); - + grpc_httpcli_context_destroy(&context); grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops), shutdown_closure); - + gpr_free(path); grpc_http_response_destroy(&rsp); } - grpc_shutdown(); -} - -typedef struct portreq { - gpr_mu* mu = nullptr; - grpc_polling_entity pops = {}; - int port = 0; - int retries = 0; - char* server = nullptr; - grpc_httpcli_context* ctx = nullptr; - grpc_httpcli_response response = {}; -} portreq; - -static void got_port_from_server(void* arg, grpc_error* error) { - size_t i; - int port = 0; - portreq* pr = static_cast<portreq*>(arg); - int failed = 0; - grpc_httpcli_response* response = &pr->response; - - if (error != GRPC_ERROR_NONE) { - failed = 1; - const char* msg = grpc_error_string(error); - gpr_log(GPR_DEBUG, "failed port pick from server: retrying [%s]", msg); - - } else if (response->status != 200) { - failed = 1; - gpr_log(GPR_DEBUG, "failed port pick from server: status=%d", - response->status); - } - - if (failed) { - grpc_httpcli_request req; - memset(&req, 0, sizeof(req)); - if (pr->retries >= 5) { - gpr_mu_lock(pr->mu); - pr->port = 0; - GRPC_LOG_IF_ERROR( - "pollset_kick", - grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr)); - gpr_mu_unlock(pr->mu); - return; - } - GPR_ASSERT(pr->retries < 10); - gpr_sleep_until(gpr_time_add( - gpr_now(GPR_CLOCK_REALTIME), - gpr_time_from_millis( - static_cast<int64_t>( - 1000.0 * (1 + pow(1.3, pr->retries) * rand() / RAND_MAX)), - GPR_TIMESPAN))); - pr->retries++; - req.host = pr->server; - req.http.path = const_cast<char*>("/get"); - grpc_http_response_destroy(&pr->response); - pr->response = {}; - grpc_resource_quota* resource_quota = - grpc_resource_quota_create("port_server_client/pick_retry"); - grpc_httpcli_get(pr->ctx, &pr->pops, resource_quota, &req, - grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC, - GRPC_CLOSURE_CREATE(got_port_from_server, pr, - grpc_schedule_on_exec_ctx), - &pr->response); - grpc_resource_quota_unref_internal(resource_quota); - return; - } - GPR_ASSERT(response); - GPR_ASSERT(response->status == 200); - for (i = 0; i < response->body_length; i++) { - GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9'); - port = port * 10 + response->body[i] - '0'; - } - GPR_ASSERT(port > 1024); - gpr_mu_lock(pr->mu); - pr->port = port; - GRPC_LOG_IF_ERROR( - "pollset_kick", - grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr)); - gpr_mu_unlock(pr->mu); -} - -int grpc_pick_port_using_server(void) { - grpc_httpcli_context context; - grpc_httpcli_request req; - portreq pr; - grpc_closure* shutdown_closure; - - grpc_init(); - { - grpc_core::ExecCtx exec_ctx; - pr = {}; - memset(&req, 0, sizeof(req)); - grpc_pollset* pollset = - static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); - grpc_pollset_init(pollset, &pr.mu); - pr.pops = grpc_polling_entity_create_from_pollset(pollset); - shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops, - grpc_schedule_on_exec_ctx); - pr.port = -1; - pr.server = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS); - pr.ctx = &context; - - req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS); - req.http.path = const_cast<char*>("/get"); - - grpc_httpcli_context_init(&context); - grpc_resource_quota* resource_quota = - grpc_resource_quota_create("port_server_client/pick"); - grpc_httpcli_get(&context, &pr.pops, resource_quota, &req, - grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC, - GRPC_CLOSURE_CREATE(got_port_from_server, &pr, - grpc_schedule_on_exec_ctx), - &pr.response); - grpc_resource_quota_unref_internal(resource_quota); - grpc_core::ExecCtx::Get()->Flush(); - gpr_mu_lock(pr.mu); - while (pr.port == -1) { - grpc_pollset_worker* worker = nullptr; - if (!GRPC_LOG_IF_ERROR( - "pollset_work", - grpc_pollset_work( - grpc_polling_entity_pollset(&pr.pops), &worker, - grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) { - pr.port = 0; - } - } - gpr_mu_unlock(pr.mu); - - grpc_http_response_destroy(&pr.response); - grpc_httpcli_context_destroy(&context); - grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops), - shutdown_closure); - - grpc_core::ExecCtx::Get()->Flush(); - } - grpc_shutdown(); - - return pr.port; -} - -#endif // GRPC_TEST_PICK_PORT + grpc_shutdown(); +} + +typedef struct portreq { + gpr_mu* mu = nullptr; + grpc_polling_entity pops = {}; + int port = 0; + int retries = 0; + char* server = nullptr; + grpc_httpcli_context* ctx = nullptr; + grpc_httpcli_response response = {}; +} portreq; + +static void got_port_from_server(void* arg, grpc_error* error) { + size_t i; + int port = 0; + portreq* pr = static_cast<portreq*>(arg); + int failed = 0; + grpc_httpcli_response* response = &pr->response; + + if (error != GRPC_ERROR_NONE) { + failed = 1; + const char* msg = grpc_error_string(error); + gpr_log(GPR_DEBUG, "failed port pick from server: retrying [%s]", msg); + + } else if (response->status != 200) { + failed = 1; + gpr_log(GPR_DEBUG, "failed port pick from server: status=%d", + response->status); + } + + if (failed) { + grpc_httpcli_request req; + memset(&req, 0, sizeof(req)); + if (pr->retries >= 5) { + gpr_mu_lock(pr->mu); + pr->port = 0; + GRPC_LOG_IF_ERROR( + "pollset_kick", + grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr)); + gpr_mu_unlock(pr->mu); + return; + } + GPR_ASSERT(pr->retries < 10); + gpr_sleep_until(gpr_time_add( + gpr_now(GPR_CLOCK_REALTIME), + gpr_time_from_millis( + static_cast<int64_t>( + 1000.0 * (1 + pow(1.3, pr->retries) * rand() / RAND_MAX)), + GPR_TIMESPAN))); + pr->retries++; + req.host = pr->server; + req.http.path = const_cast<char*>("/get"); + grpc_http_response_destroy(&pr->response); + pr->response = {}; + grpc_resource_quota* resource_quota = + grpc_resource_quota_create("port_server_client/pick_retry"); + grpc_httpcli_get(pr->ctx, &pr->pops, resource_quota, &req, + grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC, + GRPC_CLOSURE_CREATE(got_port_from_server, pr, + grpc_schedule_on_exec_ctx), + &pr->response); + grpc_resource_quota_unref_internal(resource_quota); + return; + } + GPR_ASSERT(response); + GPR_ASSERT(response->status == 200); + for (i = 0; i < response->body_length; i++) { + GPR_ASSERT(response->body[i] >= '0' && response->body[i] <= '9'); + port = port * 10 + response->body[i] - '0'; + } + GPR_ASSERT(port > 1024); + gpr_mu_lock(pr->mu); + pr->port = port; + GRPC_LOG_IF_ERROR( + "pollset_kick", + grpc_pollset_kick(grpc_polling_entity_pollset(&pr->pops), nullptr)); + gpr_mu_unlock(pr->mu); +} + +int grpc_pick_port_using_server(void) { + grpc_httpcli_context context; + grpc_httpcli_request req; + portreq pr; + grpc_closure* shutdown_closure; + + grpc_init(); + { + grpc_core::ExecCtx exec_ctx; + pr = {}; + memset(&req, 0, sizeof(req)); + grpc_pollset* pollset = + static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); + grpc_pollset_init(pollset, &pr.mu); + pr.pops = grpc_polling_entity_create_from_pollset(pollset); + shutdown_closure = GRPC_CLOSURE_CREATE(destroy_pops_and_shutdown, &pr.pops, + grpc_schedule_on_exec_ctx); + pr.port = -1; + pr.server = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS); + pr.ctx = &context; + + req.host = const_cast<char*>(GRPC_PORT_SERVER_ADDRESS); + req.http.path = const_cast<char*>("/get"); + + grpc_httpcli_context_init(&context); + grpc_resource_quota* resource_quota = + grpc_resource_quota_create("port_server_client/pick"); + grpc_httpcli_get(&context, &pr.pops, resource_quota, &req, + grpc_core::ExecCtx::Get()->Now() + 30 * GPR_MS_PER_SEC, + GRPC_CLOSURE_CREATE(got_port_from_server, &pr, + grpc_schedule_on_exec_ctx), + &pr.response); + grpc_resource_quota_unref_internal(resource_quota); + grpc_core::ExecCtx::Get()->Flush(); + gpr_mu_lock(pr.mu); + while (pr.port == -1) { + grpc_pollset_worker* worker = nullptr; + if (!GRPC_LOG_IF_ERROR( + "pollset_work", + grpc_pollset_work( + grpc_polling_entity_pollset(&pr.pops), &worker, + grpc_core::ExecCtx::Get()->Now() + GPR_MS_PER_SEC))) { + pr.port = 0; + } + } + gpr_mu_unlock(pr.mu); + + grpc_http_response_destroy(&pr.response); + grpc_httpcli_context_destroy(&context); + grpc_pollset_shutdown(grpc_polling_entity_pollset(&pr.pops), + shutdown_closure); + + grpc_core::ExecCtx::Get()->Flush(); + } + grpc_shutdown(); + + return pr.port; +} + +#endif // GRPC_TEST_PICK_PORT diff --git a/contrib/libs/grpc/test/core/util/port_server_client.h b/contrib/libs/grpc/test/core/util/port_server_client.h index 6eac403714..86dd7018ff 100644 --- a/contrib/libs/grpc/test/core/util/port_server_client.h +++ b/contrib/libs/grpc/test/core/util/port_server_client.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_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H -#define GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H - -// C interface to port_server.py - -// must be synchronized with tools/run_tests/python_utils/start_port_server.py -#define GRPC_PORT_SERVER_ADDRESS "localhost:32766" - -int grpc_pick_port_using_server(void); -void grpc_free_port_using_server(int port); - -#endif // GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_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_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H +#define GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H + +// C interface to port_server.py + +// must be synchronized with tools/run_tests/python_utils/start_port_server.py +#define GRPC_PORT_SERVER_ADDRESS "localhost:32766" + +int grpc_pick_port_using_server(void); +void grpc_free_port_using_server(int port); + +#endif // GRPC_TEST_CORE_UTIL_PORT_SERVER_CLIENT_H diff --git a/contrib/libs/grpc/test/core/util/reconnect_server.cc b/contrib/libs/grpc/test/core/util/reconnect_server.cc index 951953a69c..070ab3fa0a 100644 --- a/contrib/libs/grpc/test/core/util/reconnect_server.cc +++ b/contrib/libs/grpc/test/core/util/reconnect_server.cc @@ -1,75 +1,75 @@ -/* - * - * 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 "test/core/util/reconnect_server.h" - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/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. + * + */ + +#include "test/core/util/reconnect_server.h" + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> #include <grpc/support/string_util.h> -#include <grpc/support/sync.h> -#include <grpc/support/time.h> -#include <string.h> - +#include <grpc/support/sync.h> +#include <grpc/support/time.h> +#include <string.h> + #include "y_absl/strings/string_view.h" -#include "src/core/lib/iomgr/endpoint.h" -#include "src/core/lib/iomgr/sockaddr.h" -#include "src/core/lib/iomgr/tcp_server.h" -#include "test/core/util/port.h" -#include "test/core/util/test_tcp_server.h" - -static void pretty_print_backoffs(reconnect_server* server) { - gpr_timespec diff; - int i = 1; - double expected_backoff = 1000.0, backoff; - timestamp_list* head = server->head; - gpr_log(GPR_INFO, "reconnect server: new connection"); - for (head = server->head; head && head->next; head = head->next, i++) { - diff = gpr_time_sub(head->next->timestamp, head->timestamp); - backoff = gpr_time_to_millis(diff); - gpr_log(GPR_INFO, - "retry %2d:backoff %6.2fs,expected backoff %6.2fs, jitter %4.2f%%", - i, backoff / 1000.0, expected_backoff / 1000.0, - (backoff - expected_backoff) * 100.0 / expected_backoff); - expected_backoff *= 1.6; - int max_reconnect_backoff_ms = 120 * 1000; - if (server->max_reconnect_backoff_ms > 0) { - max_reconnect_backoff_ms = server->max_reconnect_backoff_ms; - } - if (expected_backoff > max_reconnect_backoff_ms) { - expected_backoff = max_reconnect_backoff_ms; - } - } -} - -static void on_connect(void* arg, grpc_endpoint* tcp, - grpc_pollset* /*accepting_pollset*/, - grpc_tcp_server_acceptor* acceptor) { - gpr_free(acceptor); +#include "src/core/lib/iomgr/endpoint.h" +#include "src/core/lib/iomgr/sockaddr.h" +#include "src/core/lib/iomgr/tcp_server.h" +#include "test/core/util/port.h" +#include "test/core/util/test_tcp_server.h" + +static void pretty_print_backoffs(reconnect_server* server) { + gpr_timespec diff; + int i = 1; + double expected_backoff = 1000.0, backoff; + timestamp_list* head = server->head; + gpr_log(GPR_INFO, "reconnect server: new connection"); + for (head = server->head; head && head->next; head = head->next, i++) { + diff = gpr_time_sub(head->next->timestamp, head->timestamp); + backoff = gpr_time_to_millis(diff); + gpr_log(GPR_INFO, + "retry %2d:backoff %6.2fs,expected backoff %6.2fs, jitter %4.2f%%", + i, backoff / 1000.0, expected_backoff / 1000.0, + (backoff - expected_backoff) * 100.0 / expected_backoff); + expected_backoff *= 1.6; + int max_reconnect_backoff_ms = 120 * 1000; + if (server->max_reconnect_backoff_ms > 0) { + max_reconnect_backoff_ms = server->max_reconnect_backoff_ms; + } + if (expected_backoff > max_reconnect_backoff_ms) { + expected_backoff = max_reconnect_backoff_ms; + } + } +} + +static void on_connect(void* arg, grpc_endpoint* tcp, + grpc_pollset* /*accepting_pollset*/, + grpc_tcp_server_acceptor* acceptor) { + gpr_free(acceptor); y_absl::string_view peer; int last_colon; - reconnect_server* server = static_cast<reconnect_server*>(arg); - gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); - timestamp_list* new_tail; - peer = grpc_endpoint_get_peer(tcp); - grpc_endpoint_shutdown(tcp, - GRPC_ERROR_CREATE_FROM_STATIC_STRING("Connected")); - grpc_endpoint_destroy(tcp); + reconnect_server* server = static_cast<reconnect_server*>(arg); + gpr_timespec now = gpr_now(GPR_CLOCK_REALTIME); + timestamp_list* new_tail; + peer = grpc_endpoint_get_peer(tcp); + grpc_endpoint_shutdown(tcp, + GRPC_ERROR_CREATE_FROM_STATIC_STRING("Connected")); + grpc_endpoint_destroy(tcp); last_colon = peer.rfind(':'); if (server->peer == nullptr) { server->peer = new TString(peer); @@ -80,50 +80,50 @@ static void on_connect(void* arg, grpc_endpoint* tcp, *server->peer) != 0) { gpr_log(GPR_ERROR, "mismatched peer! %s vs %s", server->peer->c_str(), TString(peer).c_str()); - } - } - new_tail = static_cast<timestamp_list*>(gpr_malloc(sizeof(timestamp_list))); - new_tail->timestamp = now; - new_tail->next = nullptr; - if (server->tail == nullptr) { - server->head = new_tail; - server->tail = new_tail; - } else { - server->tail->next = new_tail; - server->tail = new_tail; - } - pretty_print_backoffs(server); -} - -void reconnect_server_init(reconnect_server* server) { - test_tcp_server_init(&server->tcp_server, on_connect, server); - server->head = nullptr; - server->tail = nullptr; - server->peer = nullptr; - server->max_reconnect_backoff_ms = 0; -} - -void reconnect_server_start(reconnect_server* server, int port) { - test_tcp_server_start(&server->tcp_server, port); -} - -void reconnect_server_poll(reconnect_server* server, int seconds) { - test_tcp_server_poll(&server->tcp_server, 1000 * seconds); -} - -void reconnect_server_clear_timestamps(reconnect_server* server) { - timestamp_list* new_head = server->head; - while (server->head) { - new_head = server->head->next; - gpr_free(server->head); - server->head = new_head; - } - server->tail = nullptr; + } + } + new_tail = static_cast<timestamp_list*>(gpr_malloc(sizeof(timestamp_list))); + new_tail->timestamp = now; + new_tail->next = nullptr; + if (server->tail == nullptr) { + server->head = new_tail; + server->tail = new_tail; + } else { + server->tail->next = new_tail; + server->tail = new_tail; + } + pretty_print_backoffs(server); +} + +void reconnect_server_init(reconnect_server* server) { + test_tcp_server_init(&server->tcp_server, on_connect, server); + server->head = nullptr; + server->tail = nullptr; + server->peer = nullptr; + server->max_reconnect_backoff_ms = 0; +} + +void reconnect_server_start(reconnect_server* server, int port) { + test_tcp_server_start(&server->tcp_server, port); +} + +void reconnect_server_poll(reconnect_server* server, int seconds) { + test_tcp_server_poll(&server->tcp_server, 1000 * seconds); +} + +void reconnect_server_clear_timestamps(reconnect_server* server) { + timestamp_list* new_head = server->head; + while (server->head) { + new_head = server->head->next; + gpr_free(server->head); + server->head = new_head; + } + server->tail = nullptr; delete server->peer; - server->peer = nullptr; -} - -void reconnect_server_destroy(reconnect_server* server) { - reconnect_server_clear_timestamps(server); - test_tcp_server_destroy(&server->tcp_server); -} + server->peer = nullptr; +} + +void reconnect_server_destroy(reconnect_server* server) { + reconnect_server_clear_timestamps(server); + test_tcp_server_destroy(&server->tcp_server); +} diff --git a/contrib/libs/grpc/test/core/util/reconnect_server.h b/contrib/libs/grpc/test/core/util/reconnect_server.h index 56873630b9..5fd03821f7 100644 --- a/contrib/libs/grpc/test/core/util/reconnect_server.h +++ b/contrib/libs/grpc/test/core/util/reconnect_server.h @@ -1,45 +1,45 @@ -/* - * - * Copyright 2015-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. - * - */ - -#ifndef GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H -#define GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H - -#include <grpc/support/sync.h> -#include <grpc/support/time.h> -#include "test/core/util/test_tcp_server.h" - -typedef struct timestamp_list { - gpr_timespec timestamp; - struct timestamp_list* next; -} timestamp_list; - -typedef struct reconnect_server { - test_tcp_server tcp_server; - timestamp_list* head; - timestamp_list* tail; +/* + * + * Copyright 2015-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. + * + */ + +#ifndef GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H +#define GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H + +#include <grpc/support/sync.h> +#include <grpc/support/time.h> +#include "test/core/util/test_tcp_server.h" + +typedef struct timestamp_list { + gpr_timespec timestamp; + struct timestamp_list* next; +} timestamp_list; + +typedef struct reconnect_server { + test_tcp_server tcp_server; + timestamp_list* head; + timestamp_list* tail; TString* peer; - int max_reconnect_backoff_ms; -} reconnect_server; - -void reconnect_server_init(reconnect_server* server); -void reconnect_server_start(reconnect_server* server, int port); -void reconnect_server_poll(reconnect_server* server, int seconds); -void reconnect_server_destroy(reconnect_server* server); -void reconnect_server_clear_timestamps(reconnect_server* server); - -#endif /* GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H */ + int max_reconnect_backoff_ms; +} reconnect_server; + +void reconnect_server_init(reconnect_server* server); +void reconnect_server_start(reconnect_server* server, int port); +void reconnect_server_poll(reconnect_server* server, int seconds); +void reconnect_server_destroy(reconnect_server* server); +void reconnect_server_clear_timestamps(reconnect_server* server); + +#endif /* GRPC_TEST_CORE_UTIL_RECONNECT_SERVER_H */ diff --git a/contrib/libs/grpc/test/core/util/run_with_poller.sh b/contrib/libs/grpc/test/core/util/run_with_poller.sh index ad68e34b46..382a63e8ae 100755 --- a/contrib/libs/grpc/test/core/util/run_with_poller.sh +++ b/contrib/libs/grpc/test/core/util/run_with_poller.sh @@ -1,19 +1,19 @@ -#!/bin/sh -# 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. - -set -ex -export GRPC_POLL_STRATEGY=$1 -shift -"$@" +#!/bin/sh +# 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. + +set -ex +export GRPC_POLL_STRATEGY=$1 +shift +"$@" diff --git a/contrib/libs/grpc/test/core/util/slice_splitter.cc b/contrib/libs/grpc/test/core/util/slice_splitter.cc index 44e44c1e0b..1f81d03d96 100644 --- a/contrib/libs/grpc/test/core/util/slice_splitter.cc +++ b/contrib/libs/grpc/test/core/util/slice_splitter.cc @@ -1,126 +1,126 @@ -/* - * - * 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 "test/core/util/slice_splitter.h" - -#include <string.h> - -#include <grpc/support/alloc.h> - -#include "src/core/lib/gpr/useful.h" - -const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode) { - switch (mode) { - case GRPC_SLICE_SPLIT_IDENTITY: - return "identity"; - case GRPC_SLICE_SPLIT_MERGE_ALL: - return "merge_all"; - case GRPC_SLICE_SPLIT_ONE_BYTE: - return "one_byte"; - } - return "error"; -} - -void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices, - size_t src_slice_count, grpc_slice** dst_slices, - size_t* dst_slice_count) { - size_t i, j; - size_t length; - - switch (mode) { - case GRPC_SLICE_SPLIT_IDENTITY: - *dst_slice_count = src_slice_count; - *dst_slices = static_cast<grpc_slice*>( - gpr_malloc(sizeof(grpc_slice) * src_slice_count)); - for (i = 0; i < src_slice_count; i++) { - (*dst_slices)[i] = src_slices[i]; - grpc_slice_ref((*dst_slices)[i]); - } - break; - case GRPC_SLICE_SPLIT_MERGE_ALL: - *dst_slice_count = 1; - length = 0; - for (i = 0; i < src_slice_count; i++) { - length += GRPC_SLICE_LENGTH(src_slices[i]); - } - *dst_slices = static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice))); - **dst_slices = grpc_slice_malloc(length); - length = 0; - for (i = 0; i < src_slice_count; i++) { - memcpy(GRPC_SLICE_START_PTR(**dst_slices) + length, - GRPC_SLICE_START_PTR(src_slices[i]), - GRPC_SLICE_LENGTH(src_slices[i])); - length += GRPC_SLICE_LENGTH(src_slices[i]); - } - break; - case GRPC_SLICE_SPLIT_ONE_BYTE: - length = 0; - for (i = 0; i < src_slice_count; i++) { - length += GRPC_SLICE_LENGTH(src_slices[i]); - } - *dst_slice_count = length; - *dst_slices = - static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice) * length)); - length = 0; - for (i = 0; i < src_slice_count; i++) { - for (j = 0; j < GRPC_SLICE_LENGTH(src_slices[i]); j++) { - (*dst_slices)[length] = grpc_slice_sub(src_slices[i], j, j + 1); - length++; - } - } - break; - } -} - -void grpc_split_slices_to_buffer(grpc_slice_split_mode mode, - grpc_slice* src_slices, size_t src_slice_count, - grpc_slice_buffer* dst) { - grpc_slice* slices; - size_t nslices; - size_t i; - grpc_split_slices(mode, src_slices, src_slice_count, &slices, &nslices); - for (i = 0; i < nslices; i++) { - /* add indexed to avoid re-merging split slices */ - grpc_slice_buffer_add_indexed(dst, slices[i]); - } - gpr_free(slices); -} - -void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src, - grpc_slice_buffer* dst) { - grpc_split_slices_to_buffer(mode, src->slices, src->count, dst); -} - -grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices) { - uint8_t* out = nullptr; - size_t length = 0; - size_t capacity = 0; - size_t i; - - for (i = 0; i < nslices; i++) { - if (GRPC_SLICE_LENGTH(slices[i]) + length > capacity) { - capacity = GPR_MAX(capacity * 2, GRPC_SLICE_LENGTH(slices[i]) + length); - out = static_cast<uint8_t*>(gpr_realloc(out, capacity)); - } - memcpy(out + length, GRPC_SLICE_START_PTR(slices[i]), - GRPC_SLICE_LENGTH(slices[i])); - length += GRPC_SLICE_LENGTH(slices[i]); - } - - return grpc_slice_new(out, length, gpr_free); -} +/* + * + * 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 "test/core/util/slice_splitter.h" + +#include <string.h> + +#include <grpc/support/alloc.h> + +#include "src/core/lib/gpr/useful.h" + +const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode) { + switch (mode) { + case GRPC_SLICE_SPLIT_IDENTITY: + return "identity"; + case GRPC_SLICE_SPLIT_MERGE_ALL: + return "merge_all"; + case GRPC_SLICE_SPLIT_ONE_BYTE: + return "one_byte"; + } + return "error"; +} + +void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices, + size_t src_slice_count, grpc_slice** dst_slices, + size_t* dst_slice_count) { + size_t i, j; + size_t length; + + switch (mode) { + case GRPC_SLICE_SPLIT_IDENTITY: + *dst_slice_count = src_slice_count; + *dst_slices = static_cast<grpc_slice*>( + gpr_malloc(sizeof(grpc_slice) * src_slice_count)); + for (i = 0; i < src_slice_count; i++) { + (*dst_slices)[i] = src_slices[i]; + grpc_slice_ref((*dst_slices)[i]); + } + break; + case GRPC_SLICE_SPLIT_MERGE_ALL: + *dst_slice_count = 1; + length = 0; + for (i = 0; i < src_slice_count; i++) { + length += GRPC_SLICE_LENGTH(src_slices[i]); + } + *dst_slices = static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice))); + **dst_slices = grpc_slice_malloc(length); + length = 0; + for (i = 0; i < src_slice_count; i++) { + memcpy(GRPC_SLICE_START_PTR(**dst_slices) + length, + GRPC_SLICE_START_PTR(src_slices[i]), + GRPC_SLICE_LENGTH(src_slices[i])); + length += GRPC_SLICE_LENGTH(src_slices[i]); + } + break; + case GRPC_SLICE_SPLIT_ONE_BYTE: + length = 0; + for (i = 0; i < src_slice_count; i++) { + length += GRPC_SLICE_LENGTH(src_slices[i]); + } + *dst_slice_count = length; + *dst_slices = + static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice) * length)); + length = 0; + for (i = 0; i < src_slice_count; i++) { + for (j = 0; j < GRPC_SLICE_LENGTH(src_slices[i]); j++) { + (*dst_slices)[length] = grpc_slice_sub(src_slices[i], j, j + 1); + length++; + } + } + break; + } +} + +void grpc_split_slices_to_buffer(grpc_slice_split_mode mode, + grpc_slice* src_slices, size_t src_slice_count, + grpc_slice_buffer* dst) { + grpc_slice* slices; + size_t nslices; + size_t i; + grpc_split_slices(mode, src_slices, src_slice_count, &slices, &nslices); + for (i = 0; i < nslices; i++) { + /* add indexed to avoid re-merging split slices */ + grpc_slice_buffer_add_indexed(dst, slices[i]); + } + gpr_free(slices); +} + +void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src, + grpc_slice_buffer* dst) { + grpc_split_slices_to_buffer(mode, src->slices, src->count, dst); +} + +grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices) { + uint8_t* out = nullptr; + size_t length = 0; + size_t capacity = 0; + size_t i; + + for (i = 0; i < nslices; i++) { + if (GRPC_SLICE_LENGTH(slices[i]) + length > capacity) { + capacity = GPR_MAX(capacity * 2, GRPC_SLICE_LENGTH(slices[i]) + length); + out = static_cast<uint8_t*>(gpr_realloc(out, capacity)); + } + memcpy(out + length, GRPC_SLICE_START_PTR(slices[i]), + GRPC_SLICE_LENGTH(slices[i])); + length += GRPC_SLICE_LENGTH(slices[i]); + } + + return grpc_slice_new(out, length, gpr_free); +} diff --git a/contrib/libs/grpc/test/core/util/slice_splitter.h b/contrib/libs/grpc/test/core/util/slice_splitter.h index 3e698dffae..65b9f6f7df 100644 --- a/contrib/libs/grpc/test/core/util/slice_splitter.h +++ b/contrib/libs/grpc/test/core/util/slice_splitter.h @@ -1,53 +1,53 @@ -/* - * - * 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_TEST_CORE_UTIL_SLICE_SPLITTER_H -#define GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H - -/* utility function to split/merge slices together to help create test - cases */ - -#include <grpc/slice.h> -#include <grpc/slice_buffer.h> - -typedef enum { - /* merge all input slices into a single slice */ - GRPC_SLICE_SPLIT_MERGE_ALL, - /* leave slices as is */ - GRPC_SLICE_SPLIT_IDENTITY, - /* split slices into one byte chunks */ - GRPC_SLICE_SPLIT_ONE_BYTE -} grpc_slice_split_mode; - -/* allocates *dst_slices; caller must unref all slices in dst_slices then free - it */ -void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices, - size_t src_slice_count, grpc_slice** dst_slices, - size_t* dst_slice_count); - -void grpc_split_slices_to_buffer(grpc_slice_split_mode mode, - grpc_slice* src_slices, size_t src_slice_count, - grpc_slice_buffer* dst); -void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src, - grpc_slice_buffer* dst); - -grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices); - -const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode); - -#endif /* GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_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_TEST_CORE_UTIL_SLICE_SPLITTER_H +#define GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H + +/* utility function to split/merge slices together to help create test + cases */ + +#include <grpc/slice.h> +#include <grpc/slice_buffer.h> + +typedef enum { + /* merge all input slices into a single slice */ + GRPC_SLICE_SPLIT_MERGE_ALL, + /* leave slices as is */ + GRPC_SLICE_SPLIT_IDENTITY, + /* split slices into one byte chunks */ + GRPC_SLICE_SPLIT_ONE_BYTE +} grpc_slice_split_mode; + +/* allocates *dst_slices; caller must unref all slices in dst_slices then free + it */ +void grpc_split_slices(grpc_slice_split_mode mode, grpc_slice* src_slices, + size_t src_slice_count, grpc_slice** dst_slices, + size_t* dst_slice_count); + +void grpc_split_slices_to_buffer(grpc_slice_split_mode mode, + grpc_slice* src_slices, size_t src_slice_count, + grpc_slice_buffer* dst); +void grpc_split_slice_buffer(grpc_slice_split_mode mode, grpc_slice_buffer* src, + grpc_slice_buffer* dst); + +grpc_slice grpc_slice_merge(grpc_slice* slices, size_t nslices); + +const char* grpc_slice_split_mode_name(grpc_slice_split_mode mode); + +#endif /* GRPC_TEST_CORE_UTIL_SLICE_SPLITTER_H */ diff --git a/contrib/libs/grpc/test/core/util/subprocess.h b/contrib/libs/grpc/test/core/util/subprocess.h index 3163086bba..c7fe9af435 100644 --- a/contrib/libs/grpc/test/core/util/subprocess.h +++ b/contrib/libs/grpc/test/core/util/subprocess.h @@ -1,36 +1,36 @@ -/* - * - * 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_TEST_CORE_UTIL_SUBPROCESS_H -#define GRPC_TEST_CORE_UTIL_SUBPROCESS_H - -#include <grpc/support/port_platform.h> - -typedef struct gpr_subprocess gpr_subprocess; - -/** .exe on windows, empty on unices */ -const char* gpr_subprocess_binary_extension(); - -gpr_subprocess* gpr_subprocess_create(int argc, const char** argv); -/** if subprocess has not been joined, kill it */ -void gpr_subprocess_destroy(gpr_subprocess* p); -/** returns exit status; can be called at most once */ -int gpr_subprocess_join(gpr_subprocess* p); -void gpr_subprocess_interrupt(gpr_subprocess* p); - -#endif /* GRPC_TEST_CORE_UTIL_SUBPROCESS_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_TEST_CORE_UTIL_SUBPROCESS_H +#define GRPC_TEST_CORE_UTIL_SUBPROCESS_H + +#include <grpc/support/port_platform.h> + +typedef struct gpr_subprocess gpr_subprocess; + +/** .exe on windows, empty on unices */ +const char* gpr_subprocess_binary_extension(); + +gpr_subprocess* gpr_subprocess_create(int argc, const char** argv); +/** if subprocess has not been joined, kill it */ +void gpr_subprocess_destroy(gpr_subprocess* p); +/** returns exit status; can be called at most once */ +int gpr_subprocess_join(gpr_subprocess* p); +void gpr_subprocess_interrupt(gpr_subprocess* p); + +#endif /* GRPC_TEST_CORE_UTIL_SUBPROCESS_H */ diff --git a/contrib/libs/grpc/test/core/util/subprocess_posix.cc b/contrib/libs/grpc/test/core/util/subprocess_posix.cc index 263de85fbb..ab288d777f 100644 --- a/contrib/libs/grpc/test/core/util/subprocess_posix.cc +++ b/contrib/libs/grpc/test/core/util/subprocess_posix.cc @@ -1,100 +1,100 @@ -/* - * - * 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> - -#ifdef GPR_POSIX_SUBPROCESS - -#include <assert.h> -#include <errno.h> -#include <signal.h> -#include <stdbool.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <sys/wait.h> -#include <unistd.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "test/core/util/subprocess.h" - -struct gpr_subprocess { - int pid; - bool joined; -}; - -const char* gpr_subprocess_binary_extension() { return ""; } - -gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) { - gpr_subprocess* r; - int pid; - char** exec_args; - - pid = fork(); - if (pid == -1) { - return nullptr; - } else if (pid == 0) { - exec_args = static_cast<char**>( - gpr_malloc((static_cast<size_t>(argc) + 1) * sizeof(char*))); - memcpy(exec_args, argv, static_cast<size_t>(argc) * sizeof(char*)); - exec_args[argc] = nullptr; - execv(exec_args[0], exec_args); - /* if we reach here, an error has occurred */ - gpr_log(GPR_ERROR, "execv '%s' failed: %s", exec_args[0], strerror(errno)); - _exit(1); - return nullptr; - } else { - r = static_cast<gpr_subprocess*>(gpr_zalloc(sizeof(gpr_subprocess))); - r->pid = pid; - return r; - } -} - -void gpr_subprocess_destroy(gpr_subprocess* p) { - if (!p->joined) { - kill(p->pid, SIGKILL); - gpr_subprocess_join(p); - } - gpr_free(p); -} - -int gpr_subprocess_join(gpr_subprocess* p) { - int status; -retry: - if (waitpid(p->pid, &status, 0) == -1) { - if (errno == EINTR) { - goto retry; - } - gpr_log(GPR_ERROR, "waitpid failed for pid %d: %s", p->pid, - strerror(errno)); - return -1; - } - p->joined = true; - return status; -} - -void gpr_subprocess_interrupt(gpr_subprocess* p) { - if (!p->joined) { - kill(p->pid, SIGINT); - } -} - -#endif /* GPR_POSIX_SUBPROCESS */ +/* + * + * 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> + +#ifdef GPR_POSIX_SUBPROCESS + +#include <assert.h> +#include <errno.h> +#include <signal.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "test/core/util/subprocess.h" + +struct gpr_subprocess { + int pid; + bool joined; +}; + +const char* gpr_subprocess_binary_extension() { return ""; } + +gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) { + gpr_subprocess* r; + int pid; + char** exec_args; + + pid = fork(); + if (pid == -1) { + return nullptr; + } else if (pid == 0) { + exec_args = static_cast<char**>( + gpr_malloc((static_cast<size_t>(argc) + 1) * sizeof(char*))); + memcpy(exec_args, argv, static_cast<size_t>(argc) * sizeof(char*)); + exec_args[argc] = nullptr; + execv(exec_args[0], exec_args); + /* if we reach here, an error has occurred */ + gpr_log(GPR_ERROR, "execv '%s' failed: %s", exec_args[0], strerror(errno)); + _exit(1); + return nullptr; + } else { + r = static_cast<gpr_subprocess*>(gpr_zalloc(sizeof(gpr_subprocess))); + r->pid = pid; + return r; + } +} + +void gpr_subprocess_destroy(gpr_subprocess* p) { + if (!p->joined) { + kill(p->pid, SIGKILL); + gpr_subprocess_join(p); + } + gpr_free(p); +} + +int gpr_subprocess_join(gpr_subprocess* p) { + int status; +retry: + if (waitpid(p->pid, &status, 0) == -1) { + if (errno == EINTR) { + goto retry; + } + gpr_log(GPR_ERROR, "waitpid failed for pid %d: %s", p->pid, + strerror(errno)); + return -1; + } + p->joined = true; + return status; +} + +void gpr_subprocess_interrupt(gpr_subprocess* p) { + if (!p->joined) { + kill(p->pid, SIGINT); + } +} + +#endif /* GPR_POSIX_SUBPROCESS */ diff --git a/contrib/libs/grpc/test/core/util/subprocess_windows.cc b/contrib/libs/grpc/test/core/util/subprocess_windows.cc index 4ca8dc3507..d3295244ea 100644 --- a/contrib/libs/grpc/test/core/util/subprocess_windows.cc +++ b/contrib/libs/grpc/test/core/util/subprocess_windows.cc @@ -1,126 +1,126 @@ -/* - * - * 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> - -#ifdef GPR_WINDOWS_SUBPROCESS - -#include <string.h> -#include <tchar.h> -#include <windows.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/gpr/string_windows.h" -#include "test/core/util/subprocess.h" - -struct gpr_subprocess { - PROCESS_INFORMATION pi; - int joined; - int interrupted; -}; - -const char* gpr_subprocess_binary_extension() { return ".exe"; } - -gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) { - gpr_subprocess* r; - - STARTUPINFO si; - PROCESS_INFORMATION pi; - - char* args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL); - TCHAR* args_tchar; - - args_tchar = gpr_char_to_tchar(args); - gpr_free(args); - - memset(&si, 0, sizeof(si)); - si.cb = sizeof(si); - memset(&pi, 0, sizeof(pi)); - - if (!CreateProcess(NULL, args_tchar, NULL, NULL, FALSE, - CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi)) { - gpr_free(args_tchar); - return NULL; - } - gpr_free(args_tchar); - - r = (gpr_subprocess*)gpr_malloc(sizeof(gpr_subprocess)); - memset(r, 0, sizeof(*r)); - r->pi = pi; - return r; -} - -void gpr_subprocess_destroy(gpr_subprocess* p) { - if (p) { - if (!p->joined) { - gpr_subprocess_interrupt(p); - gpr_subprocess_join(p); - } - if (p->pi.hProcess) { - CloseHandle(p->pi.hProcess); - } - if (p->pi.hThread) { - CloseHandle(p->pi.hThread); - } - gpr_free(p); - } -} - -int gpr_subprocess_join(gpr_subprocess* p) { - DWORD dwExitCode; - if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { - if (dwExitCode == STILL_ACTIVE) { - if (WaitForSingleObject(p->pi.hProcess, INFINITE) == WAIT_OBJECT_0) { - p->joined = 1; - goto getExitCode; - } - return -1; // failed to join - } else { - goto getExitCode; - } - } else { - return -1; // failed to get exit code - } - -getExitCode: - if (p->interrupted) { - return 0; - } - if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { - return (int)dwExitCode; - } else { - return -1; // failed to get exit code - } -} - -void gpr_subprocess_interrupt(gpr_subprocess* p) { - DWORD dwExitCode; - if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { - if (dwExitCode == STILL_ACTIVE) { - gpr_log(GPR_INFO, "sending ctrl-break"); - GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p->pi.dwProcessId); - p->joined = 1; - p->interrupted = 1; - } - } - return; -} - -#endif /* GPR_WINDOWS_SUBPROCESS */ +/* + * + * 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> + +#ifdef GPR_WINDOWS_SUBPROCESS + +#include <string.h> +#include <tchar.h> +#include <windows.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/gpr/string_windows.h" +#include "test/core/util/subprocess.h" + +struct gpr_subprocess { + PROCESS_INFORMATION pi; + int joined; + int interrupted; +}; + +const char* gpr_subprocess_binary_extension() { return ".exe"; } + +gpr_subprocess* gpr_subprocess_create(int argc, const char** argv) { + gpr_subprocess* r; + + STARTUPINFO si; + PROCESS_INFORMATION pi; + + char* args = gpr_strjoin_sep(argv, (size_t)argc, " ", NULL); + TCHAR* args_tchar; + + args_tchar = gpr_char_to_tchar(args); + gpr_free(args); + + memset(&si, 0, sizeof(si)); + si.cb = sizeof(si); + memset(&pi, 0, sizeof(pi)); + + if (!CreateProcess(NULL, args_tchar, NULL, NULL, FALSE, + CREATE_NEW_PROCESS_GROUP, NULL, NULL, &si, &pi)) { + gpr_free(args_tchar); + return NULL; + } + gpr_free(args_tchar); + + r = (gpr_subprocess*)gpr_malloc(sizeof(gpr_subprocess)); + memset(r, 0, sizeof(*r)); + r->pi = pi; + return r; +} + +void gpr_subprocess_destroy(gpr_subprocess* p) { + if (p) { + if (!p->joined) { + gpr_subprocess_interrupt(p); + gpr_subprocess_join(p); + } + if (p->pi.hProcess) { + CloseHandle(p->pi.hProcess); + } + if (p->pi.hThread) { + CloseHandle(p->pi.hThread); + } + gpr_free(p); + } +} + +int gpr_subprocess_join(gpr_subprocess* p) { + DWORD dwExitCode; + if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { + if (dwExitCode == STILL_ACTIVE) { + if (WaitForSingleObject(p->pi.hProcess, INFINITE) == WAIT_OBJECT_0) { + p->joined = 1; + goto getExitCode; + } + return -1; // failed to join + } else { + goto getExitCode; + } + } else { + return -1; // failed to get exit code + } + +getExitCode: + if (p->interrupted) { + return 0; + } + if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { + return (int)dwExitCode; + } else { + return -1; // failed to get exit code + } +} + +void gpr_subprocess_interrupt(gpr_subprocess* p) { + DWORD dwExitCode; + if (GetExitCodeProcess(p->pi.hProcess, &dwExitCode)) { + if (dwExitCode == STILL_ACTIVE) { + gpr_log(GPR_INFO, "sending ctrl-break"); + GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p->pi.dwProcessId); + p->joined = 1; + p->interrupted = 1; + } + } + return; +} + +#endif /* GPR_WINDOWS_SUBPROCESS */ diff --git a/contrib/libs/grpc/test/core/util/test_config.cc b/contrib/libs/grpc/test/core/util/test_config.cc index 9f3e935a3a..9e57a486b2 100644 --- a/contrib/libs/grpc/test/core/util/test_config.cc +++ b/contrib/libs/grpc/test/core/util/test_config.cc @@ -1,111 +1,111 @@ -/* - * - * 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 "test/core/util/test_config.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 "test/core/util/test_config.h" + #include <grpc/impl/codegen/gpr_types.h> -#include <inttypes.h> -#include <signal.h> -#include <stdbool.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - +#include <inttypes.h> +#include <signal.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + #include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> - -#include "src/core/lib/gpr/string.h" -#include "src/core/lib/gpr/useful.h" -#include "src/core/lib/surface/init.h" - +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> + +#include "src/core/lib/gpr/string.h" +#include "src/core/lib/gpr/useful.h" +#include "src/core/lib/surface/init.h" + #include "y_absl/debugging/failure_signal_handler.h" #include "y_absl/debugging/symbolize.h" -int64_t g_fixture_slowdown_factor = 1; -int64_t g_poller_slowdown_factor = 1; - -#if GPR_GETPID_IN_UNISTD_H -#include <unistd.h> -static unsigned seed(void) { return static_cast<unsigned>(getpid()); } -#endif - -#if GPR_GETPID_IN_PROCESS_H -#include <process.h> -static unsigned seed(void) { return (unsigned)_getpid(); } -#endif - -#if GPR_WINDOWS_CRASH_HANDLER -#include <windows.h> - -#include <tchar.h> - -// disable warning 4091 - dbghelp.h is broken for msvc2015 -#pragma warning(disable : 4091) -#define DBGHELP_TRANSLATE_TCHAR -#include <dbghelp.h> - -#ifdef _MSC_VER -#pragma comment(lib, "dbghelp.lib") -#endif - +int64_t g_fixture_slowdown_factor = 1; +int64_t g_poller_slowdown_factor = 1; + +#if GPR_GETPID_IN_UNISTD_H +#include <unistd.h> +static unsigned seed(void) { return static_cast<unsigned>(getpid()); } +#endif + +#if GPR_GETPID_IN_PROCESS_H +#include <process.h> +static unsigned seed(void) { return (unsigned)_getpid(); } +#endif + +#if GPR_WINDOWS_CRASH_HANDLER +#include <windows.h> + +#include <tchar.h> + +// disable warning 4091 - dbghelp.h is broken for msvc2015 +#pragma warning(disable : 4091) +#define DBGHELP_TRANSLATE_TCHAR +#include <dbghelp.h> + +#ifdef _MSC_VER +#pragma comment(lib, "dbghelp.lib") +#endif + static void print_stack_from_context(HANDLE thread, CONTEXT c) { - STACKFRAME s; // in/out stackframe - memset(&s, 0, sizeof(s)); - DWORD imageType; -#ifdef _M_IX86 - // normally, call ImageNtHeader() and use machine info from PE header - imageType = IMAGE_FILE_MACHINE_I386; - s.AddrPC.Offset = c.Eip; - s.AddrPC.Mode = AddrModeFlat; - s.AddrFrame.Offset = c.Ebp; - s.AddrFrame.Mode = AddrModeFlat; - s.AddrStack.Offset = c.Esp; - s.AddrStack.Mode = AddrModeFlat; -#elif _M_X64 - imageType = IMAGE_FILE_MACHINE_AMD64; - s.AddrPC.Offset = c.Rip; - s.AddrPC.Mode = AddrModeFlat; - s.AddrFrame.Offset = c.Rbp; - s.AddrFrame.Mode = AddrModeFlat; - s.AddrStack.Offset = c.Rsp; - s.AddrStack.Mode = AddrModeFlat; -#elif _M_IA64 - imageType = IMAGE_FILE_MACHINE_IA64; - s.AddrPC.Offset = c.StIIP; - s.AddrPC.Mode = AddrModeFlat; - s.AddrFrame.Offset = c.IntSp; - s.AddrFrame.Mode = AddrModeFlat; - s.AddrBStore.Offset = c.RsBSP; - s.AddrBStore.Mode = AddrModeFlat; - s.AddrStack.Offset = c.IntSp; - s.AddrStack.Mode = AddrModeFlat; -#else -#error "Platform not supported!" -#endif - - HANDLE process = GetCurrentProcess(); - - SYMBOL_INFOW* symbol = - (SYMBOL_INFOW*)calloc(sizeof(SYMBOL_INFOW) + 256 * sizeof(wchar_t), 1); - symbol->MaxNameLen = 255; - symbol->SizeOfStruct = sizeof(SYMBOL_INFOW); - + STACKFRAME s; // in/out stackframe + memset(&s, 0, sizeof(s)); + DWORD imageType; +#ifdef _M_IX86 + // normally, call ImageNtHeader() and use machine info from PE header + imageType = IMAGE_FILE_MACHINE_I386; + s.AddrPC.Offset = c.Eip; + s.AddrPC.Mode = AddrModeFlat; + s.AddrFrame.Offset = c.Ebp; + s.AddrFrame.Mode = AddrModeFlat; + s.AddrStack.Offset = c.Esp; + s.AddrStack.Mode = AddrModeFlat; +#elif _M_X64 + imageType = IMAGE_FILE_MACHINE_AMD64; + s.AddrPC.Offset = c.Rip; + s.AddrPC.Mode = AddrModeFlat; + s.AddrFrame.Offset = c.Rbp; + s.AddrFrame.Mode = AddrModeFlat; + s.AddrStack.Offset = c.Rsp; + s.AddrStack.Mode = AddrModeFlat; +#elif _M_IA64 + imageType = IMAGE_FILE_MACHINE_IA64; + s.AddrPC.Offset = c.StIIP; + s.AddrPC.Mode = AddrModeFlat; + s.AddrFrame.Offset = c.IntSp; + s.AddrFrame.Mode = AddrModeFlat; + s.AddrBStore.Offset = c.RsBSP; + s.AddrBStore.Mode = AddrModeFlat; + s.AddrStack.Offset = c.IntSp; + s.AddrStack.Mode = AddrModeFlat; +#else +#error "Platform not supported!" +#endif + + HANDLE process = GetCurrentProcess(); + + SYMBOL_INFOW* symbol = + (SYMBOL_INFOW*)calloc(sizeof(SYMBOL_INFOW) + 256 * sizeof(wchar_t), 1); + symbol->MaxNameLen = 255; + symbol->SizeOfStruct = sizeof(SYMBOL_INFOW); + const unsigned short MAX_CALLERS_SHOWN = 8192; // avoid flooding the stderr if stacktrace is way too long for (int frame = 0; frame < MAX_CALLERS_SHOWN && @@ -133,265 +133,265 @@ static void print_stack_from_context(HANDLE thread, CONTEXT c) { fwprintf(stderr, L"*** %d: %016I64X %ls - %016I64X (%ls:%d)\n", frame, (DWORD64)(s.AddrPC.Offset), symbol_name, symbol_address, file_name, line_number); - fflush(stderr); - } - - free(symbol); -} - + fflush(stderr); + } + + free(symbol); +} + static void print_current_stack() { CONTEXT context; RtlCaptureContext(&context); print_stack_from_context(GetCurrentThread(), context); } -static LONG crash_handler(struct _EXCEPTION_POINTERS* ex_info) { - fprintf(stderr, "Exception handler called, dumping information\n"); - bool try_to_print_stack = true; - PEXCEPTION_RECORD exrec = ex_info->ExceptionRecord; - while (exrec) { - DWORD code = exrec->ExceptionCode; - DWORD flgs = exrec->ExceptionFlags; - PVOID addr = exrec->ExceptionAddress; - if (code == EXCEPTION_STACK_OVERFLOW) try_to_print_stack = false; - fprintf(stderr, "code: %x - flags: %d - address: %p\n", code, flgs, addr); - exrec = exrec->ExceptionRecord; - } - if (try_to_print_stack) { +static LONG crash_handler(struct _EXCEPTION_POINTERS* ex_info) { + fprintf(stderr, "Exception handler called, dumping information\n"); + bool try_to_print_stack = true; + PEXCEPTION_RECORD exrec = ex_info->ExceptionRecord; + while (exrec) { + DWORD code = exrec->ExceptionCode; + DWORD flgs = exrec->ExceptionFlags; + PVOID addr = exrec->ExceptionAddress; + if (code == EXCEPTION_STACK_OVERFLOW) try_to_print_stack = false; + fprintf(stderr, "code: %x - flags: %d - address: %p\n", code, flgs, addr); + exrec = exrec->ExceptionRecord; + } + if (try_to_print_stack) { print_stack_from_context(GetCurrentThread(), *ex_info->ContextRecord); - } - if (IsDebuggerPresent()) { - __debugbreak(); - } else { - _exit(1); - } - return EXCEPTION_EXECUTE_HANDLER; -} - -static void abort_handler(int sig) { - fprintf(stderr, "Abort handler called.\n"); - print_current_stack(); - if (IsDebuggerPresent()) { - __debugbreak(); - } else { - _exit(1); - } -} - -static void install_crash_handler() { - if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) { - fprintf(stderr, "SymInitialize failed: %d\n", GetLastError()); - } - SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)crash_handler); - _set_abort_behavior(0, _WRITE_ABORT_MSG); - _set_abort_behavior(0, _CALL_REPORTFAULT); - signal(SIGABRT, abort_handler); -} -#elif GPR_POSIX_CRASH_HANDLER -#include <errno.h> -#include <execinfo.h> -#include <stdio.h> -#include <string.h> - -#define SIGNAL_NAMES_LENGTH 32 - -static const char* const signal_names[] = { - nullptr, "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", - "SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV", - "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD", - "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG", - "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO", - "SIGPWR", "SIGSYS"}; - -static char g_alt_stack[GPR_MAX(MINSIGSTKSZ, 65536)]; - -#define MAX_FRAMES 32 - -/* signal safe output */ -static void output_string(const char* string) { - size_t len = strlen(string); - ssize_t r; - - do { - r = write(STDERR_FILENO, string, len); - } while (r == -1 && errno == EINTR); -} - -static void output_num(long num) { - char buf[GPR_LTOA_MIN_BUFSIZE]; - gpr_ltoa(num, buf); - output_string(buf); -} - -static void crash_handler(int signum, siginfo_t* /*info*/, void* /*data*/) { - void* addrlist[MAX_FRAMES + 1]; - int addrlen; - - output_string("\n\n\n*******************************\nCaught signal "); - if (signum > 0 && signum < SIGNAL_NAMES_LENGTH) { - output_string(signal_names[signum]); - } else { - output_num(signum); - } - output_string("\n"); - - addrlen = backtrace(addrlist, GPR_ARRAY_SIZE(addrlist)); - - if (addrlen == 0) { - output_string(" no backtrace\n"); - } else { - backtrace_symbols_fd(addrlist, addrlen, STDERR_FILENO); - } - - /* try to get a core dump for SIGTERM */ - if (signum == SIGTERM) signum = SIGQUIT; - raise(signum); -} - -static void install_crash_handler() { - stack_t ss; - struct sigaction sa; - - memset(&ss, 0, sizeof(ss)); - memset(&sa, 0, sizeof(sa)); - ss.ss_size = sizeof(g_alt_stack); - ss.ss_sp = g_alt_stack; - GPR_ASSERT(sigaltstack(&ss, nullptr) == 0); - sa.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_RESETHAND); - sa.sa_sigaction = crash_handler; - GPR_ASSERT(sigaction(SIGILL, &sa, nullptr) == 0); - GPR_ASSERT(sigaction(SIGABRT, &sa, nullptr) == 0); - GPR_ASSERT(sigaction(SIGBUS, &sa, nullptr) == 0); - GPR_ASSERT(sigaction(SIGSEGV, &sa, nullptr) == 0); - GPR_ASSERT(sigaction(SIGTERM, &sa, nullptr) == 0); - GPR_ASSERT(sigaction(SIGQUIT, &sa, nullptr) == 0); -} -#else -static void install_crash_handler() {} -#endif - -bool BuiltUnderValgrind() { -#ifdef RUNNING_ON_VALGRIND - return true; -#else - return false; -#endif -} - -bool BuiltUnderTsan() { -#if defined(__has_feature) -#if __has_feature(thread_sanitizer) - return true; -#else - return false; -#endif -#else -#ifdef THREAD_SANITIZER - return true; -#else - return false; -#endif -#endif -} - -bool BuiltUnderAsan() { -#if defined(__has_feature) -#if __has_feature(address_sanitizer) - return true; -#else - return false; -#endif -#else -#ifdef ADDRESS_SANITIZER - return true; -#else - return false; -#endif -#endif -} - -bool BuiltUnderMsan() { -#if defined(__has_feature) -#if __has_feature(memory_sanitizer) - return true; -#else - return false; -#endif -#else -#ifdef MEMORY_SANITIZER - return true; -#else - return false; -#endif -#endif -} - -bool BuiltUnderUbsan() { -#ifdef GRPC_UBSAN - return true; -#else - return false; -#endif -} - -int64_t grpc_test_sanitizer_slowdown_factor() { - int64_t sanitizer_multiplier = 1; - if (BuiltUnderValgrind()) { - sanitizer_multiplier = 20; - } else if (BuiltUnderTsan()) { - sanitizer_multiplier = 5; - } else if (BuiltUnderAsan()) { - sanitizer_multiplier = 3; - } else if (BuiltUnderMsan()) { - sanitizer_multiplier = 4; - } else if (BuiltUnderUbsan()) { - sanitizer_multiplier = 5; - } - return sanitizer_multiplier; -} - -int64_t grpc_test_slowdown_factor() { - return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor * - g_poller_slowdown_factor; -} - -gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) { - return gpr_time_add( - gpr_now(GPR_CLOCK_MONOTONIC), - gpr_time_from_millis( - grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s, - GPR_TIMESPAN)); -} - -gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) { - return gpr_time_add( - gpr_now(GPR_CLOCK_MONOTONIC), - gpr_time_from_micros( - grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms, - GPR_TIMESPAN)); -} - + } + if (IsDebuggerPresent()) { + __debugbreak(); + } else { + _exit(1); + } + return EXCEPTION_EXECUTE_HANDLER; +} + +static void abort_handler(int sig) { + fprintf(stderr, "Abort handler called.\n"); + print_current_stack(); + if (IsDebuggerPresent()) { + __debugbreak(); + } else { + _exit(1); + } +} + +static void install_crash_handler() { + if (!SymInitialize(GetCurrentProcess(), NULL, TRUE)) { + fprintf(stderr, "SymInitialize failed: %d\n", GetLastError()); + } + SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)crash_handler); + _set_abort_behavior(0, _WRITE_ABORT_MSG); + _set_abort_behavior(0, _CALL_REPORTFAULT); + signal(SIGABRT, abort_handler); +} +#elif GPR_POSIX_CRASH_HANDLER +#include <errno.h> +#include <execinfo.h> +#include <stdio.h> +#include <string.h> + +#define SIGNAL_NAMES_LENGTH 32 + +static const char* const signal_names[] = { + nullptr, "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", + "SIGABRT", "SIGBUS", "SIGFPE", "SIGKILL", "SIGUSR1", "SIGSEGV", + "SIGUSR2", "SIGPIPE", "SIGALRM", "SIGTERM", "SIGSTKFLT", "SIGCHLD", + "SIGCONT", "SIGSTOP", "SIGTSTP", "SIGTTIN", "SIGTTOU", "SIGURG", + "SIGXCPU", "SIGXFSZ", "SIGVTALRM", "SIGPROF", "SIGWINCH", "SIGIO", + "SIGPWR", "SIGSYS"}; + +static char g_alt_stack[GPR_MAX(MINSIGSTKSZ, 65536)]; + +#define MAX_FRAMES 32 + +/* signal safe output */ +static void output_string(const char* string) { + size_t len = strlen(string); + ssize_t r; + + do { + r = write(STDERR_FILENO, string, len); + } while (r == -1 && errno == EINTR); +} + +static void output_num(long num) { + char buf[GPR_LTOA_MIN_BUFSIZE]; + gpr_ltoa(num, buf); + output_string(buf); +} + +static void crash_handler(int signum, siginfo_t* /*info*/, void* /*data*/) { + void* addrlist[MAX_FRAMES + 1]; + int addrlen; + + output_string("\n\n\n*******************************\nCaught signal "); + if (signum > 0 && signum < SIGNAL_NAMES_LENGTH) { + output_string(signal_names[signum]); + } else { + output_num(signum); + } + output_string("\n"); + + addrlen = backtrace(addrlist, GPR_ARRAY_SIZE(addrlist)); + + if (addrlen == 0) { + output_string(" no backtrace\n"); + } else { + backtrace_symbols_fd(addrlist, addrlen, STDERR_FILENO); + } + + /* try to get a core dump for SIGTERM */ + if (signum == SIGTERM) signum = SIGQUIT; + raise(signum); +} + +static void install_crash_handler() { + stack_t ss; + struct sigaction sa; + + memset(&ss, 0, sizeof(ss)); + memset(&sa, 0, sizeof(sa)); + ss.ss_size = sizeof(g_alt_stack); + ss.ss_sp = g_alt_stack; + GPR_ASSERT(sigaltstack(&ss, nullptr) == 0); + sa.sa_flags = static_cast<int>(SA_SIGINFO | SA_ONSTACK | SA_RESETHAND); + sa.sa_sigaction = crash_handler; + GPR_ASSERT(sigaction(SIGILL, &sa, nullptr) == 0); + GPR_ASSERT(sigaction(SIGABRT, &sa, nullptr) == 0); + GPR_ASSERT(sigaction(SIGBUS, &sa, nullptr) == 0); + GPR_ASSERT(sigaction(SIGSEGV, &sa, nullptr) == 0); + GPR_ASSERT(sigaction(SIGTERM, &sa, nullptr) == 0); + GPR_ASSERT(sigaction(SIGQUIT, &sa, nullptr) == 0); +} +#else +static void install_crash_handler() {} +#endif + +bool BuiltUnderValgrind() { +#ifdef RUNNING_ON_VALGRIND + return true; +#else + return false; +#endif +} + +bool BuiltUnderTsan() { +#if defined(__has_feature) +#if __has_feature(thread_sanitizer) + return true; +#else + return false; +#endif +#else +#ifdef THREAD_SANITIZER + return true; +#else + return false; +#endif +#endif +} + +bool BuiltUnderAsan() { +#if defined(__has_feature) +#if __has_feature(address_sanitizer) + return true; +#else + return false; +#endif +#else +#ifdef ADDRESS_SANITIZER + return true; +#else + return false; +#endif +#endif +} + +bool BuiltUnderMsan() { +#if defined(__has_feature) +#if __has_feature(memory_sanitizer) + return true; +#else + return false; +#endif +#else +#ifdef MEMORY_SANITIZER + return true; +#else + return false; +#endif +#endif +} + +bool BuiltUnderUbsan() { +#ifdef GRPC_UBSAN + return true; +#else + return false; +#endif +} + +int64_t grpc_test_sanitizer_slowdown_factor() { + int64_t sanitizer_multiplier = 1; + if (BuiltUnderValgrind()) { + sanitizer_multiplier = 20; + } else if (BuiltUnderTsan()) { + sanitizer_multiplier = 5; + } else if (BuiltUnderAsan()) { + sanitizer_multiplier = 3; + } else if (BuiltUnderMsan()) { + sanitizer_multiplier = 4; + } else if (BuiltUnderUbsan()) { + sanitizer_multiplier = 5; + } + return sanitizer_multiplier; +} + +int64_t grpc_test_slowdown_factor() { + return grpc_test_sanitizer_slowdown_factor() * g_fixture_slowdown_factor * + g_poller_slowdown_factor; +} + +gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s) { + return gpr_time_add( + gpr_now(GPR_CLOCK_MONOTONIC), + gpr_time_from_millis( + grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_s, + GPR_TIMESPAN)); +} + +gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms) { + return gpr_time_add( + gpr_now(GPR_CLOCK_MONOTONIC), + gpr_time_from_micros( + grpc_test_slowdown_factor() * static_cast<int64_t>(1e3) * time_ms, + GPR_TIMESPAN)); +} + void grpc_test_init(int argc, char** argv) { #if GPR_WINDOWS // Windows cannot use y_absl::InitializeSymbolizer until it fixes mysterious // SymInitialize failure using Bazel RBE on Windows // https://github.com/grpc/grpc/issues/24178 - install_crash_handler(); + install_crash_handler(); #else y_absl::InitializeSymbolizer(argv[0]); y_absl::FailureSignalHandlerOptions options; y_absl::InstallFailureSignalHandler(options); #endif - gpr_log(GPR_DEBUG, - "test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64 - ", poller=%" PRId64 ", total=%" PRId64, - grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor, - g_poller_slowdown_factor, grpc_test_slowdown_factor()); - /* seed rng with pid, so we don't end up with the same random numbers as a - concurrently running test binary */ - srand(seed()); -} - + gpr_log(GPR_DEBUG, + "test slowdown factor: sanitizer=%" PRId64 ", fixture=%" PRId64 + ", poller=%" PRId64 ", total=%" PRId64, + grpc_test_sanitizer_slowdown_factor(), g_fixture_slowdown_factor, + g_poller_slowdown_factor, grpc_test_slowdown_factor()); + /* seed rng with pid, so we don't end up with the same random numbers as a + concurrently running test binary */ + srand(seed()); +} + bool grpc_wait_until_shutdown(int64_t time_s) { gpr_timespec deadline = grpc_timeout_seconds_to_deadline(time_s); while (grpc_is_initialized()) { @@ -405,13 +405,13 @@ bool grpc_wait_until_shutdown(int64_t time_s) { return true; } -namespace grpc { -namespace testing { - -TestEnvironment::TestEnvironment(int argc, char** argv) { - grpc_test_init(argc, argv); -} - +namespace grpc { +namespace testing { + +TestEnvironment::TestEnvironment(int argc, char** argv) { + grpc_test_init(argc, argv); +} + TestEnvironment::~TestEnvironment() { // This will wait until gRPC shutdown has actually happened to make sure // no gRPC resources (such as thread) are active. (timeout = 10s) @@ -429,7 +429,7 @@ TestEnvironment::~TestEnvironment() { } gpr_log(GPR_INFO, "TestEnvironment ends"); } - + TestGrpcScope::TestGrpcScope() { grpc_init(); } TestGrpcScope::~TestGrpcScope() { @@ -439,5 +439,5 @@ TestGrpcScope::~TestGrpcScope() { } } -} // namespace testing -} // namespace grpc +} // namespace testing +} // namespace grpc diff --git a/contrib/libs/grpc/test/core/util/test_config.h b/contrib/libs/grpc/test/core/util/test_config.h index 63ad2a51ba..6ac43de266 100644 --- a/contrib/libs/grpc/test/core/util/test_config.h +++ b/contrib/libs/grpc/test/core/util/test_config.h @@ -1,42 +1,42 @@ -/* - * - * 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_TEST_CORE_UTIL_TEST_CONFIG_H -#define GRPC_TEST_CORE_UTIL_TEST_CONFIG_H - -#include <grpc/support/time.h> - -extern int64_t g_fixture_slowdown_factor; -extern int64_t g_poller_slowdown_factor; - -/* Returns an appropriate scaling factor for timeouts. */ -int64_t grpc_test_slowdown_factor(); - -/* Converts a given timeout (in seconds) to a deadline. */ -gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s); - -/* Converts a given timeout (in milliseconds) to a deadline. */ -gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms); - -#if !defined(GRPC_TEST_CUSTOM_PICK_PORT) && !defined(GRPC_PORT_ISOLATED_RUNTIME) -#define GRPC_TEST_PICK_PORT -#endif - +/* + * + * 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_TEST_CORE_UTIL_TEST_CONFIG_H +#define GRPC_TEST_CORE_UTIL_TEST_CONFIG_H + +#include <grpc/support/time.h> + +extern int64_t g_fixture_slowdown_factor; +extern int64_t g_poller_slowdown_factor; + +/* Returns an appropriate scaling factor for timeouts. */ +int64_t grpc_test_slowdown_factor(); + +/* Converts a given timeout (in seconds) to a deadline. */ +gpr_timespec grpc_timeout_seconds_to_deadline(int64_t time_s); + +/* Converts a given timeout (in milliseconds) to a deadline. */ +gpr_timespec grpc_timeout_milliseconds_to_deadline(int64_t time_ms); + +#if !defined(GRPC_TEST_CUSTOM_PICK_PORT) && !defined(GRPC_PORT_ISOLATED_RUNTIME) +#define GRPC_TEST_PICK_PORT +#endif + // Returns whether this is built under ThreadSanitizer bool BuiltUnderTsan(); @@ -49,24 +49,24 @@ bool BuiltUnderMsan(); // Returns whether this is built under UndefinedBehaviorSanitizer bool BuiltUnderUbsan(); -// Prefer TestEnvironment below. -void grpc_test_init(int argc, char** argv); - +// Prefer TestEnvironment below. +void grpc_test_init(int argc, char** argv); + // Wait until gRPC is fully shut down. // Returns if grpc is shutdown bool grpc_wait_until_shutdown(int64_t time_s); -namespace grpc { -namespace testing { - -// A TestEnvironment object should be alive in the main function of a test. It -// provides test init and shutdown inside. -class TestEnvironment { - public: - TestEnvironment(int argc, char** argv); - ~TestEnvironment(); -}; - +namespace grpc { +namespace testing { + +// A TestEnvironment object should be alive in the main function of a test. It +// provides test init and shutdown inside. +class TestEnvironment { + public: + TestEnvironment(int argc, char** argv); + ~TestEnvironment(); +}; + // A TestGrpcScope makes sure that // - when it's created, gRPC will be initialized // - when it's destroyed, gRPC will shutdown and it waits until shutdown @@ -76,7 +76,7 @@ class TestGrpcScope { ~TestGrpcScope(); }; -} // namespace testing -} // namespace grpc - -#endif /* GRPC_TEST_CORE_UTIL_TEST_CONFIG_H */ +} // namespace testing +} // namespace grpc + +#endif /* GRPC_TEST_CORE_UTIL_TEST_CONFIG_H */ diff --git a/contrib/libs/grpc/test/core/util/test_lb_policies.cc b/contrib/libs/grpc/test/core/util/test_lb_policies.cc index e163d7b9cb..c1c1e9c56a 100644 --- a/contrib/libs/grpc/test/core/util/test_lb_policies.cc +++ b/contrib/libs/grpc/test/core/util/test_lb_policies.cc @@ -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. - * - */ - -#include "test/core/util/test_lb_policies.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 "test/core/util/test_lb_policies.h" + #include <util/generic/string.h> - -#include <grpc/support/log.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/lib/channel/channel_args.h" -#include "src/core/lib/channel/channelz.h" -#include "src/core/lib/debug/trace.h" -#include "src/core/lib/gprpp/memory.h" -#include "src/core/lib/gprpp/orphanable.h" -#include "src/core/lib/gprpp/ref_counted_ptr.h" -#include "src/core/lib/iomgr/closure.h" -#include "src/core/lib/iomgr/combiner.h" -#include "src/core/lib/iomgr/error.h" -#include "src/core/lib/iomgr/pollset_set.h" -#include "src/core/lib/json/json.h" -#include "src/core/lib/transport/connectivity_state.h" - -namespace grpc_core { - -namespace { - -// -// ForwardingLoadBalancingPolicy -// - -// A minimal forwarding class to avoid implementing a standalone test LB. -class ForwardingLoadBalancingPolicy : public LoadBalancingPolicy { - public: - ForwardingLoadBalancingPolicy( - std::unique_ptr<ChannelControlHelper> delegating_helper, Args args, + +#include <grpc/support/log.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/lib/channel/channel_args.h" +#include "src/core/lib/channel/channelz.h" +#include "src/core/lib/debug/trace.h" +#include "src/core/lib/gprpp/memory.h" +#include "src/core/lib/gprpp/orphanable.h" +#include "src/core/lib/gprpp/ref_counted_ptr.h" +#include "src/core/lib/iomgr/closure.h" +#include "src/core/lib/iomgr/combiner.h" +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/pollset_set.h" +#include "src/core/lib/json/json.h" +#include "src/core/lib/transport/connectivity_state.h" + +namespace grpc_core { + +namespace { + +// +// ForwardingLoadBalancingPolicy +// + +// A minimal forwarding class to avoid implementing a standalone test LB. +class ForwardingLoadBalancingPolicy : public LoadBalancingPolicy { + public: + ForwardingLoadBalancingPolicy( + std::unique_ptr<ChannelControlHelper> delegating_helper, Args args, const TString& delegate_policy_name, intptr_t initial_refcount = 1) - : LoadBalancingPolicy(std::move(args), initial_refcount) { - Args delegate_args; + : LoadBalancingPolicy(std::move(args), initial_refcount) { + Args delegate_args; delegate_args.work_serializer = work_serializer(); - delegate_args.channel_control_helper = std::move(delegating_helper); - delegate_args.args = args.args; - delegate_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy( - delegate_policy_name.c_str(), std::move(delegate_args)); - grpc_pollset_set_add_pollset_set(delegate_->interested_parties(), - interested_parties()); - } - - ~ForwardingLoadBalancingPolicy() override = default; - - void UpdateLocked(UpdateArgs args) override { - delegate_->UpdateLocked(std::move(args)); - } - - void ExitIdleLocked() override { delegate_->ExitIdleLocked(); } - - void ResetBackoffLocked() override { delegate_->ResetBackoffLocked(); } - - private: - void ShutdownLocked() override { delegate_.reset(); } - - OrphanablePtr<LoadBalancingPolicy> delegate_; -}; - -// + delegate_args.channel_control_helper = std::move(delegating_helper); + delegate_args.args = args.args; + delegate_ = LoadBalancingPolicyRegistry::CreateLoadBalancingPolicy( + delegate_policy_name.c_str(), std::move(delegate_args)); + grpc_pollset_set_add_pollset_set(delegate_->interested_parties(), + interested_parties()); + } + + ~ForwardingLoadBalancingPolicy() override = default; + + void UpdateLocked(UpdateArgs args) override { + delegate_->UpdateLocked(std::move(args)); + } + + void ExitIdleLocked() override { delegate_->ExitIdleLocked(); } + + void ResetBackoffLocked() override { delegate_->ResetBackoffLocked(); } + + private: + void ShutdownLocked() override { delegate_.reset(); } + + OrphanablePtr<LoadBalancingPolicy> delegate_; +}; + +// // CopyMetadataToVector() // @@ -191,117 +191,117 @@ class TestPickArgsLbFactory : public LoadBalancingPolicyFactory { }; // -// InterceptRecvTrailingMetadataLoadBalancingPolicy -// - -constexpr char kInterceptRecvTrailingMetadataLbPolicyName[] = - "intercept_trailing_metadata_lb"; - -class InterceptRecvTrailingMetadataLoadBalancingPolicy - : public ForwardingLoadBalancingPolicy { - public: - InterceptRecvTrailingMetadataLoadBalancingPolicy( +// InterceptRecvTrailingMetadataLoadBalancingPolicy +// + +constexpr char kInterceptRecvTrailingMetadataLbPolicyName[] = + "intercept_trailing_metadata_lb"; + +class InterceptRecvTrailingMetadataLoadBalancingPolicy + : public ForwardingLoadBalancingPolicy { + public: + InterceptRecvTrailingMetadataLoadBalancingPolicy( Args args, InterceptRecvTrailingMetadataCallback cb) - : ForwardingLoadBalancingPolicy( + : ForwardingLoadBalancingPolicy( y_absl::make_unique<Helper>( - RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy>( - this), + RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy>( + this), std::move(cb)), - std::move(args), - /*delegate_lb_policy_name=*/"pick_first", - /*initial_refcount=*/2) {} - - ~InterceptRecvTrailingMetadataLoadBalancingPolicy() override = default; - - const char* name() const override { - return kInterceptRecvTrailingMetadataLbPolicyName; - } - - private: - class Picker : public SubchannelPicker { - public: + std::move(args), + /*delegate_lb_policy_name=*/"pick_first", + /*initial_refcount=*/2) {} + + ~InterceptRecvTrailingMetadataLoadBalancingPolicy() override = default; + + const char* name() const override { + return kInterceptRecvTrailingMetadataLbPolicyName; + } + + private: + class Picker : public SubchannelPicker { + public: Picker(std::unique_ptr<SubchannelPicker> delegate_picker, InterceptRecvTrailingMetadataCallback cb) : delegate_picker_(std::move(delegate_picker)), cb_(std::move(cb)) {} - - PickResult Pick(PickArgs args) override { - // Do pick. - PickResult result = delegate_picker_->Pick(args); - // Intercept trailing metadata. - if (result.type == PickResult::PICK_COMPLETE && - result.subchannel != nullptr) { - new (args.call_state->Alloc(sizeof(TrailingMetadataHandler))) + + PickResult Pick(PickArgs args) override { + // Do pick. + PickResult result = delegate_picker_->Pick(args); + // Intercept trailing metadata. + if (result.type == PickResult::PICK_COMPLETE && + result.subchannel != nullptr) { + new (args.call_state->Alloc(sizeof(TrailingMetadataHandler))) TrailingMetadataHandler(&result, cb_); - } - return result; - } - - private: - std::unique_ptr<SubchannelPicker> delegate_picker_; - InterceptRecvTrailingMetadataCallback cb_; - }; - - class Helper : public ChannelControlHelper { - public: - Helper( - RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent, + } + return result; + } + + private: + std::unique_ptr<SubchannelPicker> delegate_picker_; + InterceptRecvTrailingMetadataCallback cb_; + }; + + class Helper : public ChannelControlHelper { + public: + Helper( + RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent, InterceptRecvTrailingMetadataCallback cb) : parent_(std::move(parent)), cb_(std::move(cb)) {} - - RefCountedPtr<SubchannelInterface> CreateSubchannel( + + RefCountedPtr<SubchannelInterface> CreateSubchannel( ServerAddress address, const grpc_channel_args& args) override { return parent_->channel_control_helper()->CreateSubchannel( std::move(address), args); - } - + } + void UpdateState(grpc_connectivity_state state, const y_absl::Status& status, - std::unique_ptr<SubchannelPicker> picker) override { - parent_->channel_control_helper()->UpdateState( + std::unique_ptr<SubchannelPicker> picker) override { + parent_->channel_control_helper()->UpdateState( state, status, y_absl::make_unique<Picker>(std::move(picker), cb_)); - } - - void RequestReresolution() override { - parent_->channel_control_helper()->RequestReresolution(); - } - + } + + void RequestReresolution() override { + parent_->channel_control_helper()->RequestReresolution(); + } + void AddTraceEvent(TraceSeverity severity, y_absl::string_view message) override { - parent_->channel_control_helper()->AddTraceEvent(severity, message); - } - - private: - RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent_; - InterceptRecvTrailingMetadataCallback cb_; - }; - - class TrailingMetadataHandler { - public: - TrailingMetadataHandler(PickResult* result, + parent_->channel_control_helper()->AddTraceEvent(severity, message); + } + + private: + RefCountedPtr<InterceptRecvTrailingMetadataLoadBalancingPolicy> parent_; + InterceptRecvTrailingMetadataCallback cb_; + }; + + class TrailingMetadataHandler { + public: + TrailingMetadataHandler(PickResult* result, InterceptRecvTrailingMetadataCallback cb) : cb_(std::move(cb)) { - result->recv_trailing_metadata_ready = [this](grpc_error* error, - MetadataInterface* metadata, - CallState* call_state) { - RecordRecvTrailingMetadata(error, metadata, call_state); - }; - } - - private: - void RecordRecvTrailingMetadata(grpc_error* /*error*/, - MetadataInterface* recv_trailing_metadata, - CallState* call_state) { + result->recv_trailing_metadata_ready = [this](grpc_error* error, + MetadataInterface* metadata, + CallState* call_state) { + RecordRecvTrailingMetadata(error, metadata, call_state); + }; + } + + private: + void RecordRecvTrailingMetadata(grpc_error* /*error*/, + MetadataInterface* recv_trailing_metadata, + CallState* call_state) { TrailingMetadataArgsSeen args_seen; args_seen.backend_metric_data = call_state->GetBackendMetricData(); - GPR_ASSERT(recv_trailing_metadata != nullptr); + GPR_ASSERT(recv_trailing_metadata != nullptr); args_seen.metadata = CopyMetadataToVector(recv_trailing_metadata); cb_(args_seen); - this->~TrailingMetadataHandler(); - } - - InterceptRecvTrailingMetadataCallback cb_; - }; -}; - + this->~TrailingMetadataHandler(); + } + + InterceptRecvTrailingMetadataCallback cb_; + }; +}; + class InterceptTrailingConfig : public LoadBalancingPolicy::Config { public: const char* name() const override { @@ -309,30 +309,30 @@ class InterceptTrailingConfig : public LoadBalancingPolicy::Config { } }; -class InterceptTrailingFactory : public LoadBalancingPolicyFactory { - public: +class InterceptTrailingFactory : public LoadBalancingPolicyFactory { + public: explicit InterceptTrailingFactory(InterceptRecvTrailingMetadataCallback cb) : cb_(std::move(cb)) {} - - OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy( - LoadBalancingPolicy::Args args) const override { - return MakeOrphanable<InterceptRecvTrailingMetadataLoadBalancingPolicy>( + + OrphanablePtr<LoadBalancingPolicy> CreateLoadBalancingPolicy( + LoadBalancingPolicy::Args args) const override { + return MakeOrphanable<InterceptRecvTrailingMetadataLoadBalancingPolicy>( std::move(args), cb_); - } - - const char* name() const override { - return kInterceptRecvTrailingMetadataLbPolicyName; - } - - RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig( + } + + const char* name() const override { + return kInterceptRecvTrailingMetadataLbPolicyName; + } + + RefCountedPtr<LoadBalancingPolicy::Config> ParseLoadBalancingConfig( const Json& /*json*/, grpc_error** /*error*/) const override { return MakeRefCounted<InterceptTrailingConfig>(); - } - - private: - InterceptRecvTrailingMetadataCallback cb_; -}; - + } + + private: + InterceptRecvTrailingMetadataCallback cb_; +}; + // // AddressTestLoadBalancingPolicy // @@ -414,22 +414,22 @@ class AddressTestFactory : public LoadBalancingPolicyFactory { AddressTestCallback cb_; }; -} // namespace - +} // namespace + void RegisterTestPickArgsLoadBalancingPolicy(TestPickArgsCallback cb) { LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory( y_absl::make_unique<TestPickArgsLbFactory>(std::move(cb))); } -void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy( +void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy( InterceptRecvTrailingMetadataCallback cb) { - LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory( + LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory( y_absl::make_unique<InterceptTrailingFactory>(std::move(cb))); -} - +} + void RegisterAddressTestLoadBalancingPolicy(AddressTestCallback cb) { LoadBalancingPolicyRegistry::Builder::RegisterLoadBalancingPolicyFactory( y_absl::make_unique<AddressTestFactory>(std::move(cb))); } -} // namespace grpc_core +} // namespace grpc_core diff --git a/contrib/libs/grpc/test/core/util/test_lb_policies.h b/contrib/libs/grpc/test/core/util/test_lb_policies.h index a5c02283b6..9e14c707a3 100644 --- a/contrib/libs/grpc/test/core/util/test_lb_policies.h +++ b/contrib/libs/grpc/test/core/util/test_lb_policies.h @@ -1,30 +1,30 @@ -/* - * - * 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_TEST_CORE_UTIL_TEST_LB_POLICIES_H -#define GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H - -#include "src/core/ext/filters/client_channel/lb_policy.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. + * + */ + +#ifndef GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H +#define GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H + +#include "src/core/ext/filters/client_channel/lb_policy.h" + +namespace grpc_core { + using MetadataVector = std::vector<std::pair<TString, TString>>; - + struct PickArgsSeen { TString path; MetadataVector metadata; @@ -44,17 +44,17 @@ struct TrailingMetadataArgsSeen { using InterceptRecvTrailingMetadataCallback = std::function<void(const TrailingMetadataArgsSeen&)>; -// Registers an LB policy called "intercept_trailing_metadata_lb" that +// Registers an LB policy called "intercept_trailing_metadata_lb" that // invokes cb when trailing metadata is received for each call. -void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy( +void RegisterInterceptRecvTrailingMetadataLoadBalancingPolicy( InterceptRecvTrailingMetadataCallback cb); - + using AddressTestCallback = std::function<void(const ServerAddress&)>; // Registers an LB policy called "address_test_lb" that invokes cb for each // address used to create a subchannel. void RegisterAddressTestLoadBalancingPolicy(AddressTestCallback cb); -} // namespace grpc_core - -#endif // GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H +} // namespace grpc_core + +#endif // GRPC_TEST_CORE_UTIL_TEST_LB_POLICIES_H diff --git a/contrib/libs/grpc/test/core/util/test_tcp_server.cc b/contrib/libs/grpc/test/core/util/test_tcp_server.cc index 9550ef6b08..9dd1e2af36 100644 --- a/contrib/libs/grpc/test/core/util/test_tcp_server.cc +++ b/contrib/libs/grpc/test/core/util/test_tcp_server.cc @@ -1,116 +1,116 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -#include "src/core/lib/iomgr/sockaddr.h" -#include "src/core/lib/iomgr/socket_utils.h" - -#include "test/core/util/test_tcp_server.h" - -#include <grpc/grpc.h> -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/sync.h> -#include <grpc/support/time.h> -#include <string.h> - -#include "src/core/lib/iomgr/endpoint.h" -#include "src/core/lib/iomgr/resolve_address.h" -#include "src/core/lib/iomgr/tcp_server.h" -#include "test/core/util/port.h" -#include "test/core/util/test_config.h" - -static void on_server_destroyed(void* data, grpc_error* /*error*/) { - test_tcp_server* server = static_cast<test_tcp_server*>(data); +/* + * + * Copyright 2015 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "src/core/lib/iomgr/sockaddr.h" +#include "src/core/lib/iomgr/socket_utils.h" + +#include "test/core/util/test_tcp_server.h" + +#include <grpc/grpc.h> +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/sync.h> +#include <grpc/support/time.h> +#include <string.h> + +#include "src/core/lib/iomgr/endpoint.h" +#include "src/core/lib/iomgr/resolve_address.h" +#include "src/core/lib/iomgr/tcp_server.h" +#include "test/core/util/port.h" +#include "test/core/util/test_config.h" + +static void on_server_destroyed(void* data, grpc_error* /*error*/) { + test_tcp_server* server = static_cast<test_tcp_server*>(data); server->shutdown = true; -} - -void test_tcp_server_init(test_tcp_server* server, - grpc_tcp_server_cb on_connect, void* user_data) { - grpc_init(); - GRPC_CLOSURE_INIT(&server->shutdown_complete, on_server_destroyed, server, - grpc_schedule_on_exec_ctx); +} + +void test_tcp_server_init(test_tcp_server* server, + grpc_tcp_server_cb on_connect, void* user_data) { + grpc_init(); + GRPC_CLOSURE_INIT(&server->shutdown_complete, on_server_destroyed, server, + grpc_schedule_on_exec_ctx); grpc_pollset* pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size())); grpc_pollset_init(pollset, &server->mu); server->pollset.push_back(pollset); - server->on_connect = on_connect; - server->cb_data = user_data; -} - -void test_tcp_server_start(test_tcp_server* server, int port) { - grpc_resolved_address resolved_addr; - grpc_sockaddr_in* addr = - reinterpret_cast<grpc_sockaddr_in*>(resolved_addr.addr); - int port_added; - grpc_core::ExecCtx exec_ctx; - - addr->sin_family = GRPC_AF_INET; - addr->sin_port = grpc_htons(static_cast<uint16_t>(port)); - memset(&addr->sin_addr, 0, sizeof(addr->sin_addr)); - - grpc_error* error = grpc_tcp_server_create(&server->shutdown_complete, - nullptr, &server->tcp_server); - GPR_ASSERT(error == GRPC_ERROR_NONE); - error = - grpc_tcp_server_add_port(server->tcp_server, &resolved_addr, &port_added); - GPR_ASSERT(error == GRPC_ERROR_NONE); - GPR_ASSERT(port_added == port); - + server->on_connect = on_connect; + server->cb_data = user_data; +} + +void test_tcp_server_start(test_tcp_server* server, int port) { + grpc_resolved_address resolved_addr; + grpc_sockaddr_in* addr = + reinterpret_cast<grpc_sockaddr_in*>(resolved_addr.addr); + int port_added; + grpc_core::ExecCtx exec_ctx; + + addr->sin_family = GRPC_AF_INET; + addr->sin_port = grpc_htons(static_cast<uint16_t>(port)); + memset(&addr->sin_addr, 0, sizeof(addr->sin_addr)); + + grpc_error* error = grpc_tcp_server_create(&server->shutdown_complete, + nullptr, &server->tcp_server); + GPR_ASSERT(error == GRPC_ERROR_NONE); + error = + grpc_tcp_server_add_port(server->tcp_server, &resolved_addr, &port_added); + GPR_ASSERT(error == GRPC_ERROR_NONE); + GPR_ASSERT(port_added == port); + grpc_tcp_server_start(server->tcp_server, &server->pollset, - server->on_connect, server->cb_data); - gpr_log(GPR_INFO, "test tcp server listening on 0.0.0.0:%d", port); -} - -void test_tcp_server_poll(test_tcp_server* server, int milliseconds) { - grpc_pollset_worker* worker = nullptr; - grpc_core::ExecCtx exec_ctx; - grpc_millis deadline = grpc_timespec_to_millis_round_up( - grpc_timeout_milliseconds_to_deadline(milliseconds)); - gpr_mu_lock(server->mu); - GRPC_LOG_IF_ERROR("pollset_work", + server->on_connect, server->cb_data); + gpr_log(GPR_INFO, "test tcp server listening on 0.0.0.0:%d", port); +} + +void test_tcp_server_poll(test_tcp_server* server, int milliseconds) { + grpc_pollset_worker* worker = nullptr; + grpc_core::ExecCtx exec_ctx; + grpc_millis deadline = grpc_timespec_to_millis_round_up( + grpc_timeout_milliseconds_to_deadline(milliseconds)); + gpr_mu_lock(server->mu); + GRPC_LOG_IF_ERROR("pollset_work", grpc_pollset_work(server->pollset[0], &worker, deadline)); - gpr_mu_unlock(server->mu); -} - -static void do_nothing(void* /*arg*/, grpc_error* /*error*/) {} -static void finish_pollset(void* arg, grpc_error* /*error*/) { - grpc_pollset_destroy(static_cast<grpc_pollset*>(arg)); -} - -void test_tcp_server_destroy(test_tcp_server* server) { - grpc_core::ExecCtx exec_ctx; - gpr_timespec shutdown_deadline; - grpc_closure do_nothing_cb; - grpc_tcp_server_unref(server->tcp_server); - GRPC_CLOSURE_INIT(&do_nothing_cb, do_nothing, nullptr, - grpc_schedule_on_exec_ctx); - shutdown_deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), - gpr_time_from_seconds(5, GPR_TIMESPAN)); - grpc_core::ExecCtx::Get()->Flush(); - while (!server->shutdown && - gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), shutdown_deadline) < 0) { - test_tcp_server_poll(server, 1000); - } + gpr_mu_unlock(server->mu); +} + +static void do_nothing(void* /*arg*/, grpc_error* /*error*/) {} +static void finish_pollset(void* arg, grpc_error* /*error*/) { + grpc_pollset_destroy(static_cast<grpc_pollset*>(arg)); +} + +void test_tcp_server_destroy(test_tcp_server* server) { + grpc_core::ExecCtx exec_ctx; + gpr_timespec shutdown_deadline; + grpc_closure do_nothing_cb; + grpc_tcp_server_unref(server->tcp_server); + GRPC_CLOSURE_INIT(&do_nothing_cb, do_nothing, nullptr, + grpc_schedule_on_exec_ctx); + shutdown_deadline = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), + gpr_time_from_seconds(5, GPR_TIMESPAN)); + grpc_core::ExecCtx::Get()->Flush(); + while (!server->shutdown && + gpr_time_cmp(gpr_now(GPR_CLOCK_MONOTONIC), shutdown_deadline) < 0) { + test_tcp_server_poll(server, 1000); + } grpc_pollset_shutdown(server->pollset[0], GRPC_CLOSURE_CREATE(finish_pollset, server->pollset[0], - grpc_schedule_on_exec_ctx)); - grpc_core::ExecCtx::Get()->Flush(); + grpc_schedule_on_exec_ctx)); + grpc_core::ExecCtx::Get()->Flush(); gpr_free(server->pollset[0]); - grpc_shutdown(); -} + grpc_shutdown(); +} diff --git a/contrib/libs/grpc/test/core/util/test_tcp_server.h b/contrib/libs/grpc/test/core/util/test_tcp_server.h index 8b40f3a1be..8765ea9a22 100644 --- a/contrib/libs/grpc/test/core/util/test_tcp_server.h +++ b/contrib/libs/grpc/test/core/util/test_tcp_server.h @@ -1,47 +1,47 @@ -/* - * - * 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_TEST_CORE_UTIL_TEST_TCP_SERVER_H -#define GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_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_TEST_CORE_UTIL_TEST_TCP_SERVER_H +#define GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H + #include <vector> -#include <grpc/support/sync.h> -#include "src/core/lib/iomgr/tcp_server.h" - +#include <grpc/support/sync.h> +#include "src/core/lib/iomgr/tcp_server.h" + // test_tcp_server should be stack-allocated or new'ed, never gpr_malloc'ed // since it contains C++ objects. struct test_tcp_server { grpc_tcp_server* tcp_server = nullptr; - grpc_closure shutdown_complete; + grpc_closure shutdown_complete; bool shutdown = false; // mu is filled in by grpc_pollset_init and controls the pollset. // TODO: Switch this to a Mutex once pollset_init can provide a Mutex - gpr_mu* mu; + gpr_mu* mu; std::vector<grpc_pollset*> pollset; - grpc_tcp_server_cb on_connect; - void* cb_data; + grpc_tcp_server_cb on_connect; + void* cb_data; }; - -void test_tcp_server_init(test_tcp_server* server, - grpc_tcp_server_cb on_connect, void* user_data); -void test_tcp_server_start(test_tcp_server* server, int port); -void test_tcp_server_poll(test_tcp_server* server, int milliseconds); -void test_tcp_server_destroy(test_tcp_server* server); - -#endif /* GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H */ + +void test_tcp_server_init(test_tcp_server* server, + grpc_tcp_server_cb on_connect, void* user_data); +void test_tcp_server_start(test_tcp_server* server, int port); +void test_tcp_server_poll(test_tcp_server* server, int milliseconds); +void test_tcp_server_destroy(test_tcp_server* server); + +#endif /* GRPC_TEST_CORE_UTIL_TEST_TCP_SERVER_H */ diff --git a/contrib/libs/grpc/test/core/util/tracer_util.cc b/contrib/libs/grpc/test/core/util/tracer_util.cc index 6b4dfbdccd..34a132daa7 100644 --- a/contrib/libs/grpc/test/core/util/tracer_util.cc +++ b/contrib/libs/grpc/test/core/util/tracer_util.cc @@ -1,31 +1,31 @@ -/* - * - * 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 "test/core/util/test_config.h" - -#include "src/core/lib/debug/trace.h" - -namespace grpc_core { -namespace testing { - -void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag) { - flag->set_enabled(1); -} - -} // namespace testing -} // namespace grpc_core +/* + * + * 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 "test/core/util/test_config.h" + +#include "src/core/lib/debug/trace.h" + +namespace grpc_core { +namespace testing { + +void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag) { + flag->set_enabled(1); +} + +} // namespace testing +} // namespace grpc_core diff --git a/contrib/libs/grpc/test/core/util/tracer_util.h b/contrib/libs/grpc/test/core/util/tracer_util.h index a4ad95ab5c..0b432ffa46 100644 --- a/contrib/libs/grpc/test/core/util/tracer_util.h +++ b/contrib/libs/grpc/test/core/util/tracer_util.h @@ -1,32 +1,32 @@ -/* - * - * 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_TEST_CORE_UTIL_TRACER_UTIL_H -#define GRPC_TEST_CORE_UTIL_TRACER_UTIL_H - -namespace grpc_core { -class TraceFlag; - -namespace testing { -// enables the TraceFlag passed to it. Used for testing purposes. -void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag); - -} // namespace testing -} // namespace grpc_core - -#endif /* GRPC_TEST_CORE_UTIL_TRACER_UTIL_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_TEST_CORE_UTIL_TRACER_UTIL_H +#define GRPC_TEST_CORE_UTIL_TRACER_UTIL_H + +namespace grpc_core { +class TraceFlag; + +namespace testing { +// enables the TraceFlag passed to it. Used for testing purposes. +void grpc_tracer_enable_flag(grpc_core::TraceFlag* flag); + +} // namespace testing +} // namespace grpc_core + +#endif /* GRPC_TEST_CORE_UTIL_TRACER_UTIL_H */ diff --git a/contrib/libs/grpc/test/core/util/trickle_endpoint.cc b/contrib/libs/grpc/test/core/util/trickle_endpoint.cc index 496e2586ab..28ffb0e3e7 100644 --- a/contrib/libs/grpc/test/core/util/trickle_endpoint.cc +++ b/contrib/libs/grpc/test/core/util/trickle_endpoint.cc @@ -1,215 +1,215 @@ -/* - * - * 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 "src/core/lib/iomgr/sockaddr.h" - -#include "test/core/util/passthru_endpoint.h" - -#include <inttypes.h> -#include <string.h> - -#include <grpc/support/alloc.h> -#include <grpc/support/log.h> -#include <grpc/support/string_util.h> - -#include "src/core/lib/gpr/useful.h" -#include "src/core/lib/slice/slice_internal.h" - -#define WRITE_BUFFER_SIZE (2 * 1024 * 1024) - -typedef struct { - grpc_endpoint base; - double bytes_per_second; - grpc_endpoint* wrapped; - gpr_timespec last_write; - - gpr_mu mu; - grpc_slice_buffer write_buffer; - grpc_slice_buffer writing_buffer; - grpc_error* error; - bool writing; - grpc_closure* write_cb; -} trickle_endpoint; - -static void te_read(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, bool urgent) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - grpc_endpoint_read(te->wrapped, slices, cb, urgent); -} - -static void maybe_call_write_cb_locked(trickle_endpoint* te) { - if (te->write_cb != nullptr && - (te->error != GRPC_ERROR_NONE || - te->write_buffer.length <= WRITE_BUFFER_SIZE)) { - grpc_core::ExecCtx::Run(DEBUG_LOCATION, te->write_cb, - GRPC_ERROR_REF(te->error)); - te->write_cb = nullptr; - } -} - -static void te_write(grpc_endpoint* ep, grpc_slice_buffer* slices, - grpc_closure* cb, void* /*arg*/) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - gpr_mu_lock(&te->mu); - GPR_ASSERT(te->write_cb == nullptr); - if (te->write_buffer.length == 0) { - te->last_write = gpr_now(GPR_CLOCK_MONOTONIC); - } - for (size_t i = 0; i < slices->count; i++) { - grpc_slice_buffer_add(&te->write_buffer, - grpc_slice_copy(slices->slices[i])); - } - te->write_cb = cb; - maybe_call_write_cb_locked(te); - gpr_mu_unlock(&te->mu); -} - -static void te_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - grpc_endpoint_add_to_pollset(te->wrapped, pollset); -} - -static void te_add_to_pollset_set(grpc_endpoint* ep, - grpc_pollset_set* pollset_set) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - grpc_endpoint_add_to_pollset_set(te->wrapped, pollset_set); -} - -static void te_delete_from_pollset_set(grpc_endpoint* ep, - grpc_pollset_set* pollset_set) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - grpc_endpoint_delete_from_pollset_set(te->wrapped, pollset_set); -} - -static void te_shutdown(grpc_endpoint* ep, grpc_error* why) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - gpr_mu_lock(&te->mu); - if (te->error == GRPC_ERROR_NONE) { - te->error = GRPC_ERROR_REF(why); - } - maybe_call_write_cb_locked(te); - gpr_mu_unlock(&te->mu); - grpc_endpoint_shutdown(te->wrapped, why); -} - -static void te_destroy(grpc_endpoint* ep) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - grpc_endpoint_destroy(te->wrapped); - gpr_mu_destroy(&te->mu); - grpc_slice_buffer_destroy_internal(&te->write_buffer); - grpc_slice_buffer_destroy_internal(&te->writing_buffer); - GRPC_ERROR_UNREF(te->error); - gpr_free(te); -} - -static grpc_resource_user* te_get_resource_user(grpc_endpoint* ep) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - return grpc_endpoint_get_resource_user(te->wrapped); -} - +/* + * + * 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 "src/core/lib/iomgr/sockaddr.h" + +#include "test/core/util/passthru_endpoint.h" + +#include <inttypes.h> +#include <string.h> + +#include <grpc/support/alloc.h> +#include <grpc/support/log.h> +#include <grpc/support/string_util.h> + +#include "src/core/lib/gpr/useful.h" +#include "src/core/lib/slice/slice_internal.h" + +#define WRITE_BUFFER_SIZE (2 * 1024 * 1024) + +typedef struct { + grpc_endpoint base; + double bytes_per_second; + grpc_endpoint* wrapped; + gpr_timespec last_write; + + gpr_mu mu; + grpc_slice_buffer write_buffer; + grpc_slice_buffer writing_buffer; + grpc_error* error; + bool writing; + grpc_closure* write_cb; +} trickle_endpoint; + +static void te_read(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, bool urgent) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + grpc_endpoint_read(te->wrapped, slices, cb, urgent); +} + +static void maybe_call_write_cb_locked(trickle_endpoint* te) { + if (te->write_cb != nullptr && + (te->error != GRPC_ERROR_NONE || + te->write_buffer.length <= WRITE_BUFFER_SIZE)) { + grpc_core::ExecCtx::Run(DEBUG_LOCATION, te->write_cb, + GRPC_ERROR_REF(te->error)); + te->write_cb = nullptr; + } +} + +static void te_write(grpc_endpoint* ep, grpc_slice_buffer* slices, + grpc_closure* cb, void* /*arg*/) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + gpr_mu_lock(&te->mu); + GPR_ASSERT(te->write_cb == nullptr); + if (te->write_buffer.length == 0) { + te->last_write = gpr_now(GPR_CLOCK_MONOTONIC); + } + for (size_t i = 0; i < slices->count; i++) { + grpc_slice_buffer_add(&te->write_buffer, + grpc_slice_copy(slices->slices[i])); + } + te->write_cb = cb; + maybe_call_write_cb_locked(te); + gpr_mu_unlock(&te->mu); +} + +static void te_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + grpc_endpoint_add_to_pollset(te->wrapped, pollset); +} + +static void te_add_to_pollset_set(grpc_endpoint* ep, + grpc_pollset_set* pollset_set) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + grpc_endpoint_add_to_pollset_set(te->wrapped, pollset_set); +} + +static void te_delete_from_pollset_set(grpc_endpoint* ep, + grpc_pollset_set* pollset_set) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + grpc_endpoint_delete_from_pollset_set(te->wrapped, pollset_set); +} + +static void te_shutdown(grpc_endpoint* ep, grpc_error* why) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + gpr_mu_lock(&te->mu); + if (te->error == GRPC_ERROR_NONE) { + te->error = GRPC_ERROR_REF(why); + } + maybe_call_write_cb_locked(te); + gpr_mu_unlock(&te->mu); + grpc_endpoint_shutdown(te->wrapped, why); +} + +static void te_destroy(grpc_endpoint* ep) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + grpc_endpoint_destroy(te->wrapped); + gpr_mu_destroy(&te->mu); + grpc_slice_buffer_destroy_internal(&te->write_buffer); + grpc_slice_buffer_destroy_internal(&te->writing_buffer); + GRPC_ERROR_UNREF(te->error); + gpr_free(te); +} + +static grpc_resource_user* te_get_resource_user(grpc_endpoint* ep) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + return grpc_endpoint_get_resource_user(te->wrapped); +} + static y_absl::string_view te_get_peer(grpc_endpoint* ep) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - return grpc_endpoint_get_peer(te->wrapped); -} - + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + return grpc_endpoint_get_peer(te->wrapped); +} + static y_absl::string_view te_get_local_address(grpc_endpoint* ep) { trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); return grpc_endpoint_get_local_address(te->wrapped); } -static int te_get_fd(grpc_endpoint* ep) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - return grpc_endpoint_get_fd(te->wrapped); -} - -static bool te_can_track_err(grpc_endpoint* /*ep*/) { return false; } - -static void te_finish_write(void* arg, grpc_error* /*error*/) { - trickle_endpoint* te = static_cast<trickle_endpoint*>(arg); - gpr_mu_lock(&te->mu); - te->writing = false; - grpc_slice_buffer_reset_and_unref(&te->writing_buffer); - gpr_mu_unlock(&te->mu); -} - -static const grpc_endpoint_vtable vtable = {te_read, - te_write, - te_add_to_pollset, - te_add_to_pollset_set, - te_delete_from_pollset_set, - te_shutdown, - te_destroy, - te_get_resource_user, - te_get_peer, +static int te_get_fd(grpc_endpoint* ep) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + return grpc_endpoint_get_fd(te->wrapped); +} + +static bool te_can_track_err(grpc_endpoint* /*ep*/) { return false; } + +static void te_finish_write(void* arg, grpc_error* /*error*/) { + trickle_endpoint* te = static_cast<trickle_endpoint*>(arg); + gpr_mu_lock(&te->mu); + te->writing = false; + grpc_slice_buffer_reset_and_unref(&te->writing_buffer); + gpr_mu_unlock(&te->mu); +} + +static const grpc_endpoint_vtable vtable = {te_read, + te_write, + te_add_to_pollset, + te_add_to_pollset_set, + te_delete_from_pollset_set, + te_shutdown, + te_destroy, + te_get_resource_user, + te_get_peer, te_get_local_address, - te_get_fd, - te_can_track_err}; - -grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap, - double bytes_per_second) { - trickle_endpoint* te = - static_cast<trickle_endpoint*>(gpr_malloc(sizeof(*te))); - te->base.vtable = &vtable; - te->wrapped = wrap; - te->bytes_per_second = bytes_per_second; - te->write_cb = nullptr; - gpr_mu_init(&te->mu); - grpc_slice_buffer_init(&te->write_buffer); - grpc_slice_buffer_init(&te->writing_buffer); - te->error = GRPC_ERROR_NONE; - te->writing = false; - return &te->base; -} - -static double ts2dbl(gpr_timespec s) { - return static_cast<double>(s.tv_sec) + 1e-9 * static_cast<double>(s.tv_nsec); -} - -size_t grpc_trickle_endpoint_trickle(grpc_endpoint* ep) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - gpr_mu_lock(&te->mu); - if (!te->writing && te->write_buffer.length > 0) { - gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC); - double elapsed = ts2dbl(gpr_time_sub(now, te->last_write)); - size_t bytes = static_cast<size_t>(te->bytes_per_second * elapsed); - // gpr_log(GPR_DEBUG, "%lf elapsed --> %" PRIdPTR " bytes", elapsed, bytes); - if (bytes > 0) { - grpc_slice_buffer_move_first(&te->write_buffer, - GPR_MIN(bytes, te->write_buffer.length), - &te->writing_buffer); - te->writing = true; - te->last_write = now; - grpc_endpoint_write( - te->wrapped, &te->writing_buffer, - GRPC_CLOSURE_CREATE(te_finish_write, te, grpc_schedule_on_exec_ctx), - nullptr); - maybe_call_write_cb_locked(te); - } - } - size_t backlog = te->write_buffer.length; - gpr_mu_unlock(&te->mu); - return backlog; -} - -size_t grpc_trickle_get_backlog(grpc_endpoint* ep) { - trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); - gpr_mu_lock(&te->mu); - size_t backlog = te->write_buffer.length; - gpr_mu_unlock(&te->mu); - return backlog; -} + te_get_fd, + te_can_track_err}; + +grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap, + double bytes_per_second) { + trickle_endpoint* te = + static_cast<trickle_endpoint*>(gpr_malloc(sizeof(*te))); + te->base.vtable = &vtable; + te->wrapped = wrap; + te->bytes_per_second = bytes_per_second; + te->write_cb = nullptr; + gpr_mu_init(&te->mu); + grpc_slice_buffer_init(&te->write_buffer); + grpc_slice_buffer_init(&te->writing_buffer); + te->error = GRPC_ERROR_NONE; + te->writing = false; + return &te->base; +} + +static double ts2dbl(gpr_timespec s) { + return static_cast<double>(s.tv_sec) + 1e-9 * static_cast<double>(s.tv_nsec); +} + +size_t grpc_trickle_endpoint_trickle(grpc_endpoint* ep) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + gpr_mu_lock(&te->mu); + if (!te->writing && te->write_buffer.length > 0) { + gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC); + double elapsed = ts2dbl(gpr_time_sub(now, te->last_write)); + size_t bytes = static_cast<size_t>(te->bytes_per_second * elapsed); + // gpr_log(GPR_DEBUG, "%lf elapsed --> %" PRIdPTR " bytes", elapsed, bytes); + if (bytes > 0) { + grpc_slice_buffer_move_first(&te->write_buffer, + GPR_MIN(bytes, te->write_buffer.length), + &te->writing_buffer); + te->writing = true; + te->last_write = now; + grpc_endpoint_write( + te->wrapped, &te->writing_buffer, + GRPC_CLOSURE_CREATE(te_finish_write, te, grpc_schedule_on_exec_ctx), + nullptr); + maybe_call_write_cb_locked(te); + } + } + size_t backlog = te->write_buffer.length; + gpr_mu_unlock(&te->mu); + return backlog; +} + +size_t grpc_trickle_get_backlog(grpc_endpoint* ep) { + trickle_endpoint* te = reinterpret_cast<trickle_endpoint*>(ep); + gpr_mu_lock(&te->mu); + size_t backlog = te->write_buffer.length; + gpr_mu_unlock(&te->mu); + return backlog; +} diff --git a/contrib/libs/grpc/test/core/util/trickle_endpoint.h b/contrib/libs/grpc/test/core/util/trickle_endpoint.h index 4912747d2a..cd07de905a 100644 --- a/contrib/libs/grpc/test/core/util/trickle_endpoint.h +++ b/contrib/libs/grpc/test/core/util/trickle_endpoint.h @@ -1,32 +1,32 @@ -/* - * - * 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. - * - */ - -#ifndef TRICKLE_ENDPOINT_H -#define TRICKLE_ENDPOINT_H - -#include "src/core/lib/iomgr/endpoint.h" - -grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap, - double bytes_per_second); - -/* Allow up to \a bytes through the endpoint. Returns the new backlog. */ -size_t grpc_trickle_endpoint_trickle(grpc_endpoint* endpoint); - -size_t grpc_trickle_get_backlog(grpc_endpoint* endpoint); - -#endif +/* + * + * 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. + * + */ + +#ifndef TRICKLE_ENDPOINT_H +#define TRICKLE_ENDPOINT_H + +#include "src/core/lib/iomgr/endpoint.h" + +grpc_endpoint* grpc_trickle_endpoint_create(grpc_endpoint* wrap, + double bytes_per_second); + +/* Allow up to \a bytes through the endpoint. Returns the new backlog. */ +size_t grpc_trickle_endpoint_trickle(grpc_endpoint* endpoint); + +size_t grpc_trickle_get_backlog(grpc_endpoint* endpoint); + +#endif diff --git a/contrib/libs/grpc/test/core/util/tsan_suppressions.txt b/contrib/libs/grpc/test/core/util/tsan_suppressions.txt index 8db4f52d4a..e0c7907228 100644 --- a/contrib/libs/grpc/test/core/util/tsan_suppressions.txt +++ b/contrib/libs/grpc/test/core/util/tsan_suppressions.txt @@ -1,13 +1,13 @@ -# OPENSSL_cleanse does racy access to a global -race:OPENSSL_cleanse -race:cleanse_ctr -# these are legitimate races in OpenSSL, and it appears those folks are looking at it -# https://www.mail-archive.com/openssl-dev@openssl.org/msg09019.html -race:ssleay_rand_add -race:ssleay_rand_bytes -race:__sleep_for -# protobuf has an idempotent write race in ByteSize/GetCachedSize -# https://github.com/google/protobuf/issues/2169 -race:ByteSize -race:ByteSizeLong -race:GetCachedSize +# OPENSSL_cleanse does racy access to a global +race:OPENSSL_cleanse +race:cleanse_ctr +# these are legitimate races in OpenSSL, and it appears those folks are looking at it +# https://www.mail-archive.com/openssl-dev@openssl.org/msg09019.html +race:ssleay_rand_add +race:ssleay_rand_bytes +race:__sleep_for +# protobuf has an idempotent write race in ByteSize/GetCachedSize +# https://github.com/google/protobuf/issues/2169 +race:ByteSize +race:ByteSizeLong +race:GetCachedSize diff --git a/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt b/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt index f4fdce3d5c..ca233b8a28 100644 --- a/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt +++ b/contrib/libs/grpc/test/core/util/ubsan_suppressions.txt @@ -1,27 +1,27 @@ -# Protobuf stuff -nonnull-attribute:google::protobuf::* -alignment:google::protobuf::* -nonnull-attribute:_tr_stored_block -# The following 5 suppressors should be removed as part of C++ cleanup -enum:client_fuzzer_one_entry -enum:message_compress_test -enum:transport_security_test -enum:algorithm_test -alignment:transport_security_test -# TODO(jtattermusch): address issues and remove the supressions -nonnull-attribute:gsec_aes_gcm_aead_crypter_decrypt_iovec -nonnull-attribute:gsec_test_random_encrypt_decrypt -nonnull-attribute:gsec_test_multiple_random_encrypt_decrypt -nonnull-attribute:gsec_test_copy -nonnull-attribute:gsec_test_encrypt_decrypt_test_vector +# Protobuf stuff +nonnull-attribute:google::protobuf::* +alignment:google::protobuf::* +nonnull-attribute:_tr_stored_block +# The following 5 suppressors should be removed as part of C++ cleanup +enum:client_fuzzer_one_entry +enum:message_compress_test +enum:transport_security_test +enum:algorithm_test +alignment:transport_security_test +# TODO(jtattermusch): address issues and remove the supressions +nonnull-attribute:gsec_aes_gcm_aead_crypter_decrypt_iovec +nonnull-attribute:gsec_test_random_encrypt_decrypt +nonnull-attribute:gsec_test_multiple_random_encrypt_decrypt +nonnull-attribute:gsec_test_copy +nonnull-attribute:gsec_test_encrypt_decrypt_test_vector alignment:y_absl::little_endian::Store64 alignment:y_absl::little_endian::Load64 -float-divide-by-zero:grpc::testing::postprocess_scenario_result -enum:grpc_op_string -signed-integer-overflow:chrono -enum:grpc_http2_error_to_grpc_status -enum:grpc_chttp2_cancel_stream -# TODO(juanlishen): Remove this supression after -# https://github.com/GoogleCloudPlatform/layer-definitions/issues/531 is -# addressed. -alignment:grpc_core::XdsPriorityListUpdate::* +float-divide-by-zero:grpc::testing::postprocess_scenario_result +enum:grpc_op_string +signed-integer-overflow:chrono +enum:grpc_http2_error_to_grpc_status +enum:grpc_chttp2_cancel_stream +# TODO(juanlishen): Remove this supression after +# https://github.com/GoogleCloudPlatform/layer-definitions/issues/531 is +# addressed. +alignment:grpc_core::XdsPriorityListUpdate::* diff --git a/contrib/libs/grpc/test/core/util/ya.make b/contrib/libs/grpc/test/core/util/ya.make index 51d10abb13..fbaad80cad 100644 --- a/contrib/libs/grpc/test/core/util/ya.make +++ b/contrib/libs/grpc/test/core/util/ya.make @@ -1,53 +1,53 @@ -LIBRARY() - +LIBRARY() + LICENSE(Apache-2.0) LICENSE_TEXTS(.yandex_meta/licenses.list.txt) - + OWNER(dvshkurko) -PEERDIR( - contrib/libs/grpc +PEERDIR( + contrib/libs/grpc contrib/restricted/abseil-cpp-tstring/y_absl/debugging/failure_signal_handler -) - +) + ADDINCL( ${ARCADIA_BUILD_ROOT}/contrib/libs/grpc contrib/libs/grpc ) - -NO_COMPILER_WARNINGS() - -SRCS( - # cmdline.cc - # cmdline_test.cc - # debugger_macros.cc - # fuzzer_corpus_test.cc - # fuzzer_one_entry_runner.sh* - # fuzzer_util.cc - # grpc_fuzzer.bzl - # grpc_profiler.cc - # histogram.cc - # histogram_test.cc - # lsan_suppressions.txt - # memory_counters.cc - # mock_endpoint.cc - # one_corpus_entry_fuzzer.cc - # parse_hexstring.cc - # passthru_endpoint.cc - port.cc - # port_isolated_runtime_environment.cc - port_server_client.cc - # reconnect_server.cc - # run_with_poller.sh* - # slice_splitter.cc - # subprocess_posix.cc - # subprocess_windows.cc - test_config.cc - test_lb_policies.cc - # test_tcp_server.cc - # tracer_util.cc - # trickle_endpoint.cc -) - -END() + +NO_COMPILER_WARNINGS() + +SRCS( + # cmdline.cc + # cmdline_test.cc + # debugger_macros.cc + # fuzzer_corpus_test.cc + # fuzzer_one_entry_runner.sh* + # fuzzer_util.cc + # grpc_fuzzer.bzl + # grpc_profiler.cc + # histogram.cc + # histogram_test.cc + # lsan_suppressions.txt + # memory_counters.cc + # mock_endpoint.cc + # one_corpus_entry_fuzzer.cc + # parse_hexstring.cc + # passthru_endpoint.cc + port.cc + # port_isolated_runtime_environment.cc + port_server_client.cc + # reconnect_server.cc + # run_with_poller.sh* + # slice_splitter.cc + # subprocess_posix.cc + # subprocess_windows.cc + test_config.cc + test_lb_policies.cc + # test_tcp_server.cc + # tracer_util.cc + # trickle_endpoint.cc +) + +END() |