diff --git a/.clang-tidy b/.clang-tidy index 82231364895..0c24a6df792 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,6 +1,8 @@ --- +# Disable abseil-no-namespace: https://bugs.llvm.org/show_bug.cgi?id=47947 Checks: '-*, abseil-*, + -abseil-no-namespace, bugprone-*, -bugprone-integer-division, -bugprone-narrowing-conversions, diff --git a/CMakeLists.txt b/CMakeLists.txt index ef336f89b9e..516d64ce3a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3255,6 +3255,7 @@ target_link_libraries(grpc++_test_config ${_gRPC_PROTOBUF_LIBRARIES} ${_gRPC_ALLTARGETS_LIBRARIES} gpr + absl::flags_parse ${_gRPC_GFLAGS_LIBRARIES} ) @@ -3316,6 +3317,7 @@ target_link_libraries(grpc++_test_util gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -9354,6 +9356,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) address_sorting upb ${_gRPC_BENCHMARK_LIBRARIES} + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -10164,6 +10167,7 @@ target_link_libraries(cli_call_test gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -11350,6 +11354,7 @@ target_link_libraries(grpc_cli gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -11755,6 +11760,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -12104,6 +12110,7 @@ target_link_libraries(http2_client gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -12338,6 +12345,7 @@ target_link_libraries(interop_client gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -12394,6 +12402,7 @@ target_link_libraries(interop_server gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -12437,6 +12446,7 @@ if(_gRPC_PLATFORM_LINUX OR _gRPC_PLATFORM_MAC OR _gRPC_PLATFORM_POSIX) gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -13208,6 +13218,7 @@ target_link_libraries(qps_json_driver gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -13288,6 +13299,7 @@ target_link_libraries(qps_worker gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15404,6 +15416,7 @@ target_link_libraries(xds_interop_client gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15457,6 +15470,7 @@ target_link_libraries(xds_interop_server gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15498,6 +15512,7 @@ target_link_libraries(alts_credentials_fuzzer_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15539,6 +15554,7 @@ target_link_libraries(client_fuzzer_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15580,6 +15596,7 @@ target_link_libraries(hpack_parser_fuzzer_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15621,6 +15638,7 @@ target_link_libraries(http_request_fuzzer_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15662,6 +15680,7 @@ target_link_libraries(http_response_fuzzer_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15703,6 +15722,7 @@ target_link_libraries(json_fuzzer_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15744,6 +15764,7 @@ target_link_libraries(nanopb_fuzzer_response_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15785,6 +15806,7 @@ target_link_libraries(nanopb_fuzzer_serverlist_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15826,6 +15848,7 @@ target_link_libraries(percent_decode_fuzzer_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15867,6 +15890,7 @@ target_link_libraries(percent_encode_fuzzer_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15908,6 +15932,7 @@ target_link_libraries(server_fuzzer_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15949,6 +15974,7 @@ target_link_libraries(ssl_server_fuzzer_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) @@ -15990,6 +16016,7 @@ target_link_libraries(uri_fuzzer_test_one_entry gpr address_sorting upb + absl::flags ${_gRPC_GFLAGS_LIBRARIES} ) diff --git a/bazel/grpc_deps.bzl b/bazel/grpc_deps.bzl index 37b2cb0585c..84d6079a8f1 100644 --- a/bazel/grpc_deps.bzl +++ b/bazel/grpc_deps.bzl @@ -86,11 +86,6 @@ def grpc_deps(): actual = "@com_github_google_re2//:re2", ) - native.bind( - name = "gflags", - actual = "@com_github_gflags_gflags//:gflags", - ) - native.bind( name = "grpc_cpp_plugin", actual = "@com_github_grpc_grpc//src/compiler:grpc_cpp_plugin", diff --git a/build_autogenerated.yaml b/build_autogenerated.yaml index 06b09792502..e2ef8520f41 100644 --- a/build_autogenerated.yaml +++ b/build_autogenerated.yaml @@ -2420,6 +2420,7 @@ libs: - test/cpp/util/test_config_cc.cc deps: - gpr + - absl/flags:parse - name: grpc++_test_util build: private language: c++ @@ -2448,6 +2449,7 @@ libs: - gpr - address_sorting - upb + - absl/flags:flag - name: grpc++_unsecure build: all language: c++ @@ -4746,6 +4748,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/security/corpus/alts_credentials_corpus maxlen: 2048 @@ -5239,6 +5242,7 @@ targets: - address_sorting - upb - benchmark + - absl/flags:flag benchmark: true defaults: benchmark platforms: @@ -5586,6 +5590,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: client_callback_end2end_test gtest: true build: test @@ -5649,6 +5654,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/end2end/fuzzers/client_fuzzer_corpus dict: test/core/end2end/fuzzers/hpack.dictionary @@ -6061,6 +6067,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: grpc_cpp_plugin build: protoc language: c++ @@ -6182,6 +6189,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag platforms: - linux - posix @@ -6315,6 +6323,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/transport/chttp2/hpack_parser_corpus dict: test/core/end2end/fuzzers/hpack.dictionary @@ -6338,6 +6347,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: http_request_fuzzer_test build: fuzzer language: c++ @@ -6352,6 +6362,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/http/request_corpus maxlen: 2048 @@ -6369,6 +6380,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/http/response_corpus maxlen: 2048 @@ -6462,6 +6474,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: interop_server build: test run: false @@ -6484,6 +6497,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: interop_test build: test language: c++ @@ -6499,6 +6513,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag platforms: - linux - posix @@ -6517,6 +6532,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/json/corpus maxlen: 512 @@ -6654,6 +6670,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/nanopb/corpus_response maxlen: 128 @@ -6671,6 +6688,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/nanopb/corpus_serverlist maxlen: 128 @@ -6751,6 +6769,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/slice/percent_decode_corpus maxlen: 32 @@ -6768,6 +6787,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/slice/percent_encode_corpus maxlen: 32 @@ -6894,6 +6914,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: qps_worker build: test run: false @@ -6936,6 +6957,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: raw_end2end_test gtest: true build: test @@ -7153,6 +7175,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/end2end/fuzzers/server_fuzzer_corpus dict: test/core/end2end/fuzzers/hpack.dictionary @@ -7315,6 +7338,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/security/corpus/ssl_server_corpus maxlen: 2048 @@ -7611,6 +7635,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag corpus_dirs: - test/core/uri/uri_corpus maxlen: 128 @@ -7811,6 +7836,7 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag - name: xds_interop_server build: test run: false @@ -7829,4 +7855,5 @@ targets: - gpr - address_sorting - upb + - absl/flags:flag tests: [] diff --git a/grpc.gyp b/grpc.gyp index 1aa768c519f..c296094e1b0 100644 --- a/grpc.gyp +++ b/grpc.gyp @@ -1493,6 +1493,7 @@ 'type': 'static_library', 'dependencies': [ 'gpr', + 'absl/flags:parse', ], 'sources': [ 'test/cpp/util/test_config_cc.cc', @@ -1508,6 +1509,7 @@ 'gpr', 'address_sorting', 'upb', + 'absl/flags:flag', ], 'sources': [ 'test/core/end2end/data/client_certs.cc', diff --git a/test/core/tsi/alts/fake_handshaker/BUILD b/test/core/tsi/alts/fake_handshaker/BUILD index d5216cffd66..44f57c41969 100644 --- a/test/core/tsi/alts/fake_handshaker/BUILD +++ b/test/core/tsi/alts/fake_handshaker/BUILD @@ -53,6 +53,9 @@ grpc_cc_binary( name = "fake_handshaker_server", testonly = True, srcs = ["fake_handshaker_server_main.cc"], + external_deps = [ + "absl/flags:flag", + ], language = "C++", deps = [ "fake_handshaker_lib", diff --git a/test/core/tsi/alts/fake_handshaker/fake_handshaker_server_main.cc b/test/core/tsi/alts/fake_handshaker/fake_handshaker_server_main.cc index 48e16e6a266..9e444e3124f 100644 --- a/test/core/tsi/alts/fake_handshaker/fake_handshaker_server_main.cc +++ b/test/core/tsi/alts/fake_handshaker/fake_handshaker_server_main.cc @@ -15,20 +15,19 @@ * limitations under the License. * */ -#include "test/core/tsi/alts/fake_handshaker/fake_handshaker_server.h" - -#include - -#include #include #include #include +#include + +#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/cpp/util/test_config.h" -DEFINE_int32(handshaker_port, 55056, - "TCP port on which the fake handshaker server listens to."); +ABSL_FLAG(int32_t, handshaker_port, 55056, + "TCP port on which the fake handshaker server listens to."); static void RunFakeHandshakerServer(const std::string& server_address) { std::unique_ptr service = @@ -47,9 +46,9 @@ int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); grpc::testing::InitTest(&argc, &argv, true); - GPR_ASSERT(FLAGS_handshaker_port != 0); + GPR_ASSERT(absl::GetFlag(FLAGS_handshaker_port) != 0); std::ostringstream server_address; - server_address << "[::1]:" << FLAGS_handshaker_port; + server_address << "[::1]:" << absl::GetFlag(FLAGS_handshaker_port); RunFakeHandshakerServer(server_address.str()); return 0; diff --git a/test/core/util/BUILD b/test/core/util/BUILD index ce16ccbc0cd..0ca913bdb1d 100644 --- a/test/core/util/BUILD +++ b/test/core/util/BUILD @@ -136,8 +136,8 @@ grpc_cc_library( testonly = 1, srcs = ["fuzzer_corpus_test.cc"], external_deps = [ + "absl/flags:flag", "gtest", - "gflags", ], tags = ["no_windows"], deps = [ diff --git a/test/core/util/fuzzer_corpus_test.cc b/test/core/util/fuzzer_corpus_test.cc index 25b6a24a7c0..9e9d24ba367 100644 --- a/test/core/util/fuzzer_corpus_test.cc +++ b/test/core/util/fuzzer_corpus_test.cc @@ -16,18 +16,16 @@ * */ -#include - #include -#include +#include #include #include #include +#include #include #include -#include - +#include "absl/flags/flag.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/iomgr/load_file.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 leak_check; -// In some distros, gflags is in the namespace google, and in some others, -// in gflags. This hack is enabling us to find both. -namespace google {} -namespace gflags {} -using namespace google; -using namespace gflags; - -DEFINE_string(file, "", "Use this file as test data"); -DEFINE_string(directory, "", "Use this directory as test data"); +ABSL_FLAG(std::string, file, "", "Use this file as test data"); +ABSL_FLAG(std::string, directory, "", "Use this directory as test data"); class FuzzerCorpusTest : public ::testing::TestWithParam {}; @@ -81,11 +72,12 @@ class ExampleGenerator private: void Materialize() const { if (examples_.empty()) { - if (!FLAGS_file.empty()) examples_.push_back(FLAGS_file); - if (!FLAGS_directory.empty()) { + if (!absl::GetFlag(FLAGS_file).empty()) + examples_.push_back(absl::GetFlag(FLAGS_file)); + if (!absl::GetFlag(FLAGS_directory).empty()) { char* test_srcdir = gpr_getenv("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) { directory = test_srcdir + std::string("/com_github_grpc_grpc/") + directory; diff --git a/test/cpp/codegen/BUILD b/test/cpp/codegen/BUILD index 5ee231e8fc9..b7bad5f67e4 100644 --- a/test/cpp/codegen/BUILD +++ b/test/cpp/codegen/BUILD @@ -63,8 +63,8 @@ grpc_cc_binary( testonly = True, srcs = ["golden_file_test.cc"], external_deps = [ + "absl/flags:flag", "gtest", - "gflags", ], deps = [ "//:grpc++", diff --git a/test/cpp/codegen/golden_file_test.cc b/test/cpp/codegen/golden_file_test.cc index f6492bb9cbc..66053f8a2ca 100644 --- a/test/cpp/codegen/golden_file_test.cc +++ b/test/cpp/codegen/golden_file_test.cc @@ -16,24 +16,17 @@ * */ +#include + #include #include -#include -#include - +#include "absl/flags/flag.h" #include "test/core/util/test_config.h" #include "test/cpp/util/test_config.h" -// In some distros, gflags is in the namespace google, and in some others, -// in gflags. This hack is enabling us to find both. -namespace google {} -namespace gflags {} -using namespace google; -using namespace gflags; - -DEFINE_string( - generated_file_path, "", +ABSL_FLAG( + std::string, generated_file_path, "", "path to the directory containing generated files compiler_test.grpc.pb.h " "and compiler_test_mock.grpc.pb.h"); @@ -59,23 +52,25 @@ void run_test(const std::basic_string& generated_file, } 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); } TEST(GoldenMockFileTest, TestGeneratedMockFile) { - run_test(FLAGS_generated_file_path + "compiler_test_mock.grpc.pb.h", - kMockGoldenFilePath); + run_test( + absl::GetFlag(FLAGS_generated_file_path) + "compiler_test_mock.grpc.pb.h", + kMockGoldenFilePath); } int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); grpc::testing::InitTest(&argc, &argv, true); - if (FLAGS_generated_file_path.empty()) { - FLAGS_generated_file_path = "gens/src/proto/grpc/testing/"; + if (absl::GetFlag(FLAGS_generated_file_path).empty()) { + absl::SetFlag(&FLAGS_generated_file_path, "gens/src/proto/grpc/testing/"); } - if (FLAGS_generated_file_path.back() != '/') - FLAGS_generated_file_path.append("/"); + if (absl::GetFlag(FLAGS_generated_file_path).back() != '/') + absl::SetFlag(&FLAGS_generated_file_path, + absl::GetFlag(FLAGS_generated_file_path).append("/")); return RUN_ALL_TESTS(); } diff --git a/test/cpp/end2end/BUILD b/test/cpp/end2end/BUILD index 27e73fc145b..d140a359b10 100644 --- a/test/cpp/end2end/BUILD +++ b/test/cpp/end2end/BUILD @@ -139,7 +139,7 @@ grpc_cc_binary( testonly = True, srcs = ["client_crash_test_server.cc"], external_deps = [ - "gflags", + "absl/flags:flag", "gtest", ], deps = [ @@ -544,7 +544,6 @@ grpc_cc_test( srcs = ["proto_server_reflection_test.cc"], external_deps = [ "gtest", - "gflags", ], deps = [ ":test_service_impl", @@ -611,7 +610,7 @@ grpc_cc_binary( testonly = True, srcs = ["server_crash_test_client.cc"], external_deps = [ - "gflags", + "absl/flags:flag", "gtest", ], deps = [ diff --git a/test/cpp/end2end/client_crash_test_server.cc b/test/cpp/end2end/client_crash_test_server.cc index 2fc44dc0ee6..1adf98d1461 100644 --- a/test/cpp/end2end/client_crash_test_server.cc +++ b/test/cpp/end2end/client_crash_test_server.cc @@ -16,31 +16,24 @@ * */ -#include -#include -#include -#include - #include #include #include #include +#include +#include +#include + +#include "absl/flags/flag.h" #include "src/proto/grpc/testing/echo.grpc.pb.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::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 testing { @@ -63,10 +56,12 @@ void RunServer() { ServiceImpl service; ServerBuilder builder; - builder.AddListeningPort(FLAGS_address, grpc::InsecureServerCredentials()); + builder.AddListeningPort(absl::GetFlag(FLAGS_address), + grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr 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(); } } // namespace testing diff --git a/test/cpp/end2end/server_crash_test_client.cc b/test/cpp/end2end/server_crash_test_client.cc index b261560470d..57d04a1f8df 100644 --- a/test/cpp/end2end/server_crash_test_client.cc +++ b/test/cpp/end2end/server_crash_test_client.cc @@ -16,37 +16,37 @@ * */ -#include -#include -#include -#include -#include - #include #include #include #include +#include +#include +#include +#include + +#include "absl/flags/flag.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" #include "test/cpp/util/test_config.h" -DEFINE_string(address, "", "Address to connect to"); -DEFINE_string(mode, "", "Test mode to use"); +ABSL_FLAG(std::string, address, "", "Address to connect to"); +ABSL_FLAG(std::string, mode, "", "Test mode to use"); using grpc::testing::EchoRequest; using grpc::testing::EchoResponse; int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); - auto stub = grpc::testing::EchoTestService::NewStub( - grpc::CreateChannel(FLAGS_address, grpc::InsecureChannelCredentials())); + auto stub = grpc::testing::EchoTestService::NewStub(grpc::CreateChannel( + absl::GetFlag(FLAGS_address), grpc::InsecureChannelCredentials())); EchoRequest request; EchoResponse response; grpc::ClientContext context; context.set_wait_for_ready(true); - if (FLAGS_mode == "bidi") { + if (absl::GetFlag(FLAGS_mode) == "bidi") { auto stream = stub->BidiStream(&context); for (int i = 0;; i++) { std::ostringstream msg; @@ -56,7 +56,7 @@ int main(int argc, char** argv) { GPR_ASSERT(stream->Read(&response)); GPR_ASSERT(response.message() == request.message()); } - } else if (FLAGS_mode == "response") { + } else if (absl::GetFlag(FLAGS_mode) == "response") { EchoRequest request; request.set_message("Hello"); auto stream = stub->ResponseStream(&context, request); @@ -64,7 +64,8 @@ int main(int argc, char** argv) { GPR_ASSERT(stream->Read(&response)); } } 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; } diff --git a/test/cpp/interop/BUILD b/test/cpp/interop/BUILD index c54cc4719e0..1f53c6a3dd9 100644 --- a/test/cpp/interop/BUILD +++ b/test/cpp/interop/BUILD @@ -30,7 +30,7 @@ grpc_cc_library( "server_helper.h", ], external_deps = [ - "gflags", + "absl/flags:flag", ], language = "C++", deps = [ @@ -43,6 +43,9 @@ grpc_cc_binary( srcs = [ "grpclb_fallback_test.cc", ], + external_deps = [ + "absl/flags:flag", + ], language = "C++", tags = ["no_windows"], deps = [ @@ -60,6 +63,9 @@ grpc_cc_binary( srcs = [ "interop_server_bootstrap.cc", ], + external_deps = [ + "absl/flags:flag", + ], language = "C++", deps = [ ":interop_server_lib", @@ -92,6 +98,9 @@ grpc_cc_library( "client_helper.h", "interop_client.h", ], + external_deps = [ + "absl/flags:flag", + ], language = "C++", deps = [ "//src/proto/grpc/testing:empty_proto", @@ -108,6 +117,9 @@ grpc_cc_library( srcs = [ "client.cc", ], + external_deps = [ + "absl/flags:flag", + ], language = "C++", deps = [ ":client_helper_lib", @@ -127,7 +139,7 @@ grpc_cc_binary( name = "metrics_client", srcs = ["metrics_client.cc"], external_deps = [ - "gflags", + "absl/flags:flag", ], language = "C++", deps = [ @@ -142,6 +154,9 @@ grpc_cc_binary( srcs = [ "reconnect_interop_client.cc", ], + external_deps = [ + "absl/flags:flag", + ], deps = [ ":client_helper_lib", "//:grpc++", @@ -154,6 +169,9 @@ grpc_cc_binary( srcs = [ "reconnect_interop_server.cc", ], + external_deps = [ + "absl/flags:flag", + ], language = "C++", deps = [ ":interop_server_lib", @@ -169,6 +187,9 @@ grpc_cc_binary( "stress_interop_client.h", "stress_test.cc", ], + external_deps = [ + "absl/flags:flag", + ], deps = [ ":client_helper_lib", "//:grpc++", @@ -185,7 +206,7 @@ grpc_cc_test( ":interop_server", ], external_deps = [ - "gflags", + "absl/flags:flag", ], tags = ["no_windows"], deps = [ @@ -203,6 +224,9 @@ grpc_cc_binary( srcs = [ "xds_interop_client.cc", ], + external_deps = [ + "absl/flags:flag", + ], deps = [ "//:grpc++", "//src/proto/grpc/testing:empty_proto", @@ -218,6 +242,9 @@ grpc_cc_binary( srcs = [ "xds_interop_server.cc", ], + external_deps = [ + "absl/flags:flag", + ], deps = [ "//:grpc++", "//src/proto/grpc/testing:empty_proto", @@ -234,6 +261,9 @@ grpc_cc_binary( "http2_client.cc", "http2_client.h", ], + external_deps = [ + "absl/flags:flag", + ], deps = [ "//:grpc++", "//src/proto/grpc/testing:empty_proto", diff --git a/test/cpp/interop/client.cc b/test/cpp/interop/client.cc index 9267522c812..32450d4a4f3 100644 --- a/test/cpp/interop/client.cc +++ b/test/cpp/interop/client.cc @@ -16,33 +16,34 @@ * */ -#include -#include - -#include #include #include #include #include #include +#include +#include + +#include "absl/flags/flag.h" #include "src/core/lib/gpr/string.h" #include "test/core/util/test_config.h" #include "test/cpp/interop/client_helper.h" #include "test/cpp/interop/interop_client.h" #include "test/cpp/util/test_config.h" -DEFINE_bool(use_alts, false, - "Whether to use alts. Enable alts will disable tls."); -DEFINE_bool(use_tls, false, "Whether to use tls."); -DEFINE_string(custom_credentials_type, "", "User provided credentials type."); -DEFINE_bool(use_test_ca, false, "False to use SSL roots for google"); -DEFINE_int32(server_port, 0, "Server port."); -DEFINE_string(server_host, "localhost", "Server host to connect to"); -DEFINE_string(server_host_override, "", - "Override the server host which is sent in HTTP header"); -DEFINE_string( - test_case, "large_unary", +ABSL_FLAG(bool, use_alts, false, + "Whether to use alts. Enable alts will disable tls."); +ABSL_FLAG(bool, use_tls, false, "Whether to use tls."); +ABSL_FLAG(std::string, custom_credentials_type, "", + "User provided credentials type."); +ABSL_FLAG(bool, use_test_ca, false, "False to use SSL roots for google"); +ABSL_FLAG(int32_t, server_port, 0, "Server port."); +ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to"); +ABSL_FLAG(std::string, server_host_override, "", + "Override the server host which is sent in HTTP header"); +ABSL_FLAG( + std::string, test_case, "large_unary", "Configure different test cases. Valid options are:\n\n" "all : all test cases;\n" "cancel_after_begin : cancel stream after starting it;\n" @@ -75,39 +76,39 @@ DEFINE_string( "timeout_on_sleeping_server: deadline exceeds on stream;\n" "unimplemented_method: client calls an unimplemented method;\n" "unimplemented_service: client calls an unimplemented service;\n"); -DEFINE_string(default_service_account, "", - "Email of GCE default service account"); -DEFINE_string(service_account_key_file, "", - "Path to service account json key file."); -DEFINE_string(oauth_scope, "", "Scope for OAuth tokens."); -DEFINE_bool(do_not_abort_on_transient_failures, false, - "If set to 'true', abort() is not called in case of transient " - "failures (i.e failures that are temporary and will likely go away " - "on retrying; like a temporary connection failure) and an error " - "message is printed instead. Note that this flag just controls " - "whether abort() is called or not. It does not control whether 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)"); -DEFINE_int32(soak_iterations, 1000, - "The number of iterations to use for the two soak tests; rpc_soak " - "and channel_soak."); -DEFINE_int32(soak_max_failures, 0, - "The number of iterations in soak tests that are allowed to fail " - "(either due to non-OK status code or exceeding the " - "per-iteration max acceptable latency)."); -DEFINE_int32(soak_per_iteration_max_acceptable_latency_ms, 0, - "The number of milliseconds a single iteration in the two soak " - "tests (rpc_soak and channel_soak) should take."); -DEFINE_int32(soak_overall_timeout_seconds, 0, - "The overall number of seconds after which a soak test should " - "stop and fail, if the desired number of iterations have not yet " - "completed."); -DEFINE_int32(iteration_interval, 10, - "The interval in seconds between rpcs. This is used by " - "long_connection test"); -DEFINE_string(additional_metadata, "", - "Additional metadata to send in each request, as a " - "semicolon-separated list of key:value pairs."); +ABSL_FLAG(std::string, default_service_account, "", + "Email of GCE default service account"); +ABSL_FLAG(std::string, service_account_key_file, "", + "Path to service account json key file."); +ABSL_FLAG(std::string, oauth_scope, "", "Scope for OAuth tokens."); +ABSL_FLAG(bool, do_not_abort_on_transient_failures, false, + "If set to 'true', abort() is not called in case of transient " + "failures (i.e failures that are temporary and will likely go away " + "on retrying; like a temporary connection failure) and an error " + "message is printed instead. Note that this flag just controls " + "whether abort() is called or not. It does not control whether 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)"); +ABSL_FLAG(int32_t, soak_iterations, 1000, + "The number of iterations to use for the two soak tests; rpc_soak " + "and channel_soak."); +ABSL_FLAG(int32_t, soak_max_failures, 0, + "The number of iterations in soak tests that are allowed to fail " + "(either due to non-OK status code or exceeding the " + "per-iteration max acceptable latency)."); +ABSL_FLAG(int32_t, soak_per_iteration_max_acceptable_latency_ms, 0, + "The number of milliseconds a single iteration in the two soak " + "tests (rpc_soak and channel_soak) should take."); +ABSL_FLAG(int32_t, soak_overall_timeout_seconds, 0, + "The overall number of seconds after which a soak test should " + "stop and fail, if the desired number of iterations have not yet " + "completed."); +ABSL_FLAG(int32_t, iteration_interval, 10, + "The interval in seconds between rpcs. This is used by " + "long_connection test"); +ABSL_FLAG(std::string, additional_metadata, "", + "Additional metadata to send in each request, as a " + "semicolon-separated list of key:value pairs."); using grpc::testing::CreateChannelForTestCase; using grpc::testing::GetServiceAccountJsonKey; @@ -174,18 +175,19 @@ bool ParseAdditionalMetadataFlag( int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); 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; grpc::testing::ChannelCreationFunc channel_creation_func; - std::string test_case = FLAGS_test_case; - if (FLAGS_additional_metadata.empty()) { + std::string test_case = absl::GetFlag(FLAGS_test_case); + if (absl::GetFlag(FLAGS_additional_metadata).empty()) { channel_creation_func = [test_case]() { return CreateChannelForTestCase(test_case); }; } else { std::multimap additional_metadata; - if (!ParseAdditionalMetadataFlag(FLAGS_additional_metadata, + if (!ParseAdditionalMetadataFlag(absl::GetFlag(FLAGS_additional_metadata), &additional_metadata)) { return 1; } @@ -201,8 +203,9 @@ int main(int argc, char** argv) { }; } - grpc::testing::InteropClient client(channel_creation_func, true, - FLAGS_do_not_abort_on_transient_failures); + grpc::testing::InteropClient client( + channel_creation_func, true, + absl::GetFlag(FLAGS_do_not_abort_on_transient_failures)); std::unordered_map> actions; actions["empty_unary"] = @@ -238,24 +241,27 @@ int main(int argc, char** argv) { std::bind(&grpc::testing::InteropClient::DoEmptyStream, &client); actions["pick_first_unary"] = std::bind(&grpc::testing::InteropClient::DoPickFirstUnary, &client); - if (FLAGS_use_tls) { + if (absl::GetFlag(FLAGS_use_tls)) { actions["compute_engine_creds"] = 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"] = std::bind(&grpc::testing::InteropClient::DoJwtTokenCreds, &client, GetServiceAccountJsonKey()); actions["oauth2_auth_token"] = 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"] = std::bind(&grpc::testing::InteropClient::DoPerRpcCreds, &client, GetServiceAccountJsonKey()); } - if (FLAGS_custom_credentials_type == "google_default_credentials") { + if (absl::GetFlag(FLAGS_custom_credentials_type) == + "google_default_credentials") { actions["google_default_credentials"] = std::bind(&grpc::testing::InteropClient::DoGoogleDefaultCredentials, - &client, FLAGS_default_service_account); + &client, absl::GetFlag(FLAGS_default_service_account)); } actions["status_code_and_message"] = std::bind(&grpc::testing::InteropClient::DoStatusWithMessage, &client); @@ -269,28 +275,31 @@ int main(int argc, char** argv) { std::bind(&grpc::testing::InteropClient::DoUnimplementedService, &client); actions["cacheable_unary"] = std::bind(&grpc::testing::InteropClient::DoCacheableUnary, &client); - actions["channel_soak"] = - std::bind(&grpc::testing::InteropClient::DoChannelSoakTest, &client, - FLAGS_soak_iterations, FLAGS_soak_max_failures, - FLAGS_soak_per_iteration_max_acceptable_latency_ms, - FLAGS_soak_overall_timeout_seconds); - actions["rpc_soak"] = - std::bind(&grpc::testing::InteropClient::DoRpcSoakTest, &client, - FLAGS_soak_iterations, FLAGS_soak_max_failures, - FLAGS_soak_per_iteration_max_acceptable_latency_ms, - FLAGS_soak_overall_timeout_seconds); + actions["channel_soak"] = std::bind( + &grpc::testing::InteropClient::DoChannelSoakTest, &client, + absl::GetFlag(FLAGS_soak_iterations), + absl::GetFlag(FLAGS_soak_max_failures), + absl::GetFlag(FLAGS_soak_per_iteration_max_acceptable_latency_ms), + absl::GetFlag(FLAGS_soak_overall_timeout_seconds)); + actions["rpc_soak"] = std::bind( + &grpc::testing::InteropClient::DoRpcSoakTest, &client, + absl::GetFlag(FLAGS_soak_iterations), + 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"] = 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); - if (FLAGS_test_case == "all") { + if (absl::GetFlag(FLAGS_test_case) == "all") { for (const auto& action : actions) { action.second(); } - } else if (actions.find(FLAGS_test_case) != actions.end()) { - actions.find(FLAGS_test_case)->second(); + } else if (actions.find(absl::GetFlag(FLAGS_test_case)) != actions.end()) { + actions.find(absl::GetFlag(FLAGS_test_case))->second(); } else { std::string test_cases; for (const auto& action : actions) { @@ -298,7 +307,7 @@ int main(int argc, char** argv) { test_cases += action.first; } 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; } diff --git a/test/cpp/interop/client_helper.cc b/test/cpp/interop/client_helper.cc index f43e315fbd9..29c5437551b 100644 --- a/test/cpp/interop/client_helper.cc +++ b/test/cpp/interop/client_helper.cc @@ -18,11 +18,6 @@ #include "test/cpp/interop/client_helper.h" -#include -#include -#include - -#include #include #include #include @@ -30,22 +25,27 @@ #include #include +#include +#include +#include + +#include "absl/flags/flag.h" #include "src/cpp/client/secure_credentials.h" #include "test/core/security/oauth2_utils.h" #include "test/cpp/util/create_test_channel.h" #include "test/cpp/util/test_credentials_provider.h" -DECLARE_bool(use_alts); -DECLARE_bool(use_tls); -DECLARE_string(custom_credentials_type); -DECLARE_bool(use_test_ca); -DECLARE_int32(server_port); -DECLARE_string(server_host); -DECLARE_string(server_host_override); -DECLARE_string(test_case); -DECLARE_string(default_service_account); -DECLARE_string(service_account_key_file); -DECLARE_string(oauth_scope); +ABSL_DECLARE_FLAG(bool, use_alts); +ABSL_DECLARE_FLAG(bool, use_tls); +ABSL_DECLARE_FLAG(std::string, custom_credentials_type); +ABSL_DECLARE_FLAG(bool, use_test_ca); +ABSL_DECLARE_FLAG(int32_t, server_port); +ABSL_DECLARE_FLAG(std::string, server_host); +ABSL_DECLARE_FLAG(std::string, server_host_override); +ABSL_DECLARE_FLAG(std::string, test_case); +ABSL_DECLARE_FLAG(std::string, default_service_account); +ABSL_DECLARE_FLAG(std::string, service_account_key_file); +ABSL_DECLARE_FLAG(std::string, oauth_scope); namespace grpc { namespace testing { @@ -53,7 +53,7 @@ namespace testing { std::string GetServiceAccountJsonKey() { static std::string json_key; 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; key_stream << json_key_file.rdbuf(); json_key = key_stream.str(); @@ -83,48 +83,58 @@ std::shared_ptr CreateChannelForTestCase( std::vector< std::unique_ptr> interceptor_creators) { - GPR_ASSERT(FLAGS_server_port); + GPR_ASSERT(absl::GetFlag(FLAGS_server_port)); const int host_port_buf_size = 1024; char host_port[host_port_buf_size]; - snprintf(host_port, host_port_buf_size, "%s:%d", FLAGS_server_host.c_str(), - FLAGS_server_port); + snprintf(host_port, host_port_buf_size, "%s:%d", + absl::GetFlag(FLAGS_server_host).c_str(), + absl::GetFlag(FLAGS_server_port)); std::shared_ptr 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 : GoogleComputeEngineCredentials(); } else if (test_case == "jwt_token_creds") { std::string json_key = GetServiceAccountJsonKey(); 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 : ServiceAccountJWTAccessCredentials(json_key, token_lifetime.count()); } 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 : AccessTokenCredentials(GetOauth2AccessToken()); } else if (test_case == "pick_first_unary") { ChannelArguments channel_args; // allow the LB policy to be configured with service config channel_args.SetInt(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, 0); - return CreateTestChannel(host_port, FLAGS_custom_credentials_type, - FLAGS_server_host_override, !FLAGS_use_test_ca, - creds, channel_args); + return CreateTestChannel( + host_port, absl::GetFlag(FLAGS_custom_credentials_type), + 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 = - FLAGS_use_alts ? ALTS : (FLAGS_use_tls ? TLS : INSECURE); - return CreateTestChannel(host_port, FLAGS_server_host_override, - security_type, !FLAGS_use_test_ca, creds, - std::move(interceptor_creators)); + absl::GetFlag(FLAGS_use_alts) + ? ALTS + : (absl::GetFlag(FLAGS_use_tls) ? TLS : INSECURE); + return CreateTestChannel(host_port, + absl::GetFlag(FLAGS_server_host_override), + security_type, !absl::GetFlag(FLAGS_use_test_ca), + creds, std::move(interceptor_creators)); } else { 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 { - return CreateTestChannel(host_port, FLAGS_custom_credentials_type, creds, - std::move(interceptor_creators)); + return CreateTestChannel(host_port, + absl::GetFlag(FLAGS_custom_credentials_type), + creds, std::move(interceptor_creators)); } } } diff --git a/test/cpp/interop/grpclb_fallback_test.cc b/test/cpp/interop/grpclb_fallback_test.cc index cb3e62adde7..28c358b2463 100644 --- a/test/cpp/interop/grpclb_fallback_test.cc +++ b/test/cpp/interop/grpclb_fallback_test.cc @@ -16,49 +16,47 @@ * */ -#include - -#include "src/core/lib/iomgr/port.h" - #include #include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include #include #include + #include #include #include #include #include -#include -#include -#include -#include -#include -#include - +#include "absl/flags/flag.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/proto/grpc/testing/empty.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.pb.h" - #include "test/cpp/util/test_config.h" #include "test/cpp/util/test_credentials_provider.h" -DEFINE_string(custom_credentials_type, "", "User provided credentials type."); -DEFINE_string(server_uri, "localhost:1000", "Server URI target"); -DEFINE_string(unroute_lb_and_backend_addrs_cmd, "exit 1", - "Shell command used to make LB and backend addresses unroutable"); -DEFINE_string(blackhole_lb_and_backend_addrs_cmd, "exit 1", - "Shell command used to make LB and backend addresses blackholed"); -DEFINE_string( - test_case, "", +ABSL_FLAG(std::string, custom_credentials_type, "", + "User provided credentials type."); +ABSL_FLAG(std::string, server_uri, "localhost:1000", "Server URI target"); +ABSL_FLAG(std::string, unroute_lb_and_backend_addrs_cmd, "exit 1", + "Shell command used to make LB and backend addresses unroutable"); +ABSL_FLAG(std::string, blackhole_lb_and_backend_addrs_cmd, "exit 1", + "Shell command used to make LB and backend addresses blackholed"); +ABSL_FLAG( + std::string, test_case, "", "Test case to run. Valid options are:\n\n" "fast_fallback_before_startup : fallback before establishing connection to " "LB;\n" @@ -170,9 +168,9 @@ std::unique_ptr CreateFallbackTestStub() { channel_args.SetInt(GRPC_ARG_SERVICE_CONFIG_DISABLE_RESOLUTION, 0); std::shared_ptr channel_creds = grpc::testing::GetCredentialsProvider()->GetChannelCredentials( - FLAGS_custom_credentials_type, &channel_args); - return TestService::NewStub( - grpc::CreateCustomChannel(FLAGS_server_uri, channel_creds, channel_args)); + absl::GetFlag(FLAGS_custom_credentials_type), &channel_args); + return TestService::NewStub(grpc::CreateCustomChannel( + absl::GetFlag(FLAGS_server_uri), channel_creds, channel_args)); } void RunCommand(const std::string& command) { @@ -209,11 +207,13 @@ void RunFallbackBeforeStartupTest( } void DoFastFallbackBeforeStartup() { - RunFallbackBeforeStartupTest(FLAGS_unroute_lb_and_backend_addrs_cmd, 9); + RunFallbackBeforeStartupTest( + absl::GetFlag(FLAGS_unroute_lb_and_backend_addrs_cmd), 9); } void DoSlowFallbackBeforeStartup() { - RunFallbackBeforeStartupTest(FLAGS_blackhole_lb_and_backend_addrs_cmd, 20); + RunFallbackBeforeStartupTest( + absl::GetFlag(FLAGS_blackhole_lb_and_backend_addrs_cmd), 20); } void RunFallbackAfterStartupTest( @@ -252,31 +252,34 @@ void RunFallbackAfterStartupTest( } void DoFastFallbackAfterStartup() { - RunFallbackAfterStartupTest(FLAGS_unroute_lb_and_backend_addrs_cmd); + RunFallbackAfterStartupTest( + absl::GetFlag(FLAGS_unroute_lb_and_backend_addrs_cmd)); } void DoSlowFallbackAfterStartup() { - RunFallbackAfterStartupTest(FLAGS_blackhole_lb_and_backend_addrs_cmd); + RunFallbackAfterStartupTest( + absl::GetFlag(FLAGS_blackhole_lb_and_backend_addrs_cmd)); } } // namespace int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); - gpr_log(GPR_INFO, "Testing: %s", FLAGS_test_case.c_str()); - if (FLAGS_test_case == "fast_fallback_before_startup") { + gpr_log(GPR_INFO, "Testing: %s", absl::GetFlag(FLAGS_test_case).c_str()); + if (absl::GetFlag(FLAGS_test_case) == "fast_fallback_before_startup") { DoFastFallbackBeforeStartup(); 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(); 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(); 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(); gpr_log(GPR_INFO, "DoSlowFallbackAfterStartup done!"); } 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(); } } diff --git a/test/cpp/interop/http2_client.cc b/test/cpp/interop/http2_client.cc index 3d6ac9f9660..5422fc82606 100644 --- a/test/cpp/interop/http2_client.cc +++ b/test/cpp/interop/http2_client.cc @@ -16,21 +16,21 @@ * */ -#include +#include "test/cpp/interop/http2_client.h" -#include #include #include #include #include -#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/interop/http2_client.h" +#include +#include "absl/flags/flag.h" #include "src/core/lib/gpr/string.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/test_config.h" @@ -176,42 +176,43 @@ bool Http2Client::DoMaxStreams() { } // namespace testing } // namespace grpc -DEFINE_int32(server_port, 0, "Server port."); -DEFINE_string(server_host, "localhost", "Server host to connect to"); -DEFINE_string(test_case, "rst_after_header", - "Configure different test cases. Valid options are:\n\n" - "goaway\n" - "max_streams\n" - "ping\n" - "rst_after_data\n" - "rst_after_header\n" - "rst_during_data\n"); +ABSL_FLAG(int32_t, server_port, 0, "Server port."); +ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to"); +ABSL_FLAG(std::string, test_case, "rst_after_header", + "Configure different test cases. Valid options are:\n\n" + "goaway\n" + "max_streams\n" + "ping\n" + "rst_after_data\n" + "rst_after_header\n" + "rst_during_data\n"); int main(int argc, char** argv) { 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; char host_port[host_port_buf_size]; - snprintf(host_port, host_port_buf_size, "%s:%d", FLAGS_server_host.c_str(), - FLAGS_server_port); + snprintf(host_port, host_port_buf_size, "%s:%d", + absl::GetFlag(FLAGS_server_host).c_str(), + absl::GetFlag(FLAGS_server_port)); std::shared_ptr channel = grpc::CreateTestChannel(host_port, grpc::testing::INSECURE); GPR_ASSERT(channel->WaitForConnected(gpr_time_add( gpr_now(GPR_CLOCK_REALTIME), gpr_time_from_seconds(300, GPR_TIMESPAN)))); 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; - if (FLAGS_test_case == "rst_after_header") { + if (absl::GetFlag(FLAGS_test_case) == "rst_after_header") { client.DoRstAfterHeader(); - } else if (FLAGS_test_case == "rst_after_data") { + } else if (absl::GetFlag(FLAGS_test_case) == "rst_after_data") { client.DoRstAfterData(); - } else if (FLAGS_test_case == "rst_during_data") { + } else if (absl::GetFlag(FLAGS_test_case) == "rst_during_data") { client.DoRstDuringData(); - } else if (FLAGS_test_case == "goaway") { + } else if (absl::GetFlag(FLAGS_test_case) == "goaway") { client.DoGoaway(); - } else if (FLAGS_test_case == "ping") { + } else if (absl::GetFlag(FLAGS_test_case) == "ping") { client.DoPing(); - } else if (FLAGS_test_case == "max_streams") { + } else if (absl::GetFlag(FLAGS_test_case) == "max_streams") { client.DoMaxStreams(); } else { const char* testcases[] = { @@ -221,7 +222,7 @@ int main(int argc, char** argv) { gpr_strjoin_sep(testcases, GPR_ARRAY_SIZE(testcases), "\n", nullptr); 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); ret = 1; } diff --git a/test/cpp/interop/interop_server.cc b/test/cpp/interop/interop_server.cc index 525020d7185..e6b718b84a1 100644 --- a/test/cpp/interop/interop_server.cc +++ b/test/cpp/interop/interop_server.cc @@ -16,12 +16,6 @@ * */ -#include -#include -#include -#include - -#include #include #include #include @@ -30,6 +24,12 @@ #include #include +#include +#include +#include +#include + +#include "absl/flags/flag.h" #include "src/core/lib/gpr/string.h" #include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/messages.pb.h" @@ -37,12 +37,13 @@ #include "test/cpp/interop/server_helper.h" #include "test/cpp/util/test_config.h" -DEFINE_bool(use_alts, false, - "Whether to use alts. Enable alts will disable tls."); -DEFINE_bool(use_tls, false, "Whether to use tls."); -DEFINE_string(custom_credentials_type, "", "User provided credentials type."); -DEFINE_int32(port, 0, "Server port."); -DEFINE_int32(max_send_message_size, -1, "The maximum send message size."); +ABSL_FLAG(bool, use_alts, false, + "Whether to use alts. Enable alts will disable tls."); +ABSL_FLAG(bool, use_tls, false, "Whether to use tls."); +ABSL_FLAG(std::string, custom_credentials_type, "", + "User provided credentials type."); +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::ServerBuilder; @@ -317,14 +318,15 @@ class TestServiceImpl : public TestService::Service { void grpc::testing::interop::RunServer( const std::shared_ptr& creds) { - RunServer(creds, FLAGS_port, nullptr, nullptr); + RunServer(creds, absl::GetFlag(FLAGS_port), nullptr, nullptr); } void grpc::testing::interop::RunServer( const std::shared_ptr& creds, std::unique_ptr>> 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( @@ -354,8 +356,8 @@ void grpc::testing::interop::RunServer( builder.SetOption(std::move((*server_options)[i])); } } - if (FLAGS_max_send_message_size >= 0) { - builder.SetMaxSendMessageSize(FLAGS_max_send_message_size); + if (absl::GetFlag(FLAGS_max_send_message_size) >= 0) { + builder.SetMaxSendMessageSize(absl::GetFlag(FLAGS_max_send_message_size)); } std::unique_ptr server(builder.BuildAndStart()); gpr_log(GPR_INFO, "Server listening on %s", server_address.str().c_str()); diff --git a/test/cpp/interop/interop_test.cc b/test/cpp/interop/interop_test.cc index b16a0da11d0..8a92892cc66 100644 --- a/test/cpp/interop/interop_test.cc +++ b/test/cpp/interop/interop_test.cc @@ -17,6 +17,8 @@ */ #include +#include +#include #include #include #include @@ -28,18 +30,15 @@ #include #include +#include "absl/flags/flag.h" #include "absl/strings/str_cat.h" - -#include -#include -#include -#include "test/core/util/port.h" -#include "test/cpp/util/test_config.h" - #include "src/core/lib/gpr/string.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 status; @@ -91,8 +90,9 @@ int main(int argc, char** argv) { args.push_back(const_cast(command.c_str())); std::string port_arg = absl::StrCat("--port=", port); args.push_back(const_cast(port_arg.c_str())); - if (!FLAGS_extra_server_flags.empty()) { - args.push_back(const_cast(FLAGS_extra_server_flags.c_str())); + if (!absl::GetFlag(FLAGS_extra_server_flags).empty()) { + args.push_back( + const_cast(absl::GetFlag(FLAGS_extra_server_flags).c_str())); } args.push_back(nullptr); execv(args[0], args.data()); diff --git a/test/cpp/interop/metrics_client.cc b/test/cpp/interop/metrics_client.cc index b80a32e1d82..736182c950f 100644 --- a/test/cpp/interop/metrics_client.cc +++ b/test/cpp/interop/metrics_client.cc @@ -16,13 +16,13 @@ *is % allowed in string */ -#include -#include - -#include #include #include +#include +#include + +#include "absl/flags/flag.h" #include "src/proto/grpc/testing/metrics.grpc.pb.h" #include "src/proto/grpc/testing/metrics.pb.h" #include "test/cpp/util/metrics_server.h" @@ -30,12 +30,13 @@ int kDeadlineSecs = 10; -DEFINE_string(metrics_server_address, "localhost:8081", - "The metrics server addresses in the fomrat :"); -DEFINE_int32(deadline_secs, kDeadlineSecs, - "The deadline (in seconds) for RCP call"); -DEFINE_bool(total_only, false, - "If true, this prints only the total value of all gauges"); +ABSL_FLAG(std::string, metrics_server_address, "localhost:8081", + "The metrics server addresses in the fomrat :"); +// TODO(Capstan): Consider using absl::Duration +ABSL_FLAG(int32_t, deadline_secs, kDeadlineSecs, + "The deadline (in seconds) for RCP call"); +ABSL_FLAG(bool, total_only, false, + "If true, this prints only the total value of all gauges"); using grpc::testing::EmptyMessage; using grpc::testing::GaugeResponse; @@ -92,11 +93,13 @@ int main(int argc, char** argv) { // from the grpc library appearing on stdout. gpr_set_log_function(BlackholeLogger); - std::shared_ptr channel(grpc::CreateChannel( - FLAGS_metrics_server_address, grpc::InsecureChannelCredentials())); + std::shared_ptr channel( + grpc::CreateChannel(absl::GetFlag(FLAGS_metrics_server_address), + grpc::InsecureChannelCredentials())); - if (!PrintMetrics(MetricsService::NewStub(channel), FLAGS_total_only, - FLAGS_deadline_secs)) { + if (!PrintMetrics(MetricsService::NewStub(channel), + absl::GetFlag(FLAGS_total_only), + absl::GetFlag(FLAGS_deadline_secs))) { return 1; } diff --git a/test/cpp/interop/reconnect_interop_client.cc b/test/cpp/interop/reconnect_interop_client.cc index 8a071d417e6..f24b841fdab 100644 --- a/test/cpp/interop/reconnect_interop_client.cc +++ b/test/cpp/interop/reconnect_interop_client.cc @@ -16,26 +16,29 @@ * */ -#include -#include - -#include #include #include #include #include #include + +#include +#include + +#include "absl/flags/flag.h" #include "src/proto/grpc/testing/empty.pb.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/test_config.h" -DEFINE_int32(server_control_port, 0, "Server port for control rpcs."); -DEFINE_int32(server_retry_port, 0, "Server port for testing reconnection."); -DEFINE_string(server_host, "localhost", "Server host to connect to"); -DEFINE_int32(max_reconnect_backoff_ms, 0, - "Maximum backoff time, or 0 for default."); +ABSL_FLAG(int32_t, server_control_port, 0, "Server port for control rpcs."); +ABSL_FLAG(int32_t, server_retry_port, 0, + "Server port for testing reconnection."); +ABSL_FLAG(std::string, server_host, "localhost", "Server host to connect to"); +// 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::Channel; @@ -52,17 +55,19 @@ using grpc::testing::TLS; int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); - GPR_ASSERT(FLAGS_server_control_port); - GPR_ASSERT(FLAGS_server_retry_port); + GPR_ASSERT(absl::GetFlag(FLAGS_server_control_port)); + GPR_ASSERT(absl::GetFlag(FLAGS_server_retry_port)); 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 control_stub( ReconnectService::NewStub( CreateTestChannel(server_address.str(), INSECURE))); ClientContext start_context; 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; Status start_status = 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."); 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; - 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, - FLAGS_max_reconnect_backoff_ms); + absl::GetFlag(FLAGS_max_reconnect_backoff_ms)); } std::shared_ptr retry_channel = CreateTestChannel(server_address.str(), "foo.test.google.fr", TLS, false, diff --git a/test/cpp/interop/reconnect_interop_server.cc b/test/cpp/interop/reconnect_interop_server.cc index 188674692e6..8e7ef413131 100644 --- a/test/cpp/interop/reconnect_interop_server.cc +++ b/test/cpp/interop/reconnect_interop_server.cc @@ -18,6 +18,11 @@ // Test description at doc/connection-backoff-interop-test-description.md +#include +#include +#include +#include +#include #include #include @@ -25,23 +30,17 @@ #include #include -#include -#include -#include -#include -#include -#include - +#include "absl/flags/flag.h" #include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/messages.pb.h" #include "src/proto/grpc/testing/test.grpc.pb.h" #include "test/core/util/reconnect_server.h" #include "test/cpp/util/test_config.h" -DEFINE_int32(control_port, 0, "Server port for controlling the server."); -DEFINE_int32(retry_port, 0, - "Server port for raw tcp connections. All incoming " - "connections will be closed immediately."); +ABSL_FLAG(int32_t, control_port, 0, "Server port for controlling the server."); +ABSL_FLAG(int32_t, retry_port, 0, + "Server port for raw tcp connections. All incoming " + "connections will be closed immediately."); using grpc::Server; using grpc::ServerBuilder; @@ -156,8 +155,8 @@ class ReconnectServiceImpl : public ReconnectService::Service { void RunServer() { std::ostringstream server_address; - server_address << "0.0.0.0:" << FLAGS_control_port; - ReconnectServiceImpl service(FLAGS_retry_port); + server_address << "0.0.0.0:" << absl::GetFlag(FLAGS_control_port); + ReconnectServiceImpl service(absl::GetFlag(FLAGS_retry_port)); ServerBuilder builder; builder.RegisterService(&service); @@ -177,8 +176,8 @@ int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); signal(SIGINT, sigint_handler); - GPR_ASSERT(FLAGS_control_port != 0); - GPR_ASSERT(FLAGS_retry_port != 0); + GPR_ASSERT(absl::GetFlag(FLAGS_control_port) != 0); + GPR_ASSERT(absl::GetFlag(FLAGS_retry_port) != 0); RunServer(); return 0; diff --git a/test/cpp/interop/server_helper.cc b/test/cpp/interop/server_helper.cc index d818dee3805..ab44049e673 100644 --- a/test/cpp/interop/server_helper.cc +++ b/test/cpp/interop/server_helper.cc @@ -18,29 +18,29 @@ #include "test/cpp/interop/server_helper.h" -#include - -#include #include +#include + +#include "absl/flags/flag.h" #include "src/core/lib/surface/call_test_only.h" #include "src/core/lib/transport/byte_stream.h" #include "test/cpp/util/test_credentials_provider.h" -DECLARE_bool(use_alts); -DECLARE_bool(use_tls); -DECLARE_string(custom_credentials_type); +ABSL_DECLARE_FLAG(bool, use_alts); +ABSL_DECLARE_FLAG(bool, use_tls); +ABSL_DECLARE_FLAG(std::string, custom_credentials_type); namespace grpc { namespace testing { std::shared_ptr CreateInteropServerCredentials() { - if (!FLAGS_custom_credentials_type.empty()) { + if (!absl::GetFlag(FLAGS_custom_credentials_type).empty()) { return GetCredentialsProvider()->GetServerCredentials( - FLAGS_custom_credentials_type); - } else if (FLAGS_use_alts) { + absl::GetFlag(FLAGS_custom_credentials_type)); + } else if (absl::GetFlag(FLAGS_use_alts)) { return GetCredentialsProvider()->GetServerCredentials(kAltsCredentialsType); - } else if (FLAGS_use_tls) { + } else if (absl::GetFlag(FLAGS_use_tls)) { return GetCredentialsProvider()->GetServerCredentials(kTlsCredentialsType); } else { return GetCredentialsProvider()->GetServerCredentials( diff --git a/test/cpp/interop/stress_test.cc b/test/cpp/interop/stress_test.cc index f04f8ac3783..cc7651e9764 100644 --- a/test/cpp/interop/stress_test.cc +++ b/test/cpp/interop/stress_test.cc @@ -16,18 +16,18 @@ *is % allowed in string */ +#include +#include +#include +#include + #include #include #include #include #include -#include -#include -#include -#include -#include - +#include "absl/flags/flag.h" #include "src/proto/grpc/testing/metrics.grpc.pb.h" #include "src/proto/grpc/testing/metrics.pb.h" #include "test/cpp/interop/interop_client.h" @@ -38,73 +38,76 @@ 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, - "The duration (in millisec) between two" - " consecutive test calls (per server) issued by the server."); +// TODO(Capstan): Consider using absl::Duration +ABSL_FLAG(int32_t, sleep_duration_ms, 0, + "The duration (in millisec) between two" + " consecutive test calls (per server) issued by the server."); -DEFINE_int32(test_duration_secs, -1, - "The length of time (in seconds) to run" - " the test. Enter -1 if the test should run continuously until" - " forcefully terminated."); +// TODO(Capstan): Consider using absl::Duration +ABSL_FLAG(int32_t, test_duration_secs, -1, + "The length of time (in seconds) to run" + " the test. Enter -1 if the test should run continuously until" + " forcefully terminated."); -DEFINE_string(server_addresses, "localhost:8080", - "The list of server addresses. The format is: \n" - " \":,:...:\"\n" - " Note: can be servername or IP address."); +ABSL_FLAG(std::string, server_addresses, "localhost:8080", + "The list of server addresses. The format is: \n" + " \":,:...:\"\n" + " Note: 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, - "Number of stubs per each channels to server. This number also " - "indicates the max number of parallel RPC calls on each channel " - "at any given time."); +ABSL_FLAG(int32_t, num_stubs_per_channel, 1, + "Number of stubs per each channels to server. This number also " + "indicates the max number of parallel RPC calls on each channel " + "at any given time."); // TODO(sreek): Add more test cases here in future -DEFINE_string(test_cases, "", - "List of test cases to call along with the" - " relative weights in the following format:\n" - " \",...\"\n" - " The following testcases are currently supported:\n" - " empty_unary\n" - " large_unary\n" - " large_compressed_unary\n" - " client_streaming\n" - " server_streaming\n" - " server_compressed_streaming\n" - " slow_consumer\n" - " half_duplex\n" - " ping_pong\n" - " cancel_after_begin\n" - " cancel_after_first_response\n" - " timeout_on_sleeping_server\n" - " empty_stream\n" - " status_code_and_message\n" - " custom_metadata\n" - " Example: \"empty_unary:20,large_unary:10,empty_stream:70\"\n" - " The above will execute 'empty_unary', 20% of the time," - " 'large_unary', 10% of the time and 'empty_stream' the remaining" - " 70% of the time"); - -DEFINE_int32(log_level, GPR_LOG_SEVERITY_INFO, - "Severity level of messages that should be logged. Any messages " - "greater than or equal to the level set here will be logged. " - "The choices are: 0 (GPR_LOG_SEVERITY_DEBUG), 1 " - "(GPR_LOG_SEVERITY_INFO) and 2 (GPR_LOG_SEVERITY_ERROR)"); - -DEFINE_bool(do_not_abort_on_transient_failures, true, - "If set to 'true', abort() is not called in case of transient " - "failures like temporary connection failures."); +ABSL_FLAG(std::string, test_cases, "", + "List of test cases to call along with the" + " relative weights in the following format:\n" + " \",...\"\n" + " The following testcases are currently supported:\n" + " empty_unary\n" + " large_unary\n" + " large_compressed_unary\n" + " client_streaming\n" + " server_streaming\n" + " server_compressed_streaming\n" + " slow_consumer\n" + " half_duplex\n" + " ping_pong\n" + " cancel_after_begin\n" + " cancel_after_first_response\n" + " timeout_on_sleeping_server\n" + " empty_stream\n" + " status_code_and_message\n" + " custom_metadata\n" + " Example: \"empty_unary:20,large_unary:10,empty_stream:70\"\n" + " The above will execute 'empty_unary', 20% of the time," + " 'large_unary', 10% of the time and 'empty_stream' the remaining" + " 70% of the time"); + +ABSL_FLAG(int32_t, log_level, GPR_LOG_SEVERITY_INFO, + "Severity level of messages that should be logged. Any messages " + "greater than or equal to the level set here will be logged. " + "The choices are: 0 (GPR_LOG_SEVERITY_DEBUG), 1 " + "(GPR_LOG_SEVERITY_INFO) and 2 (GPR_LOG_SEVERITY_ERROR)"); + +ABSL_FLAG(bool, do_not_abort_on_transient_failures, true, + "If set to 'true', abort() is not called in case of transient " + "failures like temporary connection failures."); // Options from client.cc (for compatibility with interop test). // TODO(sreek): Consolidate overlapping options -DEFINE_bool(use_alts, false, - "Whether to use alts. Enable alts will disable tls."); -DEFINE_bool(use_tls, false, "Whether to use tls."); -DEFINE_bool(use_test_ca, false, "False to use SSL roots for google"); -DEFINE_string(server_host_override, "", - "Override the server host which is sent in HTTP header"); +ABSL_FLAG(bool, use_alts, false, + "Whether to use alts. Enable alts will disable tls."); +ABSL_FLAG(bool, use_tls, false, "Whether to use tls."); +ABSL_FLAG(bool, use_test_ca, false, "False to use SSL roots for google"); +ABSL_FLAG(std::string, server_host_override, "", + "Override the server host which is sent in HTTP header"); using grpc::testing::ALTS; using grpc::testing::INSECURE; @@ -193,16 +196,21 @@ bool ParseTestCasesString(const std::string& test_cases, // For debugging purposes void LogParameterInfo(const std::vector& addresses, const std::vector>& tests) { - gpr_log(GPR_INFO, "server_addresses: %s", FLAGS_server_addresses.c_str()); - gpr_log(GPR_INFO, "test_cases : %s", FLAGS_test_cases.c_str()); - gpr_log(GPR_INFO, "sleep_duration_ms: %d", FLAGS_sleep_duration_ms); - gpr_log(GPR_INFO, "test_duration_secs: %d", FLAGS_test_duration_secs); + gpr_log(GPR_INFO, "server_addresses: %s", + absl::GetFlag(FLAGS_server_addresses).c_str()); + gpr_log(GPR_INFO, "test_cases : %s", absl::GetFlag(FLAGS_test_cases).c_str()); + 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", - FLAGS_num_channels_per_server); - gpr_log(GPR_INFO, "num_stubs_per_channel: %d", FLAGS_num_stubs_per_channel); - gpr_log(GPR_INFO, "log_level: %d", FLAGS_log_level); + absl::GetFlag(FLAGS_num_channels_per_server)); + gpr_log(GPR_INFO, "num_stubs_per_channel: %d", + 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", - FLAGS_do_not_abort_on_transient_failures ? "true" : "false"); + absl::GetFlag(FLAGS_do_not_abort_on_transient_failures) ? "true" + : "false"); int num = 0; for (auto it = addresses.begin(); it != addresses.end(); it++) { @@ -221,8 +229,8 @@ void LogParameterInfo(const std::vector& addresses, int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); - if (FLAGS_log_level > GPR_LOG_SEVERITY_ERROR || - FLAGS_log_level < GPR_LOG_SEVERITY_DEBUG) { + if (absl::GetFlag(FLAGS_log_level) > GPR_LOG_SEVERITY_ERROR || + 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_SEVERITY_DEBUG, GPR_LOG_SEVERITY_ERROR); return 1; @@ -230,25 +238,26 @@ int main(int argc, char** argv) { // Change the default log function to TestLogFunction which respects the // log_level setting. - log_level = FLAGS_log_level; + log_level = absl::GetFlag(FLAGS_log_level); gpr_set_log_function(TestLogFunction); srand(time(nullptr)); // Parse the server addresses std::vector server_addresses; - ParseCommaDelimitedString(FLAGS_server_addresses, server_addresses); + ParseCommaDelimitedString(absl::GetFlag(FLAGS_server_addresses), + server_addresses); // 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"); return 1; } std::vector> 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 ", - FLAGS_test_cases.c_str()); + absl::GetFlag(FLAGS_test_cases).c_str()); return 1; } @@ -274,28 +283,33 @@ int main(int argc, char** argv) { int server_idx = -1; char buffer[256]; 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++) { ++server_idx; // 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++) { gpr_log(GPR_INFO, "Starting test with %s channel_idx=%d..", it->c_str(), channel_idx); - grpc::testing::ChannelCreationFunc channel_creation_func = std::bind( - static_cast (*)( - const std::string&, const std::string&, - grpc::testing::transport_security, bool)>( - grpc::CreateTestChannel), - *it, FLAGS_server_host_override, security_type, !FLAGS_use_test_ca); + grpc::testing::ChannelCreationFunc channel_creation_func = + std::bind(static_cast (*)( + const std::string&, const std::string&, + grpc::testing::transport_security, bool)>( + grpc::CreateTestChannel), + *it, absl::GetFlag(FLAGS_server_host_override), + security_type, !absl::GetFlag(FLAGS_use_test_ca)); // Create stub(s) for each channel - for (int stub_idx = 0; stub_idx < FLAGS_num_stubs_per_channel; - stub_idx++) { + for (int stub_idx = 0; + stub_idx < absl::GetFlag(FLAGS_num_stubs_per_channel); stub_idx++) { clients.emplace_back(new StressTestInteropClient( ++thread_idx, *it, channel_creation_func, test_selector, - FLAGS_test_duration_secs, FLAGS_sleep_duration_ms, - FLAGS_do_not_abort_on_transient_failures)); + absl::GetFlag(FLAGS_test_duration_secs), + absl::GetFlag(FLAGS_sleep_duration_ms), + absl::GetFlag(FLAGS_do_not_abort_on_transient_failures))); bool is_already_created = false; // QpsGauge name @@ -315,8 +329,9 @@ int main(int argc, char** argv) { // Start metrics server before waiting for the stress test threads std::unique_ptr metrics_server; - if (FLAGS_metrics_port > 0) { - metrics_server = metrics_service.StartServer(FLAGS_metrics_port); + if (absl::GetFlag(FLAGS_metrics_port) > 0) { + metrics_server = + metrics_service.StartServer(absl::GetFlag(FLAGS_metrics_port)); } // Wait for the stress test threads to complete diff --git a/test/cpp/interop/xds_interop_client.cc b/test/cpp/interop/xds_interop_client.cc index 0e8144d6ba9..476e6765f65 100644 --- a/test/cpp/interop/xds_interop_client.cc +++ b/test/cpp/interop/xds_interop_client.cc @@ -16,6 +16,11 @@ * */ +#include +#include +#include +#include + #include #include #include @@ -27,14 +32,8 @@ #include #include +#include "absl/flags/flag.h" #include "absl/strings/str_split.h" - -#include -#include -#include -#include -#include - #include "src/core/lib/gpr/env.h" #include "src/proto/grpc/testing/empty.pb.h" #include "src/proto/grpc/testing/messages.pb.h" @@ -42,17 +41,19 @@ #include "test/core/util/test_config.h" #include "test/cpp/util/test_config.h" -DEFINE_bool(fail_on_failed_rpc, false, - "Fail client if any RPCs fail after first successful RPC."); -DEFINE_int32(num_channels, 1, "Number of channels."); -DEFINE_bool(print_response, false, "Write RPC response to stdout."); -DEFINE_int32(qps, 1, "Qps per channel."); -DEFINE_int32(rpc_timeout_sec, 30, "Per RPC timeout seconds."); -DEFINE_string(server, "localhost:50051", "Address of server."); -DEFINE_int32(stats_port, 50052, - "Port to expose peer distribution stats service."); -DEFINE_string(rpc, "UnaryCall", "a comma separated list of rpc methods."); -DEFINE_string(metadata, "", "metadata to send with the RPC."); +ABSL_FLAG(bool, fail_on_failed_rpc, false, + "Fail client if any RPCs fail after first successful RPC."); +ABSL_FLAG(int32_t, num_channels, 1, "Number of channels."); +ABSL_FLAG(bool, print_response, false, "Write RPC response to stdout."); +ABSL_FLAG(int32_t, qps, 1, "Qps per channel."); +// TODO(Capstan): Consider using absl::Duration +ABSL_FLAG(int32_t, rpc_timeout_sec, 30, "Per RPC timeout seconds."); +ABSL_FLAG(std::string, server, "localhost:50051", "Address of server."); +ABSL_FLAG(int32_t, stats_port, 50052, + "Port to expose peer distribution stats service."); +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::ClientAsyncResponseReader; @@ -156,7 +157,7 @@ class TestClient { } std::chrono::system_clock::time_point deadline = 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; call->context.set_deadline(deadline); for (const auto& data : metadata) { @@ -181,7 +182,7 @@ class TestClient { } std::chrono::system_clock::time_point deadline = 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; call->context.set_deadline(deadline); for (const auto& data : metadata) { @@ -219,15 +220,17 @@ class TestClient { } 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() << ": " << 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(); } } else { - if (FLAGS_print_response) { + if (absl::GetFlag(FLAGS_print_response)) { auto metadata_hostname = call->context.GetServerInitialMetadata().find("hostname"); std::string hostname = @@ -290,14 +293,14 @@ class LoadBalancerStatsServiceImpl : public LoadBalancerStatsService::Service { void RunTestLoop(std::chrono::duration duration_per_query) { std::vector rpc_methods = - absl::StrSplit(FLAGS_rpc, ',', absl::SkipEmpty()); + absl::StrSplit(absl::GetFlag(FLAGS_rpc), ',', absl::SkipEmpty()); // Store Metadata like // "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 // pairs. {EmptyCall, [{key1,value1}], // UnaryCall, [{key1,value1}, {key2,value2}]} std::vector rpc_metadata = - absl::StrSplit(FLAGS_metadata, ',', absl::SkipEmpty()); + absl::StrSplit(absl::GetFlag(FLAGS_metadata), ',', absl::SkipEmpty()); std::map>> metadata_map; for (auto& data : rpc_metadata) { @@ -307,8 +310,8 @@ void RunTestLoop(std::chrono::duration duration_per_query) { metadata_map[std::string(metadata[0])].push_back( {std::string(metadata[1]), std::string(metadata[2])}); } - TestClient client( - grpc::CreateChannel(FLAGS_server, grpc::InsecureChannelCredentials())); + TestClient client(grpc::CreateChannel(absl::GetFlag(FLAGS_server), + grpc::InsecureChannelCredentials())); std::chrono::time_point start = std::chrono::system_clock::now(); std::chrono::duration elapsed; @@ -361,16 +364,17 @@ int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); std::chrono::duration 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 test_threads; - test_threads.reserve(FLAGS_num_channels); - for (int i = 0; i < FLAGS_num_channels; i++) { + test_threads.reserve(absl::GetFlag(FLAGS_num_channels)); + for (int i = 0; i < absl::GetFlag(FLAGS_num_channels); i++) { 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++) { it->join(); diff --git a/test/cpp/interop/xds_interop_server.cc b/test/cpp/interop/xds_interop_server.cc index dcc5a7db6ea..fa8f3a780e0 100644 --- a/test/cpp/interop/xds_interop_server.cc +++ b/test/cpp/interop/xds_interop_server.cc @@ -16,7 +16,6 @@ * */ -#include #include #include #include @@ -26,6 +25,7 @@ #include +#include "absl/flags/flag.h" #include "src/core/lib/gpr/string.h" #include "src/core/lib/iomgr/gethostname.h" #include "src/core/lib/transport/byte_stream.h" @@ -35,8 +35,9 @@ #include "test/core/util/test_config.h" #include "test/cpp/util/test_config.h" -DEFINE_int32(port, 50051, "Server port."); -DEFINE_string(server_id, "cpp_server", "Server ID to include in responses."); +ABSL_FLAG(int32_t, port, 50051, "Server port."); +ABSL_FLAG(std::string, server_id, "cpp_server", + "Server ID to include in responses."); using grpc::Server; using grpc::ServerBuilder; @@ -53,7 +54,7 @@ class TestServiceImpl : public TestService::Service { Status UnaryCall(ServerContext* context, const SimpleRequest* request, SimpleResponse* response) override { - response->set_server_id(FLAGS_server_id); + response->set_server_id(absl::GetFlag(FLAGS_server_id)); response->set_hostname(hostname_); context->AddInitialMetadata("hostname", hostname_); return Status::OK; @@ -93,12 +94,12 @@ int main(int argc, char** argv) { std::cout << "Failed to get hostname, terminating" << std::endl; return 1; } - if (FLAGS_port == 0) { + if (absl::GetFlag(FLAGS_port) == 0) { std::cout << "Invalid port, terminating" << std::endl; return 1; } - RunServer(FLAGS_port, hostname); + RunServer(absl::GetFlag(FLAGS_port), hostname); return 0; } diff --git a/test/cpp/microbenchmarks/BUILD b/test/cpp/microbenchmarks/BUILD index 82f9952675f..f06c384abeb 100644 --- a/test/cpp/microbenchmarks/BUILD +++ b/test/cpp/microbenchmarks/BUILD @@ -217,6 +217,9 @@ grpc_cc_test( name = "bm_fullstack_trickle", size = "large", srcs = ["bm_fullstack_trickle.cc"], + external_deps = [ + "absl/flags:flag", + ], tags = [ "manual", "no_windows", diff --git a/test/cpp/microbenchmarks/bm_fullstack_trickle.cc b/test/cpp/microbenchmarks/bm_fullstack_trickle.cc index ec668374967..9fa42b5aa07 100644 --- a/test/cpp/microbenchmarks/bm_fullstack_trickle.cc +++ b/test/cpp/microbenchmarks/bm_fullstack_trickle.cc @@ -19,11 +19,11 @@ /* Benchmark gRPC end2end in various configurations */ #include -#include + #include +#include "absl/flags/flag.h" #include "absl/memory/memory.h" - #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h" #include "src/core/ext/transport/chttp2/transport/internal.h" #include "src/core/lib/iomgr/timer_manager.h" @@ -35,15 +35,13 @@ #include "test/cpp/microbenchmarks/fullstack_fixtures.h" #include "test/cpp/util/test_config.h" -DEFINE_bool(log, false, "Log state to CSV files"); -DEFINE_int32( - warmup_megabytes, 1, - "Number of megabytes to pump before collecting flow control stats"); -DEFINE_int32( - warmup_iterations, 100, - "Number of iterations to run before collecting flow control stats"); -DEFINE_int32(warmup_max_time_seconds, 10, - "Maximum number of seconds to run warmup loop"); +ABSL_FLAG(bool, log, false, "Log state to CSV files"); +ABSL_FLAG(int32_t, warmup_megabytes, 1, + "Number of megabytes to pump before collecting flow control stats"); +ABSL_FLAG(int32_t, warmup_iterations, 100, + "Number of iterations to run before collecting flow control stats"); +ABSL_FLAG(int32_t, warmup_max_time_seconds, 10, + "Maximum number of seconds to run warmup loop"); namespace grpc { namespace testing { @@ -87,7 +85,7 @@ class TrickledCHTTP2 : public EndpointPairFixture { : EndpointPairFixture(service, MakeEndpoints(kilobits_per_second, stats), FixtureConfiguration()), stats_(stats) { - if (FLAGS_log) { + if (absl::GetFlag(FLAGS_log)) { std::ostringstream fn; fn << "trickle." << (streaming ? "streaming" : "unary") << "." << req_size << "." << 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); - for (int i = 0; - i < GPR_MAX(FLAGS_warmup_iterations, FLAGS_warmup_megabytes * 1024 * - 1024 / (14 + state.range(0))); + for (int i = 0; i < GPR_MAX(absl::GetFlag(FLAGS_warmup_iterations), + absl::GetFlag(FLAGS_warmup_megabytes) * 1024 * + 1024 / (14 + state.range(0))); i++) { inner_loop(true); if (gpr_time_cmp(gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start), - gpr_time_from_seconds(FLAGS_warmup_max_time_seconds, - GPR_TIMESPAN)) > 0) { + gpr_time_from_seconds( + absl::GetFlag(FLAGS_warmup_max_time_seconds), + GPR_TIMESPAN)) > 0) { break; } } @@ -417,14 +416,15 @@ static void BM_PumpUnbalancedUnary_Trickle(benchmark::State& state) { fixture->cq(), fixture->cq(), tag(slot)); }; gpr_timespec warmup_start = gpr_now(GPR_CLOCK_MONOTONIC); - for (int i = 0; - i < GPR_MAX(FLAGS_warmup_iterations, FLAGS_warmup_megabytes * 1024 * - 1024 / (14 + state.range(0))); + for (int i = 0; i < GPR_MAX(absl::GetFlag(FLAGS_warmup_iterations), + absl::GetFlag(FLAGS_warmup_megabytes) * 1024 * + 1024 / (14 + state.range(0))); i++) { inner_loop(true); - if (gpr_time_cmp(gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start), - gpr_time_from_seconds(FLAGS_warmup_max_time_seconds, - GPR_TIMESPAN)) > 0) { + if (gpr_time_cmp( + gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), warmup_start), + gpr_time_from_seconds(absl::GetFlag(FLAGS_warmup_max_time_seconds), + GPR_TIMESPAN)) > 0) { break; } } diff --git a/test/cpp/naming/address_sorting_test.cc b/test/cpp/naming/address_sorting_test.cc index 54fded34d11..2f890149273 100644 --- a/test/cpp/naming/address_sorting_test.cc +++ b/test/cpp/naming/address_sorting_test.cc @@ -16,6 +16,8 @@ * */ +#include +#include #include #include #include @@ -23,15 +25,9 @@ #include #include #include - -#include -#include #include -#include -#include -#include "test/cpp/util/subprocess.h" -#include "test/cpp/util/test_config.h" +#include #include "src/core/ext/filters/client_channel/client_channel.h" #include "src/core/ext/filters/client_channel/resolver.h" @@ -49,6 +45,8 @@ #include "src/core/lib/iomgr/sockaddr_utils.h" #include "test/core/util/port.h" #include "test/core/util/test_config.h" +#include "test/cpp/util/subprocess.h" +#include "test/cpp/util/test_config.h" #ifndef GPR_WINDOWS #include diff --git a/test/cpp/naming/cancel_ares_query_test.cc b/test/cpp/naming/cancel_ares_query_test.cc index 477aa07cb2e..0163c2eff26 100644 --- a/test/cpp/naming/cancel_ares_query_test.cc +++ b/test/cpp/naming/cancel_ares_query_test.cc @@ -16,23 +16,19 @@ * */ -#include -#include - -#include - -#include "absl/strings/str_cat.h" -#include "absl/strings/str_format.h" - -#include #include - #include #include #include #include #include +#include +#include +#include + +#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/dns/dns_resolver_selection.h" #include "src/core/ext/filters/client_channel/resolver_registry.h" diff --git a/test/cpp/naming/generate_resolver_component_tests.bzl b/test/cpp/naming/generate_resolver_component_tests.bzl index 812bf3b71b9..c8dbee751a8 100755 --- a/test/cpp/naming/generate_resolver_component_tests.bzl +++ b/test/cpp/naming/generate_resolver_component_tests.bzl @@ -62,6 +62,9 @@ def generate_resolver_component_tests(): srcs = [ "resolver_component_tests_runner_invoker.cc", ], + external_deps = [ + "absl/flags:flag", + ], deps = [ "//test/cpp/util:test_util", "//test/core/util:grpc_test_util", diff --git a/test/cpp/naming/resolver_component_test.cc b/test/cpp/naming/resolver_component_test.cc index c1ae008c7eb..77ca6e69937 100644 --- a/test/cpp/naming/resolver_component_test.cc +++ b/test/cpp/naming/resolver_component_test.cc @@ -16,33 +16,26 @@ * */ -#include - -#include -#include -#include - #include #include -#include - -#include #include - -#include "absl/memory/memory.h" -#include "absl/strings/str_cat.h" -#include "absl/strings/str_format.h" - #include #include #include #include +#include #include #include +#include -#include "test/cpp/util/subprocess.h" -#include "test/cpp/util/test_config.h" +#include +#include +#include +#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/lb_policy/grpclb/grpclb_balancer_addresses.h" #include "src/core/ext/filters/client_channel/resolver.h" @@ -63,8 +56,9 @@ #include "src/core/lib/iomgr/work_serializer.h" #include "test/core/util/port.h" #include "test/core/util/test_config.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 // test on windows. Also set BAD_SOCKET_RETURN_VAL @@ -82,50 +76,44 @@ using std::vector; using testing::UnorderedElementsAreArray; -// Hack copied from "test/cpp/end2end/server_crash_test_client.cc"! -// In some distros, gflags is in the namespace google, and in some others, -// in gflags. This hack is enabling us to find both. -namespace google {} -namespace gflags {} -using namespace google; -using namespace gflags; - -DEFINE_string(target_name, "", "Target name to resolve."); -DEFINE_string(do_ordered_address_comparison, "", - "Whether or not to compare resolved addresses to expected " - "addresses using an ordered comparison. This is useful for " - "testing certain behaviors that involve sorting of resolved " - "addresses. Note it would be better if this argument was a " - "bool flag, but it's a string for ease of invocation from " - "the generated python test runner."); -DEFINE_string(expected_addrs, "", - "List of expected backend or balancer addresses in the form " - "',;,;...'. " - "'is_balancer' should be bool, i.e. true or false."); -DEFINE_string(expected_chosen_service_config, "", - "Expected service config json string that gets chosen (no " - "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, "", +ABSL_FLAG(std::string, target_name, "", "Target name to resolve."); +ABSL_FLAG(std::string, do_ordered_address_comparison, "", + "Whether or not to compare resolved addresses to expected " + "addresses using an ordered comparison. This is useful for " + "testing certain behaviors that involve sorting of resolved " + "addresses. Note it would be better if this argument was a " + "bool flag, but it's a string for ease of invocation from " + "the generated python test runner."); +ABSL_FLAG(std::string, expected_addrs, "", + "List of expected backend or balancer addresses in the form " + "',;,;...'. " + "'is_balancer' should be bool, i.e. true or false."); +ABSL_FLAG(std::string, expected_chosen_service_config, "", + "Expected service config json string that gets chosen (no " + "whitespace). Empty for none."); +ABSL_FLAG(std::string, expected_service_config_error, "", + "Expected service config error. Empty for none."); +ABSL_FLAG(std::string, local_dns_server_address, "", + "Optional. This address is placed as the uri authority if present."); +// TODO(Capstan): Is this worth making `bool` now with Abseil flags? +ABSL_FLAG( + std::string, enable_srv_queries, "", "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 " "generate " "the python script runner doesn't allow us to pass a gflags bool to this " "binary."); -DEFINE_string( - enable_txt_queries, "", +// TODO(Capstan): Is this worth making `bool` now with Abseil flags? +ABSL_FLAG( + std::string, enable_txt_queries, "", "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 " "generate " "the python script runner doesn't allow us to pass a gflags bool to this " "binary."); -DEFINE_string( - inject_broken_nameserver_list, "", +// TODO(Capstan): Is this worth making `bool` now with Abseil flags? +ABSL_FLAG( + std::string, inject_broken_nameserver_list, "", "Whether or not to configure c-ares to use a broken nameserver list, in " "which " "the first nameserver in the list is non-responsive, but the second one " @@ -135,9 +123,9 @@ DEFINE_string( "generate " "the python script runner doesn't allow us to pass a gflags bool to this " "binary."); -DEFINE_string(expected_lb_policy, "", - "Expected lb policy name that appears in resolver result channel " - "arg. Empty for none."); +ABSL_FLAG(std::string, expected_lb_policy, "", + "Expected lb policy name that appears in resolver result channel " + "arg. Empty for none."); namespace { @@ -495,16 +483,16 @@ class CheckingResultHandler : public ResultHandler { found_lb_addrs.size(), args->expected_addrs.size()); 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); - } else if (FLAGS_do_ordered_address_comparison == "False") { + } else if (absl::GetFlag(FLAGS_do_ordered_address_comparison) == "False") { EXPECT_THAT(args->expected_addrs, UnorderedElementsAreArray(found_lb_addrs)); } else { gpr_log(GPR_ERROR, "Invalid for setting for --do_ordered_address_comparison. " "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); } const char* service_config_json = @@ -543,13 +531,14 @@ void InjectBrokenNameServerList(ares_channel channel) { memset(dns_server_addrs, 0, sizeof(dns_server_addrs)); std::string unused_host; std::string local_dns_server_port; - GPR_ASSERT(grpc_core::SplitHostPort(FLAGS_local_dns_server_address.c_str(), - &unused_host, &local_dns_server_port)); + GPR_ASSERT(grpc_core::SplitHostPort( + absl::GetFlag(FLAGS_local_dns_server_address).c_str(), &unused_host, + &local_dns_server_port)); gpr_log(GPR_DEBUG, "Injecting broken nameserver list. Bad server address:|[::1]:%d|. " "Good server address:%s", 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. dns_server_addrs[0].family = AF_INET6; ((char*)&dns_server_addrs[0].addr.addr6)[15] = 0x1; @@ -577,55 +566,58 @@ void RunResolvesRelevantRecordsTest( grpc_core::ExecCtx exec_ctx; ArgsStruct args; ArgsInit(&args); - args.expected_addrs = ParseExpectedAddrs(FLAGS_expected_addrs); - args.expected_service_config_string = FLAGS_expected_chosen_service_config; - args.expected_service_config_error = FLAGS_expected_service_config_error; - args.expected_lb_policy = FLAGS_expected_lb_policy; + args.expected_addrs = ParseExpectedAddrs(absl::GetFlag(FLAGS_expected_addrs)); + args.expected_service_config_string = + absl::GetFlag(FLAGS_expected_chosen_service_config); + 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 std::string whole_uri; gpr_log(GPR_DEBUG, "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 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(); fake_non_responsive_dns_server = absl::make_unique( g_fake_non_responsive_dns_server_port); grpc_ares_test_only_inject_config = InjectBrokenNameServerList; - whole_uri = absl::StrCat("dns:///", FLAGS_target_name); - } else if (FLAGS_inject_broken_nameserver_list == "False") { + whole_uri = absl::StrCat("dns:///", absl::GetFlag(FLAGS_target_name)); + } else if (absl::GetFlag(FLAGS_inject_broken_nameserver_list) == "False") { gpr_log(GPR_INFO, "Specifying authority in uris to: %s", - FLAGS_local_dns_server_address.c_str()); - whole_uri = absl::StrFormat("dns://%s/%s", FLAGS_local_dns_server_address, - FLAGS_target_name); + absl::GetFlag(FLAGS_local_dns_server_address).c_str()); + whole_uri = absl::StrFormat("dns://%s/%s", + absl::GetFlag(FLAGS_local_dns_server_address), + absl::GetFlag(FLAGS_target_name)); } else { gpr_log(GPR_DEBUG, "Invalid value for --inject_broken_nameserver_list."); abort(); } 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; // 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 // 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( const_cast(GRPC_ARG_DNS_ENABLE_SRV_QUERIES), true); resolver_args = 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."); abort(); } 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 // should avoid setting any channel arg. Test cases that do rely on the TXT // 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. // Rather, we use the resolver-agnostic "service config" resolution option, // 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_destroy(resolver_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."); abort(); } @@ -679,7 +671,7 @@ int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); ::testing::InitGoogleTest(&argc, argv); 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."); abort(); } diff --git a/test/cpp/naming/resolver_component_tests_runner_invoker.cc b/test/cpp/naming/resolver_component_tests_runner_invoker.cc index 9445b70d245..258a7311972 100644 --- a/test/cpp/naming/resolver_component_tests_runner_invoker.cc +++ b/test/cpp/naming/resolver_component_tests_runner_invoker.cc @@ -24,11 +24,12 @@ #include #include -#include #include #include #include +#include "absl/flags/flag.h" + #ifdef __FreeBSD__ #include #endif @@ -39,21 +40,21 @@ #include "test/cpp/util/subprocess.h" #include "test/cpp/util/test_config.h" -DEFINE_bool( - running_under_bazel, false, +ABSL_FLAG( + bool, running_under_bazel, false, "True if this test is running under bazel. " "False indicates that this test is running under run_tests.py. " "Child process test binaries are located differently based on this flag. "); -DEFINE_string(test_bin_name, "", - "Name, without the preceding path, of the test binary"); +ABSL_FLAG(std::string, test_bin_name, "", + "Name, without the preceding path, of the test binary"); -DEFINE_string(grpc_test_directory_relative_to_test_srcdir, - "/com_github_grpc_grpc", - "This flag only applies if runner_under_bazel is true. This " - "flag is ignored if runner_under_bazel is false. " - "Directory of the /test directory relative to bazel's " - "TEST_SRCDIR environment variable"); +ABSL_FLAG(std::string, grpc_test_directory_relative_to_test_srcdir, + "/com_github_grpc_grpc", + "This flag only applies if runner_under_bazel is true. This " + "flag is ignored if runner_under_bazel is false. " + "Directory of the /test directory relative to bazel's " + "TEST_SRCDIR environment variable"); using grpc::SubProcess; @@ -163,22 +164,25 @@ int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); grpc::testing::InitTest(&argc, &argv, true); grpc_init(); - GPR_ASSERT(!FLAGS_test_bin_name.empty()); + GPR_ASSERT(!absl::GetFlag(FLAGS_test_bin_name).empty()); std::string my_bin = argv[0]; - if (FLAGS_running_under_bazel) { - GPR_ASSERT(!FLAGS_grpc_test_directory_relative_to_test_srcdir.empty()); + if (absl::GetFlag(FLAGS_running_under_bazel)) { + 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" // binaries. char* test_srcdir = gpr_getenv("TEST_SRCDIR"); 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"); // Invoke bazel's executeable links to the .sh and .py scripts (don't use // the .sh and .py suffixes) to make // sure that we're using bazel's test environment. grpc::testing::InvokeResolverComponentTestsRunner( 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 + "/utils/dns_resolver", bin_dir + "/utils/tcp_connect"); 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. grpc::testing::InvokeResolverComponentTestsRunner( "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/resolver_test_record_groups.yaml", "test/cpp/naming/utils/dns_resolver.py", diff --git a/test/cpp/qps/BUILD b/test/cpp/qps/BUILD index 974733cd2d5..6fdcfd0d407 100644 --- a/test/cpp/qps/BUILD +++ b/test/cpp/qps/BUILD @@ -46,9 +46,6 @@ grpc_cc_library( "qps_worker.h", "server.h", ], - external_deps = [ - "gflags", - ], deps = [ ":histogram", ":interarrival", @@ -100,7 +97,7 @@ grpc_cc_library( "benchmark_config.h", ], external_deps = [ - "gflags", + "absl/flags:flag", ], deps = [ ":driver_impl", @@ -126,7 +123,7 @@ grpc_cc_binary( name = "qps_json_driver", srcs = ["qps_json_driver.cc"], external_deps = [ - "gflags", + "absl/flags:flag", ], deps = [ ":benchmark_config", @@ -206,6 +203,9 @@ grpc_cc_library( grpc_cc_binary( name = "qps_worker", srcs = ["worker.cc"], + external_deps = [ + "absl/flags:flag", + ], deps = [ ":qps_worker_impl", "//:grpc++", diff --git a/test/cpp/qps/benchmark_config.cc b/test/cpp/qps/benchmark_config.cc index 0e826a0ff34..4ec07e9fde0 100644 --- a/test/cpp/qps/benchmark_config.cc +++ b/test/cpp/qps/benchmark_config.cc @@ -17,68 +17,64 @@ */ #include "test/cpp/qps/benchmark_config.h" -#include + #include #include #include +#include "absl/flags/flag.h" #include "test/cpp/util/test_credentials_provider.h" -DEFINE_bool(enable_log_reporter, true, - "Enable reporting of benchmark results through GprLog"); +ABSL_FLAG(bool, enable_log_reporter, true, + "Enable reporting of benchmark results through GprLog"); -DEFINE_string(scenario_result_file, "", - "Write JSON benchmark report to the file specified."); +ABSL_FLAG(std::string, scenario_result_file, "", + "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", - "Address of the performance database server"); +ABSL_FLAG(std::string, server_address, "localhost:50052", + "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, "", - "Server address for rpc reporter to send results to"); +ABSL_FLAG(std::string, rpc_reporter_server_address, "", + "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( - rpc_reporter_credential_type, grpc::testing::kInsecureCredentialsType, +ABSL_FLAG( + std::string, rpc_reporter_credential_type, + grpc::testing::kInsecureCredentialsType, "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 testing { static std::shared_ptr InitBenchmarkReporters() { auto* composite_reporter = new CompositeReporter; - if (FLAGS_enable_log_reporter) { + if (absl::GetFlag(FLAGS_enable_log_reporter)) { composite_reporter->add( std::unique_ptr(new GprLogReporter("LogReporter"))); } - if (!FLAGS_scenario_result_file.empty()) { - composite_reporter->add(std::unique_ptr( - new JsonReporter("JsonReporter", FLAGS_scenario_result_file))); + if (!absl::GetFlag(FLAGS_scenario_result_file).empty()) { + composite_reporter->add(std::unique_ptr(new JsonReporter( + "JsonReporter", absl::GetFlag(FLAGS_scenario_result_file)))); } - if (FLAGS_enable_rpc_reporter) { + if (absl::GetFlag(FLAGS_enable_rpc_reporter)) { ChannelArguments channel_args; std::shared_ptr channel_creds = testing::GetCredentialsProvider()->GetChannelCredentials( - FLAGS_rpc_reporter_credential_type, &channel_args); - GPR_ASSERT(!FLAGS_rpc_reporter_server_address.empty()); + absl::GetFlag(FLAGS_rpc_reporter_credential_type), &channel_args); + GPR_ASSERT(!absl::GetFlag(FLAGS_rpc_reporter_server_address).empty()); composite_reporter->add(std::unique_ptr(new RpcReporter( - "RpcReporter", grpc::CreateChannel(FLAGS_rpc_reporter_server_address, - channel_creds)))); + "RpcReporter", + grpc::CreateChannel(absl::GetFlag(FLAGS_rpc_reporter_server_address), + channel_creds)))); } return std::shared_ptr(composite_reporter); diff --git a/test/cpp/qps/qps_benchmark_script.bzl b/test/cpp/qps/qps_benchmark_script.bzl index 3f461ecc8c5..ded7d39f3c3 100644 --- a/test/cpp/qps/qps_benchmark_script.bzl +++ b/test/cpp/qps/qps_benchmark_script.bzl @@ -39,9 +39,6 @@ def qps_json_driver_batch(): "--scenarios_json", QPS_JSON_DRIVER_SCENARIOS[scenario], ], - external_deps = [ - "gflags", - ], deps = [ ":benchmark_config", ":driver_impl", diff --git a/test/cpp/qps/qps_json_driver.cc b/test/cpp/qps/qps_json_driver.cc index 27862f81425..6dcb73d3dc6 100644 --- a/test/cpp/qps/qps_json_driver.cc +++ b/test/cpp/qps/qps_json_driver.cc @@ -16,16 +16,15 @@ * */ +#include +#include + #include #include #include #include -#include - -#include -#include - +#include "absl/flags/flag.h" #include "test/core/util/test_config.h" #include "test/cpp/qps/benchmark_config.h" #include "test/cpp/qps/driver.h" @@ -35,39 +34,39 @@ #include "test/cpp/util/test_config.h" #include "test/cpp/util/test_credentials_provider.h" -DEFINE_string(scenarios_file, "", - "JSON file containing an array of Scenario objects"); -DEFINE_string(scenarios_json, "", - "JSON string containing an array of Scenario objects"); -DEFINE_bool(quit, false, "Quit the workers"); -DEFINE_string(search_param, "", - "The parameter, whose value is to be searched for to achieve " - "targeted cpu load. For now, we have 'offered_load'. Later, " - "'num_channels', 'num_outstanding_requests', etc. shall be " - "added."); -DEFINE_double( - initial_search_value, 0.0, +ABSL_FLAG(std::string, scenarios_file, "", + "JSON file containing an array of Scenario objects"); +ABSL_FLAG(std::string, scenarios_json, "", + "JSON string containing an array of Scenario objects"); +ABSL_FLAG(bool, quit, false, "Quit the workers"); +ABSL_FLAG(std::string, search_param, "", + "The parameter, whose value is to be searched for to achieve " + "targeted cpu load. For now, we have 'offered_load'. Later, " + "'num_channels', 'num_outstanding_requests', etc. shall be " + "added."); +ABSL_FLAG( + double, initial_search_value, 0.0, "initial parameter value to start the search with (i.e. lower bound)"); -DEFINE_double(targeted_cpu_load, 70.0, - "Targeted cpu load (unit: %, range [0,100])"); -DEFINE_double(stride, 1, - "Defines each stride of the search. The larger the stride is, " - "the coarser the result will be, but will also be faster."); -DEFINE_double(error_tolerance, 0.01, - "Defines threshold for stopping the search. When current search " - "range is narrower than the error_tolerance computed range, we " - "stop the search."); - -DEFINE_string(qps_server_target_override, "", - "Override QPS server target to configure in client configs." - "Only applicable if there is a single benchmark server."); - -DEFINE_string(json_file_out, "", "File to write the JSON output to."); - -DEFINE_string(credential_type, grpc::testing::kInsecureCredentialsType, - "Credential type for communication with workers"); -DEFINE_string( - per_worker_credential_types, "", +ABSL_FLAG(double, targeted_cpu_load, 70.0, + "Targeted cpu load (unit: %, range [0,100])"); +ABSL_FLAG(double, stride, 1, + "Defines each stride of the search. The larger the stride is, " + "the coarser the result will be, but will also be faster."); +ABSL_FLAG(double, error_tolerance, 0.01, + "Defines threshold for stopping the search. When current search " + "range is narrower than the error_tolerance computed range, we " + "stop the search."); + +ABSL_FLAG(std::string, qps_server_target_override, "", + "Override QPS server target to configure in client configs." + "Only applicable if there is a single benchmark server."); + +ABSL_FLAG(std::string, json_file_out, "", "File to write the JSON output to."); + +ABSL_FLAG(std::string, credential_type, grpc::testing::kInsecureCredentialsType, + "Credential type for communication with workers"); +ABSL_FLAG( + std::string, per_worker_credential_types, "", "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 " "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 " "is a semicolon-separated list of map entries, where each map entry is " "a comma-separated pair."); -DEFINE_bool(run_inproc, false, "Perform an in-process transport test"); -DEFINE_int32( - median_latency_collection_interval_millis, 0, +ABSL_FLAG(bool, run_inproc, false, "Perform an in-process transport test"); +ABSL_FLAG( + int32_t, median_latency_collection_interval_millis, 0, "Specifies the period between gathering latency medians in " "milliseconds. The medians will be logged out on the client at the " "end of the benchmark run. If 0, this periodic collection is disabled."); @@ -90,7 +89,7 @@ static std::map ConstructPerWorkerCredentialTypesMap() { // Parse a list of the form: "addr1,cred_type1;addr2,cred_type2;..." into // a map. - std::string remaining = FLAGS_per_worker_credential_types; + std::string remaining = absl::GetFlag(FLAGS_per_worker_credential_types); std::map out; while (!remaining.empty()) { size_t next_semicolon = remaining.find(';'); @@ -125,14 +124,16 @@ static std::unique_ptr RunAndReport( const std::map& per_worker_credential_types, bool* success) { std::cerr << "RUNNING SCENARIO: " << scenario.name() << "\n"; - auto result = - RunScenario(scenario.client_config(), scenario.num_clients(), - scenario.server_config(), scenario.num_servers(), - scenario.warmup_seconds(), scenario.benchmark_seconds(), - !FLAGS_run_inproc ? scenario.spawn_local_worker_count() : -2, - FLAGS_qps_server_target_override, FLAGS_credential_type, - per_worker_credential_types, FLAGS_run_inproc, - FLAGS_median_latency_collection_interval_millis); + auto result = RunScenario( + scenario.client_config(), scenario.num_clients(), + scenario.server_config(), scenario.num_servers(), + scenario.warmup_seconds(), scenario.benchmark_seconds(), + !absl::GetFlag(FLAGS_run_inproc) ? scenario.spawn_local_worker_count() + : -2, + absl::GetFlag(FLAGS_qps_server_target_override), + 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 // RunScenario contract so we don't need to touch the result here. @@ -153,9 +154,9 @@ static std::unique_ptr RunAndReport( *success = result->server_success(i); } - if (!FLAGS_json_file_out.empty()) { + if (!absl::GetFlag(FLAGS_json_file_out).empty()) { 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.close(); } @@ -179,7 +180,7 @@ static double BinarySearch( Scenario* scenario, double targeted_cpu_load, double low, double high, const std::map& per_worker_credential_types, 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 current_cpu_load = GetCpuLoad(scenario, mid, per_worker_credential_types, success); @@ -189,9 +190,9 @@ static double BinarySearch( break; } if (targeted_cpu_load <= current_cpu_load) { - high = mid - FLAGS_stride; + high = mid - absl::GetFlag(FLAGS_stride); } else { - low = mid + FLAGS_stride; + low = mid + absl::GetFlag(FLAGS_stride); } } @@ -229,10 +230,11 @@ static double SearchOfferedLoad( static bool QpsDriver() { std::string json; - bool scfile = (!FLAGS_scenarios_file.empty()); - bool scjson = (!FLAGS_scenarios_json.empty()); - if ((!scfile && !scjson && !FLAGS_quit) || - (scfile && (scjson || FLAGS_quit)) || (scjson && FLAGS_quit)) { + bool scfile = (!absl::GetFlag(FLAGS_scenarios_file).empty()); + bool scjson = (!absl::GetFlag(FLAGS_scenarios_json).empty()); + if ((!scfile && !scjson && !absl::GetFlag(FLAGS_quit)) || + (scfile && (scjson || absl::GetFlag(FLAGS_quit))) || + (scjson && absl::GetFlag(FLAGS_quit))) { gpr_log(GPR_ERROR, "Exactly one of --scenarios_file, --scenarios_json, " "or --quit must be set"); @@ -242,7 +244,7 @@ static bool QpsDriver() { auto per_worker_credential_types = ConstructPerWorkerCredentialTypesMap(); if (scfile) { // 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); fseek(json_file, 0, SEEK_END); long len = ftell(json_file); @@ -253,9 +255,10 @@ static bool QpsDriver() { json = std::string(data, data + len); delete[] data; } else if (scjson) { - json = FLAGS_scenarios_json.c_str(); - } else if (FLAGS_quit) { - return RunQuit(FLAGS_credential_type, per_worker_credential_types); + json = absl::GetFlag(FLAGS_scenarios_json).c_str(); + } else if (absl::GetFlag(FLAGS_quit)) { + return RunQuit(absl::GetFlag(FLAGS_credential_type), + per_worker_credential_types); } // Parse into an array of scenarios @@ -267,15 +270,16 @@ static bool QpsDriver() { GPR_ASSERT(scenarios.scenarios_size() > 0); 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); RunAndReport(scenario, per_worker_credential_types, &success); } else { - if (FLAGS_search_param == "offered_load") { + if (absl::GetFlag(FLAGS_search_param) == "offered_load") { Scenario* scenario = scenarios.mutable_scenarios(i); - double targeted_offered_load = SearchOfferedLoad( - FLAGS_initial_search_value, FLAGS_targeted_cpu_load, scenario, - per_worker_credential_types, &success); + double targeted_offered_load = + SearchOfferedLoad(absl::GetFlag(FLAGS_initial_search_value), + absl::GetFlag(FLAGS_targeted_cpu_load), scenario, + per_worker_credential_types, &success); gpr_log(GPR_INFO, "targeted_offered_load %f", targeted_offered_load); GetCpuLoad(scenario, targeted_offered_load, per_worker_credential_types, &success); diff --git a/test/cpp/qps/worker.cc b/test/cpp/qps/worker.cc index c88b60e2f10..6f528f20af9 100644 --- a/test/cpp/qps/worker.cc +++ b/test/cpp/qps/worker.cc @@ -16,25 +16,24 @@ * */ +#include +#include #include #include #include #include -#include -#include -#include - +#include "absl/flags/flag.h" #include "test/core/util/test_config.h" #include "test/cpp/qps/qps_worker.h" #include "test/cpp/util/test_config.h" #include "test/cpp/util/test_credentials_provider.h" -DEFINE_int32(driver_port, 0, "Port for communication with driver"); -DEFINE_int32(server_port, 0, "Port for operation as a server"); -DEFINE_string(credential_type, grpc::testing::kInsecureCredentialsType, - "Credential type for communication with driver"); +ABSL_FLAG(int32_t, driver_port, 0, "Port for communication with driver"); +ABSL_FLAG(int32_t, server_port, 0, "Port for operation as a server"); +ABSL_FLAG(std::string, credential_type, grpc::testing::kInsecureCredentialsType, + "Credential type for communication with driver"); static bool got_sigint = false; @@ -46,7 +45,9 @@ namespace testing { std::vector* g_inproc_servers = nullptr; 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()) { gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), diff --git a/test/cpp/thread_manager/BUILD b/test/cpp/thread_manager/BUILD index 03ecd2b1661..2b1ef7a90af 100644 --- a/test/cpp/thread_manager/BUILD +++ b/test/cpp/thread_manager/BUILD @@ -25,7 +25,6 @@ grpc_cc_test( name = "thread_manager_test", srcs = ["thread_manager_test.cc"], external_deps = [ - "gflags", "gtest", ], deps = [ diff --git a/test/cpp/thread_manager/thread_manager_test.cc b/test/cpp/thread_manager/thread_manager_test.cc index 882d2cd803d..31d6ad5029c 100644 --- a/test/cpp/thread_manager/thread_manager_test.cc +++ b/test/cpp/thread_manager/thread_manager_test.cc @@ -22,7 +22,6 @@ #include #include -#include #include #include #include diff --git a/test/cpp/util/BUILD b/test/cpp/util/BUILD index 21bf8535d90..6520a80e58b 100644 --- a/test/cpp/util/BUILD +++ b/test/cpp/util/BUILD @@ -30,7 +30,7 @@ grpc_cc_library( "test_config.h", ], external_deps = [ - "gflags", + "absl/flags:parse", ], deps = [ "//:gpr", @@ -75,7 +75,7 @@ grpc_cc_library( "test_credentials_provider.h", ], external_deps = [ - "gflags", + "absl/flags:flag", "protobuf", ], deps = [ @@ -133,7 +133,7 @@ grpc_cc_library( "service_describer.h", ], external_deps = [ - "gflags", + "absl/flags:flag", "protobuf", "protobuf_clib", ], @@ -153,7 +153,7 @@ grpc_cc_library( "grpc_tool.h", ], external_deps = [ - "gflags", + "absl/flags:flag", ], deps = [ ":grpc_cli_utils", @@ -188,6 +188,7 @@ grpc_cc_test( "//src/proto/grpc/testing:simple_messages.proto", ], external_deps = [ + "absl/flags:flag", "gtest", ], tags = [ @@ -300,7 +301,7 @@ grpc_cc_binary( "grpc_cli.cc", ], external_deps = [ - "gflags", + "absl/flags:flag", ], deps = [ ":grpc++_proto_reflection_desc_db", @@ -315,7 +316,7 @@ grpc_cc_binary( name = "channelz_sampler", srcs = ["channelz_sampler.cc"], external_deps = [ - "gflags", + "absl/flags:flag", ], language = "c++", tags = [ @@ -340,7 +341,6 @@ grpc_cc_test( ":channelz_sampler", ], external_deps = [ - "gflags", "gtest", ], tags = [ diff --git a/test/cpp/util/channelz_sampler.cc b/test/cpp/util/channelz_sampler.cc index faae640636d..fc6afed72f2 100644 --- a/test/cpp/util/channelz_sampler.cc +++ b/test/cpp/util/channelz_sampler.cc @@ -25,9 +25,9 @@ #include #include +#include "absl/flags/flag.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" -#include "gflags/gflags.h" #include "google/protobuf/text_format.h" #include "grpc/grpc.h" #include "grpc/support/port_platform.h" @@ -48,11 +48,13 @@ #include "test/cpp/util/test_config.h" #include "test/cpp/util/test_credentials_provider.h" -DEFINE_string(server_address, "", "channelz server address"); -DEFINE_string(custom_credentials_type, "", "custom credentials type"); -DEFINE_int64(sampling_times, 1, "number of sampling"); -DEFINE_int64(sampling_interval_seconds, 0, "sampling interval in seconds"); -DEFINE_string(output_json, "", "output filename in json format"); +ABSL_FLAG(std::string, server_address, "", "channelz server address"); +ABSL_FLAG(std::string, custom_credentials_type, "", "custom credentials type"); +ABSL_FLAG(int64_t, sampling_times, 1, "number of sampling"); +// TODO(Capstan): Consider using absl::Duration +ABSL_FLAG(int64_t, sampling_interval_seconds, 0, + "sampling interval in seconds"); +ABSL_FLAG(std::string, output_json, "", "output filename in json format"); namespace { using grpc::ClientContext; @@ -507,7 +509,8 @@ class ChannelzSampler final { std::string start, finish; gpr_timespec ago = gpr_time_sub( 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; const time_t time_now = now_.tv_sec; ss << std::put_time(std::localtime(&time_now), "%F %T"); @@ -558,15 +561,18 @@ class ChannelzSampler final { int main(int argc, char** argv) { grpc::testing::TestEnvironment env(argc, argv); grpc::testing::InitTest(&argc, &argv, true); - std::ofstream output_file(FLAGS_output_json); - for (int i = 0; i < FLAGS_sampling_times; ++i) { + std::ofstream output_file(absl::GetFlag(FLAGS_output_json)); + for (int i = 0; i < absl::GetFlag(FLAGS_sampling_times); ++i) { 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 " - << FLAGS_sampling_interval_seconds << "s..." << std::endl; + << absl::GetFlag(FLAGS_sampling_interval_seconds) << "s..." + << std::endl; const gpr_timespec kDelay = gpr_time_add( 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); std::cout << "##### " << i << "th sampling #####" << std::endl; channelz_sampler.RecordNow(); @@ -575,7 +581,7 @@ int main(int argc, char** argv) { channelz_sampler.GetTopChannelsRPC(); channelz_sampler.TraverseTopChannels(); channelz_sampler.DumpStdout(); - if (!FLAGS_output_json.empty()) { + if (!absl::GetFlag(FLAGS_output_json).empty()) { output_file << channelz_sampler.DumpJson() << "\n" << std::flush; } } diff --git a/test/cpp/util/cli_credentials.cc b/test/cpp/util/cli_credentials.cc index 053f3ad5cd3..2c4f7b1b7e1 100644 --- a/test/cpp/util/cli_credentials.cc +++ b/test/cpp/util/cli_credentials.cc @@ -18,45 +18,43 @@ #include "test/cpp/util/cli_credentials.h" -#include #include #include #include +#include "absl/flags/flag.h" #include "src/core/lib/iomgr/load_file.h" -DEFINE_bool( - enable_ssl, false, - "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); -DEFINE_bool(use_auth, false, - "Whether to create default google credentials. Deprecated. Use " - "--channel_creds_type=gdc."); -DEFINE_string( - access_token, "", +ABSL_FLAG(bool, enable_ssl, false, + "Whether to use ssl/tls. Deprecated. Use --channel_creds_type=ssl."); +ABSL_FLAG(bool, use_auth, false, + "Whether to create default google credentials. Deprecated. Use " + "--channel_creds_type=gdc."); +ABSL_FLAG( + std::string, access_token, "", "The access token that will be sent to the server to authenticate RPCs. " "Deprecated. Use --call_creds=access_token=."); -DEFINE_string( - ssl_target, "", +ABSL_FLAG( + std::string, ssl_target, "", "If not empty, treat the server host name as this for ssl/tls certificate " "validation."); -DEFINE_string( - ssl_client_cert, "", +ABSL_FLAG( + std::string, ssl_client_cert, "", "If not empty, load this PEM formatted client certificate file. Requires " "use of --ssl_client_key."); -DEFINE_string( - ssl_client_key, "", - "If not empty, load this PEM formatted private key. Requires use of " - "--ssl_client_cert"); -DEFINE_string( - local_connect_type, "local_tcp", +ABSL_FLAG(std::string, ssl_client_key, "", + "If not empty, load this PEM formatted private key. Requires use of " + "--ssl_client_cert"); +ABSL_FLAG( + std::string, local_connect_type, "local_tcp", "The type of local connections for which local channel credentials will " "be applied. Should be local_tcp or uds."); -DEFINE_string( - channel_creds_type, "", +ABSL_FLAG( + std::string, channel_creds_type, "", "The channel creds type: insecure, ssl, gdc (Google Default Credentials), " "alts, or local."); -DEFINE_string( - call_creds, "", +ABSL_FLAG( + std::string, call_creds, "", "Call credentials to use: none (default), or access_token=. If " "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 { // Compatibility logic for --enable_ssl. - if (FLAGS_enable_ssl) { + if (absl::GetFlag(FLAGS_enable_ssl)) { fprintf(stderr, "warning: --enable_ssl is deprecated. Use " "--channel_creds_type=ssl.\n"); return "ssl"; } // Compatibility logic for --use_auth. - if (FLAGS_access_token.empty() && FLAGS_use_auth) { + if (absl::GetFlag(FLAGS_access_token).empty() && + absl::GetFlag(FLAGS_use_auth)) { fprintf(stderr, "warning: --use_auth is deprecated. Use " "--channel_creds_type=gdc.\n"); @@ -102,110 +101,116 @@ std::string CliCredentials::GetDefaultChannelCredsType() const { } std::string CliCredentials::GetDefaultCallCreds() const { - if (!FLAGS_access_token.empty()) { + if (!absl::GetFlag(FLAGS_access_token).empty()) { fprintf(stderr, "warning: --access_token is deprecated. Use " "--call_creds=access_token=.\n"); - return std::string("access_token=") + FLAGS_access_token; + return std::string("access_token=") + absl::GetFlag(FLAGS_access_token); } return "none"; } std::shared_ptr CliCredentials::GetChannelCredentials() const { - if (FLAGS_channel_creds_type == "insecure") { + if (absl::GetFlag(FLAGS_channel_creds_type) == "insecure") { return grpc::InsecureChannelCredentials(); - } else if (FLAGS_channel_creds_type == "ssl") { + } else if (absl::GetFlag(FLAGS_channel_creds_type) == "ssl") { grpc::SslCredentialsOptions ssl_creds_options; // 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_LOG_IF_ERROR( "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 = grpc::StringFromCopiedSlice(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_LOG_IF_ERROR( "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 = grpc::StringFromCopiedSlice(key_slice); grpc_slice_unref(key_slice); } 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(); - } else if (FLAGS_channel_creds_type == "alts") { + } else if (absl::GetFlag(FLAGS_channel_creds_type) == "alts") { return grpc::experimental::AltsCredentials( grpc::experimental::AltsCredentialsOptions()); - } else if (FLAGS_channel_creds_type == "local") { - if (FLAGS_local_connect_type == "local_tcp") { + } else if (absl::GetFlag(FLAGS_channel_creds_type) == "local") { + if (absl::GetFlag(FLAGS_local_connect_type) == "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); } else { fprintf(stderr, "--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, "--channel_creds_type=%s invalid; must be insecure, ssl, gdc, " "alts, or local.\n", - FLAGS_channel_creds_type.c_str()); + absl::GetFlag(FLAGS_channel_creds_type).c_str()); return std::shared_ptr(); } std::shared_ptr CliCredentials::GetCallCredentials() const { - if (IsAccessToken(FLAGS_call_creds)) { - return grpc::AccessTokenCredentials(AccessToken(FLAGS_call_creds)); + if (IsAccessToken(absl::GetFlag(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. return std::shared_ptr(); } fprintf(stderr, "--call_creds=%s invalid; must be none " "or access_token=.\n", - FLAGS_call_creds.c_str()); + absl::GetFlag(FLAGS_call_creds).c_str()); return std::shared_ptr(); } std::shared_ptr CliCredentials::GetCredentials() const { - if (FLAGS_call_creds.empty()) { - FLAGS_call_creds = GetDefaultCallCreds(); - } else if (!FLAGS_access_token.empty() && !IsAccessToken(FLAGS_call_creds)) { + if (absl::GetFlag(FLAGS_call_creds).empty()) { + absl::SetFlag(&FLAGS_call_creds, GetDefaultCallCreds()); + } else if (!absl::GetFlag(FLAGS_access_token).empty() && + !IsAccessToken(absl::GetFlag(FLAGS_call_creds))) { fprintf(stderr, "warning: ignoring --access_token because --call_creds " "already set to %s.\n", - FLAGS_call_creds.c_str()); + absl::GetFlag(FLAGS_call_creds).c_str()); } - if (FLAGS_channel_creds_type.empty()) { - FLAGS_channel_creds_type = GetDefaultChannelCredsType(); - } else if (FLAGS_enable_ssl && FLAGS_channel_creds_type != "ssl") { + if (absl::GetFlag(FLAGS_channel_creds_type).empty()) { + absl::SetFlag(&FLAGS_channel_creds_type, GetDefaultChannelCredsType()); + } else if (absl::GetFlag(FLAGS_enable_ssl) && + absl::GetFlag(FLAGS_channel_creds_type) == "ssl") { fprintf(stderr, "warning: ignoring --enable_ssl because " "--channel_creds_type already set to %s.\n", - FLAGS_channel_creds_type.c_str()); - } else if (FLAGS_use_auth && FLAGS_channel_creds_type != "gdc") { + absl::GetFlag(FLAGS_channel_creds_type).c_str()); + } else if (absl::GetFlag(FLAGS_use_auth) && + absl::GetFlag(FLAGS_channel_creds_type) == "gdc") { fprintf(stderr, "warning: ignoring --use_auth because " "--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. - if (IsAccessToken(FLAGS_call_creds) && - FLAGS_channel_creds_type == "insecure") { + if (IsAccessToken(absl::GetFlag(FLAGS_call_creds)) && + absl::GetFlag(FLAGS_channel_creds_type) == "insecure") { fprintf(stderr, "warning: --channel_creds_type=insecure upgraded to ssl because " "an access token was provided.\n"); - FLAGS_channel_creds_type = "ssl"; + absl::SetFlag(&FLAGS_channel_creds_type, "ssl"); } std::shared_ptr channel_creds = GetChannelCredentials(); @@ -236,9 +241,9 @@ const std::string CliCredentials::GetCredentialUsage() const { } const std::string CliCredentials::GetSslTargetNameOverride() const { - bool use_ssl = - FLAGS_channel_creds_type == "ssl" || FLAGS_channel_creds_type == "gdc"; - return use_ssl ? FLAGS_ssl_target : ""; + bool use_ssl = absl::GetFlag(FLAGS_channel_creds_type) == "ssl" || + absl::GetFlag(FLAGS_channel_creds_type) == "gdc"; + return use_ssl ? absl::GetFlag(FLAGS_ssl_target) : ""; } } // namespace testing diff --git a/test/cpp/util/create_test_channel.cc b/test/cpp/util/create_test_channel.cc index bb2e4fa2cfd..67b6bde58e4 100644 --- a/test/cpp/util/create_test_channel.cc +++ b/test/cpp/util/create_test_channel.cc @@ -18,20 +18,18 @@ #include "test/cpp/util/create_test_channel.h" -#include - #include #include #include +#include "absl/flags/flag.h" #include "test/cpp/util/test_credentials_provider.h" -DEFINE_string( - grpc_test_use_grpclb_with_child_policy, "", - "If non-empty, set a static service config on channels created by " - "grpc::CreateTestChannel, that configures the grpclb LB policy " - "with a child policy being the value of this flag (e.g. round_robin " - "or pick_first)."); +ABSL_FLAG(std::string, grpc_test_use_grpclb_with_child_policy, "", + "If non-empty, set a static service config on channels created by " + "grpc::CreateTestChannel, that configures the grpclb LB policy " + "with a child policy being the value of this flag (e.g. round_robin " + "or pick_first)."); namespace grpc { @@ -59,12 +57,13 @@ void AddProdSslType() { } void MaybeSetCustomChannelArgs(grpc::ChannelArguments* args) { - if (!FLAGS_grpc_test_use_grpclb_with_child_policy.empty()) { - args->SetString("grpc.service_config", - "{\"loadBalancingConfig\":[{\"grpclb\":{\"childPolicy\":[{" - "\"" + - FLAGS_grpc_test_use_grpclb_with_child_policy + - "\":{}}]}}]}"); + if (!absl::GetFlag(FLAGS_grpc_test_use_grpclb_with_child_policy).empty()) { + args->SetString( + "grpc.service_config", + "{\"loadBalancingConfig\":[{\"grpclb\":{\"childPolicy\":[{" + "\"" + + absl::GetFlag(FLAGS_grpc_test_use_grpclb_with_child_policy) + + "\":{}}]}}]}"); } } diff --git a/test/cpp/util/grpc_cli.cc b/test/cpp/util/grpc_cli.cc index 614a578cc28..de085d67035 100644 --- a/test/cpp/util/grpc_cli.cc +++ b/test/cpp/util/grpc_cli.cc @@ -58,17 +58,18 @@ address of the connection that each RPC is made on to stderr. */ +#include + #include #include #include -#include -#include +#include "absl/flags/flag.h" #include "test/cpp/util/cli_credentials.h" #include "test/cpp/util/grpc_tool.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) { if (outfile.empty()) { @@ -86,5 +87,6 @@ int main(int argc, char** argv) { return grpc::testing::GrpcToolMainLib( 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)); } diff --git a/test/cpp/util/grpc_tool.cc b/test/cpp/util/grpc_tool.cc index eed3ddb3dcb..a65fb4d1aa9 100644 --- a/test/cpp/util/grpc_tool.cc +++ b/test/cpp/util/grpc_tool.cc @@ -18,7 +18,6 @@ #include "test/cpp/util/grpc_tool.h" -#include #include #include #include @@ -35,8 +34,8 @@ #include #include +#include "absl/flags/flag.h" #include "absl/memory/memory.h" - #include "test/cpp/util/cli_call.h" #include "test/cpp/util/proto_file_parser.h" #include "test/cpp/util/proto_reflection_descriptor_database.h" @@ -48,38 +47,37 @@ #include #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 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 { class GrpcTool { @@ -138,7 +136,7 @@ size_t ArraySize(T& a) { void ParseMetadataFlag( std::multimap* client_metadata) { - if (FLAGS_metadata.empty()) { + if (absl::GetFlag(FLAGS_metadata).empty()) { return; } std::vector fields; @@ -146,11 +144,11 @@ void ParseMetadataFlag( const char escape = '\\'; size_t cur = -1; std::stringstream ss; - while (++cur < FLAGS_metadata.length()) { - switch (FLAGS_metadata.at(cur)) { + while (++cur < absl::GetFlag(FLAGS_metadata).length()) { + switch (absl::GetFlag(FLAGS_metadata).at(cur)) { case escape: - if (cur < FLAGS_metadata.length() - 1) { - char c = FLAGS_metadata.at(++cur); + if (cur < absl::GetFlag(FLAGS_metadata).length() - 1) { + char c = absl::GetFlag(FLAGS_metadata).at(++cur); if (c == delim || c == escape) { ss << c; continue; @@ -164,7 +162,7 @@ void ParseMetadataFlag( ss.clear(); break; default: - ss << FLAGS_metadata.at(cur); + ss << absl::GetFlag(FLAGS_metadata).at(cur); } } 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 = false) { fprintf(stderr, "got response.\n"); - if (!FLAGS_binary_output) { + if (!absl::GetFlag(FLAGS_binary_output)) { gpr_mu_lock(parser_mu); serialized_response_proto = parser->GetFormattedStringFromMethod( method_name, serialized_response_proto, false /* is_request */, - FLAGS_json_output); + absl::GetFlag(FLAGS_json_output)); if (parser->HasError() && print_mode) { fprintf(stderr, "Failed to parse response.\n"); } @@ -231,9 +229,9 @@ std::shared_ptr CreateCliChannel( if (!cred.GetSslTargetNameOverride().empty()) { args.SetSslTargetNameOverride(cred.GetSslTargetNameOverride()); } - if (!FLAGS_default_service_config.empty()) { + if (!absl::GetFlag(FLAGS_default_service_config).empty()) { 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(), args); @@ -374,7 +372,7 @@ bool GrpcTool::ListServices(int argc, const char** argv, if (argc < 2) { // List all services, if --l is passed, then include full description, // otherwise include a summarized list only. - if (FLAGS_l) { + if (absl::GetFlag(FLAGS_l)) { output = DescribeServiceList(service_list, desc_pool); } else { 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); if (service != nullptr) { if (method_name.empty()) { - output = FLAGS_l ? DescribeService(service) : SummarizeService(service); + output = absl::GetFlag(FLAGS_l) ? DescribeService(service) + : SummarizeService(service); } else { method_name.insert(0, 1, '.'); method_name.insert(0, service_name); const grpc::protobuf::MethodDescriptor* method = desc_pool.FindMethodByName(method_name); if (method != nullptr) { - output = FLAGS_l ? DescribeMethod(method) : SummarizeMethod(method); + output = absl::GetFlag(FLAGS_l) ? DescribeMethod(method) + : SummarizeMethod(method); } else { fprintf(stderr, "Method %s not found in service %s.\n", 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 = desc_pool.FindMethodByName(service_name); if (method != nullptr) { - output = FLAGS_l ? DescribeMethod(method) : SummarizeMethod(method); + output = absl::GetFlag(FLAGS_l) ? DescribeMethod(method) + : SummarizeMethod(method); } else { fprintf(stderr, "Service or method %s not found.\n", service_name.c_str()); @@ -509,15 +510,17 @@ bool GrpcTool::CallMethod(int argc, const char** argv, std::unique_ptr parser; std::string serialized_request_proto; CliArgs cli_args; - cli_args.timeout = FLAGS_timeout; + cli_args.timeout = absl::GetFlag(FLAGS_timeout); bool print_mode = false; std::shared_ptr channel = 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( - 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()) { fprintf( 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; } else { formatted_method_name = parser->GetFormattedMethodName(method_name); @@ -544,7 +547,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv, std::istream* input_stream; std::ifstream input_file; - if (FLAGS_batch) { + if (absl::GetFlag(FLAGS_batch)) { fprintf(stderr, "Batch mode for streaming RPC is not supported.\n"); return false; } @@ -554,19 +557,20 @@ bool GrpcTool::CallMethod(int argc, const char** argv, PrintMetadata(client_metadata, "Sending client initial metadata:"); 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", formatted_method_name.c_str(), call.peer().c_str()); } - if (FLAGS_infile.empty()) { + if (absl::GetFlag(FLAGS_infile).empty()) { if (isatty(fileno(stdin))) { print_mode = true; fprintf(stderr, "reading streaming request message from stdin...\n"); } input_stream = &std::cin; } 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; } @@ -580,14 +584,14 @@ bool GrpcTool::CallMethod(int argc, const char** argv, while (!request_text.empty() || (!input_stream->eof() && getline(*input_stream, line))) { if (!request_text.empty()) { - if (FLAGS_binary_input) { + if (absl::GetFlag(FLAGS_binary_input)) { serialized_request_proto = request_text; request_text.clear(); } else { gpr_mu_lock(&parser_mu); serialized_request_proto = parser->GetSerializedProtoFromMethod( method_name, request_text, true /* is_request */, - FLAGS_json_input); + absl::GetFlag(FLAGS_json_input)); request_text.clear(); if (parser->HasError()) { if (print_mode) { @@ -636,7 +640,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv, } } else { // parser->IsStreaming(method_name, true /* is_request */) - if (FLAGS_batch) { + if (absl::GetFlag(FLAGS_batch)) { if (parser->IsStreaming(method_name, false /* is_request */)) { fprintf(stderr, "Batch mode for streaming RPC is not supported.\n"); return false; @@ -645,14 +649,15 @@ bool GrpcTool::CallMethod(int argc, const char** argv, std::istream* input_stream; std::ifstream input_file; - if (FLAGS_infile.empty()) { + if (absl::GetFlag(FLAGS_infile).empty()) { if (isatty(fileno(stdin))) { print_mode = true; fprintf(stderr, "reading request messages from stdin...\n"); } input_stream = &std::cin; } 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; } @@ -667,13 +672,13 @@ bool GrpcTool::CallMethod(int argc, const char** argv, while (!request_text.empty() || (!input_stream->eof() && getline(*input_stream, line))) { if (!request_text.empty()) { - if (FLAGS_binary_input) { + if (absl::GetFlag(FLAGS_binary_input)) { serialized_request_proto = request_text; request_text.clear(); } else { serialized_request_proto = parser->GetSerializedProtoFromMethod( method_name, request_text, true /* is_request */, - FLAGS_json_input); + absl::GetFlag(FLAGS_json_input)); request_text.clear(); if (parser->HasError()) { if (print_mode) { @@ -688,7 +693,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv, server_initial_metadata, server_trailing_metadata; 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", 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:"); } - if (FLAGS_binary_output) { + if (absl::GetFlag(FLAGS_binary_output)) { if (!callback(serialized_response_proto)) { break; } } else { std::string response_text = parser->GetFormattedStringFromMethod( method_name, serialized_response_proto, - false /* is_request */, FLAGS_json_output); + false /* is_request */, absl::GetFlag(FLAGS_json_output)); if (parser->HasError() && print_mode) { fprintf(stderr, "Failed to parse response.\n"); @@ -753,29 +758,31 @@ bool GrpcTool::CallMethod(int argc, const char** argv, } if (argc == 3) { - if (!FLAGS_infile.empty()) { + if (!absl::GetFlag(FLAGS_infile).empty()) { fprintf(stderr, "warning: request given in argv, ignoring --infile\n"); } } else { std::stringstream input_stream; - if (FLAGS_infile.empty()) { + if (absl::GetFlag(FLAGS_infile).empty()) { if (isatty(fileno(stdin))) { fprintf(stderr, "reading request message from stdin...\n"); } input_stream << std::cin.rdbuf(); } 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_file.close(); } request_text = input_stream.str(); } - if (FLAGS_binary_input) { + if (absl::GetFlag(FLAGS_binary_input)) { serialized_request_proto = request_text; } else { serialized_request_proto = parser->GetSerializedProtoFromMethod( - method_name, request_text, true /* is_request */, FLAGS_json_input); + method_name, request_text, true /* is_request */, + absl::GetFlag(FLAGS_json_input)); if (parser->HasError()) { fprintf(stderr, "Failed to parse request.\n"); return false; @@ -791,7 +798,7 @@ bool GrpcTool::CallMethod(int argc, const char** argv, PrintMetadata(client_metadata, "Sending client initial metadata:"); 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", formatted_method_name.c_str(), call.peer().c_str()); } @@ -802,10 +809,10 @@ bool GrpcTool::CallMethod(int argc, const char** argv, &serialized_response_proto, receive_initial_metadata ? &server_initial_metadata : nullptr); receive_initial_metadata = false) { - if (!FLAGS_binary_output) { + if (!absl::GetFlag(FLAGS_binary_output)) { serialized_response_proto = parser->GetFormattedStringFromMethod( method_name, serialized_response_proto, false /* is_request */, - FLAGS_json_output); + absl::GetFlag(FLAGS_json_output)); if (parser->HasError()) { fprintf(stderr, "Failed to parse response.\n"); return false; @@ -867,29 +874,32 @@ bool GrpcTool::ParseMessage(int argc, const char** argv, if (argc == 3) { message_text = argv[2]; - if (!FLAGS_infile.empty()) { + if (!absl::GetFlag(FLAGS_infile).empty()) { fprintf(stderr, "warning: message given in argv, ignoring --infile.\n"); } } else { std::stringstream input_stream; - if (FLAGS_infile.empty()) { + if (absl::GetFlag(FLAGS_infile).empty()) { if (isatty(fileno(stdin))) { fprintf(stderr, "reading request message from stdin...\n"); } input_stream << std::cin.rdbuf(); } 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_file.close(); } 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 channel = CreateCliChannel(server_address, cred); parser = absl::make_unique( - 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()) { fprintf( 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; } else { serialized_request_proto = parser->GetSerializedProtoFromMessageType( - type_name, message_text, FLAGS_json_input); + type_name, message_text, absl::GetFlag(FLAGS_json_input)); if (parser->HasError()) { fprintf(stderr, "Failed to serialize the message.\n"); return false; } } - if (FLAGS_binary_output) { + if (absl::GetFlag(FLAGS_binary_output)) { output_ss << serialized_request_proto; } else { std::string output_text; 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()) { fprintf(stderr, "Failed to deserialize the message.\n"); return false; @@ -937,10 +947,10 @@ bool GrpcTool::ToText(int argc, const char** argv, const CliCredentials& cred, " --infile ; Input filename (defaults to stdin)\n" " --outfile ; Output filename (defaults to stdout)\n"); - FLAGS_protofiles = argv[0]; - FLAGS_remotedb = false; - FLAGS_binary_input = true; - FLAGS_binary_output = false; + absl::SetFlag(&FLAGS_protofiles, argv[0]); + absl::SetFlag(&FLAGS_remotedb, false); + absl::SetFlag(&FLAGS_binary_input, true); + absl::SetFlag(&FLAGS_binary_output, false); 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" " --outfile ; Output filename (defaults to stdout)\n"); - FLAGS_protofiles = argv[0]; - FLAGS_remotedb = false; - FLAGS_binary_input = true; - FLAGS_binary_output = false; - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_protofiles, argv[0]); + absl::SetFlag(&FLAGS_remotedb, false); + absl::SetFlag(&FLAGS_binary_input, true); + absl::SetFlag(&FLAGS_binary_output, false); + absl::SetFlag(&FLAGS_json_output, true); 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" " --outfile ; Output filename (defaults to stdout)\n"); - FLAGS_protofiles = argv[0]; - FLAGS_remotedb = false; - FLAGS_binary_input = false; - FLAGS_binary_output = true; + absl::SetFlag(&FLAGS_protofiles, argv[0]); + absl::SetFlag(&FLAGS_remotedb, false); + absl::SetFlag(&FLAGS_binary_input, false); + absl::SetFlag(&FLAGS_binary_output, true); return ParseMessage(argc, argv, cred, callback); } diff --git a/test/cpp/util/grpc_tool_test.cc b/test/cpp/util/grpc_tool_test.cc index c57afedcc7a..8278e2870e2 100644 --- a/test/cpp/util/grpc_tool_test.cc +++ b/test/cpp/util/grpc_tool_test.cc @@ -18,7 +18,6 @@ #include "test/cpp/util/grpc_tool.h" -#include #include #include #include @@ -33,6 +32,7 @@ #include #include +#include "absl/flags/flag.h" #include "src/core/lib/gpr/env.h" #include "src/core/lib/iomgr/load_file.h" #include "src/proto/grpc/testing/echo.grpc.pb.h" @@ -110,24 +110,22 @@ using grpc::testing::EchoResponse; " }\n" \ "}\n\n" -DECLARE_string(channel_creds_type); -DECLARE_string(ssl_target); +ABSL_DECLARE_FLAG(std::string, channel_creds_type); +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 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 { 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 // proto3 - response->set_message(seconds.count() <= FLAGS_timeout ? "true" : "false"); + response->set_message( + seconds.count() <= absl::GetFlag(FLAGS_timeout) ? "true" : "false"); return Status::OK; } @@ -372,7 +371,7 @@ TEST_F(GrpcToolTest, ListCommand) { const std::string server_address = SetUpServer(); 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(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -391,7 +390,7 @@ TEST_F(GrpcToolTest, ListOneService) { const char* argv[] = {"grpc_cli", "ls", server_address.c_str(), "grpc.testing.EchoTestService"}; // without -l flag - FLAGS_l = false; + absl::SetFlag(&FLAGS_l, false); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -402,7 +401,7 @@ TEST_F(GrpcToolTest, ListOneService) { // with -l flag output_stream.str(std::string()); output_stream.clear(); - FLAGS_l = true; + absl::SetFlag(&FLAGS_l, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -442,7 +441,7 @@ TEST_F(GrpcToolTest, ListOneMethod) { const char* argv[] = {"grpc_cli", "ls", server_address.c_str(), "grpc.testing.EchoTestService.Echo"}; // without -l flag - FLAGS_l = false; + absl::SetFlag(&FLAGS_l, false); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -452,7 +451,7 @@ TEST_F(GrpcToolTest, ListOneMethod) { // with -l flag output_stream.str(std::string()); output_stream.clear(); - FLAGS_l = true; + absl::SetFlag(&FLAGS_l, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -496,11 +495,12 @@ TEST_F(GrpcToolTest, CallCommand) { output_stream.str(std::string()); 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(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; + absl::SetFlag(&FLAGS_json_output, false); // Expected output: // { @@ -520,7 +520,7 @@ TEST_F(GrpcToolTest, CallCommandJsonInput) { const char* argv[] = {"grpc_cli", "call", server_address.c_str(), "Echo", "{ \"message\": \"Hello\"}"}; - FLAGS_json_input = true; + absl::SetFlag(&FLAGS_json_input, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -532,12 +532,12 @@ TEST_F(GrpcToolTest, CallCommandJsonInput) { output_stream.str(std::string()); output_stream.clear(); - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_json_input = false; + absl::SetFlag(&FLAGS_json_output, false); + absl::SetFlag(&FLAGS_json_input, false); // Expected output: // { @@ -562,11 +562,11 @@ TEST_F(GrpcToolTest, CallCommandBatch) { std::istringstream ss("message: 'Hello1'\n\n message: 'Hello2'\n\n"); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; + absl::SetFlag(&FLAGS_batch, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_batch = false; + absl::SetFlag(&FLAGS_batch, false); // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: // "Hello2"\n" @@ -580,13 +580,13 @@ TEST_F(GrpcToolTest, CallCommandBatch) { ss.seekg(0); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_batch, true); + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_batch = false; + absl::SetFlag(&FLAGS_json_output, false); + absl::SetFlag(&FLAGS_batch, false); // Expected output: // { @@ -623,12 +623,12 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInput) { "{\"message\": \"Hello1\"}\n\n{\"message\": \"Hello2\" }\n\n"); std::cin.rdbuf(ss.rdbuf()); - FLAGS_json_input = true; - FLAGS_batch = true; + absl::SetFlag(&FLAGS_json_input, true); + absl::SetFlag(&FLAGS_batch, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_batch = false; + absl::SetFlag(&FLAGS_batch, false); // Expected output: "message: "Hello0"\nmessage: "Hello1"\nmessage: // "Hello2"\n" @@ -642,14 +642,14 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInput) { ss.seekg(0); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_batch, true); + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_batch = false; - FLAGS_json_input = false; + absl::SetFlag(&FLAGS_json_output, false); + absl::SetFlag(&FLAGS_batch, false); + absl::SetFlag(&FLAGS_json_input, false); // Expected output: // { @@ -685,11 +685,11 @@ TEST_F(GrpcToolTest, CallCommandBatchWithBadRequest) { std::istringstream ss("message: 1\n\n message: 'Hello2'\n\n"); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; + absl::SetFlag(&FLAGS_batch, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_batch = false; + absl::SetFlag(&FLAGS_batch, false); // Expected output: "message: "Hello0"\nmessage: "Hello2"\n" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), @@ -702,13 +702,13 @@ TEST_F(GrpcToolTest, CallCommandBatchWithBadRequest) { ss.seekg(0); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_batch, true); + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_batch = false; + absl::SetFlag(&FLAGS_json_output, false); + absl::SetFlag(&FLAGS_batch, false); // Expected output: // { @@ -741,13 +741,13 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInputWithBadRequest) { "{ \"message\": 1 }\n\n { \"message\": \"Hello2\" }\n\n"); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; - FLAGS_json_input = true; + absl::SetFlag(&FLAGS_batch, true); + absl::SetFlag(&FLAGS_json_input, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_input = false; - FLAGS_batch = false; + absl::SetFlag(&FLAGS_json_input, false); + absl::SetFlag(&FLAGS_batch, false); // Expected output: "message: "Hello0"\nmessage: "Hello2"\n" EXPECT_TRUE(nullptr != strstr(output_stream.str().c_str(), @@ -760,15 +760,15 @@ TEST_F(GrpcToolTest, CallCommandBatchJsonInputWithBadRequest) { ss.seekg(0); std::cin.rdbuf(ss.rdbuf()); - FLAGS_batch = true; - FLAGS_json_input = true; - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_batch, true); + absl::SetFlag(&FLAGS_json_input, true); + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_json_input = false; - FLAGS_batch = false; + absl::SetFlag(&FLAGS_json_output, false); + absl::SetFlag(&FLAGS_json_input, false); + absl::SetFlag(&FLAGS_batch, false); // Expected output: // { @@ -827,11 +827,11 @@ TEST_F(GrpcToolTest, CallCommandRequestStreamJsonInput) { "{ \"message\": \"Hello1\" }\n\n{ \"message\": \"Hello2\" }\n\n"); std::cin.rdbuf(ss.rdbuf()); - FLAGS_json_input = true; + absl::SetFlag(&FLAGS_json_input, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_input = false; + absl::SetFlag(&FLAGS_json_input, false); // Expected output: "message: \"Hello0Hello1Hello2\"" 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"); std::cin.rdbuf(ss.rdbuf()); - FLAGS_json_input = true; + absl::SetFlag(&FLAGS_json_input, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_input = false; + absl::SetFlag(&FLAGS_json_input, false); // Expected output: "message: \"Hello0Hello2\"" EXPECT_TRUE(nullptr != @@ -902,7 +902,7 @@ TEST_F(GrpcToolTest, CallCommandWithTimeoutDeadlineSet) { "CheckDeadlineSet"}; // Set timeout to 5000.25 seconds - FLAGS_timeout = 5000.25; + absl::SetFlag(&FLAGS_timeout, 5000.25); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, @@ -923,7 +923,7 @@ TEST_F(GrpcToolTest, CallCommandWithTimeoutDeadlineUpperBound) { "CheckDeadlineUpperBound"}; // Set timeout to 900 seconds - FLAGS_timeout = 900; + absl::SetFlag(&FLAGS_timeout, 900); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, @@ -945,7 +945,7 @@ TEST_F(GrpcToolTest, CallCommandWithNegativeTimeoutValue) { "CheckDeadlineSet"}; // Set timeout to -5 (deadline not set) - FLAGS_timeout = -5; + absl::SetFlag(&FLAGS_timeout, -5); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, @@ -967,7 +967,7 @@ TEST_F(GrpcToolTest, CallCommandWithDefaultTimeoutValue) { "CheckDeadlineSet"}; // 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(), std::bind(PrintStream, &output_stream, @@ -1005,11 +1005,11 @@ TEST_F(GrpcToolTest, CallCommandResponseStream) { output_stream.str(std::string()); output_stream.clear(); - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; + absl::SetFlag(&FLAGS_json_output, false); // Expected output: "{\n \"message\": \"Hello{n}\"\n}\n" for (int i = 0; i < kServerDefaultResponseStreamsToSend; i++) { @@ -1085,8 +1085,8 @@ TEST_F(GrpcToolTest, ParseCommand) { "grpc.testing.EchoResponse", ECHO_RESPONSE_MESSAGE_TEXT_FORMAT}; - FLAGS_binary_input = false; - FLAGS_binary_output = false; + absl::SetFlag(&FLAGS_binary_input, false); + absl::SetFlag(&FLAGS_binary_output, false); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -1098,11 +1098,11 @@ TEST_F(GrpcToolTest, ParseCommand) { output_stream.str(std::string()); output_stream.clear(); - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; + absl::SetFlag(&FLAGS_json_output, false); // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT 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 output_stream.str(std::string()); output_stream.clear(); - FLAGS_binary_output = true; + absl::SetFlag(&FLAGS_binary_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -1119,8 +1119,8 @@ TEST_F(GrpcToolTest, ParseCommand) { output_stream.str(std::string()); output_stream.clear(); argv[4] = binary_data.c_str(); - FLAGS_binary_input = true; - FLAGS_binary_output = false; + absl::SetFlag(&FLAGS_binary_input, true); + absl::SetFlag(&FLAGS_binary_output, false); EXPECT_TRUE(0 == GrpcToolMainLib(5, argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -1129,8 +1129,8 @@ TEST_F(GrpcToolTest, ParseCommand) { EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), ECHO_RESPONSE_MESSAGE_TEXT_FORMAT)); - FLAGS_binary_input = false; - FLAGS_binary_output = false; + absl::SetFlag(&FLAGS_binary_input, false); + absl::SetFlag(&FLAGS_binary_output, false); ShutdownServer(); } @@ -1145,7 +1145,7 @@ TEST_F(GrpcToolTest, ParseCommandJsonFormat) { "grpc.testing.EchoResponse", ECHO_RESPONSE_MESSAGE_JSON_FORMAT}; - FLAGS_json_input = true; + absl::SetFlag(&FLAGS_json_input, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); @@ -1158,12 +1158,12 @@ TEST_F(GrpcToolTest, ParseCommandJsonFormat) { output_stream.str(std::string()); output_stream.clear(); - FLAGS_json_output = true; + absl::SetFlag(&FLAGS_json_output, true); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_json_output = false; - FLAGS_json_input = false; + absl::SetFlag(&FLAGS_json_output, false); + absl::SetFlag(&FLAGS_json_input, false); // Expected output: ECHO_RESPONSE_MESSAGE_JSON_FORMAT EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), @@ -1211,7 +1211,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) { { 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, TestCliCredentials(), std::bind(PrintStream, &output_stream, @@ -1223,7 +1223,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) { { std::stringstream output_stream; - FLAGS_metadata = "key:val\\:val"; + absl::SetFlag(&FLAGS_metadata, "key:val\\:val"); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, @@ -1235,7 +1235,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) { { std::stringstream output_stream; - FLAGS_metadata = "key:val\\\\val"; + absl::SetFlag(&FLAGS_metadata, "key:val\\\\val"); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, @@ -1245,7 +1245,7 @@ TEST_F(GrpcToolTest, CallCommandWithMetadata) { strstr(output_stream.str().c_str(), "message: \"Hello\"")); } - FLAGS_metadata = ""; + absl::SetFlag(&FLAGS_metadata, ""); ShutdownServer(); } @@ -1254,15 +1254,16 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) { const char* argv[] = {"grpc_cli", "call", "localhost:10000", "grpc.testing.EchoTestService.Echo", "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"); 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; - FLAGS_metadata = "key0:val0:key1"; + absl::SetFlag(&FLAGS_metadata, "key0:val0:key1"); // Exit with 1 EXPECT_EXIT( GrpcToolMainLib( @@ -1273,7 +1274,7 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) { { std::stringstream output_stream; - FLAGS_metadata = "key:val\\val"; + absl::SetFlag(&FLAGS_metadata, "key:val\\val"); // Exit with 1 EXPECT_EXIT( GrpcToolMainLib( @@ -1282,8 +1283,8 @@ TEST_F(GrpcToolTest, CallCommandWithBadMetadata) { ::testing::ExitedWithCode(1), ".*Failed to parse metadata flag.*"); } - FLAGS_metadata = ""; - FLAGS_protofiles = ""; + absl::SetFlag(&FLAGS_metadata, ""); + absl::SetFlag(&FLAGS_protofiles, ""); gpr_free(test_srcdir); } @@ -1295,9 +1296,9 @@ TEST_F(GrpcToolTest, ListCommand_OverrideSslHostName) { // --ssl_target=z.test.google.fr" std::stringstream output_stream; const char* argv[] = {"grpc_cli", "ls", server_address.c_str()}; - FLAGS_l = false; - FLAGS_channel_creds_type = "ssl"; - FLAGS_ssl_target = "z.test.google.fr"; + absl::SetFlag(&FLAGS_l, false); + absl::SetFlag(&FLAGS_channel_creds_type, "ssl"); + absl::SetFlag(&FLAGS_ssl_target, "z.test.google.fr"); EXPECT_TRUE( 0 == GrpcToolMainLib( ArraySize(argv), argv, TestCliCredentials(true), @@ -1306,8 +1307,8 @@ TEST_F(GrpcToolTest, ListCommand_OverrideSslHostName) { "grpc.testing.EchoTestService\n" "grpc.reflection.v1alpha.ServerReflection\n")); - FLAGS_channel_creds_type = ""; - FLAGS_ssl_target = ""; + absl::SetFlag(&FLAGS_channel_creds_type, ""); + absl::SetFlag(&FLAGS_ssl_target, ""); ShutdownServer(); } @@ -1320,13 +1321,13 @@ TEST_F(GrpcToolTest, ConfiguringDefaultServiceConfig) { // Just check that the tool is still operational when --default_service_config // is configured. This particular service config is in reality redundant with // the channel's default configuration. - FLAGS_l = false; - FLAGS_default_service_config = - "{\"loadBalancingConfig\":[{\"pick_first\":{}}]}"; + absl::SetFlag(&FLAGS_l, false); + absl::SetFlag(&FLAGS_default_service_config, + "{\"loadBalancingConfig\":[{\"pick_first\":{}}]}"); EXPECT_TRUE(0 == GrpcToolMainLib(ArraySize(argv), argv, TestCliCredentials(), std::bind(PrintStream, &output_stream, std::placeholders::_1))); - FLAGS_default_service_config = ""; + absl::SetFlag(&FLAGS_default_service_config, ""); EXPECT_TRUE(0 == strcmp(output_stream.str().c_str(), "grpc.testing.EchoTestService\n" "grpc.reflection.v1alpha.ServerReflection\n")); diff --git a/test/cpp/util/test_config_cc.cc b/test/cpp/util/test_config_cc.cc index e4b68863354..d7d065c0927 100644 --- a/test/cpp/util/test_config_cc.cc +++ b/test/cpp/util/test_config_cc.cc @@ -16,21 +16,22 @@ * */ -#include -#include "test/cpp/util/test_config.h" +#include -// 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; +#include "absl/flags/parse.h" +#include "test/cpp/util/test_config.h" namespace grpc { namespace testing { void InitTest(int* argc, char*** argv, bool remove_flags) { - ParseCommandLineFlags(argc, argv, remove_flags); + std::vector 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 diff --git a/test/cpp/util/test_credentials_provider.cc b/test/cpp/util/test_credentials_provider.cc index 43da2344739..6ac77985380 100644 --- a/test/cpp/util/test_credentials_provider.cc +++ b/test/cpp/util/test_credentials_provider.cc @@ -19,22 +19,23 @@ #include "test/cpp/util/test_credentials_provider.h" +#include +#include +#include + #include #include #include - #include #include -#include -#include -#include -#include - +#include "absl/flags/flag.h" #include "test/core/end2end/data/ssl_test_data.h" -DEFINE_string(tls_cert_file, "", "The TLS cert file used when --use_tls=true"); -DEFINE_string(tls_key_file, "", "The TLS key file used when --use_tls=true"); +ABSL_FLAG(std::string, tls_cert_file, "", + "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 testing { @@ -56,11 +57,11 @@ std::string ReadFile(const std::string& src_path) { class DefaultCredentialsProvider : public CredentialsProvider { public: DefaultCredentialsProvider() { - if (!FLAGS_tls_key_file.empty()) { - custom_server_key_ = ReadFile(FLAGS_tls_key_file); + if (!absl::GetFlag(FLAGS_tls_key_file).empty()) { + custom_server_key_ = ReadFile(absl::GetFlag(FLAGS_tls_key_file)); } - if (!FLAGS_tls_cert_file.empty()) { - custom_server_cert_ = ReadFile(FLAGS_tls_cert_file); + if (!absl::GetFlag(FLAGS_tls_cert_file).empty()) { + custom_server_cert_ = ReadFile(absl::GetFlag(FLAGS_tls_cert_file)); } } ~DefaultCredentialsProvider() override {}