Merge pull request #24506 from Capstan/absl-flags

Abseil Flags
pull/24555/head
Esun Kim 4 years ago committed by GitHub
commit 3528a40fe5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      .clang-tidy
  2. 27
      CMakeLists.txt
  3. 5
      bazel/grpc_deps.bzl
  4. 27
      build_autogenerated.yaml
  5. 2
      grpc.gyp
  6. 3
      test/core/tsi/alts/fake_handshaker/BUILD
  7. 17
      test/core/tsi/alts/fake_handshaker/fake_handshaker_server_main.cc
  8. 2
      test/core/util/BUILD
  9. 26
      test/core/util/fuzzer_corpus_test.cc
  10. 2
      test/cpp/codegen/BUILD
  11. 33
      test/cpp/codegen/golden_file_test.cc
  12. 5
      test/cpp/end2end/BUILD
  13. 25
      test/cpp/end2end/client_crash_test_server.cc
  14. 27
      test/cpp/end2end/server_crash_test_client.cc
  15. 36
      test/cpp/interop/BUILD
  16. 157
      test/cpp/interop/client.cc
  17. 78
      test/cpp/interop/client_helper.cc
  18. 71
      test/cpp/interop/grpclb_fallback_test.cc
  19. 55
      test/cpp/interop/http2_client.cc
  20. 34
      test/cpp/interop/interop_server.cc
  21. 20
      test/cpp/interop/interop_test.cc
  22. 31
      test/cpp/interop/metrics_client.cc
  23. 38
      test/cpp/interop/reconnect_interop_client.cc
  24. 29
      test/cpp/interop/reconnect_interop_server.cc
  25. 20
      test/cpp/interop/server_helper.cc
  26. 199
      test/cpp/interop/stress_test.cc
  27. 66
      test/cpp/interop/xds_interop_client.cc
  28. 13
      test/cpp/interop/xds_interop_server.cc
  29. 3
      test/cpp/microbenchmarks/BUILD
  30. 46
      test/cpp/microbenchmarks/bm_fullstack_trickle.cc
  31. 12
      test/cpp/naming/address_sorting_test.cc
  32. 16
      test/cpp/naming/cancel_ares_query_test.cc
  33. 3
      test/cpp/naming/generate_resolver_component_tests.bzl
  34. 148
      test/cpp/naming/resolver_component_test.cc
  35. 38
      test/cpp/naming/resolver_component_tests_runner_invoker.cc
  36. 10
      test/cpp/qps/BUILD
  37. 60
      test/cpp/qps/benchmark_config.cc
  38. 3
      test/cpp/qps/qps_benchmark_script.bzl
  39. 138
      test/cpp/qps/qps_json_driver.cc
  40. 19
      test/cpp/qps/worker.cc
  41. 1
      test/cpp/thread_manager/BUILD
  42. 1
      test/cpp/thread_manager/thread_manager_test.cc
  43. 14
      test/cpp/util/BUILD
  44. 32
      test/cpp/util/channelz_sampler.cc
  45. 125
      test/cpp/util/cli_credentials.cc
  46. 27
      test/cpp/util/create_test_channel.cc
  47. 10
      test/cpp/util/grpc_cli.cc
  48. 198
      test/cpp/util/grpc_tool.cc
  49. 201
      test/cpp/util/grpc_tool_test.cc
  50. 19
      test/cpp/util/test_config_cc.cc
  51. 25
      test/cpp/util/test_credentials_provider.cc

@ -1,6 +1,8 @@
--- ---
# Disable abseil-no-namespace: https://bugs.llvm.org/show_bug.cgi?id=47947
Checks: '-*, Checks: '-*,
abseil-*, abseil-*,
-abseil-no-namespace,
bugprone-*, bugprone-*,
-bugprone-integer-division, -bugprone-integer-division,
-bugprone-narrowing-conversions, -bugprone-narrowing-conversions,

@ -3257,6 +3257,7 @@ target_link_libraries(grpc++_test_config
${_gRPC_PROTOBUF_LIBRARIES} ${_gRPC_PROTOBUF_LIBRARIES}
${_gRPC_ALLTARGETS_LIBRARIES} ${_gRPC_ALLTARGETS_LIBRARIES}
gpr gpr
absl::flags_parse
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -3318,6 +3319,7 @@ target_link_libraries(grpc++_test_util
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -9356,6 +9358,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX)
address_sorting address_sorting
upb upb
${_gRPC_BENCHMARK_LIBRARIES} ${_gRPC_BENCHMARK_LIBRARIES}
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -10166,6 +10169,7 @@ target_link_libraries(cli_call_test
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -11352,6 +11356,7 @@ target_link_libraries(grpc_cli
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -11757,6 +11762,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX)
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -12106,6 +12112,7 @@ target_link_libraries(http2_client
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -12340,6 +12347,7 @@ target_link_libraries(interop_client
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -12396,6 +12404,7 @@ target_link_libraries(interop_server
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -12439,6 +12448,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX)
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -13210,6 +13220,7 @@ target_link_libraries(qps_json_driver
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -13290,6 +13301,7 @@ target_link_libraries(qps_worker
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15407,6 +15419,7 @@ target_link_libraries(xds_interop_client
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15460,6 +15473,7 @@ target_link_libraries(xds_interop_server
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15501,6 +15515,7 @@ target_link_libraries(alts_credentials_fuzzer_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15542,6 +15557,7 @@ target_link_libraries(client_fuzzer_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15583,6 +15599,7 @@ target_link_libraries(hpack_parser_fuzzer_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15624,6 +15641,7 @@ target_link_libraries(http_request_fuzzer_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15665,6 +15683,7 @@ target_link_libraries(http_response_fuzzer_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15706,6 +15725,7 @@ target_link_libraries(json_fuzzer_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15747,6 +15767,7 @@ target_link_libraries(nanopb_fuzzer_response_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15788,6 +15809,7 @@ target_link_libraries(nanopb_fuzzer_serverlist_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15829,6 +15851,7 @@ target_link_libraries(percent_decode_fuzzer_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15870,6 +15893,7 @@ target_link_libraries(percent_encode_fuzzer_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15911,6 +15935,7 @@ target_link_libraries(server_fuzzer_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15952,6 +15977,7 @@ target_link_libraries(ssl_server_fuzzer_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )
@ -15993,6 +16019,7 @@ target_link_libraries(uri_fuzzer_test_one_entry
gpr gpr
address_sorting address_sorting
upb upb
absl::flags
${_gRPC_GFLAGS_LIBRARIES} ${_gRPC_GFLAGS_LIBRARIES}
) )

@ -86,11 +86,6 @@ def grpc_deps():
actual = "@com_github_google_re2//:re2", actual = "@com_github_google_re2//:re2",
) )
native.bind(
name = "gflags",
actual = "@com_github_gflags_gflags//:gflags",
)
native.bind( native.bind(
name = "grpc_cpp_plugin", name = "grpc_cpp_plugin",
actual = "@com_github_grpc_grpc//src/compiler:grpc_cpp_plugin", actual = "@com_github_grpc_grpc//src/compiler:grpc_cpp_plugin",

@ -2424,6 +2424,7 @@ libs:
- test/cpp/util/test_config_cc.cc - test/cpp/util/test_config_cc.cc
deps: deps:
- gpr - gpr
- absl/flags:parse
- name: grpc++_test_util - name: grpc++_test_util
build: private build: private
language: c++ language: c++
@ -2452,6 +2453,7 @@ libs:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: grpc++_unsecure - name: grpc++_unsecure
build: all build: all
language: c++ language: c++
@ -4750,6 +4752,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/security/corpus/alts_credentials_corpus - test/core/security/corpus/alts_credentials_corpus
maxlen: 2048 maxlen: 2048
@ -5243,6 +5246,7 @@ targets:
- address_sorting - address_sorting
- upb - upb
- benchmark - benchmark
- absl/flags:flag
benchmark: true benchmark: true
defaults: benchmark defaults: benchmark
platforms: platforms:
@ -5590,6 +5594,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: client_callback_end2end_test - name: client_callback_end2end_test
gtest: true gtest: true
build: test build: test
@ -5653,6 +5658,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/end2end/fuzzers/client_fuzzer_corpus - test/core/end2end/fuzzers/client_fuzzer_corpus
dict: test/core/end2end/fuzzers/hpack.dictionary dict: test/core/end2end/fuzzers/hpack.dictionary
@ -6065,6 +6071,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: grpc_cpp_plugin - name: grpc_cpp_plugin
build: protoc build: protoc
language: c++ language: c++
@ -6186,6 +6193,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
platforms: platforms:
- linux - linux
- posix - posix
@ -6319,6 +6327,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/transport/chttp2/hpack_parser_corpus - test/core/transport/chttp2/hpack_parser_corpus
dict: test/core/end2end/fuzzers/hpack.dictionary dict: test/core/end2end/fuzzers/hpack.dictionary
@ -6342,6 +6351,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: http_request_fuzzer_test - name: http_request_fuzzer_test
build: fuzzer build: fuzzer
language: c++ language: c++
@ -6356,6 +6366,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/http/request_corpus - test/core/http/request_corpus
maxlen: 2048 maxlen: 2048
@ -6373,6 +6384,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/http/response_corpus - test/core/http/response_corpus
maxlen: 2048 maxlen: 2048
@ -6466,6 +6478,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: interop_server - name: interop_server
build: test build: test
run: false run: false
@ -6488,6 +6501,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: interop_test - name: interop_test
build: test build: test
language: c++ language: c++
@ -6503,6 +6517,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
platforms: platforms:
- linux - linux
- posix - posix
@ -6521,6 +6536,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/json/corpus - test/core/json/corpus
maxlen: 512 maxlen: 512
@ -6658,6 +6674,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/nanopb/corpus_response - test/core/nanopb/corpus_response
maxlen: 128 maxlen: 128
@ -6675,6 +6692,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/nanopb/corpus_serverlist - test/core/nanopb/corpus_serverlist
maxlen: 128 maxlen: 128
@ -6755,6 +6773,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/slice/percent_decode_corpus - test/core/slice/percent_decode_corpus
maxlen: 32 maxlen: 32
@ -6772,6 +6791,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/slice/percent_encode_corpus - test/core/slice/percent_encode_corpus
maxlen: 32 maxlen: 32
@ -6898,6 +6918,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: qps_worker - name: qps_worker
build: test build: test
run: false run: false
@ -6940,6 +6961,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: raw_end2end_test - name: raw_end2end_test
gtest: true gtest: true
build: test build: test
@ -7157,6 +7179,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/end2end/fuzzers/server_fuzzer_corpus - test/core/end2end/fuzzers/server_fuzzer_corpus
dict: test/core/end2end/fuzzers/hpack.dictionary dict: test/core/end2end/fuzzers/hpack.dictionary
@ -7319,6 +7342,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/security/corpus/ssl_server_corpus - test/core/security/corpus/ssl_server_corpus
maxlen: 2048 maxlen: 2048
@ -7615,6 +7639,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
corpus_dirs: corpus_dirs:
- test/core/uri/uri_corpus - test/core/uri/uri_corpus
maxlen: 128 maxlen: 128
@ -7817,6 +7842,7 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
- name: xds_interop_server - name: xds_interop_server
build: test build: test
run: false run: false
@ -7835,4 +7861,5 @@ targets:
- gpr - gpr
- address_sorting - address_sorting
- upb - upb
- absl/flags:flag
tests: [] tests: []

@ -1495,6 +1495,7 @@
'type': 'static_library', 'type': 'static_library',
'dependencies': [ 'dependencies': [
'gpr', 'gpr',
'absl/flags:parse',
], ],
'sources': [ 'sources': [
'test/cpp/util/test_config_cc.cc', 'test/cpp/util/test_config_cc.cc',
@ -1510,6 +1511,7 @@
'gpr', 'gpr',
'address_sorting', 'address_sorting',
'upb', 'upb',
'absl/flags:flag',
], ],
'sources': [ 'sources': [
'test/core/end2end/data/client_certs.cc', 'test/core/end2end/data/client_certs.cc',

@ -53,6 +53,9 @@ grpc_cc_binary(
name = "fake_handshaker_server", name = "fake_handshaker_server",
testonly = True, testonly = True,
srcs = ["fake_handshaker_server_main.cc"], srcs = ["fake_handshaker_server_main.cc"],
external_deps = [
"absl/flags:flag",
],
language = "C++", language = "C++",
deps = [ deps = [
"fake_handshaker_lib", "fake_handshaker_lib",

@ -15,20 +15,19 @@
* limitations under the License. * limitations under the License.
* *
*/ */
#include "test/core/tsi/alts/fake_handshaker/fake_handshaker_server.h"
#include <sstream>
#include <gflags/gflags.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/service_type.h>
#include <grpcpp/server_builder.h> #include <grpcpp/server_builder.h>
#include <sstream>
#include "absl/flags/flag.h"
#include "test/core/tsi/alts/fake_handshaker/fake_handshaker_server.h"
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_int32(handshaker_port, 55056, ABSL_FLAG(int32_t, handshaker_port, 55056,
"TCP port on which the fake handshaker server listens to."); "TCP port on which the fake handshaker server listens to.");
static void RunFakeHandshakerServer(const std::string& server_address) { static void RunFakeHandshakerServer(const std::string& server_address) {
std::unique_ptr<grpc::Service> service = std::unique_ptr<grpc::Service> service =
@ -47,9 +46,9 @@ int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv); grpc::testing::TestEnvironment env(argc, argv);
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
GPR_ASSERT(FLAGS_handshaker_port != 0); GPR_ASSERT(absl::GetFlag(FLAGS_handshaker_port) != 0);
std::ostringstream server_address; std::ostringstream server_address;
server_address << "[::1]:" << FLAGS_handshaker_port; server_address << "[::1]:" << absl::GetFlag(FLAGS_handshaker_port);
RunFakeHandshakerServer(server_address.str()); RunFakeHandshakerServer(server_address.str());
return 0; return 0;

@ -139,8 +139,8 @@ grpc_cc_library(
testonly = 1, testonly = 1,
srcs = ["fuzzer_corpus_test.cc"], srcs = ["fuzzer_corpus_test.cc"],
external_deps = [ external_deps = [
"absl/flags:flag",
"gtest", "gtest",
"gflags",
], ],
tags = ["no_windows"], tags = ["no_windows"],
deps = [ deps = [

@ -16,18 +16,16 @@
* *
*/ */
#include <stdbool.h>
#include <dirent.h> #include <dirent.h>
#include <gflags/gflags.h> #include <grpc/grpc.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <gtest/gtest.h> #include <gtest/gtest.h>
#include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h>
#include <grpc/grpc.h> #include "absl/flags/flag.h"
#include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/env.h"
#include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/iomgr/load_file.h"
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
@ -37,15 +35,8 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size);
extern bool squelch; extern bool squelch;
extern bool leak_check; extern bool leak_check;
// In some distros, gflags is in the namespace google, and in some others, ABSL_FLAG(std::string, file, "", "Use this file as test data");
// in gflags. This hack is enabling us to find both. ABSL_FLAG(std::string, directory, "", "Use this directory as test data");
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<std::string> {}; class FuzzerCorpusTest : public ::testing::TestWithParam<std::string> {};
@ -81,11 +72,12 @@ class ExampleGenerator
private: private:
void Materialize() const { void Materialize() const {
if (examples_.empty()) { if (examples_.empty()) {
if (!FLAGS_file.empty()) examples_.push_back(FLAGS_file); if (!absl::GetFlag(FLAGS_file).empty())
if (!FLAGS_directory.empty()) { examples_.push_back(absl::GetFlag(FLAGS_file));
if (!absl::GetFlag(FLAGS_directory).empty()) {
char* test_srcdir = gpr_getenv("TEST_SRCDIR"); char* test_srcdir = gpr_getenv("TEST_SRCDIR");
gpr_log(GPR_DEBUG, "test_srcdir=\"%s\"", test_srcdir); gpr_log(GPR_DEBUG, "test_srcdir=\"%s\"", test_srcdir);
std::string directory = FLAGS_directory; std::string directory = absl::GetFlag(FLAGS_directory);
if (test_srcdir != nullptr) { if (test_srcdir != nullptr) {
directory = directory =
test_srcdir + std::string("/com_github_grpc_grpc/") + directory; test_srcdir + std::string("/com_github_grpc_grpc/") + directory;

@ -63,8 +63,8 @@ grpc_cc_binary(
testonly = True, testonly = True,
srcs = ["golden_file_test.cc"], srcs = ["golden_file_test.cc"],
external_deps = [ external_deps = [
"absl/flags:flag",
"gtest", "gtest",
"gflags",
], ],
deps = [ deps = [
"//:grpc++", "//:grpc++",

@ -16,24 +16,17 @@
* *
*/ */
#include <gtest/gtest.h>
#include <fstream> #include <fstream>
#include <sstream> #include <sstream>
#include <gflags/gflags.h> #include "absl/flags/flag.h"
#include <gtest/gtest.h>
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
// In some distros, gflags is in the namespace google, and in some others, ABSL_FLAG(
// in gflags. This hack is enabling us to find both. std::string, generated_file_path, "",
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
DEFINE_string(
generated_file_path, "",
"path to the directory containing generated files compiler_test.grpc.pb.h " "path to the directory containing generated files compiler_test.grpc.pb.h "
"and compiler_test_mock.grpc.pb.h"); "and compiler_test_mock.grpc.pb.h");
@ -59,23 +52,25 @@ void run_test(const std::basic_string<char>& generated_file,
} }
TEST(GoldenFileTest, TestGeneratedFile) { TEST(GoldenFileTest, TestGeneratedFile) {
run_test(FLAGS_generated_file_path + "compiler_test.grpc.pb.h", run_test(absl::GetFlag(FLAGS_generated_file_path) + "compiler_test.grpc.pb.h",
kGoldenFilePath); kGoldenFilePath);
} }
TEST(GoldenMockFileTest, TestGeneratedMockFile) { TEST(GoldenMockFileTest, TestGeneratedMockFile) {
run_test(FLAGS_generated_file_path + "compiler_test_mock.grpc.pb.h", run_test(
kMockGoldenFilePath); absl::GetFlag(FLAGS_generated_file_path) + "compiler_test_mock.grpc.pb.h",
kMockGoldenFilePath);
} }
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv); grpc::testing::TestEnvironment env(argc, argv);
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
if (FLAGS_generated_file_path.empty()) { if (absl::GetFlag(FLAGS_generated_file_path).empty()) {
FLAGS_generated_file_path = "gens/src/proto/grpc/testing/"; absl::SetFlag(&FLAGS_generated_file_path, "gens/src/proto/grpc/testing/");
} }
if (FLAGS_generated_file_path.back() != '/') if (absl::GetFlag(FLAGS_generated_file_path).back() != '/')
FLAGS_generated_file_path.append("/"); absl::SetFlag(&FLAGS_generated_file_path,
absl::GetFlag(FLAGS_generated_file_path).append("/"));
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

@ -139,7 +139,7 @@ grpc_cc_binary(
testonly = True, testonly = True,
srcs = ["client_crash_test_server.cc"], srcs = ["client_crash_test_server.cc"],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
"gtest", "gtest",
], ],
deps = [ deps = [
@ -544,7 +544,6 @@ grpc_cc_test(
srcs = ["proto_server_reflection_test.cc"], srcs = ["proto_server_reflection_test.cc"],
external_deps = [ external_deps = [
"gtest", "gtest",
"gflags",
], ],
deps = [ deps = [
":test_service_impl", ":test_service_impl",
@ -611,7 +610,7 @@ grpc_cc_binary(
testonly = True, testonly = True,
srcs = ["server_crash_test_client.cc"], srcs = ["server_crash_test_client.cc"],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
"gtest", "gtest",
], ],
deps = [ deps = [

@ -16,31 +16,24 @@
* *
*/ */
#include <gflags/gflags.h>
#include <iostream>
#include <memory>
#include <string>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/server.h> #include <grpcpp/server.h>
#include <grpcpp/server_builder.h> #include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h> #include <grpcpp/server_context.h>
#include <iostream>
#include <memory>
#include <string>
#include "absl/flags/flag.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h" #include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_string(address, "", "Address to bind to"); ABSL_FLAG(std::string, address, "", "Address to bind to");
using grpc::testing::EchoRequest; using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse; using grpc::testing::EchoResponse;
// 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;
namespace grpc { namespace grpc {
namespace testing { namespace testing {
@ -63,10 +56,12 @@ void RunServer() {
ServiceImpl service; ServiceImpl service;
ServerBuilder builder; ServerBuilder builder;
builder.AddListeningPort(FLAGS_address, grpc::InsecureServerCredentials()); builder.AddListeningPort(absl::GetFlag(FLAGS_address),
grpc::InsecureServerCredentials());
builder.RegisterService(&service); builder.RegisterService(&service);
std::unique_ptr<Server> server(builder.BuildAndStart()); std::unique_ptr<Server> server(builder.BuildAndStart());
std::cout << "Server listening on " << FLAGS_address << std::endl; std::cout << "Server listening on " << absl::GetFlag(FLAGS_address)
<< std::endl;
server->Wait(); server->Wait();
} }
} // namespace testing } // namespace testing

@ -16,37 +16,37 @@
* *
*/ */
#include <gflags/gflags.h>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/channel.h> #include <grpcpp/channel.h>
#include <grpcpp/client_context.h> #include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h> #include <grpcpp/create_channel.h>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include "absl/flags/flag.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h" #include "src/proto/grpc/testing/echo.grpc.pb.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_string(address, "", "Address to connect to"); ABSL_FLAG(std::string, address, "", "Address to connect to");
DEFINE_string(mode, "", "Test mode to use"); ABSL_FLAG(std::string, mode, "", "Test mode to use");
using grpc::testing::EchoRequest; using grpc::testing::EchoRequest;
using grpc::testing::EchoResponse; using grpc::testing::EchoResponse;
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
auto stub = grpc::testing::EchoTestService::NewStub( auto stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannel(
grpc::CreateChannel(FLAGS_address, grpc::InsecureChannelCredentials())); absl::GetFlag(FLAGS_address), grpc::InsecureChannelCredentials()));
EchoRequest request; EchoRequest request;
EchoResponse response; EchoResponse response;
grpc::ClientContext context; grpc::ClientContext context;
context.set_wait_for_ready(true); context.set_wait_for_ready(true);
if (FLAGS_mode == "bidi") { if (absl::GetFlag(FLAGS_mode) == "bidi") {
auto stream = stub->BidiStream(&context); auto stream = stub->BidiStream(&context);
for (int i = 0;; i++) { for (int i = 0;; i++) {
std::ostringstream msg; std::ostringstream msg;
@ -56,7 +56,7 @@ int main(int argc, char** argv) {
GPR_ASSERT(stream->Read(&response)); GPR_ASSERT(stream->Read(&response));
GPR_ASSERT(response.message() == request.message()); GPR_ASSERT(response.message() == request.message());
} }
} else if (FLAGS_mode == "response") { } else if (absl::GetFlag(FLAGS_mode) == "response") {
EchoRequest request; EchoRequest request;
request.set_message("Hello"); request.set_message("Hello");
auto stream = stub->ResponseStream(&context, request); auto stream = stub->ResponseStream(&context, request);
@ -64,7 +64,8 @@ int main(int argc, char** argv) {
GPR_ASSERT(stream->Read(&response)); GPR_ASSERT(stream->Read(&response));
} }
} else { } else {
gpr_log(GPR_ERROR, "invalid test mode '%s'", FLAGS_mode.c_str()); gpr_log(GPR_ERROR, "invalid test mode '%s'",
absl::GetFlag(FLAGS_mode).c_str());
return 1; return 1;
} }

@ -30,7 +30,7 @@ grpc_cc_library(
"server_helper.h", "server_helper.h",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
language = "C++", language = "C++",
deps = [ deps = [
@ -43,6 +43,9 @@ grpc_cc_binary(
srcs = [ srcs = [
"grpclb_fallback_test.cc", "grpclb_fallback_test.cc",
], ],
external_deps = [
"absl/flags:flag",
],
language = "C++", language = "C++",
tags = ["no_windows"], tags = ["no_windows"],
deps = [ deps = [
@ -60,6 +63,9 @@ grpc_cc_binary(
srcs = [ srcs = [
"interop_server_bootstrap.cc", "interop_server_bootstrap.cc",
], ],
external_deps = [
"absl/flags:flag",
],
language = "C++", language = "C++",
deps = [ deps = [
":interop_server_lib", ":interop_server_lib",
@ -92,6 +98,9 @@ grpc_cc_library(
"client_helper.h", "client_helper.h",
"interop_client.h", "interop_client.h",
], ],
external_deps = [
"absl/flags:flag",
],
language = "C++", language = "C++",
deps = [ deps = [
"//src/proto/grpc/testing:empty_proto", "//src/proto/grpc/testing:empty_proto",
@ -108,6 +117,9 @@ grpc_cc_library(
srcs = [ srcs = [
"client.cc", "client.cc",
], ],
external_deps = [
"absl/flags:flag",
],
language = "C++", language = "C++",
deps = [ deps = [
":client_helper_lib", ":client_helper_lib",
@ -127,7 +139,7 @@ grpc_cc_binary(
name = "metrics_client", name = "metrics_client",
srcs = ["metrics_client.cc"], srcs = ["metrics_client.cc"],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
language = "C++", language = "C++",
deps = [ deps = [
@ -142,6 +154,9 @@ grpc_cc_binary(
srcs = [ srcs = [
"reconnect_interop_client.cc", "reconnect_interop_client.cc",
], ],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
":client_helper_lib", ":client_helper_lib",
"//:grpc++", "//:grpc++",
@ -154,6 +169,9 @@ grpc_cc_binary(
srcs = [ srcs = [
"reconnect_interop_server.cc", "reconnect_interop_server.cc",
], ],
external_deps = [
"absl/flags:flag",
],
language = "C++", language = "C++",
deps = [ deps = [
":interop_server_lib", ":interop_server_lib",
@ -169,6 +187,9 @@ grpc_cc_binary(
"stress_interop_client.h", "stress_interop_client.h",
"stress_test.cc", "stress_test.cc",
], ],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
":client_helper_lib", ":client_helper_lib",
"//:grpc++", "//:grpc++",
@ -185,7 +206,7 @@ grpc_cc_test(
":interop_server", ":interop_server",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
tags = ["no_windows"], tags = ["no_windows"],
deps = [ deps = [
@ -203,6 +224,9 @@ grpc_cc_binary(
srcs = [ srcs = [
"xds_interop_client.cc", "xds_interop_client.cc",
], ],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
"//:grpc++", "//:grpc++",
"//src/proto/grpc/testing:empty_proto", "//src/proto/grpc/testing:empty_proto",
@ -218,6 +242,9 @@ grpc_cc_binary(
srcs = [ srcs = [
"xds_interop_server.cc", "xds_interop_server.cc",
], ],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
"//:grpc++", "//:grpc++",
"//src/proto/grpc/testing:empty_proto", "//src/proto/grpc/testing:empty_proto",
@ -234,6 +261,9 @@ grpc_cc_binary(
"http2_client.cc", "http2_client.cc",
"http2_client.h", "http2_client.h",
], ],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
"//:grpc++", "//:grpc++",
"//src/proto/grpc/testing:empty_proto", "//src/proto/grpc/testing:empty_proto",

@ -16,33 +16,34 @@
* *
*/ */
#include <memory>
#include <unordered_map>
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/channel.h> #include <grpcpp/channel.h>
#include <grpcpp/client_context.h> #include <grpcpp/client_context.h>
#include <memory>
#include <unordered_map>
#include "absl/flags/flag.h"
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/interop/client_helper.h" #include "test/cpp/interop/client_helper.h"
#include "test/cpp/interop/interop_client.h" #include "test/cpp/interop/interop_client.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_bool(use_alts, false, ABSL_FLAG(bool, use_alts, false,
"Whether to use alts. Enable alts will disable tls."); "Whether to use alts. Enable alts will disable tls.");
DEFINE_bool(use_tls, false, "Whether to use tls."); ABSL_FLAG(bool, use_tls, false, "Whether to use tls.");
DEFINE_string(custom_credentials_type, "", "User provided credentials type."); ABSL_FLAG(std::string, custom_credentials_type, "",
DEFINE_bool(use_test_ca, false, "False to use SSL roots for google"); "User provided credentials type.");
DEFINE_int32(server_port, 0, "Server port."); ABSL_FLAG(bool, use_test_ca, false, "False to use SSL roots for google");
DEFINE_string(server_host, "localhost", "Server host to connect to"); ABSL_FLAG(int32_t, server_port, 0, "Server port.");
DEFINE_string(server_host_override, "", ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to");
"Override the server host which is sent in HTTP header"); ABSL_FLAG(std::string, server_host_override, "",
DEFINE_string( "Override the server host which is sent in HTTP header");
test_case, "large_unary", ABSL_FLAG(
std::string, test_case, "large_unary",
"Configure different test cases. Valid options are:\n\n" "Configure different test cases. Valid options are:\n\n"
"all : all test cases;\n" "all : all test cases;\n"
"cancel_after_begin : cancel stream after starting it;\n" "cancel_after_begin : cancel stream after starting it;\n"
@ -75,39 +76,39 @@ DEFINE_string(
"timeout_on_sleeping_server: deadline exceeds on stream;\n" "timeout_on_sleeping_server: deadline exceeds on stream;\n"
"unimplemented_method: client calls an unimplemented method;\n" "unimplemented_method: client calls an unimplemented method;\n"
"unimplemented_service: client calls an unimplemented service;\n"); "unimplemented_service: client calls an unimplemented service;\n");
DEFINE_string(default_service_account, "", ABSL_FLAG(std::string, default_service_account, "",
"Email of GCE default service account"); "Email of GCE default service account");
DEFINE_string(service_account_key_file, "", ABSL_FLAG(std::string, service_account_key_file, "",
"Path to service account json key file."); "Path to service account json key file.");
DEFINE_string(oauth_scope, "", "Scope for OAuth tokens."); ABSL_FLAG(std::string, oauth_scope, "", "Scope for OAuth tokens.");
DEFINE_bool(do_not_abort_on_transient_failures, false, ABSL_FLAG(bool, do_not_abort_on_transient_failures, false,
"If set to 'true', abort() is not called in case of transient " "If set to 'true', abort() is not called in case of transient "
"failures (i.e failures that are temporary and will likely go away " "failures (i.e failures that are temporary and will likely go away "
"on retrying; like a temporary connection failure) and an error " "on retrying; like a temporary connection failure) and an error "
"message is printed instead. Note that this flag just controls " "message is printed instead. Note that this flag just controls "
"whether abort() is called or not. It does not control whether the " "whether abort() is called or not. It does not control whether the "
"test is retried in case of transient failures (and currently the " "test is retried in case of transient failures (and currently the "
"interop tests are not retried even if this flag is set to true)"); "interop tests are not retried even if this flag is set to true)");
DEFINE_int32(soak_iterations, 1000, ABSL_FLAG(int32_t, soak_iterations, 1000,
"The number of iterations to use for the two soak tests; rpc_soak " "The number of iterations to use for the two soak tests; rpc_soak "
"and channel_soak."); "and channel_soak.");
DEFINE_int32(soak_max_failures, 0, ABSL_FLAG(int32_t, soak_max_failures, 0,
"The number of iterations in soak tests that are allowed to fail " "The number of iterations in soak tests that are allowed to fail "
"(either due to non-OK status code or exceeding the " "(either due to non-OK status code or exceeding the "
"per-iteration max acceptable latency)."); "per-iteration max acceptable latency).");
DEFINE_int32(soak_per_iteration_max_acceptable_latency_ms, 0, ABSL_FLAG(int32_t, soak_per_iteration_max_acceptable_latency_ms, 0,
"The number of milliseconds a single iteration in the two soak " "The number of milliseconds a single iteration in the two soak "
"tests (rpc_soak and channel_soak) should take."); "tests (rpc_soak and channel_soak) should take.");
DEFINE_int32(soak_overall_timeout_seconds, 0, ABSL_FLAG(int32_t, soak_overall_timeout_seconds, 0,
"The overall number of seconds after which a soak test should " "The overall number of seconds after which a soak test should "
"stop and fail, if the desired number of iterations have not yet " "stop and fail, if the desired number of iterations have not yet "
"completed."); "completed.");
DEFINE_int32(iteration_interval, 10, ABSL_FLAG(int32_t, iteration_interval, 10,
"The interval in seconds between rpcs. This is used by " "The interval in seconds between rpcs. This is used by "
"long_connection test"); "long_connection test");
DEFINE_string(additional_metadata, "", ABSL_FLAG(std::string, additional_metadata, "",
"Additional metadata to send in each request, as a " "Additional metadata to send in each request, as a "
"semicolon-separated list of key:value pairs."); "semicolon-separated list of key:value pairs.");
using grpc::testing::CreateChannelForTestCase; using grpc::testing::CreateChannelForTestCase;
using grpc::testing::GetServiceAccountJsonKey; using grpc::testing::GetServiceAccountJsonKey;
@ -174,18 +175,19 @@ bool ParseAdditionalMetadataFlag(
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv); grpc::testing::TestEnvironment env(argc, argv);
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
gpr_log(GPR_INFO, "Testing these cases: %s", FLAGS_test_case.c_str()); gpr_log(GPR_INFO, "Testing these cases: %s",
absl::GetFlag(FLAGS_test_case).c_str());
int ret = 0; int ret = 0;
grpc::testing::ChannelCreationFunc channel_creation_func; grpc::testing::ChannelCreationFunc channel_creation_func;
std::string test_case = FLAGS_test_case; std::string test_case = absl::GetFlag(FLAGS_test_case);
if (FLAGS_additional_metadata.empty()) { if (absl::GetFlag(FLAGS_additional_metadata).empty()) {
channel_creation_func = [test_case]() { channel_creation_func = [test_case]() {
return CreateChannelForTestCase(test_case); return CreateChannelForTestCase(test_case);
}; };
} else { } else {
std::multimap<std::string, std::string> additional_metadata; std::multimap<std::string, std::string> additional_metadata;
if (!ParseAdditionalMetadataFlag(FLAGS_additional_metadata, if (!ParseAdditionalMetadataFlag(absl::GetFlag(FLAGS_additional_metadata),
&additional_metadata)) { &additional_metadata)) {
return 1; return 1;
} }
@ -201,8 +203,9 @@ int main(int argc, char** argv) {
}; };
} }
grpc::testing::InteropClient client(channel_creation_func, true, grpc::testing::InteropClient client(
FLAGS_do_not_abort_on_transient_failures); channel_creation_func, true,
absl::GetFlag(FLAGS_do_not_abort_on_transient_failures));
std::unordered_map<std::string, std::function<bool()>> actions; std::unordered_map<std::string, std::function<bool()>> actions;
actions["empty_unary"] = actions["empty_unary"] =
@ -238,24 +241,27 @@ int main(int argc, char** argv) {
std::bind(&grpc::testing::InteropClient::DoEmptyStream, &client); std::bind(&grpc::testing::InteropClient::DoEmptyStream, &client);
actions["pick_first_unary"] = actions["pick_first_unary"] =
std::bind(&grpc::testing::InteropClient::DoPickFirstUnary, &client); std::bind(&grpc::testing::InteropClient::DoPickFirstUnary, &client);
if (FLAGS_use_tls) { if (absl::GetFlag(FLAGS_use_tls)) {
actions["compute_engine_creds"] = actions["compute_engine_creds"] =
std::bind(&grpc::testing::InteropClient::DoComputeEngineCreds, &client, std::bind(&grpc::testing::InteropClient::DoComputeEngineCreds, &client,
FLAGS_default_service_account, FLAGS_oauth_scope); absl::GetFlag(FLAGS_default_service_account),
absl::GetFlag(FLAGS_oauth_scope));
actions["jwt_token_creds"] = actions["jwt_token_creds"] =
std::bind(&grpc::testing::InteropClient::DoJwtTokenCreds, &client, std::bind(&grpc::testing::InteropClient::DoJwtTokenCreds, &client,
GetServiceAccountJsonKey()); GetServiceAccountJsonKey());
actions["oauth2_auth_token"] = actions["oauth2_auth_token"] =
std::bind(&grpc::testing::InteropClient::DoOauth2AuthToken, &client, std::bind(&grpc::testing::InteropClient::DoOauth2AuthToken, &client,
FLAGS_default_service_account, FLAGS_oauth_scope); absl::GetFlag(FLAGS_default_service_account),
absl::GetFlag(FLAGS_oauth_scope));
actions["per_rpc_creds"] = actions["per_rpc_creds"] =
std::bind(&grpc::testing::InteropClient::DoPerRpcCreds, &client, std::bind(&grpc::testing::InteropClient::DoPerRpcCreds, &client,
GetServiceAccountJsonKey()); GetServiceAccountJsonKey());
} }
if (FLAGS_custom_credentials_type == "google_default_credentials") { if (absl::GetFlag(FLAGS_custom_credentials_type) ==
"google_default_credentials") {
actions["google_default_credentials"] = actions["google_default_credentials"] =
std::bind(&grpc::testing::InteropClient::DoGoogleDefaultCredentials, std::bind(&grpc::testing::InteropClient::DoGoogleDefaultCredentials,
&client, FLAGS_default_service_account); &client, absl::GetFlag(FLAGS_default_service_account));
} }
actions["status_code_and_message"] = actions["status_code_and_message"] =
std::bind(&grpc::testing::InteropClient::DoStatusWithMessage, &client); std::bind(&grpc::testing::InteropClient::DoStatusWithMessage, &client);
@ -269,28 +275,31 @@ int main(int argc, char** argv) {
std::bind(&grpc::testing::InteropClient::DoUnimplementedService, &client); std::bind(&grpc::testing::InteropClient::DoUnimplementedService, &client);
actions["cacheable_unary"] = actions["cacheable_unary"] =
std::bind(&grpc::testing::InteropClient::DoCacheableUnary, &client); std::bind(&grpc::testing::InteropClient::DoCacheableUnary, &client);
actions["channel_soak"] = actions["channel_soak"] = std::bind(
std::bind(&grpc::testing::InteropClient::DoChannelSoakTest, &client, &grpc::testing::InteropClient::DoChannelSoakTest, &client,
FLAGS_soak_iterations, FLAGS_soak_max_failures, absl::GetFlag(FLAGS_soak_iterations),
FLAGS_soak_per_iteration_max_acceptable_latency_ms, absl::GetFlag(FLAGS_soak_max_failures),
FLAGS_soak_overall_timeout_seconds); absl::GetFlag(FLAGS_soak_per_iteration_max_acceptable_latency_ms),
actions["rpc_soak"] = absl::GetFlag(FLAGS_soak_overall_timeout_seconds));
std::bind(&grpc::testing::InteropClient::DoRpcSoakTest, &client, actions["rpc_soak"] = std::bind(
FLAGS_soak_iterations, FLAGS_soak_max_failures, &grpc::testing::InteropClient::DoRpcSoakTest, &client,
FLAGS_soak_per_iteration_max_acceptable_latency_ms, absl::GetFlag(FLAGS_soak_iterations),
FLAGS_soak_overall_timeout_seconds); absl::GetFlag(FLAGS_soak_max_failures),
absl::GetFlag(FLAGS_soak_per_iteration_max_acceptable_latency_ms),
absl::GetFlag(FLAGS_soak_overall_timeout_seconds));
actions["long_lived_channel"] = actions["long_lived_channel"] =
std::bind(&grpc::testing::InteropClient::DoLongLivedChannelTest, &client, std::bind(&grpc::testing::InteropClient::DoLongLivedChannelTest, &client,
FLAGS_soak_iterations, FLAGS_iteration_interval); absl::GetFlag(FLAGS_soak_iterations),
absl::GetFlag(FLAGS_iteration_interval));
UpdateActions(&actions); UpdateActions(&actions);
if (FLAGS_test_case == "all") { if (absl::GetFlag(FLAGS_test_case) == "all") {
for (const auto& action : actions) { for (const auto& action : actions) {
action.second(); action.second();
} }
} else if (actions.find(FLAGS_test_case) != actions.end()) { } else if (actions.find(absl::GetFlag(FLAGS_test_case)) != actions.end()) {
actions.find(FLAGS_test_case)->second(); actions.find(absl::GetFlag(FLAGS_test_case))->second();
} else { } else {
std::string test_cases; std::string test_cases;
for (const auto& action : actions) { for (const auto& action : actions) {
@ -298,7 +307,7 @@ int main(int argc, char** argv) {
test_cases += action.first; test_cases += action.first;
} }
gpr_log(GPR_ERROR, "Unsupported test case %s. Valid options are\n%s", gpr_log(GPR_ERROR, "Unsupported test case %s. Valid options are\n%s",
FLAGS_test_case.c_str(), test_cases.c_str()); absl::GetFlag(FLAGS_test_case).c_str(), test_cases.c_str());
ret = 1; ret = 1;
} }

@ -18,11 +18,6 @@
#include "test/cpp/interop/client_helper.h" #include "test/cpp/interop/client_helper.h"
#include <fstream>
#include <memory>
#include <sstream>
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
@ -30,22 +25,27 @@
#include <grpcpp/create_channel.h> #include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h> #include <grpcpp/security/credentials.h>
#include <fstream>
#include <memory>
#include <sstream>
#include "absl/flags/flag.h"
#include "src/cpp/client/secure_credentials.h" #include "src/cpp/client/secure_credentials.h"
#include "test/core/security/oauth2_utils.h" #include "test/core/security/oauth2_utils.h"
#include "test/cpp/util/create_test_channel.h" #include "test/cpp/util/create_test_channel.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DECLARE_bool(use_alts); ABSL_DECLARE_FLAG(bool, use_alts);
DECLARE_bool(use_tls); ABSL_DECLARE_FLAG(bool, use_tls);
DECLARE_string(custom_credentials_type); ABSL_DECLARE_FLAG(std::string, custom_credentials_type);
DECLARE_bool(use_test_ca); ABSL_DECLARE_FLAG(bool, use_test_ca);
DECLARE_int32(server_port); ABSL_DECLARE_FLAG(int32_t, server_port);
DECLARE_string(server_host); ABSL_DECLARE_FLAG(std::string, server_host);
DECLARE_string(server_host_override); ABSL_DECLARE_FLAG(std::string, server_host_override);
DECLARE_string(test_case); ABSL_DECLARE_FLAG(std::string, test_case);
DECLARE_string(default_service_account); ABSL_DECLARE_FLAG(std::string, default_service_account);
DECLARE_string(service_account_key_file); ABSL_DECLARE_FLAG(std::string, service_account_key_file);
DECLARE_string(oauth_scope); ABSL_DECLARE_FLAG(std::string, oauth_scope);
namespace grpc { namespace grpc {
namespace testing { namespace testing {
@ -53,7 +53,7 @@ namespace testing {
std::string GetServiceAccountJsonKey() { std::string GetServiceAccountJsonKey() {
static std::string json_key; static std::string json_key;
if (json_key.empty()) { if (json_key.empty()) {
std::ifstream json_key_file(FLAGS_service_account_key_file); std::ifstream json_key_file(absl::GetFlag(FLAGS_service_account_key_file));
std::stringstream key_stream; std::stringstream key_stream;
key_stream << json_key_file.rdbuf(); key_stream << json_key_file.rdbuf();
json_key = key_stream.str(); json_key = key_stream.str();
@ -83,48 +83,58 @@ std::shared_ptr<Channel> CreateChannelForTestCase(
std::vector< std::vector<
std::unique_ptr<experimental::ClientInterceptorFactoryInterface>> std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>
interceptor_creators) { interceptor_creators) {
GPR_ASSERT(FLAGS_server_port); GPR_ASSERT(absl::GetFlag(FLAGS_server_port));
const int host_port_buf_size = 1024; const int host_port_buf_size = 1024;
char host_port[host_port_buf_size]; char host_port[host_port_buf_size];
snprintf(host_port, host_port_buf_size, "%s:%d", FLAGS_server_host.c_str(), snprintf(host_port, host_port_buf_size, "%s:%d",
FLAGS_server_port); absl::GetFlag(FLAGS_server_host).c_str(),
absl::GetFlag(FLAGS_server_port));
std::shared_ptr<CallCredentials> creds; std::shared_ptr<CallCredentials> creds;
if (test_case == "compute_engine_creds") { if (test_case == "compute_engine_creds") {
creds = FLAGS_custom_credentials_type == "google_default_credentials" creds = absl::GetFlag(FLAGS_custom_credentials_type) ==
"google_default_credentials"
? nullptr ? nullptr
: GoogleComputeEngineCredentials(); : GoogleComputeEngineCredentials();
} else if (test_case == "jwt_token_creds") { } else if (test_case == "jwt_token_creds") {
std::string json_key = GetServiceAccountJsonKey(); std::string json_key = GetServiceAccountJsonKey();
std::chrono::seconds token_lifetime = std::chrono::hours(1); std::chrono::seconds token_lifetime = std::chrono::hours(1);
creds = FLAGS_custom_credentials_type == "google_default_credentials" creds = absl::GetFlag(FLAGS_custom_credentials_type) ==
"google_default_credentials"
? nullptr ? nullptr
: ServiceAccountJWTAccessCredentials(json_key, : ServiceAccountJWTAccessCredentials(json_key,
token_lifetime.count()); token_lifetime.count());
} else if (test_case == "oauth2_auth_token") { } else if (test_case == "oauth2_auth_token") {
creds = FLAGS_custom_credentials_type == "google_default_credentials" creds = absl::GetFlag(FLAGS_custom_credentials_type) ==
"google_default_credentials"
? nullptr ? nullptr
: AccessTokenCredentials(GetOauth2AccessToken()); : AccessTokenCredentials(GetOauth2AccessToken());
} else if (test_case == "pick_first_unary") { } else if (test_case == "pick_first_unary") {
ChannelArguments channel_args; ChannelArguments channel_args;
// allow the LB policy to be configured with service config // allow the LB policy to be configured with service config
channel_args.SetInt(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, 0); channel_args.SetInt(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, 0);
return CreateTestChannel(host_port, FLAGS_custom_credentials_type, return CreateTestChannel(
FLAGS_server_host_override, !FLAGS_use_test_ca, host_port, absl::GetFlag(FLAGS_custom_credentials_type),
creds, channel_args); absl::GetFlag(FLAGS_server_host_override),
!absl::GetFlag(FLAGS_use_test_ca), creds, channel_args);
} }
if (FLAGS_custom_credentials_type.empty()) { if (absl::GetFlag(FLAGS_custom_credentials_type).empty()) {
transport_security security_type = transport_security security_type =
FLAGS_use_alts ? ALTS : (FLAGS_use_tls ? TLS : INSECURE); absl::GetFlag(FLAGS_use_alts)
return CreateTestChannel(host_port, FLAGS_server_host_override, ? ALTS
security_type, !FLAGS_use_test_ca, creds, : (absl::GetFlag(FLAGS_use_tls) ? TLS : INSECURE);
std::move(interceptor_creators)); return CreateTestChannel(host_port,
absl::GetFlag(FLAGS_server_host_override),
security_type, !absl::GetFlag(FLAGS_use_test_ca),
creds, std::move(interceptor_creators));
} else { } else {
if (interceptor_creators.empty()) { if (interceptor_creators.empty()) {
return CreateTestChannel(host_port, FLAGS_custom_credentials_type, creds); return CreateTestChannel(
host_port, absl::GetFlag(FLAGS_custom_credentials_type), creds);
} else { } else {
return CreateTestChannel(host_port, FLAGS_custom_credentials_type, creds, return CreateTestChannel(host_port,
std::move(interceptor_creators)); absl::GetFlag(FLAGS_custom_credentials_type),
creds, std::move(interceptor_creators));
} }
} }
} }

@ -16,49 +16,47 @@
* *
*/ */
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#include <arpa/inet.h> #include <arpa/inet.h>
#include <fcntl.h> #include <fcntl.h>
#include <gflags/gflags.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/support/channel_arguments.h>
#include <inttypes.h> #include <inttypes.h>
#include <netinet/in.h> #include <netinet/in.h>
#include <netinet/tcp.h> #include <netinet/tcp.h>
#include <sys/wait.h> #include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
#include <chrono> #include <chrono>
#include <cstdlib> #include <cstdlib>
#include <memory> #include <memory>
#include <string> #include <string>
#include <thread> #include <thread>
#include <grpc/support/alloc.h> #include "absl/flags/flag.h"
#include <grpc/support/log.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/support/channel_arguments.h>
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/socket_mutator.h" #include "src/core/lib/iomgr/socket_mutator.h"
#include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h" #include "src/proto/grpc/testing/test.grpc.pb.h"
#include "src/proto/grpc/testing/test.pb.h" #include "src/proto/grpc/testing/test.pb.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DEFINE_string(custom_credentials_type, "", "User provided credentials type."); ABSL_FLAG(std::string, custom_credentials_type, "",
DEFINE_string(server_uri, "localhost:1000", "Server URI target"); "User provided credentials type.");
DEFINE_string(unroute_lb_and_backend_addrs_cmd, "exit 1", ABSL_FLAG(std::string, server_uri, "localhost:1000", "Server URI target");
"Shell command used to make LB and backend addresses unroutable"); ABSL_FLAG(std::string, unroute_lb_and_backend_addrs_cmd, "exit 1",
DEFINE_string(blackhole_lb_and_backend_addrs_cmd, "exit 1", "Shell command used to make LB and backend addresses unroutable");
"Shell command used to make LB and backend addresses blackholed"); ABSL_FLAG(std::string, blackhole_lb_and_backend_addrs_cmd, "exit 1",
DEFINE_string( "Shell command used to make LB and backend addresses blackholed");
test_case, "", ABSL_FLAG(
std::string, test_case, "",
"Test case to run. Valid options are:\n\n" "Test case to run. Valid options are:\n\n"
"fast_fallback_before_startup : fallback before establishing connection to " "fast_fallback_before_startup : fallback before establishing connection to "
"LB;\n" "LB;\n"
@ -170,9 +168,9 @@ std::unique_ptr<TestService::Stub> CreateFallbackTestStub() {
channel_args.SetInt(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, 0); channel_args.SetInt(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, 0);
std::shared_ptr<grpc::ChannelCredentials> channel_creds = std::shared_ptr<grpc::ChannelCredentials> channel_creds =
grpc::testing::GetCredentialsProvider()->GetChannelCredentials( grpc::testing::GetCredentialsProvider()->GetChannelCredentials(
FLAGS_custom_credentials_type, &channel_args); absl::GetFlag(FLAGS_custom_credentials_type), &channel_args);
return TestService::NewStub( return TestService::NewStub(grpc::CreateCustomChannel(
grpc::CreateCustomChannel(FLAGS_server_uri, channel_creds, channel_args)); absl::GetFlag(FLAGS_server_uri), channel_creds, channel_args));
} }
void RunCommand(const std::string& command) { void RunCommand(const std::string& command) {
@ -209,11 +207,13 @@ void RunFallbackBeforeStartupTest(
} }
void DoFastFallbackBeforeStartup() { void DoFastFallbackBeforeStartup() {
RunFallbackBeforeStartupTest(FLAGS_unroute_lb_and_backend_addrs_cmd, 9); RunFallbackBeforeStartupTest(
absl::GetFlag(FLAGS_unroute_lb_and_backend_addrs_cmd), 9);
} }
void DoSlowFallbackBeforeStartup() { void DoSlowFallbackBeforeStartup() {
RunFallbackBeforeStartupTest(FLAGS_blackhole_lb_and_backend_addrs_cmd, 20); RunFallbackBeforeStartupTest(
absl::GetFlag(FLAGS_blackhole_lb_and_backend_addrs_cmd), 20);
} }
void RunFallbackAfterStartupTest( void RunFallbackAfterStartupTest(
@ -252,31 +252,34 @@ void RunFallbackAfterStartupTest(
} }
void DoFastFallbackAfterStartup() { void DoFastFallbackAfterStartup() {
RunFallbackAfterStartupTest(FLAGS_unroute_lb_and_backend_addrs_cmd); RunFallbackAfterStartupTest(
absl::GetFlag(FLAGS_unroute_lb_and_backend_addrs_cmd));
} }
void DoSlowFallbackAfterStartup() { void DoSlowFallbackAfterStartup() {
RunFallbackAfterStartupTest(FLAGS_blackhole_lb_and_backend_addrs_cmd); RunFallbackAfterStartupTest(
absl::GetFlag(FLAGS_blackhole_lb_and_backend_addrs_cmd));
} }
} // namespace } // namespace
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
gpr_log(GPR_INFO, "Testing: %s", FLAGS_test_case.c_str()); gpr_log(GPR_INFO, "Testing: %s", absl::GetFlag(FLAGS_test_case).c_str());
if (FLAGS_test_case == "fast_fallback_before_startup") { if (absl::GetFlag(FLAGS_test_case) == "fast_fallback_before_startup") {
DoFastFallbackBeforeStartup(); DoFastFallbackBeforeStartup();
gpr_log(GPR_INFO, "DoFastFallbackBeforeStartup done!"); gpr_log(GPR_INFO, "DoFastFallbackBeforeStartup done!");
} else if (FLAGS_test_case == "slow_fallback_before_startup") { } else if (absl::GetFlag(FLAGS_test_case) == "slow_fallback_before_startup") {
DoSlowFallbackBeforeStartup(); DoSlowFallbackBeforeStartup();
gpr_log(GPR_INFO, "DoSlowFallbackBeforeStartup done!"); gpr_log(GPR_INFO, "DoSlowFallbackBeforeStartup done!");
} else if (FLAGS_test_case == "fast_fallback_after_startup") { } else if (absl::GetFlag(FLAGS_test_case) == "fast_fallback_after_startup") {
DoFastFallbackAfterStartup(); DoFastFallbackAfterStartup();
gpr_log(GPR_INFO, "DoFastFallbackAfterStartup done!"); gpr_log(GPR_INFO, "DoFastFallbackAfterStartup done!");
} else if (FLAGS_test_case == "slow_fallback_after_startup") { } else if (absl::GetFlag(FLAGS_test_case) == "slow_fallback_after_startup") {
DoSlowFallbackAfterStartup(); DoSlowFallbackAfterStartup();
gpr_log(GPR_INFO, "DoSlowFallbackAfterStartup done!"); gpr_log(GPR_INFO, "DoSlowFallbackAfterStartup done!");
} else { } else {
gpr_log(GPR_ERROR, "Invalid test case: %s", FLAGS_test_case.c_str()); gpr_log(GPR_ERROR, "Invalid test case: %s",
absl::GetFlag(FLAGS_test_case).c_str());
abort(); abort();
} }
} }

@ -16,21 +16,21 @@
* *
*/ */
#include <thread> #include "test/cpp/interop/http2_client.h"
#include <gflags/gflags.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/channel.h> #include <grpcpp/channel.h>
#include <grpcpp/client_context.h> #include <grpcpp/client_context.h>
#include "src/core/lib/transport/byte_stream.h" #include <thread>
#include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h"
#include "test/cpp/interop/http2_client.h"
#include "absl/flags/flag.h"
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "src/core/lib/gpr/useful.h" #include "src/core/lib/gpr/useful.h"
#include "src/core/lib/transport/byte_stream.h"
#include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h"
#include "test/cpp/util/create_test_channel.h" #include "test/cpp/util/create_test_channel.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
@ -176,42 +176,43 @@ bool Http2Client::DoMaxStreams() {
} // namespace testing } // namespace testing
} // namespace grpc } // namespace grpc
DEFINE_int32(server_port, 0, "Server port."); ABSL_FLAG(int32_t, server_port, 0, "Server port.");
DEFINE_string(server_host, "localhost", "Server host to connect to"); ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to");
DEFINE_string(test_case, "rst_after_header", ABSL_FLAG(std::string, test_case, "rst_after_header",
"Configure different test cases. Valid options are:\n\n" "Configure different test cases. Valid options are:\n\n"
"goaway\n" "goaway\n"
"max_streams\n" "max_streams\n"
"ping\n" "ping\n"
"rst_after_data\n" "rst_after_data\n"
"rst_after_header\n" "rst_after_header\n"
"rst_during_data\n"); "rst_during_data\n");
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
GPR_ASSERT(FLAGS_server_port); GPR_ASSERT(absl::GetFlag(FLAGS_server_port));
const int host_port_buf_size = 1024; const int host_port_buf_size = 1024;
char host_port[host_port_buf_size]; char host_port[host_port_buf_size];
snprintf(host_port, host_port_buf_size, "%s:%d", FLAGS_server_host.c_str(), snprintf(host_port, host_port_buf_size, "%s:%d",
FLAGS_server_port); absl::GetFlag(FLAGS_server_host).c_str(),
absl::GetFlag(FLAGS_server_port));
std::shared_ptr<grpc::Channel> channel = std::shared_ptr<grpc::Channel> channel =
grpc::CreateTestChannel(host_port, grpc::testing::INSECURE); grpc::CreateTestChannel(host_port, grpc::testing::INSECURE);
GPR_ASSERT(channel->WaitForConnected(gpr_time_add( GPR_ASSERT(channel->WaitForConnected(gpr_time_add(
gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(300, GPR_TIMESPAN)))); gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(300, GPR_TIMESPAN))));
grpc::testing::Http2Client client(channel); grpc::testing::Http2Client client(channel);
gpr_log(GPR_INFO, "Testing case: %s", FLAGS_test_case.c_str()); gpr_log(GPR_INFO, "Testing case: %s", absl::GetFlag(FLAGS_test_case).c_str());
int ret = 0; int ret = 0;
if (FLAGS_test_case == "rst_after_header") { if (absl::GetFlag(FLAGS_test_case) == "rst_after_header") {
client.DoRstAfterHeader(); client.DoRstAfterHeader();
} else if (FLAGS_test_case == "rst_after_data") { } else if (absl::GetFlag(FLAGS_test_case) == "rst_after_data") {
client.DoRstAfterData(); client.DoRstAfterData();
} else if (FLAGS_test_case == "rst_during_data") { } else if (absl::GetFlag(FLAGS_test_case) == "rst_during_data") {
client.DoRstDuringData(); client.DoRstDuringData();
} else if (FLAGS_test_case == "goaway") { } else if (absl::GetFlag(FLAGS_test_case) == "goaway") {
client.DoGoaway(); client.DoGoaway();
} else if (FLAGS_test_case == "ping") { } else if (absl::GetFlag(FLAGS_test_case) == "ping") {
client.DoPing(); client.DoPing();
} else if (FLAGS_test_case == "max_streams") { } else if (absl::GetFlag(FLAGS_test_case) == "max_streams") {
client.DoMaxStreams(); client.DoMaxStreams();
} else { } else {
const char* testcases[] = { const char* testcases[] = {
@ -221,7 +222,7 @@ int main(int argc, char** argv) {
gpr_strjoin_sep(testcases, GPR_ARRAY_SIZE(testcases), "\n", nullptr); gpr_strjoin_sep(testcases, GPR_ARRAY_SIZE(testcases), "\n", nullptr);
gpr_log(GPR_ERROR, "Unsupported test case %s. Valid options are\n%s", gpr_log(GPR_ERROR, "Unsupported test case %s. Valid options are\n%s",
FLAGS_test_case.c_str(), joined_testcases); absl::GetFlag(FLAGS_test_case).c_str(), joined_testcases);
gpr_free(joined_testcases); gpr_free(joined_testcases);
ret = 1; ret = 1;
} }

@ -16,12 +16,6 @@
* *
*/ */
#include <fstream>
#include <memory>
#include <sstream>
#include <thread>
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/time.h> #include <grpc/support/time.h>
@ -30,6 +24,12 @@
#include <grpcpp/server_builder.h> #include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h> #include <grpcpp/server_context.h>
#include <fstream>
#include <memory>
#include <sstream>
#include <thread>
#include "absl/flags/flag.h"
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/messages.pb.h"
@ -37,12 +37,13 @@
#include "test/cpp/interop/server_helper.h" #include "test/cpp/interop/server_helper.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_bool(use_alts, false, ABSL_FLAG(bool, use_alts, false,
"Whether to use alts. Enable alts will disable tls."); "Whether to use alts. Enable alts will disable tls.");
DEFINE_bool(use_tls, false, "Whether to use tls."); ABSL_FLAG(bool, use_tls, false, "Whether to use tls.");
DEFINE_string(custom_credentials_type, "", "User provided credentials type."); ABSL_FLAG(std::string, custom_credentials_type, "",
DEFINE_int32(port, 0, "Server port."); "User provided credentials type.");
DEFINE_int32(max_send_message_size, -1, "The maximum send message size."); ABSL_FLAG(int32_t, port, 0, "Server port.");
ABSL_FLAG(int32_t, max_send_message_size, -1, "The maximum send message size.");
using grpc::Server; using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
@ -317,14 +318,15 @@ class TestServiceImpl : public TestService::Service {
void grpc::testing::interop::RunServer( void grpc::testing::interop::RunServer(
const std::shared_ptr<ServerCredentials>& creds) { const std::shared_ptr<ServerCredentials>& creds) {
RunServer(creds, FLAGS_port, nullptr, nullptr); RunServer(creds, absl::GetFlag(FLAGS_port), nullptr, nullptr);
} }
void grpc::testing::interop::RunServer( void grpc::testing::interop::RunServer(
const std::shared_ptr<ServerCredentials>& creds, const std::shared_ptr<ServerCredentials>& creds,
std::unique_ptr<std::vector<std::unique_ptr<ServerBuilderOption>>> std::unique_ptr<std::vector<std::unique_ptr<ServerBuilderOption>>>
server_options) { server_options) {
RunServer(creds, FLAGS_port, nullptr, std::move(server_options)); RunServer(creds, absl::GetFlag(FLAGS_port), nullptr,
std::move(server_options));
} }
void grpc::testing::interop::RunServer( void grpc::testing::interop::RunServer(
@ -354,8 +356,8 @@ void grpc::testing::interop::RunServer(
builder.SetOption(std::move((*server_options)[i])); builder.SetOption(std::move((*server_options)[i]));
} }
} }
if (FLAGS_max_send_message_size >= 0) { if (absl::GetFlag(FLAGS_max_send_message_size) >= 0) {
builder.SetMaxSendMessageSize(FLAGS_max_send_message_size); builder.SetMaxSendMessageSize(absl::GetFlag(FLAGS_max_send_message_size));
} }
std::unique_ptr<Server> server(builder.BuildAndStart()); std::unique_ptr<Server> server(builder.BuildAndStart());
gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str()); gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str());

@ -17,6 +17,8 @@
*/ */
#include <assert.h> #include <assert.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <signal.h> #include <signal.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
@ -28,18 +30,15 @@
#include <string> #include <string>
#include <vector> #include <vector>
#include "absl/flags/flag.h"
#include "absl/strings/str_cat.h" #include "absl/strings/str_cat.h"
#include <gflags/gflags.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "test/core/util/port.h"
#include "test/cpp/util/test_config.h"
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/socket_utils_posix.h" #include "src/core/lib/iomgr/socket_utils_posix.h"
#include "test/core/util/port.h"
#include "test/cpp/util/test_config.h"
DEFINE_string(extra_server_flags, "", "Extra flags to pass to server."); ABSL_FLAG(std::string, extra_server_flags, "",
"Extra flags to pass to server.");
int test_client(const char* root, const char* host, int port) { int test_client(const char* root, const char* host, int port) {
int status; int status;
@ -91,8 +90,9 @@ int main(int argc, char** argv) {
args.push_back(const_cast<char*>(command.c_str())); args.push_back(const_cast<char*>(command.c_str()));
std::string port_arg = absl::StrCat("--port=", port); std::string port_arg = absl::StrCat("--port=", port);
args.push_back(const_cast<char*>(port_arg.c_str())); args.push_back(const_cast<char*>(port_arg.c_str()));
if (!FLAGS_extra_server_flags.empty()) { if (!absl::GetFlag(FLAGS_extra_server_flags).empty()) {
args.push_back(const_cast<char*>(FLAGS_extra_server_flags.c_str())); args.push_back(
const_cast<char*>(absl::GetFlag(FLAGS_extra_server_flags).c_str()));
} }
args.push_back(nullptr); args.push_back(nullptr);
execv(args[0], args.data()); execv(args[0], args.data());

@ -16,13 +16,13 @@
*is % allowed in string *is % allowed in string
*/ */
#include <memory>
#include <string>
#include <gflags/gflags.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/grpcpp.h> #include <grpcpp/grpcpp.h>
#include <memory>
#include <string>
#include "absl/flags/flag.h"
#include "src/proto/grpc/testing/metrics.grpc.pb.h" #include "src/proto/grpc/testing/metrics.grpc.pb.h"
#include "src/proto/grpc/testing/metrics.pb.h" #include "src/proto/grpc/testing/metrics.pb.h"
#include "test/cpp/util/metrics_server.h" #include "test/cpp/util/metrics_server.h"
@ -30,12 +30,13 @@
int kDeadlineSecs = 10; int kDeadlineSecs = 10;
DEFINE_string(metrics_server_address, "localhost:8081", ABSL_FLAG(std::string, metrics_server_address, "localhost:8081",
"The metrics server addresses in the fomrat <hostname>:<port>"); "The metrics server addresses in the fomrat <hostname>:<port>");
DEFINE_int32(deadline_secs, kDeadlineSecs, // TODO(Capstan): Consider using absl::Duration
"The deadline (in seconds) for RCP call"); ABSL_FLAG(int32_t, deadline_secs, kDeadlineSecs,
DEFINE_bool(total_only, false, "The deadline (in seconds) for RCP call");
"If true, this prints only the total value of all gauges"); ABSL_FLAG(bool, total_only, false,
"If true, this prints only the total value of all gauges");
using grpc::testing::EmptyMessage; using grpc::testing::EmptyMessage;
using grpc::testing::GaugeResponse; using grpc::testing::GaugeResponse;
@ -92,11 +93,13 @@ int main(int argc, char** argv) {
// from the grpc library appearing on stdout. // from the grpc library appearing on stdout.
gpr_set_log_function(BlackholeLogger); gpr_set_log_function(BlackholeLogger);
std::shared_ptr<grpc::Channel> channel(grpc::CreateChannel( std::shared_ptr<grpc::Channel> channel(
FLAGS_metrics_server_address, grpc::InsecureChannelCredentials())); grpc::CreateChannel(absl::GetFlag(FLAGS_metrics_server_address),
grpc::InsecureChannelCredentials()));
if (!PrintMetrics(MetricsService::NewStub(channel), FLAGS_total_only, if (!PrintMetrics(MetricsService::NewStub(channel),
FLAGS_deadline_secs)) { absl::GetFlag(FLAGS_total_only),
absl::GetFlag(FLAGS_deadline_secs))) {
return 1; return 1;
} }

@ -16,26 +16,29 @@
* *
*/ */
#include <memory>
#include <sstream>
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/channel.h> #include <grpcpp/channel.h>
#include <grpcpp/client_context.h> #include <grpcpp/client_context.h>
#include <grpcpp/support/channel_arguments.h> #include <grpcpp/support/channel_arguments.h>
#include <memory>
#include <sstream>
#include "absl/flags/flag.h"
#include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h" #include "src/proto/grpc/testing/test.grpc.pb.h"
#include "test/cpp/util/create_test_channel.h" #include "test/cpp/util/create_test_channel.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_int32(server_control_port, 0, "Server port for control rpcs."); ABSL_FLAG(int32_t, server_control_port, 0, "Server port for control rpcs.");
DEFINE_int32(server_retry_port, 0, "Server port for testing reconnection."); ABSL_FLAG(int32_t, server_retry_port, 0,
DEFINE_string(server_host, "localhost", "Server host to connect to"); "Server port for testing reconnection.");
DEFINE_int32(max_reconnect_backoff_ms, 0, ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to");
"Maximum backoff time, or 0 for default."); // TODO(Capstan): Consider using absl::Duration
ABSL_FLAG(int32_t, max_reconnect_backoff_ms, 0,
"Maximum backoff time, or 0 for default.");
using grpc::CallCredentials; using grpc::CallCredentials;
using grpc::Channel; using grpc::Channel;
@ -52,17 +55,19 @@ using grpc::testing::TLS;
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
GPR_ASSERT(FLAGS_server_control_port); GPR_ASSERT(absl::GetFlag(FLAGS_server_control_port));
GPR_ASSERT(FLAGS_server_retry_port); GPR_ASSERT(absl::GetFlag(FLAGS_server_retry_port));
std::ostringstream server_address; std::ostringstream server_address;
server_address << FLAGS_server_host << ':' << FLAGS_server_control_port; server_address << absl::GetFlag(FLAGS_server_host) << ':'
<< absl::GetFlag(FLAGS_server_control_port);
std::unique_ptr<ReconnectService::Stub> control_stub( std::unique_ptr<ReconnectService::Stub> control_stub(
ReconnectService::NewStub( ReconnectService::NewStub(
CreateTestChannel(server_address.str(), INSECURE))); CreateTestChannel(server_address.str(), INSECURE)));
ClientContext start_context; ClientContext start_context;
ReconnectParams reconnect_params; ReconnectParams reconnect_params;
reconnect_params.set_max_reconnect_backoff_ms(FLAGS_max_reconnect_backoff_ms); reconnect_params.set_max_reconnect_backoff_ms(
absl::GetFlag(FLAGS_max_reconnect_backoff_ms));
Empty empty_response; Empty empty_response;
Status start_status = Status start_status =
control_stub->Start(&start_context, reconnect_params, &empty_response); control_stub->Start(&start_context, reconnect_params, &empty_response);
@ -70,11 +75,12 @@ int main(int argc, char** argv) {
gpr_log(GPR_INFO, "Starting connections with retries."); gpr_log(GPR_INFO, "Starting connections with retries.");
server_address.str(""); server_address.str("");
server_address << FLAGS_server_host << ':' << FLAGS_server_retry_port; server_address << absl::GetFlag(FLAGS_server_host) << ':'
<< absl::GetFlag(FLAGS_server_retry_port);
ChannelArguments channel_args; ChannelArguments channel_args;
if (FLAGS_max_reconnect_backoff_ms > 0) { if (absl::GetFlag(FLAGS_max_reconnect_backoff_ms) > 0) {
channel_args.SetInt(GRPC_ARG_MAX_RECONNECT_BACKOFF_MS, channel_args.SetInt(GRPC_ARG_MAX_RECONNECT_BACKOFF_MS,
FLAGS_max_reconnect_backoff_ms); absl::GetFlag(FLAGS_max_reconnect_backoff_ms));
} }
std::shared_ptr<Channel> retry_channel = std::shared_ptr<Channel> retry_channel =
CreateTestChannel(server_address.str(), "foo.test.google.fr", TLS, false, CreateTestChannel(server_address.str(), "foo.test.google.fr", TLS, false,

@ -18,6 +18,11 @@
// Test description at doc/connection-backoff-interop-test-description.md // Test description at doc/connection-backoff-interop-test-description.md
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include <signal.h> #include <signal.h>
#include <condition_variable> #include <condition_variable>
@ -25,23 +30,17 @@
#include <mutex> #include <mutex>
#include <sstream> #include <sstream>
#include <gflags/gflags.h> #include "absl/flags/flag.h"
#include <grpc/grpc.h>
#include <grpc/support/log.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/messages.pb.h"
#include "src/proto/grpc/testing/test.grpc.pb.h" #include "src/proto/grpc/testing/test.grpc.pb.h"
#include "test/core/util/reconnect_server.h" #include "test/core/util/reconnect_server.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_int32(control_port, 0, "Server port for controlling the server."); ABSL_FLAG(int32_t, control_port, 0, "Server port for controlling the server.");
DEFINE_int32(retry_port, 0, ABSL_FLAG(int32_t, retry_port, 0,
"Server port for raw tcp connections. All incoming " "Server port for raw tcp connections. All incoming "
"connections will be closed immediately."); "connections will be closed immediately.");
using grpc::Server; using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
@ -156,8 +155,8 @@ class ReconnectServiceImpl : public ReconnectService::Service {
void RunServer() { void RunServer() {
std::ostringstream server_address; std::ostringstream server_address;
server_address << "0.0.0.0:" << FLAGS_control_port; server_address << "0.0.0.0:" << absl::GetFlag(FLAGS_control_port);
ReconnectServiceImpl service(FLAGS_retry_port); ReconnectServiceImpl service(absl::GetFlag(FLAGS_retry_port));
ServerBuilder builder; ServerBuilder builder;
builder.RegisterService(&service); builder.RegisterService(&service);
@ -177,8 +176,8 @@ int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
signal(SIGINT, sigint_handler); signal(SIGINT, sigint_handler);
GPR_ASSERT(FLAGS_control_port != 0); GPR_ASSERT(absl::GetFlag(FLAGS_control_port) != 0);
GPR_ASSERT(FLAGS_retry_port != 0); GPR_ASSERT(absl::GetFlag(FLAGS_retry_port) != 0);
RunServer(); RunServer();
return 0; return 0;

@ -18,29 +18,29 @@
#include "test/cpp/interop/server_helper.h" #include "test/cpp/interop/server_helper.h"
#include <memory>
#include <gflags/gflags.h>
#include <grpcpp/security/server_credentials.h> #include <grpcpp/security/server_credentials.h>
#include <memory>
#include "absl/flags/flag.h"
#include "src/core/lib/surface/call_test_only.h" #include "src/core/lib/surface/call_test_only.h"
#include "src/core/lib/transport/byte_stream.h" #include "src/core/lib/transport/byte_stream.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DECLARE_bool(use_alts); ABSL_DECLARE_FLAG(bool, use_alts);
DECLARE_bool(use_tls); ABSL_DECLARE_FLAG(bool, use_tls);
DECLARE_string(custom_credentials_type); ABSL_DECLARE_FLAG(std::string, custom_credentials_type);
namespace grpc { namespace grpc {
namespace testing { namespace testing {
std::shared_ptr<ServerCredentials> CreateInteropServerCredentials() { std::shared_ptr<ServerCredentials> CreateInteropServerCredentials() {
if (!FLAGS_custom_credentials_type.empty()) { if (!absl::GetFlag(FLAGS_custom_credentials_type).empty()) {
return GetCredentialsProvider()->GetServerCredentials( return GetCredentialsProvider()->GetServerCredentials(
FLAGS_custom_credentials_type); absl::GetFlag(FLAGS_custom_credentials_type));
} else if (FLAGS_use_alts) { } else if (absl::GetFlag(FLAGS_use_alts)) {
return GetCredentialsProvider()->GetServerCredentials(kAltsCredentialsType); return GetCredentialsProvider()->GetServerCredentials(kAltsCredentialsType);
} else if (FLAGS_use_tls) { } else if (absl::GetFlag(FLAGS_use_tls)) {
return GetCredentialsProvider()->GetServerCredentials(kTlsCredentialsType); return GetCredentialsProvider()->GetServerCredentials(kTlsCredentialsType);
} else { } else {
return GetCredentialsProvider()->GetServerCredentials( return GetCredentialsProvider()->GetServerCredentials(

@ -16,18 +16,18 @@
*is % allowed in string *is % allowed in string
*/ */
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/grpcpp.h>
#include <memory> #include <memory>
#include <string> #include <string>
#include <thread> #include <thread>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include <gflags/gflags.h> #include "absl/flags/flag.h"
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/grpcpp.h>
#include "src/proto/grpc/testing/metrics.grpc.pb.h" #include "src/proto/grpc/testing/metrics.grpc.pb.h"
#include "src/proto/grpc/testing/metrics.pb.h" #include "src/proto/grpc/testing/metrics.pb.h"
#include "test/cpp/interop/interop_client.h" #include "test/cpp/interop/interop_client.h"
@ -38,73 +38,76 @@
extern void gpr_default_log(gpr_log_func_args* args); extern void gpr_default_log(gpr_log_func_args* args);
DEFINE_int32(metrics_port, 8081, "The metrics server port."); ABSL_FLAG(int32_t, metrics_port, 8081, "The metrics server port.");
DEFINE_int32(sleep_duration_ms, 0, // TODO(Capstan): Consider using absl::Duration
"The duration (in millisec) between two" ABSL_FLAG(int32_t, sleep_duration_ms, 0,
" consecutive test calls (per server) issued by the server."); "The duration (in millisec) between two"
" consecutive test calls (per server) issued by the server.");
DEFINE_int32(test_duration_secs, -1, // TODO(Capstan): Consider using absl::Duration
"The length of time (in seconds) to run" ABSL_FLAG(int32_t, test_duration_secs, -1,
" the test. Enter -1 if the test should run continuously until" "The length of time (in seconds) to run"
" forcefully terminated."); " the test. Enter -1 if the test should run continuously until"
" forcefully terminated.");
DEFINE_string(server_addresses, "localhost:8080", ABSL_FLAG(std::string, server_addresses, "localhost:8080",
"The list of server addresses. The format is: \n" "The list of server addresses. The format is: \n"
" \"<name_1>:<port_1>,<name_2>:<port_1>...<name_N>:<port_N>\"\n" " \"<name_1>:<port_1>,<name_2>:<port_1>...<name_N>:<port_N>\"\n"
" Note: <name> can be servername or IP address."); " Note: <name> can be servername or IP address.");
DEFINE_int32(num_channels_per_server, 1, "Number of channels for each server"); ABSL_FLAG(int32_t, num_channels_per_server, 1,
"Number of channels for each server");
DEFINE_int32(num_stubs_per_channel, 1, ABSL_FLAG(int32_t, num_stubs_per_channel, 1,
"Number of stubs per each channels to server. This number also " "Number of stubs per each channels to server. This number also "
"indicates the max number of parallel RPC calls on each channel " "indicates the max number of parallel RPC calls on each channel "
"at any given time."); "at any given time.");
// TODO(sreek): Add more test cases here in future // TODO(sreek): Add more test cases here in future
DEFINE_string(test_cases, "", ABSL_FLAG(std::string, test_cases, "",
"List of test cases to call along with the" "List of test cases to call along with the"
" relative weights in the following format:\n" " relative weights in the following format:\n"
" \"<testcase_1:w_1>,<testcase_2:w_2>...<testcase_n:w_n>\"\n" " \"<testcase_1:w_1>,<testcase_2:w_2>...<testcase_n:w_n>\"\n"
" The following testcases are currently supported:\n" " The following testcases are currently supported:\n"
" empty_unary\n" " empty_unary\n"
" large_unary\n" " large_unary\n"
" large_compressed_unary\n" " large_compressed_unary\n"
" client_streaming\n" " client_streaming\n"
" server_streaming\n" " server_streaming\n"
" server_compressed_streaming\n" " server_compressed_streaming\n"
" slow_consumer\n" " slow_consumer\n"
" half_duplex\n" " half_duplex\n"
" ping_pong\n" " ping_pong\n"
" cancel_after_begin\n" " cancel_after_begin\n"
" cancel_after_first_response\n" " cancel_after_first_response\n"
" timeout_on_sleeping_server\n" " timeout_on_sleeping_server\n"
" empty_stream\n" " empty_stream\n"
" status_code_and_message\n" " status_code_and_message\n"
" custom_metadata\n" " custom_metadata\n"
" Example: \"empty_unary:20,large_unary:10,empty_stream:70\"\n" " Example: \"empty_unary:20,large_unary:10,empty_stream:70\"\n"
" The above will execute 'empty_unary', 20% of the time," " The above will execute 'empty_unary', 20% of the time,"
" 'large_unary', 10% of the time and 'empty_stream' the remaining" " 'large_unary', 10% of the time and 'empty_stream' the remaining"
" 70% of the time"); " 70% of the time");
DEFINE_int32(log_level, GPR_LOG_SEVERITY_INFO, ABSL_FLAG(int32_t, log_level, GPR_LOG_SEVERITY_INFO,
"Severity level of messages that should be logged. Any messages " "Severity level of messages that should be logged. Any messages "
"greater than or equal to the level set here will be logged. " "greater than or equal to the level set here will be logged. "
"The choices are: 0 (GPR_LOG_SEVERITY_DEBUG), 1 " "The choices are: 0 (GPR_LOG_SEVERITY_DEBUG), 1 "
"(GPR_LOG_SEVERITY_INFO) and 2 (GPR_LOG_SEVERITY_ERROR)"); "(GPR_LOG_SEVERITY_INFO) and 2 (GPR_LOG_SEVERITY_ERROR)");
DEFINE_bool(do_not_abort_on_transient_failures, true, ABSL_FLAG(bool, do_not_abort_on_transient_failures, true,
"If set to 'true', abort() is not called in case of transient " "If set to 'true', abort() is not called in case of transient "
"failures like temporary connection failures."); "failures like temporary connection failures.");
// Options from client.cc (for compatibility with interop test). // Options from client.cc (for compatibility with interop test).
// TODO(sreek): Consolidate overlapping options // TODO(sreek): Consolidate overlapping options
DEFINE_bool(use_alts, false, ABSL_FLAG(bool, use_alts, false,
"Whether to use alts. Enable alts will disable tls."); "Whether to use alts. Enable alts will disable tls.");
DEFINE_bool(use_tls, false, "Whether to use tls."); ABSL_FLAG(bool, use_tls, false, "Whether to use tls.");
DEFINE_bool(use_test_ca, false, "False to use SSL roots for google"); ABSL_FLAG(bool, use_test_ca, false, "False to use SSL roots for google");
DEFINE_string(server_host_override, "", ABSL_FLAG(std::string, server_host_override, "",
"Override the server host which is sent in HTTP header"); "Override the server host which is sent in HTTP header");
using grpc::testing::ALTS; using grpc::testing::ALTS;
using grpc::testing::INSECURE; using grpc::testing::INSECURE;
@ -193,16 +196,21 @@ bool ParseTestCasesString(const std::string& test_cases,
// For debugging purposes // For debugging purposes
void LogParameterInfo(const std::vector<std::string>& addresses, void LogParameterInfo(const std::vector<std::string>& addresses,
const std::vector<std::pair<TestCaseType, int>>& tests) { const std::vector<std::pair<TestCaseType, int>>& tests) {
gpr_log(GPR_INFO, "server_addresses: %s", FLAGS_server_addresses.c_str()); gpr_log(GPR_INFO, "server_addresses: %s",
gpr_log(GPR_INFO, "test_cases : %s", FLAGS_test_cases.c_str()); absl::GetFlag(FLAGS_server_addresses).c_str());
gpr_log(GPR_INFO, "sleep_duration_ms: %d", FLAGS_sleep_duration_ms); gpr_log(GPR_INFO, "test_cases : %s", absl::GetFlag(FLAGS_test_cases).c_str());
gpr_log(GPR_INFO, "test_duration_secs: %d", FLAGS_test_duration_secs); gpr_log(GPR_INFO, "sleep_duration_ms: %d",
absl::GetFlag(FLAGS_sleep_duration_ms));
gpr_log(GPR_INFO, "test_duration_secs: %d",
absl::GetFlag(FLAGS_test_duration_secs));
gpr_log(GPR_INFO, "num_channels_per_server: %d", gpr_log(GPR_INFO, "num_channels_per_server: %d",
FLAGS_num_channels_per_server); absl::GetFlag(FLAGS_num_channels_per_server));
gpr_log(GPR_INFO, "num_stubs_per_channel: %d", FLAGS_num_stubs_per_channel); gpr_log(GPR_INFO, "num_stubs_per_channel: %d",
gpr_log(GPR_INFO, "log_level: %d", FLAGS_log_level); absl::GetFlag(FLAGS_num_stubs_per_channel));
gpr_log(GPR_INFO, "log_level: %d", absl::GetFlag(FLAGS_log_level));
gpr_log(GPR_INFO, "do_not_abort_on_transient_failures: %s", gpr_log(GPR_INFO, "do_not_abort_on_transient_failures: %s",
FLAGS_do_not_abort_on_transient_failures ? "true" : "false"); absl::GetFlag(FLAGS_do_not_abort_on_transient_failures) ? "true"
: "false");
int num = 0; int num = 0;
for (auto it = addresses.begin(); it != addresses.end(); it++) { for (auto it = addresses.begin(); it != addresses.end(); it++) {
@ -221,8 +229,8 @@ void LogParameterInfo(const std::vector<std::string>& addresses,
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
if (FLAGS_log_level > GPR_LOG_SEVERITY_ERROR || if (absl::GetFlag(FLAGS_log_level) > GPR_LOG_SEVERITY_ERROR ||
FLAGS_log_level < GPR_LOG_SEVERITY_DEBUG) { absl::GetFlag(FLAGS_log_level) < GPR_LOG_SEVERITY_DEBUG) {
gpr_log(GPR_ERROR, "log_level should be an integer between %d and %d", gpr_log(GPR_ERROR, "log_level should be an integer between %d and %d",
GPR_LOG_SEVERITY_DEBUG, GPR_LOG_SEVERITY_ERROR); GPR_LOG_SEVERITY_DEBUG, GPR_LOG_SEVERITY_ERROR);
return 1; return 1;
@ -230,25 +238,26 @@ int main(int argc, char** argv) {
// Change the default log function to TestLogFunction which respects the // Change the default log function to TestLogFunction which respects the
// log_level setting. // log_level setting.
log_level = FLAGS_log_level; log_level = absl::GetFlag(FLAGS_log_level);
gpr_set_log_function(TestLogFunction); gpr_set_log_function(TestLogFunction);
srand(time(nullptr)); srand(time(nullptr));
// Parse the server addresses // Parse the server addresses
std::vector<std::string> server_addresses; std::vector<std::string> server_addresses;
ParseCommaDelimitedString(FLAGS_server_addresses, server_addresses); ParseCommaDelimitedString(absl::GetFlag(FLAGS_server_addresses),
server_addresses);
// Parse test cases and weights // Parse test cases and weights
if (FLAGS_test_cases.length() == 0) { if (absl::GetFlag(FLAGS_test_cases).length() == 0) {
gpr_log(GPR_ERROR, "No test cases supplied"); gpr_log(GPR_ERROR, "No test cases supplied");
return 1; return 1;
} }
std::vector<std::pair<TestCaseType, int>> tests; std::vector<std::pair<TestCaseType, int>> tests;
if (!ParseTestCasesString(FLAGS_test_cases, tests)) { if (!ParseTestCasesString(absl::GetFlag(FLAGS_test_cases), tests)) {
gpr_log(GPR_ERROR, "Error in parsing test cases string %s ", gpr_log(GPR_ERROR, "Error in parsing test cases string %s ",
FLAGS_test_cases.c_str()); absl::GetFlag(FLAGS_test_cases).c_str());
return 1; return 1;
} }
@ -274,28 +283,33 @@ int main(int argc, char** argv) {
int server_idx = -1; int server_idx = -1;
char buffer[256]; char buffer[256];
transport_security security_type = transport_security security_type =
FLAGS_use_alts ? ALTS : (FLAGS_use_tls ? TLS : INSECURE); absl::GetFlag(FLAGS_use_alts)
? ALTS
: (absl::GetFlag(FLAGS_use_tls) ? TLS : INSECURE);
for (auto it = server_addresses.begin(); it != server_addresses.end(); it++) { for (auto it = server_addresses.begin(); it != server_addresses.end(); it++) {
++server_idx; ++server_idx;
// Create channel(s) for each server // Create channel(s) for each server
for (int channel_idx = 0; channel_idx < FLAGS_num_channels_per_server; for (int channel_idx = 0;
channel_idx < absl::GetFlag(FLAGS_num_channels_per_server);
channel_idx++) { channel_idx++) {
gpr_log(GPR_INFO, "Starting test with %s channel_idx=%d..", it->c_str(), gpr_log(GPR_INFO, "Starting test with %s channel_idx=%d..", it->c_str(),
channel_idx); channel_idx);
grpc::testing::ChannelCreationFunc channel_creation_func = std::bind( grpc::testing::ChannelCreationFunc channel_creation_func =
static_cast<std::shared_ptr<grpc::Channel> (*)( std::bind(static_cast<std::shared_ptr<grpc::Channel> (*)(
const std::string&, const std::string&, const std::string&, const std::string&,
grpc::testing::transport_security, bool)>( grpc::testing::transport_security, bool)>(
grpc::CreateTestChannel), grpc::CreateTestChannel),
*it, FLAGS_server_host_override, security_type, !FLAGS_use_test_ca); *it, absl::GetFlag(FLAGS_server_host_override),
security_type, !absl::GetFlag(FLAGS_use_test_ca));
// Create stub(s) for each channel // Create stub(s) for each channel
for (int stub_idx = 0; stub_idx < FLAGS_num_stubs_per_channel; for (int stub_idx = 0;
stub_idx++) { stub_idx < absl::GetFlag(FLAGS_num_stubs_per_channel); stub_idx++) {
clients.emplace_back(new StressTestInteropClient( clients.emplace_back(new StressTestInteropClient(
++thread_idx, *it, channel_creation_func, test_selector, ++thread_idx, *it, channel_creation_func, test_selector,
FLAGS_test_duration_secs, FLAGS_sleep_duration_ms, absl::GetFlag(FLAGS_test_duration_secs),
FLAGS_do_not_abort_on_transient_failures)); absl::GetFlag(FLAGS_sleep_duration_ms),
absl::GetFlag(FLAGS_do_not_abort_on_transient_failures)));
bool is_already_created = false; bool is_already_created = false;
// QpsGauge name // QpsGauge name
@ -315,8 +329,9 @@ int main(int argc, char** argv) {
// Start metrics server before waiting for the stress test threads // Start metrics server before waiting for the stress test threads
std::unique_ptr<grpc::Server> metrics_server; std::unique_ptr<grpc::Server> metrics_server;
if (FLAGS_metrics_port > 0) { if (absl::GetFlag(FLAGS_metrics_port) > 0) {
metrics_server = metrics_service.StartServer(FLAGS_metrics_port); metrics_server =
metrics_service.StartServer(absl::GetFlag(FLAGS_metrics_port));
} }
// Wait for the stress test threads to complete // Wait for the stress test threads to complete

@ -16,6 +16,11 @@
* *
*/ */
#include <grpcpp/grpcpp.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include <atomic> #include <atomic>
#include <chrono> #include <chrono>
#include <condition_variable> #include <condition_variable>
@ -27,14 +32,8 @@
#include <thread> #include <thread>
#include <vector> #include <vector>
#include "absl/flags/flag.h"
#include "absl/strings/str_split.h" #include "absl/strings/str_split.h"
#include <gflags/gflags.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/server.h>
#include <grpcpp/server_builder.h>
#include <grpcpp/server_context.h>
#include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/env.h"
#include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/empty.pb.h"
#include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/messages.pb.h"
@ -42,17 +41,19 @@
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_bool(fail_on_failed_rpc, false, ABSL_FLAG(bool, fail_on_failed_rpc, false,
"Fail client if any RPCs fail after first successful RPC."); "Fail client if any RPCs fail after first successful RPC.");
DEFINE_int32(num_channels, 1, "Number of channels."); ABSL_FLAG(int32_t, num_channels, 1, "Number of channels.");
DEFINE_bool(print_response, false, "Write RPC response to stdout."); ABSL_FLAG(bool, print_response, false, "Write RPC response to stdout.");
DEFINE_int32(qps, 1, "Qps per channel."); ABSL_FLAG(int32_t, qps, 1, "Qps per channel.");
DEFINE_int32(rpc_timeout_sec, 30, "Per RPC timeout seconds."); // TODO(Capstan): Consider using absl::Duration
DEFINE_string(server, "localhost:50051", "Address of server."); ABSL_FLAG(int32_t, rpc_timeout_sec, 30, "Per RPC timeout seconds.");
DEFINE_int32(stats_port, 50052, ABSL_FLAG(std::string, server, "localhost:50051", "Address of server.");
"Port to expose peer distribution stats service."); ABSL_FLAG(int32_t, stats_port, 50052,
DEFINE_string(rpc, "UnaryCall", "a comma separated list of rpc methods."); "Port to expose peer distribution stats service.");
DEFINE_string(metadata, "", "metadata to send with the RPC."); ABSL_FLAG(std::string, rpc, "UnaryCall",
"a comma separated list of rpc methods.");
ABSL_FLAG(std::string, metadata, "", "metadata to send with the RPC.");
using grpc::Channel; using grpc::Channel;
using grpc::ClientAsyncResponseReader; using grpc::ClientAsyncResponseReader;
@ -156,7 +157,7 @@ class TestClient {
} }
std::chrono::system_clock::time_point deadline = std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::system_clock::now() +
std::chrono::seconds(FLAGS_rpc_timeout_sec); std::chrono::seconds(absl::GetFlag(FLAGS_rpc_timeout_sec));
AsyncClientCall* call = new AsyncClientCall; AsyncClientCall* call = new AsyncClientCall;
call->context.set_deadline(deadline); call->context.set_deadline(deadline);
for (const auto& data : metadata) { for (const auto& data : metadata) {
@ -181,7 +182,7 @@ class TestClient {
} }
std::chrono::system_clock::time_point deadline = std::chrono::system_clock::time_point deadline =
std::chrono::system_clock::now() + std::chrono::system_clock::now() +
std::chrono::seconds(FLAGS_rpc_timeout_sec); std::chrono::seconds(absl::GetFlag(FLAGS_rpc_timeout_sec));
AsyncClientCall* call = new AsyncClientCall; AsyncClientCall* call = new AsyncClientCall;
call->context.set_deadline(deadline); call->context.set_deadline(deadline);
for (const auto& data : metadata) { for (const auto& data : metadata) {
@ -219,15 +220,17 @@ class TestClient {
} }
if (!call->status.ok()) { if (!call->status.ok()) {
if (FLAGS_print_response || FLAGS_fail_on_failed_rpc) { if (absl::GetFlag(FLAGS_print_response) ||
absl::GetFlag(FLAGS_fail_on_failed_rpc)) {
std::cout << "RPC failed: " << call->status.error_code() << ": " std::cout << "RPC failed: " << call->status.error_code() << ": "
<< call->status.error_message() << std::endl; << call->status.error_message() << std::endl;
} }
if (FLAGS_fail_on_failed_rpc && one_rpc_succeeded.load()) { if (absl::GetFlag(FLAGS_fail_on_failed_rpc) &&
one_rpc_succeeded.load()) {
abort(); abort();
} }
} else { } else {
if (FLAGS_print_response) { if (absl::GetFlag(FLAGS_print_response)) {
auto metadata_hostname = auto metadata_hostname =
call->context.GetServerInitialMetadata().find("hostname"); call->context.GetServerInitialMetadata().find("hostname");
std::string hostname = std::string hostname =
@ -290,14 +293,14 @@ class LoadBalancerStatsServiceImpl : public LoadBalancerStatsService::Service {
void RunTestLoop(std::chrono::duration<double> duration_per_query) { void RunTestLoop(std::chrono::duration<double> duration_per_query) {
std::vector<absl::string_view> rpc_methods = std::vector<absl::string_view> rpc_methods =
absl::StrSplit(FLAGS_rpc, ',', absl::SkipEmpty()); absl::StrSplit(absl::GetFlag(FLAGS_rpc), ',', absl::SkipEmpty());
// Store Metadata like // Store Metadata like
// "EmptyCall:key1:value1,UnaryCall:key1:value1,UnaryCall:key2:value2" into a // "EmptyCall:key1:value1,UnaryCall:key1:value1,UnaryCall:key2:value2" into a
// map where the key is the RPC method and value is a vector of key:value // map where the key is the RPC method and value is a vector of key:value
// pairs. {EmptyCall, [{key1,value1}], // pairs. {EmptyCall, [{key1,value1}],
// UnaryCall, [{key1,value1}, {key2,value2}]} // UnaryCall, [{key1,value1}, {key2,value2}]}
std::vector<absl::string_view> rpc_metadata = std::vector<absl::string_view> rpc_metadata =
absl::StrSplit(FLAGS_metadata, ',', absl::SkipEmpty()); absl::StrSplit(absl::GetFlag(FLAGS_metadata), ',', absl::SkipEmpty());
std::map<std::string, std::vector<std::pair<std::string, std::string>>> std::map<std::string, std::vector<std::pair<std::string, std::string>>>
metadata_map; metadata_map;
for (auto& data : rpc_metadata) { for (auto& data : rpc_metadata) {
@ -307,8 +310,8 @@ void RunTestLoop(std::chrono::duration<double> duration_per_query) {
metadata_map[std::string(metadata[0])].push_back( metadata_map[std::string(metadata[0])].push_back(
{std::string(metadata[1]), std::string(metadata[2])}); {std::string(metadata[1]), std::string(metadata[2])});
} }
TestClient client( TestClient client(grpc::CreateChannel(absl::GetFlag(FLAGS_server),
grpc::CreateChannel(FLAGS_server, grpc::InsecureChannelCredentials())); grpc::InsecureChannelCredentials()));
std::chrono::time_point<std::chrono::system_clock> start = std::chrono::time_point<std::chrono::system_clock> start =
std::chrono::system_clock::now(); std::chrono::system_clock::now();
std::chrono::duration<double> elapsed; std::chrono::duration<double> elapsed;
@ -361,16 +364,17 @@ int main(int argc, char** argv) {
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
std::chrono::duration<double> duration_per_query = std::chrono::duration<double> duration_per_query =
std::chrono::nanoseconds(std::chrono::seconds(1)) / FLAGS_qps; std::chrono::nanoseconds(std::chrono::seconds(1)) /
absl::GetFlag(FLAGS_qps);
std::vector<std::thread> test_threads; std::vector<std::thread> test_threads;
test_threads.reserve(FLAGS_num_channels); test_threads.reserve(absl::GetFlag(FLAGS_num_channels));
for (int i = 0; i < FLAGS_num_channels; i++) { for (int i = 0; i < absl::GetFlag(FLAGS_num_channels); i++) {
test_threads.emplace_back(std::thread(&RunTestLoop, duration_per_query)); test_threads.emplace_back(std::thread(&RunTestLoop, duration_per_query));
} }
RunServer(FLAGS_stats_port); RunServer(absl::GetFlag(FLAGS_stats_port));
for (auto it = test_threads.begin(); it != test_threads.end(); it++) { for (auto it = test_threads.begin(); it != test_threads.end(); it++) {
it->join(); it->join();

@ -16,7 +16,6 @@
* *
*/ */
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/time.h> #include <grpc/support/time.h>
@ -26,6 +25,7 @@
#include <sstream> #include <sstream>
#include "absl/flags/flag.h"
#include "src/core/lib/gpr/string.h" #include "src/core/lib/gpr/string.h"
#include "src/core/lib/iomgr/gethostname.h" #include "src/core/lib/iomgr/gethostname.h"
#include "src/core/lib/transport/byte_stream.h" #include "src/core/lib/transport/byte_stream.h"
@ -35,8 +35,9 @@
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_int32(port, 50051, "Server port."); ABSL_FLAG(int32_t, port, 50051, "Server port.");
DEFINE_string(server_id, "cpp_server", "Server ID to include in responses."); ABSL_FLAG(std::string, server_id, "cpp_server",
"Server ID to include in responses.");
using grpc::Server; using grpc::Server;
using grpc::ServerBuilder; using grpc::ServerBuilder;
@ -53,7 +54,7 @@ class TestServiceImpl : public TestService::Service {
Status UnaryCall(ServerContext* context, const SimpleRequest* request, Status UnaryCall(ServerContext* context, const SimpleRequest* request,
SimpleResponse* response) override { SimpleResponse* response) override {
response->set_server_id(FLAGS_server_id); response->set_server_id(absl::GetFlag(FLAGS_server_id));
response->set_hostname(hostname_); response->set_hostname(hostname_);
context->AddInitialMetadata("hostname", hostname_); context->AddInitialMetadata("hostname", hostname_);
return Status::OK; return Status::OK;
@ -93,12 +94,12 @@ int main(int argc, char** argv) {
std::cout << "Failed to get hostname, terminating" << std::endl; std::cout << "Failed to get hostname, terminating" << std::endl;
return 1; return 1;
} }
if (FLAGS_port == 0) { if (absl::GetFlag(FLAGS_port) == 0) {
std::cout << "Invalid port, terminating" << std::endl; std::cout << "Invalid port, terminating" << std::endl;
return 1; return 1;
} }
RunServer(FLAGS_port, hostname); RunServer(absl::GetFlag(FLAGS_port), hostname);
return 0; return 0;
} }

@ -217,6 +217,9 @@ grpc_cc_test(
name = "bm_fullstack_trickle", name = "bm_fullstack_trickle",
size = "large", size = "large",
srcs = ["bm_fullstack_trickle.cc"], srcs = ["bm_fullstack_trickle.cc"],
external_deps = [
"absl/flags:flag",
],
tags = [ tags = [
"manual", "manual",
"no_windows", "no_windows",

@ -19,11 +19,11 @@
/* Benchmark gRPC end2end in various configurations */ /* Benchmark gRPC end2end in various configurations */
#include <benchmark/benchmark.h> #include <benchmark/benchmark.h>
#include <gflags/gflags.h>
#include <fstream> #include <fstream>
#include "absl/flags/flag.h"
#include "absl/memory/memory.h" #include "absl/memory/memory.h"
#include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
#include "src/core/ext/transport/chttp2/transport/internal.h" #include "src/core/ext/transport/chttp2/transport/internal.h"
#include "src/core/lib/iomgr/timer_manager.h" #include "src/core/lib/iomgr/timer_manager.h"
@ -35,15 +35,13 @@
#include "test/cpp/microbenchmarks/fullstack_fixtures.h" #include "test/cpp/microbenchmarks/fullstack_fixtures.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_bool(log, false, "Log state to CSV files"); ABSL_FLAG(bool, log, false, "Log state to CSV files");
DEFINE_int32( ABSL_FLAG(int32_t, warmup_megabytes, 1,
warmup_megabytes, 1, "Number of megabytes to pump before collecting flow control stats");
"Number of megabytes to pump before collecting flow control stats"); ABSL_FLAG(int32_t, warmup_iterations, 100,
DEFINE_int32( "Number of iterations to run before collecting flow control stats");
warmup_iterations, 100, ABSL_FLAG(int32_t, warmup_max_time_seconds, 10,
"Number of iterations to run before collecting flow control stats"); "Maximum number of seconds to run warmup loop");
DEFINE_int32(warmup_max_time_seconds, 10,
"Maximum number of seconds to run warmup loop");
namespace grpc { namespace grpc {
namespace testing { namespace testing {
@ -87,7 +85,7 @@ class TrickledCHTTP2 : public EndpointPairFixture {
: EndpointPairFixture(service, MakeEndpoints(kilobits_per_second, stats), : EndpointPairFixture(service, MakeEndpoints(kilobits_per_second, stats),
FixtureConfiguration()), FixtureConfiguration()),
stats_(stats) { stats_(stats) {
if (FLAGS_log) { if (absl::GetFlag(FLAGS_log)) {
std::ostringstream fn; std::ostringstream fn;
fn << "trickle." << (streaming ? "streaming" : "unary") << "." << req_size fn << "trickle." << (streaming ? "streaming" : "unary") << "." << req_size
<< "." << resp_size << "." << kilobits_per_second << ".csv"; << "." << resp_size << "." << kilobits_per_second << ".csv";
@ -304,14 +302,15 @@ static void BM_PumpStreamServerToClient_Trickle(benchmark::State& state) {
} }
}; };
gpr_timespec warmup_start = gpr_now(GPR_CLOCK_MONOTONIC); gpr_timespec warmup_start = gpr_now(GPR_CLOCK_MONOTONIC);
for (int i = 0; for (int i = 0; i < GPR_MAX(absl::GetFlag(FLAGS_warmup_iterations),
i < GPR_MAX(FLAGS_warmup_iterations, FLAGS_warmup_megabytes * 1024 * absl::GetFlag(FLAGS_warmup_megabytes) * 1024 *
1024 / (14 + state.range(0))); 1024 / (14 + state.range(0)));
i++) { i++) {
inner_loop(true); inner_loop(true);
if (gpr_time_cmp(gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start), if (gpr_time_cmp(gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start),
gpr_time_from_seconds(FLAGS_warmup_max_time_seconds, gpr_time_from_seconds(
GPR_TIMESPAN)) > 0) { absl::GetFlag(FLAGS_warmup_max_time_seconds),
GPR_TIMESPAN)) > 0) {
break; break;
} }
} }
@ -417,14 +416,15 @@ static void BM_PumpUnbalancedUnary_Trickle(benchmark::State& state) {
fixture->cq(), fixture->cq(), tag(slot)); fixture->cq(), fixture->cq(), tag(slot));
}; };
gpr_timespec warmup_start = gpr_now(GPR_CLOCK_MONOTONIC); gpr_timespec warmup_start = gpr_now(GPR_CLOCK_MONOTONIC);
for (int i = 0; for (int i = 0; i < GPR_MAX(absl::GetFlag(FLAGS_warmup_iterations),
i < GPR_MAX(FLAGS_warmup_iterations, FLAGS_warmup_megabytes * 1024 * absl::GetFlag(FLAGS_warmup_megabytes) * 1024 *
1024 / (14 + state.range(0))); 1024 / (14 + state.range(0)));
i++) { i++) {
inner_loop(true); inner_loop(true);
if (gpr_time_cmp(gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start), if (gpr_time_cmp(
gpr_time_from_seconds(FLAGS_warmup_max_time_seconds, gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start),
GPR_TIMESPAN)) > 0) { gpr_time_from_seconds(absl::GetFlag(FLAGS_warmup_max_time_seconds),
GPR_TIMESPAN)) > 0) {
break; break;
} }
} }

@ -16,6 +16,8 @@
* *
*/ */
#include <address_sorting/address_sorting.h>
#include <gmock/gmock.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
@ -23,15 +25,9 @@
#include <grpc/support/sync.h> #include <grpc/support/sync.h>
#include <grpc/support/time.h> #include <grpc/support/time.h>
#include <string.h> #include <string.h>
#include <gflags/gflags.h>
#include <gmock/gmock.h>
#include <sys/types.h> #include <sys/types.h>
#include <vector>
#include <address_sorting/address_sorting.h> #include <vector>
#include "test/cpp/util/subprocess.h"
#include "test/cpp/util/test_config.h"
#include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/ext/filters/client_channel/resolver.h"
@ -49,6 +45,8 @@
#include "src/core/lib/iomgr/sockaddr_utils.h" #include "src/core/lib/iomgr/sockaddr_utils.h"
#include "test/core/util/port.h" #include "test/core/util/port.h"
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/util/subprocess.h"
#include "test/cpp/util/test_config.h"
#ifndef GPR_WINDOWS #ifndef GPR_WINDOWS
#include <arpa/inet.h> #include <arpa/inet.h>

@ -16,23 +16,19 @@
* *
*/ */
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <gflags/gflags.h>
#include <gmock/gmock.h> #include <gmock/gmock.h>
#include <grpc/byte_buffer.h> #include <grpc/byte_buffer.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/time.h> #include <grpc/support/time.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/ext/filters/client_channel/resolver.h"
#include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h" #include "src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h" #include "src/core/ext/filters/client_channel/resolver_registry.h"

@ -62,6 +62,9 @@ def generate_resolver_component_tests():
srcs = [ srcs = [
"resolver_component_tests_runner_invoker.cc", "resolver_component_tests_runner_invoker.cc",
], ],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
"//test/cpp/util:test_util", "//test/cpp/util:test_util",
"//test/core/util:grpc_test_util", "//test/core/util:grpc_test_util",

@ -16,33 +16,26 @@
* *
*/ */
#include <grpc/support/port_platform.h>
#include <string>
#include <thread>
#include <vector>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <string.h>
#include <gflags/gflags.h>
#include <gmock/gmock.h> #include <gmock/gmock.h>
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/impl/codegen/grpc_types.h> #include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include <grpc/support/sync.h> #include <grpc/support/sync.h>
#include <grpc/support/time.h> #include <grpc/support/time.h>
#include <string.h>
#include "test/cpp/util/subprocess.h" #include <string>
#include "test/cpp/util/test_config.h" #include <thread>
#include <vector>
#include "absl/flags/flag.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h" #include "src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.h"
#include "src/core/ext/filters/client_channel/resolver.h" #include "src/core/ext/filters/client_channel/resolver.h"
@ -63,8 +56,9 @@
#include "src/core/lib/iomgr/work_serializer.h" #include "src/core/lib/iomgr/work_serializer.h"
#include "test/core/util/port.h" #include "test/core/util/port.h"
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/naming/dns_test_util.h" #include "test/cpp/naming/dns_test_util.h"
#include "test/cpp/util/subprocess.h"
#include "test/cpp/util/test_config.h"
// TODO: pull in different headers when enabling this // TODO: pull in different headers when enabling this
// test on windows. Also set BAD_SOCKET_RETURN_VAL // test on windows. Also set BAD_SOCKET_RETURN_VAL
@ -82,50 +76,44 @@
using std::vector; using std::vector;
using testing::UnorderedElementsAreArray; using testing::UnorderedElementsAreArray;
// Hack copied from "test/cpp/end2end/server_crash_test_client.cc"! ABSL_FLAG(std::string, target_name, "", "Target name to resolve.");
// In some distros, gflags is in the namespace google, and in some others, ABSL_FLAG(std::string, do_ordered_address_comparison, "",
// in gflags. This hack is enabling us to find both. "Whether or not to compare resolved addresses to expected "
namespace google {} "addresses using an ordered comparison. This is useful for "
namespace gflags {} "testing certain behaviors that involve sorting of resolved "
using namespace google; "addresses. Note it would be better if this argument was a "
using namespace gflags; "bool flag, but it's a string for ease of invocation from "
"the generated python test runner.");
DEFINE_string(target_name, "", "Target name to resolve."); ABSL_FLAG(std::string, expected_addrs, "",
DEFINE_string(do_ordered_address_comparison, "", "List of expected backend or balancer addresses in the form "
"Whether or not to compare resolved addresses to expected " "'<ip0:port0>,<is_balancer0>;<ip1:port1>,<is_balancer1>;...'. "
"addresses using an ordered comparison. This is useful for " "'is_balancer' should be bool, i.e. true or false.");
"testing certain behaviors that involve sorting of resolved " ABSL_FLAG(std::string, expected_chosen_service_config, "",
"addresses. Note it would be better if this argument was a " "Expected service config json string that gets chosen (no "
"bool flag, but it's a string for ease of invocation from " "whitespace). Empty for none.");
"the generated python test runner."); ABSL_FLAG(std::string, expected_service_config_error, "",
DEFINE_string(expected_addrs, "", "Expected service config error. Empty for none.");
"List of expected backend or balancer addresses in the form " ABSL_FLAG(std::string, local_dns_server_address, "",
"'<ip0:port0>,<is_balancer0>;<ip1:port1>,<is_balancer1>;...'. " "Optional. This address is placed as the uri authority if present.");
"'is_balancer' should be bool, i.e. true or false."); // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
DEFINE_string(expected_chosen_service_config, "", ABSL_FLAG(
"Expected service config json string that gets chosen (no " std::string, enable_srv_queries, "",
"whitespace). Empty for none.");
DEFINE_string(expected_service_config_error, "",
"Expected service config error. Empty for none.");
DEFINE_string(
local_dns_server_address, "",
"Optional. This address is placed as the uri authority if present.");
DEFINE_string(
enable_srv_queries, "",
"Whether or not to enable SRV queries for the ares resolver instance." "Whether or not to enable SRV queries for the ares resolver instance."
"It would be better if this arg could be bool, but the way that we " "It would be better if this arg could be bool, but the way that we "
"generate " "generate "
"the python script runner doesn't allow us to pass a gflags bool to this " "the python script runner doesn't allow us to pass a gflags bool to this "
"binary."); "binary.");
DEFINE_string( // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
enable_txt_queries, "", ABSL_FLAG(
std::string, enable_txt_queries, "",
"Whether or not to enable TXT queries for the ares resolver instance." "Whether or not to enable TXT queries for the ares resolver instance."
"It would be better if this arg could be bool, but the way that we " "It would be better if this arg could be bool, but the way that we "
"generate " "generate "
"the python script runner doesn't allow us to pass a gflags bool to this " "the python script runner doesn't allow us to pass a gflags bool to this "
"binary."); "binary.");
DEFINE_string( // TODO(Capstan): Is this worth making `bool` now with Abseil flags?
inject_broken_nameserver_list, "", ABSL_FLAG(
std::string, inject_broken_nameserver_list, "",
"Whether or not to configure c-ares to use a broken nameserver list, in " "Whether or not to configure c-ares to use a broken nameserver list, in "
"which " "which "
"the first nameserver in the list is non-responsive, but the second one " "the first nameserver in the list is non-responsive, but the second one "
@ -135,9 +123,9 @@ DEFINE_string(
"generate " "generate "
"the python script runner doesn't allow us to pass a gflags bool to this " "the python script runner doesn't allow us to pass a gflags bool to this "
"binary."); "binary.");
DEFINE_string(expected_lb_policy, "", ABSL_FLAG(std::string, expected_lb_policy, "",
"Expected lb policy name that appears in resolver result channel " "Expected lb policy name that appears in resolver result channel "
"arg. Empty for none."); "arg. Empty for none.");
namespace { namespace {
@ -495,16 +483,16 @@ class CheckingResultHandler : public ResultHandler {
found_lb_addrs.size(), args->expected_addrs.size()); found_lb_addrs.size(), args->expected_addrs.size());
abort(); abort();
} }
if (FLAGS_do_ordered_address_comparison == "True") { if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "True") {
EXPECT_EQ(args->expected_addrs, found_lb_addrs); EXPECT_EQ(args->expected_addrs, found_lb_addrs);
} else if (FLAGS_do_ordered_address_comparison == "False") { } else if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "False") {
EXPECT_THAT(args->expected_addrs, EXPECT_THAT(args->expected_addrs,
UnorderedElementsAreArray(found_lb_addrs)); UnorderedElementsAreArray(found_lb_addrs));
} else { } else {
gpr_log(GPR_ERROR, gpr_log(GPR_ERROR,
"Invalid for setting for --do_ordered_address_comparison. " "Invalid for setting for --do_ordered_address_comparison. "
"Have %s, want True or False", "Have %s, want True or False",
FLAGS_do_ordered_address_comparison.c_str()); absl::GetFlag(FLAGS_do_ordered_address_comparison).c_str());
GPR_ASSERT(0); GPR_ASSERT(0);
} }
const char* service_config_json = const char* service_config_json =
@ -543,13 +531,14 @@ void InjectBrokenNameServerList(ares_channel channel) {
memset(dns_server_addrs, 0, sizeof(dns_server_addrs)); memset(dns_server_addrs, 0, sizeof(dns_server_addrs));
std::string unused_host; std::string unused_host;
std::string local_dns_server_port; std::string local_dns_server_port;
GPR_ASSERT(grpc_core::SplitHostPort(FLAGS_local_dns_server_address.c_str(), GPR_ASSERT(grpc_core::SplitHostPort(
&unused_host, &local_dns_server_port)); absl::GetFlag(FLAGS_local_dns_server_address).c_str(), &unused_host,
&local_dns_server_port));
gpr_log(GPR_DEBUG, gpr_log(GPR_DEBUG,
"Injecting broken nameserver list. Bad server address:|[::1]:%d|. " "Injecting broken nameserver list. Bad server address:|[::1]:%d|. "
"Good server address:%s", "Good server address:%s",
g_fake_non_responsive_dns_server_port, g_fake_non_responsive_dns_server_port,
FLAGS_local_dns_server_address.c_str()); absl::GetFlag(FLAGS_local_dns_server_address).c_str());
// Put the non-responsive DNS server at the front of c-ares's nameserver list. // Put the non-responsive DNS server at the front of c-ares's nameserver list.
dns_server_addrs[0].family = AF_INET6; dns_server_addrs[0].family = AF_INET6;
((char*)&dns_server_addrs[0].addr.addr6)[15] = 0x1; ((char*)&dns_server_addrs[0].addr.addr6)[15] = 0x1;
@ -577,55 +566,58 @@ void RunResolvesRelevantRecordsTest(
grpc_core::ExecCtx exec_ctx; grpc_core::ExecCtx exec_ctx;
ArgsStruct args; ArgsStruct args;
ArgsInit(&args); ArgsInit(&args);
args.expected_addrs = ParseExpectedAddrs(FLAGS_expected_addrs); args.expected_addrs = ParseExpectedAddrs(absl::GetFlag(FLAGS_expected_addrs));
args.expected_service_config_string = FLAGS_expected_chosen_service_config; args.expected_service_config_string =
args.expected_service_config_error = FLAGS_expected_service_config_error; absl::GetFlag(FLAGS_expected_chosen_service_config);
args.expected_lb_policy = FLAGS_expected_lb_policy; args.expected_service_config_error =
absl::GetFlag(FLAGS_expected_service_config_error);
args.expected_lb_policy = absl::GetFlag(FLAGS_expected_lb_policy);
// maybe build the address with an authority // maybe build the address with an authority
std::string whole_uri; std::string whole_uri;
gpr_log(GPR_DEBUG, gpr_log(GPR_DEBUG,
"resolver_component_test: --inject_broken_nameserver_list: %s", "resolver_component_test: --inject_broken_nameserver_list: %s",
FLAGS_inject_broken_nameserver_list.c_str()); absl::GetFlag(FLAGS_inject_broken_nameserver_list).c_str());
std::unique_ptr<grpc::testing::FakeNonResponsiveDNSServer> std::unique_ptr<grpc::testing::FakeNonResponsiveDNSServer>
fake_non_responsive_dns_server; fake_non_responsive_dns_server;
if (FLAGS_inject_broken_nameserver_list == "True") { if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "True") {
g_fake_non_responsive_dns_server_port = grpc_pick_unused_port_or_die(); g_fake_non_responsive_dns_server_port = grpc_pick_unused_port_or_die();
fake_non_responsive_dns_server = fake_non_responsive_dns_server =
absl::make_unique<grpc::testing::FakeNonResponsiveDNSServer>( absl::make_unique<grpc::testing::FakeNonResponsiveDNSServer>(
g_fake_non_responsive_dns_server_port); g_fake_non_responsive_dns_server_port);
grpc_ares_test_only_inject_config = InjectBrokenNameServerList; grpc_ares_test_only_inject_config = InjectBrokenNameServerList;
whole_uri = absl::StrCat("dns:///", FLAGS_target_name); whole_uri = absl::StrCat("dns:///", absl::GetFlag(FLAGS_target_name));
} else if (FLAGS_inject_broken_nameserver_list == "False") { } else if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "False") {
gpr_log(GPR_INFO, "Specifying authority in uris to: %s", gpr_log(GPR_INFO, "Specifying authority in uris to: %s",
FLAGS_local_dns_server_address.c_str()); absl::GetFlag(FLAGS_local_dns_server_address).c_str());
whole_uri = absl::StrFormat("dns://%s/%s", FLAGS_local_dns_server_address, whole_uri = absl::StrFormat("dns://%s/%s",
FLAGS_target_name); absl::GetFlag(FLAGS_local_dns_server_address),
absl::GetFlag(FLAGS_target_name));
} else { } else {
gpr_log(GPR_DEBUG, "Invalid value for --inject_broken_nameserver_list."); gpr_log(GPR_DEBUG, "Invalid value for --inject_broken_nameserver_list.");
abort(); abort();
} }
gpr_log(GPR_DEBUG, "resolver_component_test: --enable_srv_queries: %s", gpr_log(GPR_DEBUG, "resolver_component_test: --enable_srv_queries: %s",
FLAGS_enable_srv_queries.c_str()); absl::GetFlag(FLAGS_enable_srv_queries).c_str());
grpc_channel_args* resolver_args = nullptr; grpc_channel_args* resolver_args = nullptr;
// By default, SRV queries are disabled, so tests that expect no SRV query // By default, SRV queries are disabled, so tests that expect no SRV query
// should avoid setting any channel arg. Test cases that do rely on the SRV // should avoid setting any channel arg. Test cases that do rely on the SRV
// query must explicitly enable SRV though. // query must explicitly enable SRV though.
if (FLAGS_enable_srv_queries == "True") { if (absl::GetFlag(FLAGS_enable_srv_queries) == "True") {
grpc_arg srv_queries_arg = grpc_channel_arg_integer_create( grpc_arg srv_queries_arg = grpc_channel_arg_integer_create(
const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true); const_cast<char*>(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true);
resolver_args = resolver_args =
grpc_channel_args_copy_and_add(nullptr, &srv_queries_arg, 1); grpc_channel_args_copy_and_add(nullptr, &srv_queries_arg, 1);
} else if (FLAGS_enable_srv_queries != "False") { } else if (absl::GetFlag(FLAGS_enable_srv_queries) != "False") {
gpr_log(GPR_DEBUG, "Invalid value for --enable_srv_queries."); gpr_log(GPR_DEBUG, "Invalid value for --enable_srv_queries.");
abort(); abort();
} }
gpr_log(GPR_DEBUG, "resolver_component_test: --enable_txt_queries: %s", gpr_log(GPR_DEBUG, "resolver_component_test: --enable_txt_queries: %s",
FLAGS_enable_txt_queries.c_str()); absl::GetFlag(FLAGS_enable_txt_queries).c_str());
// By default, TXT queries are disabled, so tests that expect no TXT query // By default, TXT queries are disabled, so tests that expect no TXT query
// should avoid setting any channel arg. Test cases that do rely on the TXT // should avoid setting any channel arg. Test cases that do rely on the TXT
// query must explicitly enable TXT though. // query must explicitly enable TXT though.
if (FLAGS_enable_txt_queries == "True") { if (absl::GetFlag(FLAGS_enable_txt_queries) == "True") {
// Unlike SRV queries, there isn't a channel arg specific to TXT records. // Unlike SRV queries, there isn't a channel arg specific to TXT records.
// Rather, we use the resolver-agnostic "service config" resolution option, // Rather, we use the resolver-agnostic "service config" resolution option,
// for which c-ares has its own specific default value, which isn't // for which c-ares has its own specific default value, which isn't
@ -636,7 +628,7 @@ void RunResolvesRelevantRecordsTest(
grpc_channel_args_copy_and_add(resolver_args, &txt_queries_arg, 1); grpc_channel_args_copy_and_add(resolver_args, &txt_queries_arg, 1);
grpc_channel_args_destroy(resolver_args); grpc_channel_args_destroy(resolver_args);
resolver_args = tmp_args; resolver_args = tmp_args;
} else if (FLAGS_enable_txt_queries != "False") { } else if (absl::GetFlag(FLAGS_enable_txt_queries) != "False") {
gpr_log(GPR_DEBUG, "Invalid value for --enable_txt_queries."); gpr_log(GPR_DEBUG, "Invalid value for --enable_txt_queries.");
abort(); abort();
} }
@ -679,7 +671,7 @@ int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv); grpc::testing::TestEnvironment env(argc, argv);
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
if (FLAGS_target_name.empty()) { if (absl::GetFlag(FLAGS_target_name).empty()) {
gpr_log(GPR_ERROR, "Missing target_name param."); gpr_log(GPR_ERROR, "Missing target_name param.");
abort(); abort();
} }

@ -24,11 +24,12 @@
#include <string.h> #include <string.h>
#include <unistd.h> #include <unistd.h>
#include <gflags/gflags.h>
#include <string> #include <string>
#include <thread> #include <thread>
#include <vector> #include <vector>
#include "absl/flags/flag.h"
#ifdef __FreeBSD__ #ifdef __FreeBSD__
#include <sys/wait.h> #include <sys/wait.h>
#endif #endif
@ -39,21 +40,21 @@
#include "test/cpp/util/subprocess.h" #include "test/cpp/util/subprocess.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_bool( ABSL_FLAG(
running_under_bazel, false, bool, running_under_bazel, false,
"True if this test is running under bazel. " "True if this test is running under bazel. "
"False indicates that this test is running under run_tests.py. " "False indicates that this test is running under run_tests.py. "
"Child process test binaries are located differently based on this flag. "); "Child process test binaries are located differently based on this flag. ");
DEFINE_string(test_bin_name, "", ABSL_FLAG(std::string, test_bin_name, "",
"Name, without the preceding path, of the test binary"); "Name, without the preceding path, of the test binary");
DEFINE_string(grpc_test_directory_relative_to_test_srcdir, ABSL_FLAG(std::string, grpc_test_directory_relative_to_test_srcdir,
"/com_github_grpc_grpc", "/com_github_grpc_grpc",
"This flag only applies if runner_under_bazel is true. This " "This flag only applies if runner_under_bazel is true. This "
"flag is ignored if runner_under_bazel is false. " "flag is ignored if runner_under_bazel is false. "
"Directory of the <repo-root>/test directory relative to bazel's " "Directory of the <repo-root>/test directory relative to bazel's "
"TEST_SRCDIR environment variable"); "TEST_SRCDIR environment variable");
using grpc::SubProcess; using grpc::SubProcess;
@ -163,22 +164,25 @@ int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv); grpc::testing::TestEnvironment env(argc, argv);
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
grpc_init(); grpc_init();
GPR_ASSERT(!FLAGS_test_bin_name.empty()); GPR_ASSERT(!absl::GetFlag(FLAGS_test_bin_name).empty());
std::string my_bin = argv[0]; std::string my_bin = argv[0];
if (FLAGS_running_under_bazel) { if (absl::GetFlag(FLAGS_running_under_bazel)) {
GPR_ASSERT(!FLAGS_grpc_test_directory_relative_to_test_srcdir.empty()); GPR_ASSERT(!absl::GetFlag(FLAGS_grpc_test_directory_relative_to_test_srcdir)
.empty());
// Use bazel's TEST_SRCDIR environment variable to locate the "test data" // Use bazel's TEST_SRCDIR environment variable to locate the "test data"
// binaries. // binaries.
char* test_srcdir = gpr_getenv("TEST_SRCDIR"); char* test_srcdir = gpr_getenv("TEST_SRCDIR");
std::string const bin_dir = std::string const bin_dir =
test_srcdir + FLAGS_grpc_test_directory_relative_to_test_srcdir + test_srcdir +
absl::GetFlag(FLAGS_grpc_test_directory_relative_to_test_srcdir) +
std::string("/test/cpp/naming"); std::string("/test/cpp/naming");
// Invoke bazel's executeable links to the .sh and .py scripts (don't use // Invoke bazel's executeable links to the .sh and .py scripts (don't use
// the .sh and .py suffixes) to make // the .sh and .py suffixes) to make
// sure that we're using bazel's test environment. // sure that we're using bazel's test environment.
grpc::testing::InvokeResolverComponentTestsRunner( grpc::testing::InvokeResolverComponentTestsRunner(
bin_dir + "/resolver_component_tests_runner", bin_dir + "/resolver_component_tests_runner",
bin_dir + "/" + FLAGS_test_bin_name, bin_dir + "/utils/dns_server", bin_dir + "/" + absl::GetFlag(FLAGS_test_bin_name),
bin_dir + "/utils/dns_server",
bin_dir + "/resolver_test_record_groups.yaml", bin_dir + "/resolver_test_record_groups.yaml",
bin_dir + "/utils/dns_resolver", bin_dir + "/utils/tcp_connect"); bin_dir + "/utils/dns_resolver", bin_dir + "/utils/tcp_connect");
gpr_free(test_srcdir); gpr_free(test_srcdir);
@ -189,7 +193,7 @@ int main(int argc, char** argv) {
// Invoke the .sh and .py scripts directly where they are in source code. // Invoke the .sh and .py scripts directly where they are in source code.
grpc::testing::InvokeResolverComponentTestsRunner( grpc::testing::InvokeResolverComponentTestsRunner(
"test/cpp/naming/resolver_component_tests_runner.py", "test/cpp/naming/resolver_component_tests_runner.py",
bin_dir + "/" + FLAGS_test_bin_name, bin_dir + "/" + absl::GetFlag(FLAGS_test_bin_name),
"test/cpp/naming/utils/dns_server.py", "test/cpp/naming/utils/dns_server.py",
"test/cpp/naming/resolver_test_record_groups.yaml", "test/cpp/naming/resolver_test_record_groups.yaml",
"test/cpp/naming/utils/dns_resolver.py", "test/cpp/naming/utils/dns_resolver.py",

@ -46,9 +46,6 @@ grpc_cc_library(
"qps_worker.h", "qps_worker.h",
"server.h", "server.h",
], ],
external_deps = [
"gflags",
],
deps = [ deps = [
":histogram", ":histogram",
":interarrival", ":interarrival",
@ -100,7 +97,7 @@ grpc_cc_library(
"benchmark_config.h", "benchmark_config.h",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
deps = [ deps = [
":driver_impl", ":driver_impl",
@ -126,7 +123,7 @@ grpc_cc_binary(
name = "qps_json_driver", name = "qps_json_driver",
srcs = ["qps_json_driver.cc"], srcs = ["qps_json_driver.cc"],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
deps = [ deps = [
":benchmark_config", ":benchmark_config",
@ -206,6 +203,9 @@ grpc_cc_library(
grpc_cc_binary( grpc_cc_binary(
name = "qps_worker", name = "qps_worker",
srcs = ["worker.cc"], srcs = ["worker.cc"],
external_deps = [
"absl/flags:flag",
],
deps = [ deps = [
":qps_worker_impl", ":qps_worker_impl",
"//:grpc++", "//:grpc++",

@ -17,68 +17,64 @@
*/ */
#include "test/cpp/qps/benchmark_config.h" #include "test/cpp/qps/benchmark_config.h"
#include <gflags/gflags.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/create_channel.h> #include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h> #include <grpcpp/security/credentials.h>
#include "absl/flags/flag.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DEFINE_bool(enable_log_reporter, true, ABSL_FLAG(bool, enable_log_reporter, true,
"Enable reporting of benchmark results through GprLog"); "Enable reporting of benchmark results through GprLog");
DEFINE_string(scenario_result_file, "", ABSL_FLAG(std::string, scenario_result_file, "",
"Write JSON benchmark report to the file specified."); "Write JSON benchmark report to the file specified.");
DEFINE_string(hashed_id, "", "Hash of the user id"); ABSL_FLAG(std::string, hashed_id, "", "Hash of the user id");
DEFINE_string(test_name, "", "Name of the test being executed"); ABSL_FLAG(std::string, test_name, "", "Name of the test being executed");
DEFINE_string(sys_info, "", "System information"); ABSL_FLAG(std::string, sys_info, "", "System information");
DEFINE_string(server_address, "localhost:50052", ABSL_FLAG(std::string, server_address, "localhost:50052",
"Address of the performance database server"); "Address of the performance database server");
DEFINE_string(tag, "", "Optional tag for the test"); ABSL_FLAG(std::string, tag, "", "Optional tag for the test");
DEFINE_string(rpc_reporter_server_address, "", ABSL_FLAG(std::string, rpc_reporter_server_address, "",
"Server address for rpc reporter to send results to"); "Server address for rpc reporter to send results to");
DEFINE_bool(enable_rpc_reporter, false, "Enable use of RPC reporter"); ABSL_FLAG(bool, enable_rpc_reporter, false, "Enable use of RPC reporter");
DEFINE_string( ABSL_FLAG(
rpc_reporter_credential_type, grpc::testing::kInsecureCredentialsType, std::string, rpc_reporter_credential_type,
grpc::testing::kInsecureCredentialsType,
"Credential type for communication to the QPS benchmark report server"); "Credential type for communication to the QPS benchmark report server");
// 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;
namespace grpc { namespace grpc {
namespace testing { namespace testing {
static std::shared_ptr<Reporter> InitBenchmarkReporters() { static std::shared_ptr<Reporter> InitBenchmarkReporters() {
auto* composite_reporter = new CompositeReporter; auto* composite_reporter = new CompositeReporter;
if (FLAGS_enable_log_reporter) { if (absl::GetFlag(FLAGS_enable_log_reporter)) {
composite_reporter->add( composite_reporter->add(
std::unique_ptr<Reporter>(new GprLogReporter("LogReporter"))); std::unique_ptr<Reporter>(new GprLogReporter("LogReporter")));
} }
if (!FLAGS_scenario_result_file.empty()) { if (!absl::GetFlag(FLAGS_scenario_result_file).empty()) {
composite_reporter->add(std::unique_ptr<Reporter>( composite_reporter->add(std::unique_ptr<Reporter>(new JsonReporter(
new JsonReporter("JsonReporter", FLAGS_scenario_result_file))); "JsonReporter", absl::GetFlag(FLAGS_scenario_result_file))));
} }
if (FLAGS_enable_rpc_reporter) { if (absl::GetFlag(FLAGS_enable_rpc_reporter)) {
ChannelArguments channel_args; ChannelArguments channel_args;
std::shared_ptr<ChannelCredentials> channel_creds = std::shared_ptr<ChannelCredentials> channel_creds =
testing::GetCredentialsProvider()->GetChannelCredentials( testing::GetCredentialsProvider()->GetChannelCredentials(
FLAGS_rpc_reporter_credential_type, &channel_args); absl::GetFlag(FLAGS_rpc_reporter_credential_type), &channel_args);
GPR_ASSERT(!FLAGS_rpc_reporter_server_address.empty()); GPR_ASSERT(!absl::GetFlag(FLAGS_rpc_reporter_server_address).empty());
composite_reporter->add(std::unique_ptr<Reporter>(new RpcReporter( composite_reporter->add(std::unique_ptr<Reporter>(new RpcReporter(
"RpcReporter", grpc::CreateChannel(FLAGS_rpc_reporter_server_address, "RpcReporter",
channel_creds)))); grpc::CreateChannel(absl::GetFlag(FLAGS_rpc_reporter_server_address),
channel_creds))));
} }
return std::shared_ptr<Reporter>(composite_reporter); return std::shared_ptr<Reporter>(composite_reporter);

@ -39,9 +39,6 @@ def qps_json_driver_batch():
"--scenarios_json", "--scenarios_json",
QPS_JSON_DRIVER_SCENARIOS[scenario], QPS_JSON_DRIVER_SCENARIOS[scenario],
], ],
external_deps = [
"gflags",
],
deps = [ deps = [
":benchmark_config", ":benchmark_config",
":driver_impl", ":driver_impl",

@ -16,16 +16,15 @@
* *
*/ */
#include <grpc/support/log.h>
#include <grpcpp/impl/codegen/config_protobuf.h>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <memory> #include <memory>
#include <set> #include <set>
#include <grpcpp/impl/codegen/config_protobuf.h> #include "absl/flags/flag.h"
#include <gflags/gflags.h>
#include <grpc/support/log.h>
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/qps/benchmark_config.h" #include "test/cpp/qps/benchmark_config.h"
#include "test/cpp/qps/driver.h" #include "test/cpp/qps/driver.h"
@ -35,39 +34,39 @@
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DEFINE_string(scenarios_file, "", ABSL_FLAG(std::string, scenarios_file, "",
"JSON file containing an array of Scenario objects"); "JSON file containing an array of Scenario objects");
DEFINE_string(scenarios_json, "", ABSL_FLAG(std::string, scenarios_json, "",
"JSON string containing an array of Scenario objects"); "JSON string containing an array of Scenario objects");
DEFINE_bool(quit, false, "Quit the workers"); ABSL_FLAG(bool, quit, false, "Quit the workers");
DEFINE_string(search_param, "", ABSL_FLAG(std::string, search_param, "",
"The parameter, whose value is to be searched for to achieve " "The parameter, whose value is to be searched for to achieve "
"targeted cpu load. For now, we have 'offered_load'. Later, " "targeted cpu load. For now, we have 'offered_load'. Later, "
"'num_channels', 'num_outstanding_requests', etc. shall be " "'num_channels', 'num_outstanding_requests', etc. shall be "
"added."); "added.");
DEFINE_double( ABSL_FLAG(
initial_search_value, 0.0, double, initial_search_value, 0.0,
"initial parameter value to start the search with (i.e. lower bound)"); "initial parameter value to start the search with (i.e. lower bound)");
DEFINE_double(targeted_cpu_load, 70.0, ABSL_FLAG(double, targeted_cpu_load, 70.0,
"Targeted cpu load (unit: %, range [0,100])"); "Targeted cpu load (unit: %, range [0,100])");
DEFINE_double(stride, 1, ABSL_FLAG(double, stride, 1,
"Defines each stride of the search. The larger the stride is, " "Defines each stride of the search. The larger the stride is, "
"the coarser the result will be, but will also be faster."); "the coarser the result will be, but will also be faster.");
DEFINE_double(error_tolerance, 0.01, ABSL_FLAG(double, error_tolerance, 0.01,
"Defines threshold for stopping the search. When current search " "Defines threshold for stopping the search. When current search "
"range is narrower than the error_tolerance computed range, we " "range is narrower than the error_tolerance computed range, we "
"stop the search."); "stop the search.");
DEFINE_string(qps_server_target_override, "", ABSL_FLAG(std::string, qps_server_target_override, "",
"Override QPS server target to configure in client configs." "Override QPS server target to configure in client configs."
"Only applicable if there is a single benchmark server."); "Only applicable if there is a single benchmark server.");
DEFINE_string(json_file_out, "", "File to write the JSON output to."); ABSL_FLAG(std::string, json_file_out, "", "File to write the JSON output to.");
DEFINE_string(credential_type, grpc::testing::kInsecureCredentialsType, ABSL_FLAG(std::string, credential_type, grpc::testing::kInsecureCredentialsType,
"Credential type for communication with workers"); "Credential type for communication with workers");
DEFINE_string( ABSL_FLAG(
per_worker_credential_types, "", std::string, per_worker_credential_types, "",
"A map of QPS worker addresses to credential types. When creating a " "A map of QPS worker addresses to credential types. When creating a "
"channel to a QPS worker's driver port, the qps_json_driver first checks " "channel to a QPS worker's driver port, the qps_json_driver first checks "
"if the 'name:port' string is in the map, and it uses the corresponding " "if the 'name:port' string is in the map, and it uses the corresponding "
@ -76,9 +75,9 @@ DEFINE_string(
"the credentials specified in --credential_type. The value of this flag " "the credentials specified in --credential_type. The value of this flag "
"is a semicolon-separated list of map entries, where each map entry is " "is a semicolon-separated list of map entries, where each map entry is "
"a comma-separated pair."); "a comma-separated pair.");
DEFINE_bool(run_inproc, false, "Perform an in-process transport test"); ABSL_FLAG(bool, run_inproc, false, "Perform an in-process transport test");
DEFINE_int32( ABSL_FLAG(
median_latency_collection_interval_millis, 0, int32_t, median_latency_collection_interval_millis, 0,
"Specifies the period between gathering latency medians in " "Specifies the period between gathering latency medians in "
"milliseconds. The medians will be logged out on the client at the " "milliseconds. The medians will be logged out on the client at the "
"end of the benchmark run. If 0, this periodic collection is disabled."); "end of the benchmark run. If 0, this periodic collection is disabled.");
@ -90,7 +89,7 @@ static std::map<std::string, std::string>
ConstructPerWorkerCredentialTypesMap() { ConstructPerWorkerCredentialTypesMap() {
// Parse a list of the form: "addr1,cred_type1;addr2,cred_type2;..." into // Parse a list of the form: "addr1,cred_type1;addr2,cred_type2;..." into
// a map. // a map.
std::string remaining = FLAGS_per_worker_credential_types; std::string remaining = absl::GetFlag(FLAGS_per_worker_credential_types);
std::map<std::string, std::string> out; std::map<std::string, std::string> out;
while (!remaining.empty()) { while (!remaining.empty()) {
size_t next_semicolon = remaining.find(';'); size_t next_semicolon = remaining.find(';');
@ -125,14 +124,16 @@ static std::unique_ptr<ScenarioResult> RunAndReport(
const std::map<std::string, std::string>& per_worker_credential_types, const std::map<std::string, std::string>& per_worker_credential_types,
bool* success) { bool* success) {
std::cerr << "RUNNING SCENARIO: " << scenario.name() << "\n"; std::cerr << "RUNNING SCENARIO: " << scenario.name() << "\n";
auto result = auto result = RunScenario(
RunScenario(scenario.client_config(), scenario.num_clients(), scenario.client_config(), scenario.num_clients(),
scenario.server_config(), scenario.num_servers(), scenario.server_config(), scenario.num_servers(),
scenario.warmup_seconds(), scenario.benchmark_seconds(), scenario.warmup_seconds(), scenario.benchmark_seconds(),
!FLAGS_run_inproc ? scenario.spawn_local_worker_count() : -2, !absl::GetFlag(FLAGS_run_inproc) ? scenario.spawn_local_worker_count()
FLAGS_qps_server_target_override, FLAGS_credential_type, : -2,
per_worker_credential_types, FLAGS_run_inproc, absl::GetFlag(FLAGS_qps_server_target_override),
FLAGS_median_latency_collection_interval_millis); absl::GetFlag(FLAGS_credential_type), per_worker_credential_types,
absl::GetFlag(FLAGS_run_inproc),
absl::GetFlag(FLAGS_median_latency_collection_interval_millis));
// Amend the result with scenario config. Eventually we should adjust // Amend the result with scenario config. Eventually we should adjust
// RunScenario contract so we don't need to touch the result here. // RunScenario contract so we don't need to touch the result here.
@ -153,9 +154,9 @@ static std::unique_ptr<ScenarioResult> RunAndReport(
*success = result->server_success(i); *success = result->server_success(i);
} }
if (!FLAGS_json_file_out.empty()) { if (!absl::GetFlag(FLAGS_json_file_out).empty()) {
std::ofstream json_outfile; std::ofstream json_outfile;
json_outfile.open(FLAGS_json_file_out); json_outfile.open(absl::GetFlag(FLAGS_json_file_out));
json_outfile << "{\"qps\": " << result->summary().qps() << "}\n"; json_outfile << "{\"qps\": " << result->summary().qps() << "}\n";
json_outfile.close(); json_outfile.close();
} }
@ -179,7 +180,7 @@ static double BinarySearch(
Scenario* scenario, double targeted_cpu_load, double low, double high, Scenario* scenario, double targeted_cpu_load, double low, double high,
const std::map<std::string, std::string>& per_worker_credential_types, const std::map<std::string, std::string>& per_worker_credential_types,
bool* success) { bool* success) {
while (low <= high * (1 - FLAGS_error_tolerance)) { while (low <= high * (1 - absl::GetFlag(FLAGS_error_tolerance))) {
double mid = low + (high - low) / 2; double mid = low + (high - low) / 2;
double current_cpu_load = double current_cpu_load =
GetCpuLoad(scenario, mid, per_worker_credential_types, success); GetCpuLoad(scenario, mid, per_worker_credential_types, success);
@ -189,9 +190,9 @@ static double BinarySearch(
break; break;
} }
if (targeted_cpu_load <= current_cpu_load) { if (targeted_cpu_load <= current_cpu_load) {
high = mid - FLAGS_stride; high = mid - absl::GetFlag(FLAGS_stride);
} else { } else {
low = mid + FLAGS_stride; low = mid + absl::GetFlag(FLAGS_stride);
} }
} }
@ -229,10 +230,11 @@ static double SearchOfferedLoad(
static bool QpsDriver() { static bool QpsDriver() {
std::string json; std::string json;
bool scfile = (!FLAGS_scenarios_file.empty()); bool scfile = (!absl::GetFlag(FLAGS_scenarios_file).empty());
bool scjson = (!FLAGS_scenarios_json.empty()); bool scjson = (!absl::GetFlag(FLAGS_scenarios_json).empty());
if ((!scfile && !scjson && !FLAGS_quit) || if ((!scfile && !scjson && !absl::GetFlag(FLAGS_quit)) ||
(scfile && (scjson || FLAGS_quit)) || (scjson && FLAGS_quit)) { (scfile && (scjson || absl::GetFlag(FLAGS_quit))) ||
(scjson && absl::GetFlag(FLAGS_quit))) {
gpr_log(GPR_ERROR, gpr_log(GPR_ERROR,
"Exactly one of --scenarios_file, --scenarios_json, " "Exactly one of --scenarios_file, --scenarios_json, "
"or --quit must be set"); "or --quit must be set");
@ -242,7 +244,7 @@ static bool QpsDriver() {
auto per_worker_credential_types = ConstructPerWorkerCredentialTypesMap(); auto per_worker_credential_types = ConstructPerWorkerCredentialTypesMap();
if (scfile) { if (scfile) {
// Read the json data from disk // Read the json data from disk
FILE* json_file = fopen(FLAGS_scenarios_file.c_str(), "r"); FILE* json_file = fopen(absl::GetFlag(FLAGS_scenarios_file).c_str(), "r");
GPR_ASSERT(json_file != nullptr); GPR_ASSERT(json_file != nullptr);
fseek(json_file, 0, SEEK_END); fseek(json_file, 0, SEEK_END);
long len = ftell(json_file); long len = ftell(json_file);
@ -253,9 +255,10 @@ static bool QpsDriver() {
json = std::string(data, data + len); json = std::string(data, data + len);
delete[] data; delete[] data;
} else if (scjson) { } else if (scjson) {
json = FLAGS_scenarios_json.c_str(); json = absl::GetFlag(FLAGS_scenarios_json).c_str();
} else if (FLAGS_quit) { } else if (absl::GetFlag(FLAGS_quit)) {
return RunQuit(FLAGS_credential_type, per_worker_credential_types); return RunQuit(absl::GetFlag(FLAGS_credential_type),
per_worker_credential_types);
} }
// Parse into an array of scenarios // Parse into an array of scenarios
@ -267,15 +270,16 @@ static bool QpsDriver() {
GPR_ASSERT(scenarios.scenarios_size() > 0); GPR_ASSERT(scenarios.scenarios_size() > 0);
for (int i = 0; i < scenarios.scenarios_size(); i++) { for (int i = 0; i < scenarios.scenarios_size(); i++) {
if (FLAGS_search_param.empty()) { if (absl::GetFlag(FLAGS_search_param).empty()) {
const Scenario& scenario = scenarios.scenarios(i); const Scenario& scenario = scenarios.scenarios(i);
RunAndReport(scenario, per_worker_credential_types, &success); RunAndReport(scenario, per_worker_credential_types, &success);
} else { } else {
if (FLAGS_search_param == "offered_load") { if (absl::GetFlag(FLAGS_search_param) == "offered_load") {
Scenario* scenario = scenarios.mutable_scenarios(i); Scenario* scenario = scenarios.mutable_scenarios(i);
double targeted_offered_load = SearchOfferedLoad( double targeted_offered_load =
FLAGS_initial_search_value, FLAGS_targeted_cpu_load, scenario, SearchOfferedLoad(absl::GetFlag(FLAGS_initial_search_value),
per_worker_credential_types, &success); absl::GetFlag(FLAGS_targeted_cpu_load), scenario,
per_worker_credential_types, &success);
gpr_log(GPR_INFO, "targeted_offered_load %f", targeted_offered_load); gpr_log(GPR_INFO, "targeted_offered_load %f", targeted_offered_load);
GetCpuLoad(scenario, targeted_offered_load, per_worker_credential_types, GetCpuLoad(scenario, targeted_offered_load, per_worker_credential_types,
&success); &success);

@ -16,25 +16,24 @@
* *
*/ */
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#include <signal.h> #include <signal.h>
#include <chrono> #include <chrono>
#include <thread> #include <thread>
#include <vector> #include <vector>
#include <gflags/gflags.h> #include "absl/flags/flag.h"
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#include "test/core/util/test_config.h" #include "test/core/util/test_config.h"
#include "test/cpp/qps/qps_worker.h" #include "test/cpp/qps/qps_worker.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DEFINE_int32(driver_port, 0, "Port for communication with driver"); ABSL_FLAG(int32_t, driver_port, 0, "Port for communication with driver");
DEFINE_int32(server_port, 0, "Port for operation as a server"); ABSL_FLAG(int32_t, server_port, 0, "Port for operation as a server");
DEFINE_string(credential_type, grpc::testing::kInsecureCredentialsType, ABSL_FLAG(std::string, credential_type, grpc::testing::kInsecureCredentialsType,
"Credential type for communication with driver"); "Credential type for communication with driver");
static bool got_sigint = false; static bool got_sigint = false;
@ -46,7 +45,9 @@ namespace testing {
std::vector<grpc::testing::Server*>* g_inproc_servers = nullptr; std::vector<grpc::testing::Server*>* g_inproc_servers = nullptr;
static void RunServer() { static void RunServer() {
QpsWorker worker(FLAGS_driver_port, FLAGS_server_port, FLAGS_credential_type); QpsWorker worker(absl::GetFlag(FLAGS_driver_port),
absl::GetFlag(FLAGS_server_port),
absl::GetFlag(FLAGS_credential_type));
while (!got_sigint && !worker.Done()) { while (!got_sigint && !worker.Done()) {
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),

@ -25,7 +25,6 @@ grpc_cc_test(
name = "thread_manager_test", name = "thread_manager_test",
srcs = ["thread_manager_test.cc"], srcs = ["thread_manager_test.cc"],
external_deps = [ external_deps = [
"gflags",
"gtest", "gtest",
], ],
deps = [ deps = [

@ -22,7 +22,6 @@
#include <memory> #include <memory>
#include <thread> #include <thread>
#include <gflags/gflags.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <grpcpp/grpcpp.h> #include <grpcpp/grpcpp.h>

@ -30,7 +30,7 @@ grpc_cc_library(
"test_config.h", "test_config.h",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:parse",
], ],
deps = [ deps = [
"//:gpr", "//:gpr",
@ -75,7 +75,7 @@ grpc_cc_library(
"test_credentials_provider.h", "test_credentials_provider.h",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
"protobuf", "protobuf",
], ],
deps = [ deps = [
@ -133,7 +133,7 @@ grpc_cc_library(
"service_describer.h", "service_describer.h",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
"protobuf", "protobuf",
"protobuf_clib", "protobuf_clib",
], ],
@ -153,7 +153,7 @@ grpc_cc_library(
"grpc_tool.h", "grpc_tool.h",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
deps = [ deps = [
":grpc_cli_utils", ":grpc_cli_utils",
@ -188,6 +188,7 @@ grpc_cc_test(
"//src/proto/grpc/testing:simple_messages.proto", "//src/proto/grpc/testing:simple_messages.proto",
], ],
external_deps = [ external_deps = [
"absl/flags:flag",
"gtest", "gtest",
], ],
tags = [ tags = [
@ -300,7 +301,7 @@ grpc_cc_binary(
"grpc_cli.cc", "grpc_cli.cc",
], ],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
deps = [ deps = [
":grpc++_proto_reflection_desc_db", ":grpc++_proto_reflection_desc_db",
@ -315,7 +316,7 @@ grpc_cc_binary(
name = "channelz_sampler", name = "channelz_sampler",
srcs = ["channelz_sampler.cc"], srcs = ["channelz_sampler.cc"],
external_deps = [ external_deps = [
"gflags", "absl/flags:flag",
], ],
language = "c++", language = "c++",
tags = [ tags = [
@ -340,7 +341,6 @@ grpc_cc_test(
":channelz_sampler", ":channelz_sampler",
], ],
external_deps = [ external_deps = [
"gflags",
"gtest", "gtest",
], ],
tags = [ tags = [

@ -25,9 +25,9 @@
#include <queue> #include <queue>
#include <string> #include <string>
#include "absl/flags/flag.h"
#include "absl/strings/str_format.h" #include "absl/strings/str_format.h"
#include "absl/strings/str_join.h" #include "absl/strings/str_join.h"
#include "gflags/gflags.h"
#include "google/protobuf/text_format.h" #include "google/protobuf/text_format.h"
#include "grpc/grpc.h" #include "grpc/grpc.h"
#include "grpc/support/port_platform.h" #include "grpc/support/port_platform.h"
@ -48,11 +48,13 @@
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DEFINE_string(server_address, "", "channelz server address"); ABSL_FLAG(std::string, server_address, "", "channelz server address");
DEFINE_string(custom_credentials_type, "", "custom credentials type"); ABSL_FLAG(std::string, custom_credentials_type, "", "custom credentials type");
DEFINE_int64(sampling_times, 1, "number of sampling"); ABSL_FLAG(int64_t, sampling_times, 1, "number of sampling");
DEFINE_int64(sampling_interval_seconds, 0, "sampling interval in seconds"); // TODO(Capstan): Consider using absl::Duration
DEFINE_string(output_json, "", "output filename in json format"); ABSL_FLAG(int64_t, sampling_interval_seconds, 0,
"sampling interval in seconds");
ABSL_FLAG(std::string, output_json, "", "output filename in json format");
namespace { namespace {
using grpc::ClientContext; using grpc::ClientContext;
@ -507,7 +509,8 @@ class ChannelzSampler final {
std::string start, finish; std::string start, finish;
gpr_timespec ago = gpr_time_sub( gpr_timespec ago = gpr_time_sub(
now_, now_,
gpr_time_from_seconds(FLAGS_sampling_interval_seconds, GPR_TIMESPAN)); gpr_time_from_seconds(absl::GetFlag(FLAGS_sampling_interval_seconds),
GPR_TIMESPAN));
std::stringstream ss; std::stringstream ss;
const time_t time_now = now_.tv_sec; const time_t time_now = now_.tv_sec;
ss << std::put_time(std::localtime(&time_now), "%F %T"); ss << std::put_time(std::localtime(&time_now), "%F %T");
@ -558,15 +561,18 @@ class ChannelzSampler final {
int main(int argc, char** argv) { int main(int argc, char** argv) {
grpc::testing::TestEnvironment env(argc, argv); grpc::testing::TestEnvironment env(argc, argv);
grpc::testing::InitTest(&argc, &argv, true); grpc::testing::InitTest(&argc, &argv, true);
std::ofstream output_file(FLAGS_output_json); std::ofstream output_file(absl::GetFlag(FLAGS_output_json));
for (int i = 0; i < FLAGS_sampling_times; ++i) { for (int i = 0; i < absl::GetFlag(FLAGS_sampling_times); ++i) {
ChannelzSampler channelz_sampler; ChannelzSampler channelz_sampler;
channelz_sampler.Setup(FLAGS_custom_credentials_type, FLAGS_server_address); channelz_sampler.Setup(absl::GetFlag(FLAGS_custom_credentials_type),
absl::GetFlag(FLAGS_server_address));
std::cout << "Wait for sampling interval " std::cout << "Wait for sampling interval "
<< FLAGS_sampling_interval_seconds << "s..." << std::endl; << absl::GetFlag(FLAGS_sampling_interval_seconds) << "s..."
<< std::endl;
const gpr_timespec kDelay = gpr_time_add( const gpr_timespec kDelay = gpr_time_add(
gpr_now(GPR_CLOCK_MONOTONIC), gpr_now(GPR_CLOCK_MONOTONIC),
gpr_time_from_seconds(FLAGS_sampling_interval_seconds, GPR_TIMESPAN)); gpr_time_from_seconds(absl::GetFlag(FLAGS_sampling_interval_seconds),
GPR_TIMESPAN));
gpr_sleep_until(kDelay); gpr_sleep_until(kDelay);
std::cout << "##### " << i << "th sampling #####" << std::endl; std::cout << "##### " << i << "th sampling #####" << std::endl;
channelz_sampler.RecordNow(); channelz_sampler.RecordNow();
@ -575,7 +581,7 @@ int main(int argc, char** argv) {
channelz_sampler.GetTopChannelsRPC(); channelz_sampler.GetTopChannelsRPC();
channelz_sampler.TraverseTopChannels(); channelz_sampler.TraverseTopChannels();
channelz_sampler.DumpStdout(); channelz_sampler.DumpStdout();
if (!FLAGS_output_json.empty()) { if (!absl::GetFlag(FLAGS_output_json).empty()) {
output_file << channelz_sampler.DumpJson() << "\n" << std::flush; output_file << channelz_sampler.DumpJson() << "\n" << std::flush;
} }
} }

@ -18,45 +18,43 @@
#include "test/cpp/util/cli_credentials.h" #include "test/cpp/util/cli_credentials.h"
#include <gflags/gflags.h>
#include <grpc/slice.h> #include <grpc/slice.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/impl/codegen/slice.h> #include <grpcpp/impl/codegen/slice.h>
#include "absl/flags/flag.h"
#include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/iomgr/load_file.h"
DEFINE_bool( ABSL_FLAG(bool, enable_ssl, false,
enable_ssl, false, "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl.");
"Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); ABSL_FLAG(bool, use_auth, false,
DEFINE_bool(use_auth, false, "Whether to create default google credentials. Deprecated. Use "
"Whether to create default google credentials. Deprecated. Use " "--channel_creds_type=gdc.");
"--channel_creds_type=gdc."); ABSL_FLAG(
DEFINE_string( std::string, access_token, "",
access_token, "",
"The access token that will be sent to the server to authenticate RPCs. " "The access token that will be sent to the server to authenticate RPCs. "
"Deprecated. Use --call_creds=access_token=<token>."); "Deprecated. Use --call_creds=access_token=<token>.");
DEFINE_string( ABSL_FLAG(
ssl_target, "", std::string, ssl_target, "",
"If not empty, treat the server host name as this for ssl/tls certificate " "If not empty, treat the server host name as this for ssl/tls certificate "
"validation."); "validation.");
DEFINE_string( ABSL_FLAG(
ssl_client_cert, "", std::string, ssl_client_cert, "",
"If not empty, load this PEM formatted client certificate file. Requires " "If not empty, load this PEM formatted client certificate file. Requires "
"use of --ssl_client_key."); "use of --ssl_client_key.");
DEFINE_string( ABSL_FLAG(std::string, ssl_client_key, "",
ssl_client_key, "", "If not empty, load this PEM formatted private key. Requires use of "
"If not empty, load this PEM formatted private key. Requires use of " "--ssl_client_cert");
"--ssl_client_cert"); ABSL_FLAG(
DEFINE_string( std::string, local_connect_type, "local_tcp",
local_connect_type, "local_tcp",
"The type of local connections for which local channel credentials will " "The type of local connections for which local channel credentials will "
"be applied. Should be local_tcp or uds."); "be applied. Should be local_tcp or uds.");
DEFINE_string( ABSL_FLAG(
channel_creds_type, "", std::string, channel_creds_type, "",
"The channel creds type: insecure, ssl, gdc (Google Default Credentials), " "The channel creds type: insecure, ssl, gdc (Google Default Credentials), "
"alts, or local."); "alts, or local.");
DEFINE_string( ABSL_FLAG(
call_creds, "", std::string, call_creds, "",
"Call credentials to use: none (default), or access_token=<token>. If " "Call credentials to use: none (default), or access_token=<token>. If "
"provided, the call creds are composited on top of channel creds."); "provided, the call creds are composited on top of channel creds.");
@ -85,14 +83,15 @@ std::string AccessToken(const std::string& auth) {
std::string CliCredentials::GetDefaultChannelCredsType() const { std::string CliCredentials::GetDefaultChannelCredsType() const {
// Compatibility logic for --enable_ssl. // Compatibility logic for --enable_ssl.
if (FLAGS_enable_ssl) { if (absl::GetFlag(FLAGS_enable_ssl)) {
fprintf(stderr, fprintf(stderr,
"warning: --enable_ssl is deprecated. Use " "warning: --enable_ssl is deprecated. Use "
"--channel_creds_type=ssl.\n"); "--channel_creds_type=ssl.\n");
return "ssl"; return "ssl";
} }
// Compatibility logic for --use_auth. // Compatibility logic for --use_auth.
if (FLAGS_access_token.empty() && FLAGS_use_auth) { if (absl::GetFlag(FLAGS_access_token).empty() &&
absl::GetFlag(FLAGS_use_auth)) {
fprintf(stderr, fprintf(stderr,
"warning: --use_auth is deprecated. Use " "warning: --use_auth is deprecated. Use "
"--channel_creds_type=gdc.\n"); "--channel_creds_type=gdc.\n");
@ -102,110 +101,116 @@ std::string CliCredentials::GetDefaultChannelCredsType() const {
} }
std::string CliCredentials::GetDefaultCallCreds() const { std::string CliCredentials::GetDefaultCallCreds() const {
if (!FLAGS_access_token.empty()) { if (!absl::GetFlag(FLAGS_access_token).empty()) {
fprintf(stderr, fprintf(stderr,
"warning: --access_token is deprecated. Use " "warning: --access_token is deprecated. Use "
"--call_creds=access_token=<token>.\n"); "--call_creds=access_token=<token>.\n");
return std::string("access_token=") + FLAGS_access_token; return std::string("access_token=") + absl::GetFlag(FLAGS_access_token);
} }
return "none"; return "none";
} }
std::shared_ptr<grpc::ChannelCredentials> std::shared_ptr<grpc::ChannelCredentials>
CliCredentials::GetChannelCredentials() const { CliCredentials::GetChannelCredentials() const {
if (FLAGS_channel_creds_type == "insecure") { if (absl::GetFlag(FLAGS_channel_creds_type) == "insecure") {
return grpc::InsecureChannelCredentials(); return grpc::InsecureChannelCredentials();
} else if (FLAGS_channel_creds_type == "ssl") { } else if (absl::GetFlag(FLAGS_channel_creds_type) == "ssl") {
grpc::SslCredentialsOptions ssl_creds_options; grpc::SslCredentialsOptions ssl_creds_options;
// TODO(@Capstan): This won't affect Google Default Credentials using SSL. // TODO(@Capstan): This won't affect Google Default Credentials using SSL.
if (!FLAGS_ssl_client_cert.empty()) { if (!absl::GetFlag(FLAGS_ssl_client_cert).empty()) {
grpc_slice cert_slice = grpc_empty_slice(); grpc_slice cert_slice = grpc_empty_slice();
GRPC_LOG_IF_ERROR( GRPC_LOG_IF_ERROR(
"load_file", "load_file",
grpc_load_file(FLAGS_ssl_client_cert.c_str(), 1, &cert_slice)); grpc_load_file(absl::GetFlag(FLAGS_ssl_client_cert).c_str(), 1,
&cert_slice));
ssl_creds_options.pem_cert_chain = ssl_creds_options.pem_cert_chain =
grpc::StringFromCopiedSlice(cert_slice); grpc::StringFromCopiedSlice(cert_slice);
grpc_slice_unref(cert_slice); grpc_slice_unref(cert_slice);
} }
if (!FLAGS_ssl_client_key.empty()) { if (!absl::GetFlag(FLAGS_ssl_client_key).empty()) {
grpc_slice key_slice = grpc_empty_slice(); grpc_slice key_slice = grpc_empty_slice();
GRPC_LOG_IF_ERROR( GRPC_LOG_IF_ERROR(
"load_file", "load_file",
grpc_load_file(FLAGS_ssl_client_key.c_str(), 1, &key_slice)); grpc_load_file(absl::GetFlag(FLAGS_ssl_client_key).c_str(), 1,
&key_slice));
ssl_creds_options.pem_private_key = ssl_creds_options.pem_private_key =
grpc::StringFromCopiedSlice(key_slice); grpc::StringFromCopiedSlice(key_slice);
grpc_slice_unref(key_slice); grpc_slice_unref(key_slice);
} }
return grpc::SslCredentials(ssl_creds_options); return grpc::SslCredentials(ssl_creds_options);
} else if (FLAGS_channel_creds_type == "gdc") { } else if (absl::GetFlag(FLAGS_channel_creds_type) == "gdc") {
return grpc::GoogleDefaultCredentials(); return grpc::GoogleDefaultCredentials();
} else if (FLAGS_channel_creds_type == "alts") { } else if (absl::GetFlag(FLAGS_channel_creds_type) == "alts") {
return grpc::experimental::AltsCredentials( return grpc::experimental::AltsCredentials(
grpc::experimental::AltsCredentialsOptions()); grpc::experimental::AltsCredentialsOptions());
} else if (FLAGS_channel_creds_type == "local") { } else if (absl::GetFlag(FLAGS_channel_creds_type) == "local") {
if (FLAGS_local_connect_type == "local_tcp") { if (absl::GetFlag(FLAGS_local_connect_type) == "local_tcp") {
return grpc::experimental::LocalCredentials(LOCAL_TCP); return grpc::experimental::LocalCredentials(LOCAL_TCP);
} else if (FLAGS_local_connect_type == "uds") { } else if (absl::GetFlag(FLAGS_local_connect_type) == "uds") {
return grpc::experimental::LocalCredentials(UDS); return grpc::experimental::LocalCredentials(UDS);
} else { } else {
fprintf(stderr, fprintf(stderr,
"--local_connect_type=%s invalid; must be local_tcp or uds.\n", "--local_connect_type=%s invalid; must be local_tcp or uds.\n",
FLAGS_local_connect_type.c_str()); absl::GetFlag(FLAGS_local_connect_type).c_str());
} }
} }
fprintf(stderr, fprintf(stderr,
"--channel_creds_type=%s invalid; must be insecure, ssl, gdc, " "--channel_creds_type=%s invalid; must be insecure, ssl, gdc, "
"alts, or local.\n", "alts, or local.\n",
FLAGS_channel_creds_type.c_str()); absl::GetFlag(FLAGS_channel_creds_type).c_str());
return std::shared_ptr<grpc::ChannelCredentials>(); return std::shared_ptr<grpc::ChannelCredentials>();
} }
std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials() std::shared_ptr<grpc::CallCredentials> CliCredentials::GetCallCredentials()
const { const {
if (IsAccessToken(FLAGS_call_creds)) { if (IsAccessToken(absl::GetFlag(FLAGS_call_creds))) {
return grpc::AccessTokenCredentials(AccessToken(FLAGS_call_creds)); return grpc::AccessTokenCredentials(
AccessToken(absl::GetFlag(FLAGS_call_creds)));
} }
if (FLAGS_call_creds == "none") { if (absl::GetFlag(FLAGS_call_creds) == "none") {
// Nothing to do; creds, if any, are baked into the channel. // Nothing to do; creds, if any, are baked into the channel.
return std::shared_ptr<grpc::CallCredentials>(); return std::shared_ptr<grpc::CallCredentials>();
} }
fprintf(stderr, fprintf(stderr,
"--call_creds=%s invalid; must be none " "--call_creds=%s invalid; must be none "
"or access_token=<token>.\n", "or access_token=<token>.\n",
FLAGS_call_creds.c_str()); absl::GetFlag(FLAGS_call_creds).c_str());
return std::shared_ptr<grpc::CallCredentials>(); return std::shared_ptr<grpc::CallCredentials>();
} }
std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials() std::shared_ptr<grpc::ChannelCredentials> CliCredentials::GetCredentials()
const { const {
if (FLAGS_call_creds.empty()) { if (absl::GetFlag(FLAGS_call_creds).empty()) {
FLAGS_call_creds = GetDefaultCallCreds(); absl::SetFlag(&FLAGS_call_creds, GetDefaultCallCreds());
} else if (!FLAGS_access_token.empty() && !IsAccessToken(FLAGS_call_creds)) { } else if (!absl::GetFlag(FLAGS_access_token).empty() &&
!IsAccessToken(absl::GetFlag(FLAGS_call_creds))) {
fprintf(stderr, fprintf(stderr,
"warning: ignoring --access_token because --call_creds " "warning: ignoring --access_token because --call_creds "
"already set to %s.\n", "already set to %s.\n",
FLAGS_call_creds.c_str()); absl::GetFlag(FLAGS_call_creds).c_str());
} }
if (FLAGS_channel_creds_type.empty()) { if (absl::GetFlag(FLAGS_channel_creds_type).empty()) {
FLAGS_channel_creds_type = GetDefaultChannelCredsType(); absl::SetFlag(&FLAGS_channel_creds_type, GetDefaultChannelCredsType());
} else if (FLAGS_enable_ssl && FLAGS_channel_creds_type != "ssl") { } else if (absl::GetFlag(FLAGS_enable_ssl) &&
absl::GetFlag(FLAGS_channel_creds_type) == "ssl") {
fprintf(stderr, fprintf(stderr,
"warning: ignoring --enable_ssl because " "warning: ignoring --enable_ssl because "
"--channel_creds_type already set to %s.\n", "--channel_creds_type already set to %s.\n",
FLAGS_channel_creds_type.c_str()); absl::GetFlag(FLAGS_channel_creds_type).c_str());
} else if (FLAGS_use_auth && FLAGS_channel_creds_type != "gdc") { } else if (absl::GetFlag(FLAGS_use_auth) &&
absl::GetFlag(FLAGS_channel_creds_type) == "gdc") {
fprintf(stderr, fprintf(stderr,
"warning: ignoring --use_auth because " "warning: ignoring --use_auth because "
"--channel_creds_type already set to %s.\n", "--channel_creds_type already set to %s.\n",
FLAGS_channel_creds_type.c_str()); absl::GetFlag(FLAGS_channel_creds_type).c_str());
} }
// Legacy transport upgrade logic for insecure requests. // Legacy transport upgrade logic for insecure requests.
if (IsAccessToken(FLAGS_call_creds) && if (IsAccessToken(absl::GetFlag(FLAGS_call_creds)) &&
FLAGS_channel_creds_type == "insecure") { absl::GetFlag(FLAGS_channel_creds_type) == "insecure") {
fprintf(stderr, fprintf(stderr,
"warning: --channel_creds_type=insecure upgraded to ssl because " "warning: --channel_creds_type=insecure upgraded to ssl because "
"an access token was provided.\n"); "an access token was provided.\n");
FLAGS_channel_creds_type = "ssl"; absl::SetFlag(&FLAGS_channel_creds_type, "ssl");
} }
std::shared_ptr<grpc::ChannelCredentials> channel_creds = std::shared_ptr<grpc::ChannelCredentials> channel_creds =
GetChannelCredentials(); GetChannelCredentials();
@ -236,9 +241,9 @@ const std::string CliCredentials::GetCredentialUsage() const {
} }
const std::string CliCredentials::GetSslTargetNameOverride() const { const std::string CliCredentials::GetSslTargetNameOverride() const {
bool use_ssl = bool use_ssl = absl::GetFlag(FLAGS_channel_creds_type) == "ssl" ||
FLAGS_channel_creds_type == "ssl" || FLAGS_channel_creds_type == "gdc"; absl::GetFlag(FLAGS_channel_creds_type) == "gdc";
return use_ssl ? FLAGS_ssl_target : ""; return use_ssl ? absl::GetFlag(FLAGS_ssl_target) : "";
} }
} // namespace testing } // namespace testing

@ -18,20 +18,18 @@
#include "test/cpp/util/create_test_channel.h" #include "test/cpp/util/create_test_channel.h"
#include <gflags/gflags.h>
#include <grpc/support/log.h> #include <grpc/support/log.h>
#include <grpcpp/create_channel.h> #include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h> #include <grpcpp/security/credentials.h>
#include "absl/flags/flag.h"
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
DEFINE_string( ABSL_FLAG(std::string, grpc_test_use_grpclb_with_child_policy, "",
grpc_test_use_grpclb_with_child_policy, "", "If non-empty, set a static service config on channels created by "
"If non-empty, set a static service config on channels created by " "grpc::CreateTestChannel, that configures the grpclb LB policy "
"grpc::CreateTestChannel, that configures the grpclb LB policy " "with a child policy being the value of this flag (e.g. round_robin "
"with a child policy being the value of this flag (e.g. round_robin " "or pick_first).");
"or pick_first).");
namespace grpc { namespace grpc {
@ -59,12 +57,13 @@ void AddProdSslType() {
} }
void MaybeSetCustomChannelArgs(grpc::ChannelArguments* args) { void MaybeSetCustomChannelArgs(grpc::ChannelArguments* args) {
if (!FLAGS_grpc_test_use_grpclb_with_child_policy.empty()) { if (!absl::GetFlag(FLAGS_grpc_test_use_grpclb_with_child_policy).empty()) {
args->SetString("grpc.service_config", args->SetString(
"{\"loadBalancingConfig\":[{\"grpclb\":{\"childPolicy\":[{" "grpc.service_config",
"\"" + "{\"loadBalancingConfig\":[{\"grpclb\":{\"childPolicy\":[{"
FLAGS_grpc_test_use_grpclb_with_child_policy + "\"" +
"\":{}}]}}]}"); absl::GetFlag(FLAGS_grpc_test_use_grpclb_with_child_policy) +
"\":{}}]}}]}");
} }
} }

@ -58,17 +58,18 @@
address of the connection that each RPC is made on to stderr. address of the connection that each RPC is made on to stderr.
*/ */
#include <grpcpp/support/config.h>
#include <fstream> #include <fstream>
#include <functional> #include <functional>
#include <iostream> #include <iostream>
#include <gflags/gflags.h> #include "absl/flags/flag.h"
#include <grpcpp/support/config.h>
#include "test/cpp/util/cli_credentials.h" #include "test/cpp/util/cli_credentials.h"
#include "test/cpp/util/grpc_tool.h" #include "test/cpp/util/grpc_tool.h"
#include "test/cpp/util/test_config.h" #include "test/cpp/util/test_config.h"
DEFINE_string(outfile, "", "Output file (default is stdout)"); ABSL_FLAG(std::string, outfile, "", "Output file (default is stdout)");
static bool SimplePrint(const std::string& outfile, const std::string& output) { static bool SimplePrint(const std::string& outfile, const std::string& output) {
if (outfile.empty()) { if (outfile.empty()) {
@ -86,5 +87,6 @@ int main(int argc, char** argv) {
return grpc::testing::GrpcToolMainLib( return grpc::testing::GrpcToolMainLib(
argc, (const char**)argv, grpc::testing::CliCredentials(), argc, (const char**)argv, grpc::testing::CliCredentials(),
std::bind(SimplePrint, FLAGS_outfile, std::placeholders::_1)); std::bind(SimplePrint, absl::GetFlag(FLAGS_outfile),
std::placeholders::_1));
} }

@ -18,7 +18,6 @@
#include "test/cpp/util/grpc_tool.h" #include "test/cpp/util/grpc_tool.h"
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/port_platform.h> #include <grpc/support/port_platform.h>
#include <grpcpp/channel.h> #include <grpcpp/channel.h>
@ -35,8 +34,8 @@
#include <string> #include <string>
#include <thread> #include <thread>
#include "absl/flags/flag.h"
#include "absl/memory/memory.h" #include "absl/memory/memory.h"
#include "test/cpp/util/cli_call.h" #include "test/cpp/util/cli_call.h"
#include "test/cpp/util/proto_file_parser.h" #include "test/cpp/util/proto_file_parser.h"
#include "test/cpp/util/proto_reflection_descriptor_database.h" #include "test/cpp/util/proto_reflection_descriptor_database.h"
@ -48,38 +47,37 @@
#include <unistd.h> #include <unistd.h>
#endif #endif
ABSL_FLAG(bool, l, false, "Use a long listing format");
ABSL_FLAG(bool, remotedb, true,
"Use server types to parse and format messages");
ABSL_FLAG(std::string, metadata, "",
"Metadata to send to server, in the form of key1:val1:key2:val2");
ABSL_FLAG(std::string, proto_path, ".", "Path to look for the proto file.");
ABSL_FLAG(std::string, protofiles, "", "Name of the proto file.");
ABSL_FLAG(bool, binary_input, false, "Input in binary format");
ABSL_FLAG(bool, binary_output, false, "Output in binary format");
ABSL_FLAG(std::string, default_service_config, "",
"Default service config to use on the channel, if non-empty. Note "
"that this will be ignored if the name resolver returns a service "
"config.");
ABSL_FLAG(bool, display_peer_address, false,
"Log the peer socket address of the connection that each RPC is made "
"on to stderr.");
ABSL_FLAG(bool, json_input, false, "Input in json format");
ABSL_FLAG(bool, json_output, false, "Output in json format");
ABSL_FLAG(std::string, infile, "", "Input file (default is stdin)");
ABSL_FLAG(bool, batch, false,
"Input contains multiple requests. Please do not use this to send "
"more than a few RPCs. gRPC CLI has very different performance "
"characteristics compared with normal RPC calls which make it "
"unsuitable for loadtesting or significant production traffic.");
// TODO(Capstan): Consider using absl::Duration
ABSL_FLAG(double, timeout, -1,
"Specify timeout in seconds, used to set the deadline for all "
"RPCs. The default value of -1 means no deadline has been set.");
namespace grpc { namespace grpc {
namespace testing { namespace testing {
DEFINE_bool(l, false, "Use a long listing format");
DEFINE_bool(remotedb, true, "Use server types to parse and format messages");
DEFINE_string(metadata, "",
"Metadata to send to server, in the form of key1:val1:key2:val2");
DEFINE_string(proto_path, ".", "Path to look for the proto file.");
DEFINE_string(protofiles, "", "Name of the proto file.");
DEFINE_bool(binary_input, false, "Input in binary format");
DEFINE_bool(binary_output, false, "Output in binary format");
DEFINE_string(
default_service_config, "",
"Default service config to use on the channel, if non-empty. Note "
"that this will be ignored if the name resolver returns a service "
"config.");
DEFINE_bool(
display_peer_address, false,
"Log the peer socket address of the connection that each RPC is made "
"on to stderr.");
DEFINE_bool(json_input, false, "Input in json format");
DEFINE_bool(json_output, false, "Output in json format");
DEFINE_string(infile, "", "Input file (default is stdin)");
DEFINE_bool(batch, false,
"Input contains multiple requests. Please do not use this to send "
"more than a few RPCs. gRPC CLI has very different performance "
"characteristics compared with normal RPC calls which make it "
"unsuitable for loadtesting or significant production traffic.");
DEFINE_double(timeout, -1,
"Specify timeout in seconds, used to set the deadline for all "
"RPCs. The default value of -1 means no deadline has been set.");
namespace { namespace {
class GrpcTool { class GrpcTool {
@ -138,7 +136,7 @@ size_t ArraySize(T& a) {
void ParseMetadataFlag( void ParseMetadataFlag(
std::multimap<std::string, std::string>* client_metadata) { std::multimap<std::string, std::string>* client_metadata) {
if (FLAGS_metadata.empty()) { if (absl::GetFlag(FLAGS_metadata).empty()) {
return; return;
} }
std::vector<std::string> fields; std::vector<std::string> fields;
@ -146,11 +144,11 @@ void ParseMetadataFlag(
const char escape = '\\'; const char escape = '\\';
size_t cur = -1; size_t cur = -1;
std::stringstream ss; std::stringstream ss;
while (++cur < FLAGS_metadata.length()) { while (++cur < absl::GetFlag(FLAGS_metadata).length()) {
switch (FLAGS_metadata.at(cur)) { switch (absl::GetFlag(FLAGS_metadata).at(cur)) {
case escape: case escape:
if (cur < FLAGS_metadata.length() - 1) { if (cur < absl::GetFlag(FLAGS_metadata).length() - 1) {
char c = FLAGS_metadata.at(++cur); char c = absl::GetFlag(FLAGS_metadata).at(++cur);
if (c == delim || c == escape) { if (c == delim || c == escape) {
ss << c; ss << c;
continue; continue;
@ -164,7 +162,7 @@ void ParseMetadataFlag(
ss.clear(); ss.clear();
break; break;
default: default:
ss << FLAGS_metadata.at(cur); ss << absl::GetFlag(FLAGS_metadata).at(cur);
} }
} }
fields.push_back(ss.str()); fields.push_back(ss.str());
@ -205,11 +203,11 @@ void ReadResponse(CliCall* call, const std::string& method_name,
receive_initial_metadata ? &server_initial_metadata : nullptr); receive_initial_metadata ? &server_initial_metadata : nullptr);
receive_initial_metadata = false) { receive_initial_metadata = false) {
fprintf(stderr, "got response.\n"); fprintf(stderr, "got response.\n");
if (!FLAGS_binary_output) { if (!absl::GetFlag(FLAGS_binary_output)) {
gpr_mu_lock(parser_mu); gpr_mu_lock(parser_mu);
serialized_response_proto = parser->GetFormattedStringFromMethod( serialized_response_proto = parser->GetFormattedStringFromMethod(
method_name, serialized_response_proto, false /* is_request */, method_name, serialized_response_proto, false /* is_request */,
FLAGS_json_output); absl::GetFlag(FLAGS_json_output));
if (parser->HasError() && print_mode) { if (parser->HasError() && print_mode) {
fprintf(stderr, "Failed to parse response.\n"); fprintf(stderr, "Failed to parse response.\n");
} }
@ -231,9 +229,9 @@ std::shared_ptr<grpc::Channel> CreateCliChannel(
if (!cred.GetSslTargetNameOverride().empty()) { if (!cred.GetSslTargetNameOverride().empty()) {
args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride()); args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride());
} }
if (!FLAGS_default_service_config.empty()) { if (!absl::GetFlag(FLAGS_default_service_config).empty()) {
args.SetString(GRPC_ARG_SERVICE_CONFIG, args.SetString(GRPC_ARG_SERVICE_CONFIG,
FLAGS_default_service_config.c_str()); absl::GetFlag(FLAGS_default_service_config).c_str());
} }
return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(), return ::grpc::CreateCustomChannel(server_address, cred.GetCredentials(),
args); args);
@ -374,7 +372,7 @@ bool GrpcTool::ListServices(int argc, const char** argv,
if (argc < 2) { if (argc < 2) {
// List all services, if --l is passed, then include full description, // List all services, if --l is passed, then include full description,
// otherwise include a summarized list only. // otherwise include a summarized list only.
if (FLAGS_l) { if (absl::GetFlag(FLAGS_l)) {
output = DescribeServiceList(service_list, desc_pool); output = DescribeServiceList(service_list, desc_pool);
} else { } else {
for (auto it = service_list.begin(); it != service_list.end(); it++) { for (auto it = service_list.begin(); it != service_list.end(); it++) {
@ -411,14 +409,16 @@ bool GrpcTool::ListServices(int argc, const char** argv,
desc_pool.FindServiceByName(service_name); desc_pool.FindServiceByName(service_name);
if (service != nullptr) { if (service != nullptr) {
if (method_name.empty()) { if (method_name.empty()) {
output = FLAGS_l ? DescribeService(service) : SummarizeService(service); output = absl::GetFlag(FLAGS_l) ? DescribeService(service)
: SummarizeService(service);
} else { } else {
method_name.insert(0, 1, '.'); method_name.insert(0, 1, '.');
method_name.insert(0, service_name); method_name.insert(0, service_name);
const grpc::protobuf::MethodDescriptor* method = const grpc::protobuf::MethodDescriptor* method =
desc_pool.FindMethodByName(method_name); desc_pool.FindMethodByName(method_name);
if (method != nullptr) { if (method != nullptr) {
output = FLAGS_l ? DescribeMethod(method) : SummarizeMethod(method); output = absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
: SummarizeMethod(method);
} else { } else {
fprintf(stderr, "Method %s not found in service %s.\n", fprintf(stderr, "Method %s not found in service %s.\n",
method_name.c_str(), service_name.c_str()); method_name.c_str(), service_name.c_str());
@ -433,7 +433,8 @@ bool GrpcTool::ListServices(int argc, const char** argv,
const grpc::protobuf::MethodDescriptor* method = const grpc::protobuf::MethodDescriptor* method =
desc_pool.FindMethodByName(service_name); desc_pool.FindMethodByName(service_name);
if (method != nullptr) { if (method != nullptr) {
output = FLAGS_l ? DescribeMethod(method) : SummarizeMethod(method); output = absl::GetFlag(FLAGS_l) ? DescribeMethod(method)
: SummarizeMethod(method);
} else { } else {
fprintf(stderr, "Service or method %s not found.\n", fprintf(stderr, "Service or method %s not found.\n",
service_name.c_str()); service_name.c_str());
@ -509,15 +510,17 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
std::unique_ptr<ProtoFileParser> parser; std::unique_ptr<ProtoFileParser> parser;
std::string serialized_request_proto; std::string serialized_request_proto;
CliArgs cli_args; CliArgs cli_args;
cli_args.timeout = FLAGS_timeout; cli_args.timeout = absl::GetFlag(FLAGS_timeout);
bool print_mode = false; bool print_mode = false;
std::shared_ptr<grpc::Channel> channel = std::shared_ptr<grpc::Channel> channel =
CreateCliChannel(server_address, cred); CreateCliChannel(server_address, cred);
if (!FLAGS_binary_input || !FLAGS_binary_output) { if (!absl::GetFlag(FLAGS_binary_input) ||
!absl::GetFlag(FLAGS_binary_output)) {
parser = absl::make_unique<grpc::testing::ProtoFileParser>( parser = absl::make_unique<grpc::testing::ProtoFileParser>(
FLAGS_remotedb ? channel : nullptr, FLAGS_proto_path, FLAGS_protofiles); absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
absl::GetFlag(FLAGS_proto_path), absl::GetFlag(FLAGS_protofiles));
if (parser->HasError()) { if (parser->HasError()) {
fprintf( fprintf(
stderr, stderr,
@ -526,7 +529,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
} }
} }
if (FLAGS_binary_input) { if (absl::GetFlag(FLAGS_binary_input)) {
formatted_method_name = method_name; formatted_method_name = method_name;
} else { } else {
formatted_method_name = parser->GetFormattedMethodName(method_name); formatted_method_name = parser->GetFormattedMethodName(method_name);
@ -544,7 +547,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
std::istream* input_stream; std::istream* input_stream;
std::ifstream input_file; std::ifstream input_file;
if (FLAGS_batch) { if (absl::GetFlag(FLAGS_batch)) {
fprintf(stderr, "Batch mode for streaming RPC is not supported.\n"); fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
return false; return false;
} }
@ -554,19 +557,20 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
PrintMetadata(client_metadata, "Sending client initial metadata:"); PrintMetadata(client_metadata, "Sending client initial metadata:");
CliCall call(channel, formatted_method_name, client_metadata, cli_args); CliCall call(channel, formatted_method_name, client_metadata, cli_args);
if (FLAGS_display_peer_address) { if (absl::GetFlag(FLAGS_display_peer_address)) {
fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n", fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
formatted_method_name.c_str(), call.peer().c_str()); formatted_method_name.c_str(), call.peer().c_str());
} }
if (FLAGS_infile.empty()) { if (absl::GetFlag(FLAGS_infile).empty()) {
if (isatty(fileno(stdin))) { if (isatty(fileno(stdin))) {
print_mode = true; print_mode = true;
fprintf(stderr, "reading streaming request message from stdin...\n"); fprintf(stderr, "reading streaming request message from stdin...\n");
} }
input_stream = &std::cin; input_stream = &std::cin;
} else { } else {
input_file.open(FLAGS_infile, std::ios::in | std::ios::binary); input_file.open(absl::GetFlag(FLAGS_infile),
std::ios::in | std::ios::binary);
input_stream = &input_file; input_stream = &input_file;
} }
@ -580,14 +584,14 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
while (!request_text.empty() || while (!request_text.empty() ||
(!input_stream->eof() && getline(*input_stream, line))) { (!input_stream->eof() && getline(*input_stream, line))) {
if (!request_text.empty()) { if (!request_text.empty()) {
if (FLAGS_binary_input) { if (absl::GetFlag(FLAGS_binary_input)) {
serialized_request_proto = request_text; serialized_request_proto = request_text;
request_text.clear(); request_text.clear();
} else { } else {
gpr_mu_lock(&parser_mu); gpr_mu_lock(&parser_mu);
serialized_request_proto = parser->GetSerializedProtoFromMethod( serialized_request_proto = parser->GetSerializedProtoFromMethod(
method_name, request_text, true /* is_request */, method_name, request_text, true /* is_request */,
FLAGS_json_input); absl::GetFlag(FLAGS_json_input));
request_text.clear(); request_text.clear();
if (parser->HasError()) { if (parser->HasError()) {
if (print_mode) { if (print_mode) {
@ -636,7 +640,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
} }
} else { // parser->IsStreaming(method_name, true /* is_request */) } else { // parser->IsStreaming(method_name, true /* is_request */)
if (FLAGS_batch) { if (absl::GetFlag(FLAGS_batch)) {
if (parser->IsStreaming(method_name, false /* is_request */)) { if (parser->IsStreaming(method_name, false /* is_request */)) {
fprintf(stderr, "Batch mode for streaming RPC is not supported.\n"); fprintf(stderr, "Batch mode for streaming RPC is not supported.\n");
return false; return false;
@ -645,14 +649,15 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
std::istream* input_stream; std::istream* input_stream;
std::ifstream input_file; std::ifstream input_file;
if (FLAGS_infile.empty()) { if (absl::GetFlag(FLAGS_infile).empty()) {
if (isatty(fileno(stdin))) { if (isatty(fileno(stdin))) {
print_mode = true; print_mode = true;
fprintf(stderr, "reading request messages from stdin...\n"); fprintf(stderr, "reading request messages from stdin...\n");
} }
input_stream = &std::cin; input_stream = &std::cin;
} else { } else {
input_file.open(FLAGS_infile, std::ios::in | std::ios::binary); input_file.open(absl::GetFlag(FLAGS_infile),
std::ios::in | std::ios::binary);
input_stream = &input_file; input_stream = &input_file;
} }
@ -667,13 +672,13 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
while (!request_text.empty() || while (!request_text.empty() ||
(!input_stream->eof() && getline(*input_stream, line))) { (!input_stream->eof() && getline(*input_stream, line))) {
if (!request_text.empty()) { if (!request_text.empty()) {
if (FLAGS_binary_input) { if (absl::GetFlag(FLAGS_binary_input)) {
serialized_request_proto = request_text; serialized_request_proto = request_text;
request_text.clear(); request_text.clear();
} else { } else {
serialized_request_proto = parser->GetSerializedProtoFromMethod( serialized_request_proto = parser->GetSerializedProtoFromMethod(
method_name, request_text, true /* is_request */, method_name, request_text, true /* is_request */,
FLAGS_json_input); absl::GetFlag(FLAGS_json_input));
request_text.clear(); request_text.clear();
if (parser->HasError()) { if (parser->HasError()) {
if (print_mode) { if (print_mode) {
@ -688,7 +693,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
server_initial_metadata, server_trailing_metadata; server_initial_metadata, server_trailing_metadata;
CliCall call(channel, formatted_method_name, client_metadata, CliCall call(channel, formatted_method_name, client_metadata,
cli_args); cli_args);
if (FLAGS_display_peer_address) { if (absl::GetFlag(FLAGS_display_peer_address)) {
fprintf(stderr, fprintf(stderr,
"New call for method_name:%s has peer address:|%s|\n", "New call for method_name:%s has peer address:|%s|\n",
formatted_method_name.c_str(), call.peer().c_str()); formatted_method_name.c_str(), call.peer().c_str());
@ -710,14 +715,14 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
"Received trailing metadata from server:"); "Received trailing metadata from server:");
} }
if (FLAGS_binary_output) { if (absl::GetFlag(FLAGS_binary_output)) {
if (!callback(serialized_response_proto)) { if (!callback(serialized_response_proto)) {
break; break;
} }
} else { } else {
std::string response_text = parser->GetFormattedStringFromMethod( std::string response_text = parser->GetFormattedStringFromMethod(
method_name, serialized_response_proto, method_name, serialized_response_proto,
false /* is_request */, FLAGS_json_output); false /* is_request */, absl::GetFlag(FLAGS_json_output));
if (parser->HasError() && print_mode) { if (parser->HasError() && print_mode) {
fprintf(stderr, "Failed to parse response.\n"); fprintf(stderr, "Failed to parse response.\n");
@ -753,29 +758,31 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
} }
if (argc == 3) { if (argc == 3) {
if (!FLAGS_infile.empty()) { if (!absl::GetFlag(FLAGS_infile).empty()) {
fprintf(stderr, "warning: request given in argv, ignoring --infile\n"); fprintf(stderr, "warning: request given in argv, ignoring --infile\n");
} }
} else { } else {
std::stringstream input_stream; std::stringstream input_stream;
if (FLAGS_infile.empty()) { if (absl::GetFlag(FLAGS_infile).empty()) {
if (isatty(fileno(stdin))) { if (isatty(fileno(stdin))) {
fprintf(stderr, "reading request message from stdin...\n"); fprintf(stderr, "reading request message from stdin...\n");
} }
input_stream << std::cin.rdbuf(); input_stream << std::cin.rdbuf();
} else { } else {
std::ifstream input_file(FLAGS_infile, std::ios::in | std::ios::binary); std::ifstream input_file(absl::GetFlag(FLAGS_infile),
std::ios::in | std::ios::binary);
input_stream << input_file.rdbuf(); input_stream << input_file.rdbuf();
input_file.close(); input_file.close();
} }
request_text = input_stream.str(); request_text = input_stream.str();
} }
if (FLAGS_binary_input) { if (absl::GetFlag(FLAGS_binary_input)) {
serialized_request_proto = request_text; serialized_request_proto = request_text;
} else { } else {
serialized_request_proto = parser->GetSerializedProtoFromMethod( serialized_request_proto = parser->GetSerializedProtoFromMethod(
method_name, request_text, true /* is_request */, FLAGS_json_input); method_name, request_text, true /* is_request */,
absl::GetFlag(FLAGS_json_input));
if (parser->HasError()) { if (parser->HasError()) {
fprintf(stderr, "Failed to parse request.\n"); fprintf(stderr, "Failed to parse request.\n");
return false; return false;
@ -791,7 +798,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
PrintMetadata(client_metadata, "Sending client initial metadata:"); PrintMetadata(client_metadata, "Sending client initial metadata:");
CliCall call(channel, formatted_method_name, client_metadata, cli_args); CliCall call(channel, formatted_method_name, client_metadata, cli_args);
if (FLAGS_display_peer_address) { if (absl::GetFlag(FLAGS_display_peer_address)) {
fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n", fprintf(stderr, "New call for method_name:%s has peer address:|%s|\n",
formatted_method_name.c_str(), call.peer().c_str()); formatted_method_name.c_str(), call.peer().c_str());
} }
@ -802,10 +809,10 @@ bool GrpcTool::CallMethod(int argc, const char** argv,
&serialized_response_proto, &serialized_response_proto,
receive_initial_metadata ? &server_initial_metadata : nullptr); receive_initial_metadata ? &server_initial_metadata : nullptr);
receive_initial_metadata = false) { receive_initial_metadata = false) {
if (!FLAGS_binary_output) { if (!absl::GetFlag(FLAGS_binary_output)) {
serialized_response_proto = parser->GetFormattedStringFromMethod( serialized_response_proto = parser->GetFormattedStringFromMethod(
method_name, serialized_response_proto, false /* is_request */, method_name, serialized_response_proto, false /* is_request */,
FLAGS_json_output); absl::GetFlag(FLAGS_json_output));
if (parser->HasError()) { if (parser->HasError()) {
fprintf(stderr, "Failed to parse response.\n"); fprintf(stderr, "Failed to parse response.\n");
return false; return false;
@ -867,29 +874,32 @@ bool GrpcTool::ParseMessage(int argc, const char** argv,
if (argc == 3) { if (argc == 3) {
message_text = argv[2]; message_text = argv[2];
if (!FLAGS_infile.empty()) { if (!absl::GetFlag(FLAGS_infile).empty()) {
fprintf(stderr, "warning: message given in argv, ignoring --infile.\n"); fprintf(stderr, "warning: message given in argv, ignoring --infile.\n");
} }
} else { } else {
std::stringstream input_stream; std::stringstream input_stream;
if (FLAGS_infile.empty()) { if (absl::GetFlag(FLAGS_infile).empty()) {
if (isatty(fileno(stdin))) { if (isatty(fileno(stdin))) {
fprintf(stderr, "reading request message from stdin...\n"); fprintf(stderr, "reading request message from stdin...\n");
} }
input_stream << std::cin.rdbuf(); input_stream << std::cin.rdbuf();
} else { } else {
std::ifstream input_file(FLAGS_infile, std::ios::in | std::ios::binary); std::ifstream input_file(absl::GetFlag(FLAGS_infile),
std::ios::in | std::ios::binary);
input_stream << input_file.rdbuf(); input_stream << input_file.rdbuf();
input_file.close(); input_file.close();
} }
message_text = input_stream.str(); message_text = input_stream.str();
} }
if (!FLAGS_binary_input || !FLAGS_binary_output) { if (!absl::GetFlag(FLAGS_binary_input) ||
!absl::GetFlag(FLAGS_binary_output)) {
std::shared_ptr<grpc::Channel> channel = std::shared_ptr<grpc::Channel> channel =
CreateCliChannel(server_address, cred); CreateCliChannel(server_address, cred);
parser = absl::make_unique<grpc::testing::ProtoFileParser>( parser = absl::make_unique<grpc::testing::ProtoFileParser>(
FLAGS_remotedb ? channel : nullptr, FLAGS_proto_path, FLAGS_protofiles); absl::GetFlag(FLAGS_remotedb) ? channel : nullptr,
absl::GetFlag(FLAGS_proto_path), absl::GetFlag(FLAGS_protofiles));
if (parser->HasError()) { if (parser->HasError()) {
fprintf( fprintf(
stderr, stderr,
@ -898,23 +908,23 @@ bool GrpcTool::ParseMessage(int argc, const char** argv,
} }
} }
if (FLAGS_binary_input) { if (absl::GetFlag(FLAGS_binary_input)) {
serialized_request_proto = message_text; serialized_request_proto = message_text;
} else { } else {
serialized_request_proto = parser->GetSerializedProtoFromMessageType( serialized_request_proto = parser->GetSerializedProtoFromMessageType(
type_name, message_text, FLAGS_json_input); type_name, message_text, absl::GetFlag(FLAGS_json_input));
if (parser->HasError()) { if (parser->HasError()) {
fprintf(stderr, "Failed to serialize the message.\n"); fprintf(stderr, "Failed to serialize the message.\n");
return false; return false;
} }
} }
if (FLAGS_binary_output) { if (absl::GetFlag(FLAGS_binary_output)) {
output_ss << serialized_request_proto; output_ss << serialized_request_proto;
} else { } else {
std::string output_text; std::string output_text;
output_text = parser->GetFormattedStringFromMessageType( output_text = parser->GetFormattedStringFromMessageType(
type_name, serialized_request_proto, FLAGS_json_output); type_name, serialized_request_proto, absl::GetFlag(FLAGS_json_output));
if (parser->HasError()) { if (parser->HasError()) {
fprintf(stderr, "Failed to deserialize the message.\n"); fprintf(stderr, "Failed to deserialize the message.\n");
return false; return false;
@ -937,10 +947,10 @@ bool GrpcTool::ToText(int argc, const char** argv, const CliCredentials& cred,
" --infile ; Input filename (defaults to stdin)\n" " --infile ; Input filename (defaults to stdin)\n"
" --outfile ; Output filename (defaults to stdout)\n"); " --outfile ; Output filename (defaults to stdout)\n");
FLAGS_protofiles = argv[0]; absl::SetFlag(&FLAGS_protofiles, argv[0]);
FLAGS_remotedb = false; absl::SetFlag(&FLAGS_remotedb, false);
FLAGS_binary_input = true; absl::SetFlag(&FLAGS_binary_input, true);
FLAGS_binary_output = false; absl::SetFlag(&FLAGS_binary_output, false);
return ParseMessage(argc, argv, cred, callback); return ParseMessage(argc, argv, cred, callback);
} }
@ -955,11 +965,11 @@ bool GrpcTool::ToJson(int argc, const char** argv, const CliCredentials& cred,
" --infile ; Input filename (defaults to stdin)\n" " --infile ; Input filename (defaults to stdin)\n"
" --outfile ; Output filename (defaults to stdout)\n"); " --outfile ; Output filename (defaults to stdout)\n");
FLAGS_protofiles = argv[0]; absl::SetFlag(&FLAGS_protofiles, argv[0]);
FLAGS_remotedb = false; absl::SetFlag(&FLAGS_remotedb, false);
FLAGS_binary_input = true; absl::SetFlag(&FLAGS_binary_input, true);
FLAGS_binary_output = false; absl::SetFlag(&FLAGS_binary_output, false);
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
return ParseMessage(argc, argv, cred, callback); return ParseMessage(argc, argv, cred, callback);
} }
@ -974,10 +984,10 @@ bool GrpcTool::ToBinary(int argc, const char** argv, const CliCredentials& cred,
" --infile ; Input filename (defaults to stdin)\n" " --infile ; Input filename (defaults to stdin)\n"
" --outfile ; Output filename (defaults to stdout)\n"); " --outfile ; Output filename (defaults to stdout)\n");
FLAGS_protofiles = argv[0]; absl::SetFlag(&FLAGS_protofiles, argv[0]);
FLAGS_remotedb = false; absl::SetFlag(&FLAGS_remotedb, false);
FLAGS_binary_input = false; absl::SetFlag(&FLAGS_binary_input, false);
FLAGS_binary_output = true; absl::SetFlag(&FLAGS_binary_output, true);
return ParseMessage(argc, argv, cred, callback); return ParseMessage(argc, argv, cred, callback);
} }

@ -18,7 +18,6 @@
#include "test/cpp/util/grpc_tool.h" #include "test/cpp/util/grpc_tool.h"
#include <gflags/gflags.h>
#include <grpc/grpc.h> #include <grpc/grpc.h>
#include <grpc/support/alloc.h> #include <grpc/support/alloc.h>
#include <grpcpp/channel.h> #include <grpcpp/channel.h>
@ -33,6 +32,7 @@
#include <chrono> #include <chrono>
#include <sstream> #include <sstream>
#include "absl/flags/flag.h"
#include "src/core/lib/gpr/env.h" #include "src/core/lib/gpr/env.h"
#include "src/core/lib/iomgr/load_file.h" #include "src/core/lib/iomgr/load_file.h"
#include "src/proto/grpc/testing/echo.grpc.pb.h" #include "src/proto/grpc/testing/echo.grpc.pb.h"
@ -110,24 +110,22 @@ using grpc::testing::EchoResponse;
" }\n" \ " }\n" \
"}\n\n" "}\n\n"
DECLARE_string(channel_creds_type); ABSL_DECLARE_FLAG(std::string, channel_creds_type);
DECLARE_string(ssl_target); ABSL_DECLARE_FLAG(std::string, ssl_target);
ABSL_DECLARE_FLAG(bool, binary_input);
ABSL_DECLARE_FLAG(bool, binary_output);
ABSL_DECLARE_FLAG(bool, json_input);
ABSL_DECLARE_FLAG(bool, json_output);
ABSL_DECLARE_FLAG(bool, l);
ABSL_DECLARE_FLAG(bool, batch);
ABSL_DECLARE_FLAG(std::string, metadata);
ABSL_DECLARE_FLAG(std::string, protofiles);
ABSL_DECLARE_FLAG(std::string, proto_path);
ABSL_DECLARE_FLAG(std::string, default_service_config);
ABSL_DECLARE_FLAG(double, timeout);
namespace grpc { namespace grpc {
namespace testing { namespace testing {
DECLARE_bool(binary_input);
DECLARE_bool(binary_output);
DECLARE_bool(json_input);
DECLARE_bool(json_output);
DECLARE_bool(l);
DECLARE_bool(batch);
DECLARE_string(metadata);
DECLARE_string(protofiles);
DECLARE_string(proto_path);
DECLARE_string(default_service_config);
DECLARE_double(timeout);
namespace { namespace {
const int kServerDefaultResponseStreamsToSend = 3; const int kServerDefaultResponseStreamsToSend = 3;
@ -204,7 +202,8 @@ class TestServiceImpl : public ::grpc::testing::EchoTestService::Service {
// Returning string instead of bool to avoid using embedded messages in // Returning string instead of bool to avoid using embedded messages in
// proto3 // proto3
response->set_message(seconds.count() <= FLAGS_timeout ? "true" : "false"); response->set_message(
seconds.count() <= absl::GetFlag(FLAGS_timeout) ? "true" : "false");
return Status::OK; return Status::OK;
} }
@ -372,7 +371,7 @@ TEST_F(GrpcToolTest, ListCommand) {
const std::string server_address = SetUpServer(); const std::string server_address = SetUpServer();
const char* argv[] = {"grpc_cli", "ls", server_address.c_str()}; const char* argv[] = {"grpc_cli", "ls", server_address.c_str()};
FLAGS_l = false; absl::SetFlag(&FLAGS_l, false);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -391,7 +390,7 @@ TEST_F(GrpcToolTest, ListOneService) {
const char* argv[] = {"grpc_cli", "ls", server_address.c_str(), const char* argv[] = {"grpc_cli", "ls", server_address.c_str(),
"grpc.testing.EchoTestService"}; "grpc.testing.EchoTestService"};
// without -l flag // without -l flag
FLAGS_l = false; absl::SetFlag(&FLAGS_l, false);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -402,7 +401,7 @@ TEST_F(GrpcToolTest, ListOneService) {
// with -l flag // with -l flag
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_l = true; absl::SetFlag(&FLAGS_l, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -442,7 +441,7 @@ TEST_F(GrpcToolTest, ListOneMethod) {
const char* argv[] = {"grpc_cli", "ls", server_address.c_str(), const char* argv[] = {"grpc_cli", "ls", server_address.c_str(),
"grpc.testing.EchoTestService.Echo"}; "grpc.testing.EchoTestService.Echo"};
// without -l flag // without -l flag
FLAGS_l = false; absl::SetFlag(&FLAGS_l, false);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -452,7 +451,7 @@ TEST_F(GrpcToolTest, ListOneMethod) {
// with -l flag // with -l flag
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_l = true; absl::SetFlag(&FLAGS_l, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -496,11 +495,12 @@ TEST_F(GrpcToolTest, CallCommand) {
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_json_output = true; // TODO(Capstan): Consider using absl::FlagSaver
absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
// Expected output: // Expected output:
// { // {
@ -520,7 +520,7 @@ TEST_F(GrpcToolTest, CallCommandJsonInput) {
const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo",
"{ \"message\": \"Hello\"}"}; "{ \"message\": \"Hello\"}"};
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -532,12 +532,12 @@ TEST_F(GrpcToolTest, CallCommandJsonInput) {
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
// Expected output: // Expected output:
// { // {
@ -562,11 +562,11 @@ TEST_F(GrpcToolTest, CallCommandBatch) {
std::istringstream ss("message: 'Hello1'\n\n message: 'Hello2'\n\n"); std::istringstream ss("message: 'Hello1'\n\n message: 'Hello2'\n\n");
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage:
// "Hello2"\n" // "Hello2"\n"
@ -580,13 +580,13 @@ TEST_F(GrpcToolTest, CallCommandBatch) {
ss.seekg(0); ss.seekg(0);
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: // Expected output:
// { // {
@ -623,12 +623,12 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInput) {
"{\"message\": \"Hello1\"}\n\n{\"message\": \"Hello2\" }\n\n"); "{\"message\": \"Hello1\"}\n\n{\"message\": \"Hello2\" }\n\n");
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage:
// "Hello2"\n" // "Hello2"\n"
@ -642,14 +642,14 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInput) {
ss.seekg(0); ss.seekg(0);
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
// Expected output: // Expected output:
// { // {
@ -685,11 +685,11 @@ TEST_F(GrpcToolTest, CallCommandBatchWithBadRequest) {
std::istringstream ss("message: 1\n\n message: 'Hello2'\n\n"); std::istringstream ss("message: 1\n\n message: 'Hello2'\n\n");
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: "message: "Hello0"\nmessage: "Hello2"\n" // Expected output: "message: "Hello0"\nmessage: "Hello2"\n"
EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(),
@ -702,13 +702,13 @@ TEST_F(GrpcToolTest, CallCommandBatchWithBadRequest) {
ss.seekg(0); ss.seekg(0);
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: // Expected output:
// { // {
@ -741,13 +741,13 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInputWithBadRequest) {
"{ \"message\": 1 }\n\n { \"message\": \"Hello2\" }\n\n"); "{ \"message\": 1 }\n\n { \"message\": \"Hello2\" }\n\n");
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: "message: "Hello0"\nmessage: "Hello2"\n" // Expected output: "message: "Hello0"\nmessage: "Hello2"\n"
EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(),
@ -760,15 +760,15 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInputWithBadRequest) {
ss.seekg(0); ss.seekg(0);
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_batch = true; absl::SetFlag(&FLAGS_batch, true);
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
FLAGS_batch = false; absl::SetFlag(&FLAGS_batch, false);
// Expected output: // Expected output:
// { // {
@ -827,11 +827,11 @@ TEST_F(GrpcToolTest, CallCommandRequestStreamJsonInput) {
"{ \"message\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); "{ \"message\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n");
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
// Expected output: "message: \"Hello0Hello1Hello2\"" // Expected output: "message: \"Hello0Hello1Hello2\""
EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(),
@ -880,11 +880,11 @@ TEST_F(GrpcToolTest, CallCommandRequestStreamWithBadRequestJsonInput) {
"{ \"bad_field\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); "{ \"bad_field\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n");
std::cin.rdbuf(ss.rdbuf()); std::cin.rdbuf(ss.rdbuf());
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
// Expected output: "message: \"Hello0Hello2\"" // Expected output: "message: \"Hello0Hello2\""
EXPECT_TRUE(nullptr != EXPECT_TRUE(nullptr !=
@ -902,7 +902,7 @@ TEST_F(GrpcToolTest, CallCommandWithTimeoutDeadlineSet) {
"CheckDeadlineSet"}; "CheckDeadlineSet"};
// Set timeout to 5000.25 seconds // Set timeout to 5000.25 seconds
FLAGS_timeout = 5000.25; absl::SetFlag(&FLAGS_timeout, 5000.25);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -923,7 +923,7 @@ TEST_F(GrpcToolTest, CallCommandWithTimeoutDeadlineUpperBound) {
"CheckDeadlineUpperBound"}; "CheckDeadlineUpperBound"};
// Set timeout to 900 seconds // Set timeout to 900 seconds
FLAGS_timeout = 900; absl::SetFlag(&FLAGS_timeout, 900);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -945,7 +945,7 @@ TEST_F(GrpcToolTest, CallCommandWithNegativeTimeoutValue) {
"CheckDeadlineSet"}; "CheckDeadlineSet"};
// Set timeout to -5 (deadline not set) // Set timeout to -5 (deadline not set)
FLAGS_timeout = -5; absl::SetFlag(&FLAGS_timeout, -5);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -967,7 +967,7 @@ TEST_F(GrpcToolTest, CallCommandWithDefaultTimeoutValue) {
"CheckDeadlineSet"}; "CheckDeadlineSet"};
// Set timeout to -1 (default value, deadline not set) // Set timeout to -1 (default value, deadline not set)
FLAGS_timeout = -1; absl::SetFlag(&FLAGS_timeout, -1);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -1005,11 +1005,11 @@ TEST_F(GrpcToolTest, CallCommandResponseStream) {
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
// Expected output: "{\n \"message\": \"Hello{n}\"\n}\n" // Expected output: "{\n \"message\": \"Hello{n}\"\n}\n"
for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) { for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) {
@ -1085,8 +1085,8 @@ TEST_F(GrpcToolTest, ParseCommand) {
"grpc.testing.EchoResponse", "grpc.testing.EchoResponse",
ECHO_RESPONSE_MESSAGE_TEXT_FORMAT}; ECHO_RESPONSE_MESSAGE_TEXT_FORMAT};
FLAGS_binary_input = false; absl::SetFlag(&FLAGS_binary_input, false);
FLAGS_binary_output = false; absl::SetFlag(&FLAGS_binary_output, false);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -1098,11 +1098,11 @@ TEST_F(GrpcToolTest, ParseCommand) {
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
// Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(),
@ -1111,7 +1111,7 @@ TEST_F(GrpcToolTest, ParseCommand) {
// Parse text message to binary message and then parse it back to text message // Parse text message to binary message and then parse it back to text message
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_binary_output = true; absl::SetFlag(&FLAGS_binary_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -1119,8 +1119,8 @@ TEST_F(GrpcToolTest, ParseCommand) {
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
argv[4] = binary_data.c_str(); argv[4] = binary_data.c_str();
FLAGS_binary_input = true; absl::SetFlag(&FLAGS_binary_input, true);
FLAGS_binary_output = false; absl::SetFlag(&FLAGS_binary_output, false);
EXPECT_TRUE(0 == GrpcToolMainLib(5, argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(5, argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -1129,8 +1129,8 @@ TEST_F(GrpcToolTest, ParseCommand) {
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(),
ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); ECHO_RESPONSE_MESSAGE_TEXT_FORMAT));
FLAGS_binary_input = false; absl::SetFlag(&FLAGS_binary_input, false);
FLAGS_binary_output = false; absl::SetFlag(&FLAGS_binary_output, false);
ShutdownServer(); ShutdownServer();
} }
@ -1145,7 +1145,7 @@ TEST_F(GrpcToolTest, ParseCommandJsonFormat) {
"grpc.testing.EchoResponse", "grpc.testing.EchoResponse",
ECHO_RESPONSE_MESSAGE_JSON_FORMAT}; ECHO_RESPONSE_MESSAGE_JSON_FORMAT};
FLAGS_json_input = true; absl::SetFlag(&FLAGS_json_input, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
@ -1158,12 +1158,12 @@ TEST_F(GrpcToolTest, ParseCommandJsonFormat) {
output_stream.str(std::string()); output_stream.str(std::string());
output_stream.clear(); output_stream.clear();
FLAGS_json_output = true; absl::SetFlag(&FLAGS_json_output, true);
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_json_output = false; absl::SetFlag(&FLAGS_json_output, false);
FLAGS_json_input = false; absl::SetFlag(&FLAGS_json_input, false);
// Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(),
@ -1211,7 +1211,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) {
{ {
std::stringstream output_stream; std::stringstream output_stream;
FLAGS_metadata = "key0:val0:key1:valq:key2:val2"; absl::SetFlag(&FLAGS_metadata, "key0:val0:key1:valq:key2:val2");
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv,
TestCliCredentials(), TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -1223,7 +1223,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) {
{ {
std::stringstream output_stream; std::stringstream output_stream;
FLAGS_metadata = "key:val\\:val"; absl::SetFlag(&FLAGS_metadata, "key:val\\:val");
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv,
TestCliCredentials(), TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -1235,7 +1235,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) {
{ {
std::stringstream output_stream; std::stringstream output_stream;
FLAGS_metadata = "key:val\\\\val"; absl::SetFlag(&FLAGS_metadata, "key:val\\\\val");
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv,
TestCliCredentials(), TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
@ -1245,7 +1245,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) {
strstr(output_stream.str().c_str(), "message: \"Hello\"")); strstr(output_stream.str().c_str(), "message: \"Hello\""));
} }
FLAGS_metadata = ""; absl::SetFlag(&FLAGS_metadata, "");
ShutdownServer(); ShutdownServer();
} }
@ -1254,15 +1254,16 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) {
const char* argv[] = {"grpc_cli", "call", "localhost:10000", const char* argv[] = {"grpc_cli", "call", "localhost:10000",
"grpc.testing.EchoTestService.Echo", "grpc.testing.EchoTestService.Echo",
"message: 'Hello'"}; "message: 'Hello'"};
FLAGS_protofiles = "src/proto/grpc/testing/echo.proto"; absl::SetFlag(&FLAGS_protofiles, "src/proto/grpc/testing/echo.proto");
char* test_srcdir = gpr_getenv("TEST_SRCDIR"); char* test_srcdir = gpr_getenv("TEST_SRCDIR");
if (test_srcdir != nullptr) { if (test_srcdir != nullptr) {
FLAGS_proto_path = test_srcdir + std::string("/com_github_grpc_grpc"); absl::SetFlag(&FLAGS_proto_path,
test_srcdir + std::string("/com_github_grpc_grpc"));
} }
{ {
std::stringstream output_stream; std::stringstream output_stream;
FLAGS_metadata = "key0:val0:key1"; absl::SetFlag(&FLAGS_metadata, "key0:val0:key1");
// Exit with 1 // Exit with 1
EXPECT_EXIT( EXPECT_EXIT(
GrpcToolMainLib( GrpcToolMainLib(
@ -1273,7 +1274,7 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) {
{ {
std::stringstream output_stream; std::stringstream output_stream;
FLAGS_metadata = "key:val\\val"; absl::SetFlag(&FLAGS_metadata, "key:val\\val");
// Exit with 1 // Exit with 1
EXPECT_EXIT( EXPECT_EXIT(
GrpcToolMainLib( GrpcToolMainLib(
@ -1282,8 +1283,8 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) {
::testing::ExitedWithCode(1), ".*Failed to parse metadata flag.*"); ::testing::ExitedWithCode(1), ".*Failed to parse metadata flag.*");
} }
FLAGS_metadata = ""; absl::SetFlag(&FLAGS_metadata, "");
FLAGS_protofiles = ""; absl::SetFlag(&FLAGS_protofiles, "");
gpr_free(test_srcdir); gpr_free(test_srcdir);
} }
@ -1295,9 +1296,9 @@ TEST_F(GrpcToolTest, ListCommand_OverrideSslHostName) {
// --ssl_target=z.test.google.fr" // --ssl_target=z.test.google.fr"
std::stringstream output_stream; std::stringstream output_stream;
const char* argv[] = {"grpc_cli", "ls", server_address.c_str()}; const char* argv[] = {"grpc_cli", "ls", server_address.c_str()};
FLAGS_l = false; absl::SetFlag(&FLAGS_l, false);
FLAGS_channel_creds_type = "ssl"; absl::SetFlag(&FLAGS_channel_creds_type, "ssl");
FLAGS_ssl_target = "z.test.google.fr"; absl::SetFlag(&FLAGS_ssl_target, "z.test.google.fr");
EXPECT_TRUE( EXPECT_TRUE(
0 == GrpcToolMainLib( 0 == GrpcToolMainLib(
ArraySize(argv), argv, TestCliCredentials(true), ArraySize(argv), argv, TestCliCredentials(true),
@ -1306,8 +1307,8 @@ TEST_F(GrpcToolTest, ListCommand_OverrideSslHostName) {
"grpc.testing.EchoTestService\n" "grpc.testing.EchoTestService\n"
"grpc.reflection.v1alpha.ServerReflection\n")); "grpc.reflection.v1alpha.ServerReflection\n"));
FLAGS_channel_creds_type = ""; absl::SetFlag(&FLAGS_channel_creds_type, "");
FLAGS_ssl_target = ""; absl::SetFlag(&FLAGS_ssl_target, "");
ShutdownServer(); ShutdownServer();
} }
@ -1320,13 +1321,13 @@ TEST_F(GrpcToolTest, ConfiguringDefaultServiceConfig) {
// Just check that the tool is still operational when --default_service_config // Just check that the tool is still operational when --default_service_config
// is configured. This particular service config is in reality redundant with // is configured. This particular service config is in reality redundant with
// the channel's default configuration. // the channel's default configuration.
FLAGS_l = false; absl::SetFlag(&FLAGS_l, false);
FLAGS_default_service_config = absl::SetFlag(&FLAGS_default_service_config,
"{\"loadBalancingConfig\":[{\"pick_first\":{}}]}"; "{\"loadBalancingConfig\":[{\"pick_first\":{}}]}");
EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(),
std::bind(PrintStream, &output_stream, std::bind(PrintStream, &output_stream,
std::placeholders::_1))); std::placeholders::_1)));
FLAGS_default_service_config = ""; absl::SetFlag(&FLAGS_default_service_config, "");
EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(),
"grpc.testing.EchoTestService\n" "grpc.testing.EchoTestService\n"
"grpc.reflection.v1alpha.ServerReflection\n")); "grpc.reflection.v1alpha.ServerReflection\n"));

@ -16,21 +16,22 @@
* *
*/ */
#include <gflags/gflags.h> #include <vector>
#include "test/cpp/util/test_config.h"
// In some distros, gflags is in the namespace google, and in some others, #include "absl/flags/parse.h"
// in gflags. This hack is enabling us to find both. #include "test/cpp/util/test_config.h"
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
namespace grpc { namespace grpc {
namespace testing { namespace testing {
void InitTest(int* argc, char*** argv, bool remove_flags) { void InitTest(int* argc, char*** argv, bool remove_flags) {
ParseCommandLineFlags(argc, argv, remove_flags); std::vector<char*> reduced_argv = absl::ParseCommandLine(*argc, *argv);
if (remove_flags) {
*argc = reduced_argv.size();
for (int i = 0; i < *argc; i++) {
(*argv)[i] = reduced_argv.at(i);
}
}
} }
} // namespace testing } // namespace testing

@ -19,22 +19,23 @@
#include "test/cpp/util/test_credentials_provider.h" #include "test/cpp/util/test_credentials_provider.h"
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpcpp/security/server_credentials.h>
#include <cstdio> #include <cstdio>
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <mutex> #include <mutex>
#include <unordered_map> #include <unordered_map>
#include <gflags/gflags.h> #include "absl/flags/flag.h"
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpcpp/security/server_credentials.h>
#include "test/core/end2end/data/ssl_test_data.h" #include "test/core/end2end/data/ssl_test_data.h"
DEFINE_string(tls_cert_file, "", "The TLS cert file used when --use_tls=true"); ABSL_FLAG(std::string, tls_cert_file, "",
DEFINE_string(tls_key_file, "", "The TLS key file used when --use_tls=true"); "The TLS cert file used when --use_tls=true");
ABSL_FLAG(std::string, tls_key_file, "",
"The TLS key file used when --use_tls=true");
namespace grpc { namespace grpc {
namespace testing { namespace testing {
@ -56,11 +57,11 @@ std::string ReadFile(const std::string& src_path) {
class DefaultCredentialsProvider : public CredentialsProvider { class DefaultCredentialsProvider : public CredentialsProvider {
public: public:
DefaultCredentialsProvider() { DefaultCredentialsProvider() {
if (!FLAGS_tls_key_file.empty()) { if (!absl::GetFlag(FLAGS_tls_key_file).empty()) {
custom_server_key_ = ReadFile(FLAGS_tls_key_file); custom_server_key_ = ReadFile(absl::GetFlag(FLAGS_tls_key_file));
} }
if (!FLAGS_tls_cert_file.empty()) { if (!absl::GetFlag(FLAGS_tls_cert_file).empty()) {
custom_server_cert_ = ReadFile(FLAGS_tls_cert_file); custom_server_cert_ = ReadFile(absl::GetFlag(FLAGS_tls_cert_file));
} }
} }
~DefaultCredentialsProvider() override {} ~DefaultCredentialsProvider() override {}

Loading…
Cancel
Save