From fb0c648f171360d7479a1402666d5a67b5bb50d8 Mon Sep 17 00:00:00 2001 From: knight <1004815462@qq.com> Date: Sat, 2 Feb 2019 00:57:17 +0800 Subject: [PATCH 01/51] code clarity: replace HC with health check (#5785) Signed-off-by: knightXun <100481562@qq.com> --- .../configuration/health_checkers/redis.rst | 2 +- docs/root/intro/arch_overview/init.rst | 2 +- .../intro/arch_overview/service_discovery.rst | 2 +- docs/root/operations/fs_flags.rst | 2 +- include/envoy/stream_info/stream_info.h | 4 +-- .../upstream/health_check_host_monitor.h | 3 +- source/common/access_log/access_log_impl.h | 2 +- source/common/config/cds_json.cc | 8 ++--- source/common/http/conn_manager_impl.cc | 2 +- source/common/stream_info/stream_info_impl.h | 6 ++-- source/common/tracing/http_tracer_impl.cc | 2 +- source/common/upstream/health_checker_impl.cc | 24 +++++++------- source/common/upstream/health_checker_impl.h | 4 +-- source/common/upstream/upstream_impl.cc | 4 +-- .../extensions/health_checkers/redis/redis.h | 2 +- .../health_checkers/redis/utility.h | 4 +-- source/server/drain_manager_impl.cc | 2 +- .../common/access_log/access_log_impl_test.cc | 6 ++-- test/common/stream_info/test_util.h | 6 ++-- test/common/tracing/http_tracer_impl_test.cc | 2 +- .../health_checkers/redis/redis_test.cc | 32 +++++++++---------- test/integration/hds_integration_test.cc | 6 ++-- test/mocks/stream_info/mocks.h | 2 +- 23 files changed, 65 insertions(+), 64 deletions(-) diff --git a/docs/root/configuration/health_checkers/redis.rst b/docs/root/configuration/health_checkers/redis.rst index 1859c005adb1e..37af55665b53a 100644 --- a/docs/root/configuration/health_checkers/redis.rst +++ b/docs/root/configuration/health_checkers/redis.rst @@ -7,7 +7,7 @@ The Redis health checker is a custom health checker (with :code:`envoy.health_ch which checks Redis upstream hosts. It sends a Redis PING command and expect a PONG response. The upstream Redis server can respond with anything other than PONG to cause an immediate active health check failure. Optionally, Envoy can perform EXISTS on a user-specified key. If the key does not exist it is considered a -passing healthcheck. This allows the user to mark a Redis instance for maintenance by setting the +passing health check. This allows the user to mark a Redis instance for maintenance by setting the specified :ref:`key ` to any value and waiting for traffic to drain. diff --git a/docs/root/intro/arch_overview/init.rst b/docs/root/intro/arch_overview/init.rst index 1a82a749ec1c2..af0320a57f322 100644 --- a/docs/root/intro/arch_overview/init.rst +++ b/docs/root/intro/arch_overview/init.rst @@ -11,7 +11,7 @@ accepting new connections. :ref:`CDS ` if applicable, waits for one response (or failure), and does the same primary/secondary initialization of CDS provided clusters. * If clusters use :ref:`active health checking `, Envoy also does a - single active HC round. + single active health check round. * Once cluster manager initialization is done, :ref:`RDS ` and :ref:`LDS ` initialize (if applicable). The server doesn't start accepting connections until there has been at least one response (or failure) for diff --git a/docs/root/intro/arch_overview/service_discovery.rst b/docs/root/intro/arch_overview/service_discovery.rst index 52ef417b4034a..f950b82b667a2 100644 --- a/docs/root/intro/arch_overview/service_discovery.rst +++ b/docs/root/intro/arch_overview/service_discovery.rst @@ -122,7 +122,7 @@ paradigm has a number of benefits: whether to route to a host: .. csv-table:: - :header: Discovery Status, HC OK, HC Failed + :header: Discovery Status, Health Check OK, Health Check Failed :widths: 1, 1, 2 Discovered, Route, Don't Route diff --git a/docs/root/operations/fs_flags.rst b/docs/root/operations/fs_flags.rst index 2f4a3b21b6682..a4c154bd207a6 100644 --- a/docs/root/operations/fs_flags.rst +++ b/docs/root/operations/fs_flags.rst @@ -10,5 +10,5 @@ in the directory specified in the :ref:`flags_path option. The currently supported flag files are: drain - If this file exists, Envoy will start in HC failing mode, similar to after the + If this file exists, Envoy will start in health check failing mode, similar to after the :http:post:`/healthcheck/fail` command has been executed. diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index d9145a2571630..14c01cc4486c8 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -260,9 +260,9 @@ class StreamInfo { virtual bool healthCheck() const PURE; /** - * @param is_hc whether the request is a health check request or not. + * @param is_health_check whether the request is a health check request or not. */ - virtual void healthCheck(bool is_hc) PURE; + virtual void healthCheck(bool is_health_check) PURE; /** * @param downstream_local_address sets the local address of the downstream connection. Note that diff --git a/include/envoy/upstream/health_check_host_monitor.h b/include/envoy/upstream/health_check_host_monitor.h index 53a24801a5e77..1358760550961 100644 --- a/include/envoy/upstream/health_check_host_monitor.h +++ b/include/envoy/upstream/health_check_host_monitor.h @@ -10,7 +10,8 @@ namespace Upstream { /** * A monitor for "passive" health check events that might happen on every thread. For example, if a * special HTTP header is received, the data plane may decide to fast fail a host to avoid waiting - * for the full HC interval to elapse before determining the host is active HC failed. + * for the full Health Check interval to elapse before determining the host is active health check + * failed. */ class HealthCheckHostMonitor { public: diff --git a/source/common/access_log/access_log_impl.h b/source/common/access_log/access_log_impl.h index 5c875a33f1770..34c77a22164f3 100644 --- a/source/common/access_log/access_log_impl.h +++ b/source/common/access_log/access_log_impl.h @@ -109,7 +109,7 @@ class OrFilter : public OperatorFilter { }; /** - * Filter out HC requests. + * Filter out health check requests. */ class NotHealthCheckFilter : public Filter { public: diff --git a/source/common/config/cds_json.cc b/source/common/config/cds_json.cc index a7a684a590d62..6addcc437a5d3 100644 --- a/source/common/config/cds_json.cc +++ b/source/common/config/cds_json.cc @@ -30,14 +30,14 @@ void CdsJson::translateHealthCheck(const Json::Object& json_health_check, JSON_UTIL_SET_INTEGER(json_health_check, health_check, healthy_threshold); JSON_UTIL_SET_BOOL(json_health_check, health_check, reuse_connection); - const std::string hc_type = json_health_check.getString("type"); - if (hc_type == "http") { + const std::string health_check_type = json_health_check.getString("type"); + if (health_check_type == "http") { health_check.mutable_http_health_check()->set_path(json_health_check.getString("path")); if (json_health_check.hasObject("service_name")) { health_check.mutable_http_health_check()->set_service_name( json_health_check.getString("service_name")); } - } else if (hc_type == "tcp") { + } else if (health_check_type == "tcp") { auto* tcp_health_check = health_check.mutable_tcp_health_check(); std::string send_text; for (const Json::ObjectSharedPtr& entry : json_health_check.getObjectArray("send")) { @@ -52,7 +52,7 @@ void CdsJson::translateHealthCheck(const Json::Object& json_health_check, tcp_health_check->mutable_receive()->Add()->set_text(hex_string); } } else { - ASSERT(hc_type == "redis"); + ASSERT(health_check_type == "redis"); auto* redis_health_check = health_check.mutable_custom_health_check(); redis_health_check->set_name("envoy.health_checkers.redis"); if (json_health_check.hasObject("redis_key")) { diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index 9c7e3fe220e0f..c941694efb99d 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -498,7 +498,7 @@ void ConnectionManagerImpl::ActiveStream::chargeStats(const HeaderMap& headers) uint64_t response_code = Utility::getResponseStatus(headers); stream_info_.response_code_ = response_code; - if (stream_info_.hc_request_) { + if (stream_info_.health_check_request_) { return; } diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 2e4a49c517aba..4cf6d10c0020f 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -152,9 +152,9 @@ struct StreamInfoImpl : public StreamInfo { return upstream_local_address_; } - bool healthCheck() const override { return hc_request_; } + bool healthCheck() const override { return health_check_request_; } - void healthCheck(bool is_hc) override { hc_request_ = is_hc; } + void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } void setDownstreamLocalAddress( const Network::Address::InstanceConstSharedPtr& downstream_local_address) override { @@ -218,7 +218,7 @@ struct StreamInfoImpl : public StreamInfo { absl::optional response_code_; uint64_t response_flags_{}; Upstream::HostDescriptionConstSharedPtr upstream_host_{}; - bool hc_request_{}; + bool health_check_request_{}; const Router::RouteEntry* route_entry_{}; envoy::api::v2::core::Metadata metadata_{}; FilterStateImpl filter_state_{}; diff --git a/source/common/tracing/http_tracer_impl.cc b/source/common/tracing/http_tracer_impl.cc index 8128b2f7fe84d..662501a4bf382 100644 --- a/source/common/tracing/http_tracer_impl.cc +++ b/source/common/tracing/http_tracer_impl.cc @@ -55,7 +55,7 @@ const std::string& HttpTracerUtility::toString(OperationName operation_name) { Decision HttpTracerUtility::isTracing(const StreamInfo::StreamInfo& stream_info, const Http::HeaderMap& request_headers) { - // Exclude HC requests immediately. + // Exclude health check requests immediately. if (stream_info.healthCheck()) { return {Reason::HealthCheck, false}; } diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index 9b6428f764bda..2e76168e6a374 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -45,37 +45,37 @@ class HealthCheckerFactoryContextImpl : public Server::Configuration::HealthChec }; HealthCheckerSharedPtr -HealthCheckerFactory::create(const envoy::api::v2::core::HealthCheck& hc_config, +HealthCheckerFactory::create(const envoy::api::v2::core::HealthCheck& health_check_config, Upstream::Cluster& cluster, Runtime::Loader& runtime, Runtime::RandomGenerator& random, Event::Dispatcher& dispatcher, AccessLog::AccessLogManager& log_manager) { HealthCheckEventLoggerPtr event_logger; - if (!hc_config.event_log_path().empty()) { + if (!health_check_config.event_log_path().empty()) { event_logger = std::make_unique( - log_manager, dispatcher.timeSystem(), hc_config.event_log_path()); + log_manager, dispatcher.timeSystem(), health_check_config.event_log_path()); } - switch (hc_config.health_checker_case()) { + switch (health_check_config.health_checker_case()) { case envoy::api::v2::core::HealthCheck::HealthCheckerCase::kHttpHealthCheck: - return std::make_shared(cluster, hc_config, dispatcher, runtime, - random, std::move(event_logger)); + return std::make_shared(cluster, health_check_config, dispatcher, + runtime, random, std::move(event_logger)); case envoy::api::v2::core::HealthCheck::HealthCheckerCase::kTcpHealthCheck: - return std::make_shared(cluster, hc_config, dispatcher, runtime, random, - std::move(event_logger)); + return std::make_shared(cluster, health_check_config, dispatcher, runtime, + random, std::move(event_logger)); case envoy::api::v2::core::HealthCheck::HealthCheckerCase::kGrpcHealthCheck: if (!(cluster.info()->features() & Upstream::ClusterInfo::Features::HTTP2)) { throw EnvoyException(fmt::format("{} cluster must support HTTP/2 for gRPC healthchecking", cluster.info()->name())); } - return std::make_shared(cluster, hc_config, dispatcher, runtime, - random, std::move(event_logger)); + return std::make_shared(cluster, health_check_config, dispatcher, + runtime, random, std::move(event_logger)); case envoy::api::v2::core::HealthCheck::HealthCheckerCase::kCustomHealthCheck: { auto& factory = Config::Utility::getAndCheckFactory( - std::string(hc_config.custom_health_check().name())); + std::string(health_check_config.custom_health_check().name())); std::unique_ptr context( new HealthCheckerFactoryContextImpl(cluster, runtime, random, dispatcher, std::move(event_logger))); - return factory.createCustomHealthChecker(hc_config, *context); + return factory.createCustomHealthChecker(health_check_config, *context); } default: // Checked by schema. diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index 67302ca989b22..48690a178de86 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -23,7 +23,7 @@ class HealthCheckerFactory : public Logger::Loggable public: /** * Create a health checker. - * @param hc_config supplies the health check proto. + * @param health_check_config supplies the health check proto. * @param cluster supplies the owning cluster. * @param runtime supplies the runtime loader. * @param random supplies the random generator. @@ -31,7 +31,7 @@ class HealthCheckerFactory : public Logger::Loggable * @param event_logger supplies the event_logger. * @return a health checker. */ - static HealthCheckerSharedPtr create(const envoy::api::v2::core::HealthCheck& hc_config, + static HealthCheckerSharedPtr create(const envoy::api::v2::core::HealthCheck& health_check_config, Upstream::Cluster& cluster, Runtime::Loader& runtime, Runtime::RandomGenerator& random, Event::Dispatcher& dispatcher, diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index 8bd40b96997d8..3229e67a74464 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -749,10 +749,10 @@ void ClusterImplBase::setOutlierDetector(const Outlier::DetectorSharedPtr& outli } void ClusterImplBase::reloadHealthyHosts() { - // Every time a host changes HC state we cause a full healthy host recalculation which + // Every time a host changes Health Check state we cause a full healthy host recalculation which // for expensive LBs (ring, subset, etc.) can be quite time consuming. During startup, this // can also block worker threads by doing this repeatedly. There is no reason to do this - // as we will not start taking traffic until we are initialized. By blocking HC updates + // as we will not start taking traffic until we are initialized. By blocking Health Check updates // while initializing we can avoid this. if (initialization_complete_callback_ != nullptr) { return; diff --git a/source/extensions/health_checkers/redis/redis.h b/source/extensions/health_checkers/redis/redis.h index 5f3c42770d3dc..7de0ddb682519 100644 --- a/source/extensions/health_checkers/redis/redis.h +++ b/source/extensions/health_checkers/redis/redis.h @@ -54,7 +54,7 @@ class RedisHealthChecker : public Upstream::HealthCheckerImplBase { // Extensions::NetworkFilters::RedisProxy::ConnPool::Config bool disableOutlierEvents() const override { return true; } std::chrono::milliseconds opTimeout() const override { - // Allow the main HC infra to control timeout. + // Allow the main Health Check infra to control timeout. return parent_.timeout_ * 2; } diff --git a/source/extensions/health_checkers/redis/utility.h b/source/extensions/health_checkers/redis/utility.h index 40fe9bcaf8eb6..dd012c0b8f52b 100644 --- a/source/extensions/health_checkers/redis/utility.h +++ b/source/extensions/health_checkers/redis/utility.h @@ -14,10 +14,10 @@ namespace RedisHealthChecker { namespace { static const envoy::config::health_checker::redis::v2::Redis -getRedisHealthCheckConfig(const envoy::api::v2::core::HealthCheck& hc_config) { +getRedisHealthCheckConfig(const envoy::api::v2::core::HealthCheck& health_check_config) { ProtobufTypes::MessagePtr config = ProtobufTypes::MessagePtr{new envoy::config::health_checker::redis::v2::Redis()}; - MessageUtil::jsonConvert(hc_config.custom_health_check().config(), *config); + MessageUtil::jsonConvert(health_check_config.custom_health_check().config(), *config); return MessageUtil::downcastAndValidate( *config); } diff --git a/source/server/drain_manager_impl.cc b/source/server/drain_manager_impl.cc index 2e5c468b25881..e7ca1852f57c8 100644 --- a/source/server/drain_manager_impl.cc +++ b/source/server/drain_manager_impl.cc @@ -18,7 +18,7 @@ DrainManagerImpl::DrainManagerImpl(Instance& server, envoy::api::v2::Listener::D : server_(server), drain_type_(drain_type) {} bool DrainManagerImpl::drainClose() const { - // If we are actively HC failed and the drain type is default, always drain close. + // If we are actively health check failed and the drain type is default, always drain close. // // TODO(mattklein123): In relation to x-envoy-immediate-health-check-fail, it would be better // if even in the case of server health check failure we had some period of drain ramp up. This diff --git a/test/common/access_log/access_log_impl_test.cc b/test/common/access_log/access_log_impl_test.cc index f41b113d5c308..378617adb5bac 100644 --- a/test/common/access_log/access_log_impl_test.cc +++ b/test/common/access_log/access_log_impl_test.cc @@ -351,7 +351,7 @@ TEST_F(AccessLogImplTest, healthCheckTrue) { InstanceSharedPtr log = AccessLogFactory::fromProto(parseAccessLogFromJson(json), context_); Http::TestHeaderMapImpl header_map{}; - stream_info_.hc_request_ = true; + stream_info_.health_check_request_ = true; EXPECT_CALL(*file_, write(_)).Times(0); log->log(&header_map, &response_headers_, &response_trailers_, stream_info_); @@ -464,7 +464,7 @@ TEST_F(AccessLogImplTest, andFilter) { { EXPECT_CALL(*file_, write(_)).Times(0); Http::TestHeaderMapImpl header_map{}; - stream_info_.hc_request_ = true; + stream_info_.health_check_request_ = true; log->log(&header_map, &response_headers_, &response_trailers_, stream_info_); } } @@ -527,7 +527,7 @@ TEST_F(AccessLogImplTest, multipleOperators) { { EXPECT_CALL(*file_, write(_)).Times(0); Http::TestHeaderMapImpl header_map{}; - stream_info_.hc_request_ = true; + stream_info_.health_check_request_ = true; log->log(&header_map, &response_headers_, &response_trailers_, stream_info_); } diff --git a/test/common/stream_info/test_util.h b/test/common/stream_info/test_util.h index 11592c29f65fd..f708c9e4f470d 100644 --- a/test/common/stream_info/test_util.h +++ b/test/common/stream_info/test_util.h @@ -54,8 +54,8 @@ class TestStreamInfo : public StreamInfo::StreamInfo { const Network::Address::InstanceConstSharedPtr& upstreamLocalAddress() const override { return upstream_local_address_; } - bool healthCheck() const override { return hc_request_; } - void healthCheck(bool is_hc) override { hc_request_ = is_hc; } + bool healthCheck() const override { return health_check_request_; } + void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } void setDownstreamLocalAddress( const Network::Address::InstanceConstSharedPtr& downstream_local_address) override { @@ -194,7 +194,7 @@ class TestStreamInfo : public StreamInfo::StreamInfo { absl::optional response_code_; uint64_t response_flags_{}; Upstream::HostDescriptionConstSharedPtr upstream_host_{}; - bool hc_request_{}; + bool health_check_request_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; Network::Address::InstanceConstSharedPtr downstream_local_address_; Network::Address::InstanceConstSharedPtr downstream_direct_remote_address_; diff --git a/test/common/tracing/http_tracer_impl_test.cc b/test/common/tracing/http_tracer_impl_test.cc index 99e07658df811..ac5ad1a0ddc90 100644 --- a/test/common/tracing/http_tracer_impl_test.cc +++ b/test/common/tracing/http_tracer_impl_test.cc @@ -72,7 +72,7 @@ TEST(HttpTracerUtilityTest, IsTracing) { EXPECT_TRUE(result.traced); } - // HC request. + // Health Check request. { Http::TestHeaderMapImpl traceable_header_hc{{"x-request-id", forced_guid}}; EXPECT_CALL(stream_info, healthCheck()).WillOnce(Return(true)); diff --git a/test/extensions/health_checkers/redis/redis_test.cc b/test/extensions/health_checkers/redis/redis_test.cc index 4e4f119c75c00..1fa714c68d90a 100644 --- a/test/extensions/health_checkers/redis/redis_test.cc +++ b/test/extensions/health_checkers/redis/redis_test.cc @@ -45,12 +45,12 @@ class RedisHealthCheckerTest config: )EOF"; - const auto& hc_config = Upstream::parseHealthCheckFromV2Yaml(yaml); - const auto& redis_config = getRedisHealthCheckConfig(hc_config); + const auto& health_check_config = Upstream::parseHealthCheckFromV2Yaml(yaml); + const auto& redis_config = getRedisHealthCheckConfig(health_check_config); health_checker_.reset( - new RedisHealthChecker(*cluster_, hc_config, redis_config, dispatcher_, runtime_, random_, - Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); + new RedisHealthChecker(*cluster_, health_check_config, redis_config, dispatcher_, runtime_, + random_, Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); } void setupAlwaysLogHealthCheckFailures() { @@ -67,12 +67,12 @@ class RedisHealthCheckerTest config: )EOF"; - const auto& hc_config = Upstream::parseHealthCheckFromV2Yaml(yaml); - const auto& redis_config = getRedisHealthCheckConfig(hc_config); + const auto& health_check_config = Upstream::parseHealthCheckFromV2Yaml(yaml); + const auto& redis_config = getRedisHealthCheckConfig(health_check_config); health_checker_.reset( - new RedisHealthChecker(*cluster_, hc_config, redis_config, dispatcher_, runtime_, random_, - Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); + new RedisHealthChecker(*cluster_, health_check_config, redis_config, dispatcher_, runtime_, + random_, Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); } void setupExistsHealthcheck() { @@ -89,12 +89,12 @@ class RedisHealthCheckerTest key: foo )EOF"; - const auto& hc_config = Upstream::parseHealthCheckFromV2Yaml(yaml); - const auto& redis_config = getRedisHealthCheckConfig(hc_config); + const auto& health_check_config = Upstream::parseHealthCheckFromV2Yaml(yaml); + const auto& redis_config = getRedisHealthCheckConfig(health_check_config); health_checker_.reset( - new RedisHealthChecker(*cluster_, hc_config, redis_config, dispatcher_, runtime_, random_, - Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); + new RedisHealthChecker(*cluster_, health_check_config, redis_config, dispatcher_, runtime_, + random_, Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); } void setupDontReuseConnection() { @@ -111,12 +111,12 @@ class RedisHealthCheckerTest config: )EOF"; - const auto& hc_config = Upstream::parseHealthCheckFromV2Yaml(yaml); - const auto& redis_config = getRedisHealthCheckConfig(hc_config); + const auto& health_check_config = Upstream::parseHealthCheckFromV2Yaml(yaml); + const auto& redis_config = getRedisHealthCheckConfig(health_check_config); health_checker_.reset( - new RedisHealthChecker(*cluster_, hc_config, redis_config, dispatcher_, runtime_, random_, - Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); + new RedisHealthChecker(*cluster_, health_check_config, redis_config, dispatcher_, runtime_, + random_, Upstream::HealthCheckEventLoggerPtr(event_logger_), *this)); } Extensions::NetworkFilters::RedisProxy::ConnPool::ClientPtr diff --git a/test/integration/hds_integration_test.cc b/test/integration/hds_integration_test.cc index 702d731ae6d89..bd3d6de7607a9 100644 --- a/test/integration/hds_integration_test.cc +++ b/test/integration/hds_integration_test.cc @@ -167,9 +167,9 @@ class HdsIntegrationTest : public HttpIntegrationTest, health_check->mutable_health_checks(0)->mutable_interval()->set_seconds(MaxTimeout); health_check->mutable_health_checks(0)->mutable_unhealthy_threshold()->set_value(2); health_check->mutable_health_checks(0)->mutable_healthy_threshold()->set_value(2); - auto* tcp_hc = health_check->mutable_health_checks(0)->mutable_tcp_health_check(); - tcp_hc->mutable_send()->set_text("50696E67"); - tcp_hc->add_receive()->set_text("506F6E67"); + auto* tcp_health_check = health_check->mutable_health_checks(0)->mutable_tcp_health_check(); + tcp_health_check->mutable_send()->set_text("50696E67"); + tcp_health_check->add_receive()->set_text("506F6E67"); return server_health_check_specifier_; } diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index a6f46d09b8975..ece9ad8f93419 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -52,7 +52,7 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD1(setUpstreamLocalAddress, void(const Network::Address::InstanceConstSharedPtr&)); MOCK_CONST_METHOD0(upstreamLocalAddress, const Network::Address::InstanceConstSharedPtr&()); MOCK_CONST_METHOD0(healthCheck, bool()); - MOCK_METHOD1(healthCheck, void(bool is_hc)); + MOCK_METHOD1(healthCheck, void(bool is_health_check)); MOCK_METHOD1(setDownstreamLocalAddress, void(const Network::Address::InstanceConstSharedPtr&)); MOCK_CONST_METHOD0(downstreamLocalAddress, const Network::Address::InstanceConstSharedPtr&()); MOCK_METHOD1(setDownstreamDirectRemoteAddress, From c2b5b0326539f82c63a2e85d9b9134660e7e03d2 Mon Sep 17 00:00:00 2001 From: Suhail Patel Date: Fri, 1 Feb 2019 19:00:10 +0000 Subject: [PATCH 02/51] stats: add usedonly option to prometheus output format (#5805) Signed-off-by: Suhail Patel --- docs/root/intro/version_history.rst | 2 + docs/root/operations/admin.rst | 4 ++ source/server/http/admin.cc | 21 ++++++- source/server/http/admin.h | 10 ++- test/server/http/admin_test.cc | 94 +++++++++++++++++++++++++++-- 5 files changed, 123 insertions(+), 8 deletions(-) diff --git a/docs/root/intro/version_history.rst b/docs/root/intro/version_history.rst index f40ca143c43a0..cc3cb90f95107 100644 --- a/docs/root/intro/version_history.rst +++ b/docs/root/intro/version_history.rst @@ -30,6 +30,8 @@ Version history * router: added ability to configure a :ref:`retry policy ` at the virtual host level. * stats: added support for histograms in prometheus +* stats: added usedonly flag to prometheus stats to only output metrics which have been + updated at least once. * tap: added new alpha :ref:`HTTP tap filter `. * tls: enabled TLS 1.3 on the server-side (non-FIPS builds). * router: added per-route configuration of :ref:`internal redirects `. diff --git a/docs/root/operations/admin.rst b/docs/root/operations/admin.rst index 502312fefbaac..d1e46de993ccf 100644 --- a/docs/root/operations/admin.rst +++ b/docs/root/operations/admin.rst @@ -312,6 +312,10 @@ explanation of the output. Outputs /stats in `Prometheus `_ v0.0.4 format. This can be used to integrate with a Prometheus server. + You can optionally pass the `usedonly` URL query argument to only get statistics that + Envoy has updated (counters incremented at least once, gauges changed at least once, + and histograms added to at least once) + .. _operations_admin_interface_runtime: .. http:get:: /runtime diff --git a/source/server/http/admin.cc b/source/server/http/admin.cc index 1df56ddcf8614..c16b7ae5396ba 100644 --- a/source/server/http/admin.cc +++ b/source/server/http/admin.cc @@ -669,10 +669,12 @@ Http::Code AdminImpl::handlerStats(absl::string_view url, Http::HeaderMap& respo return rc; } -Http::Code AdminImpl::handlerPrometheusStats(absl::string_view, Http::HeaderMap&, +Http::Code AdminImpl::handlerPrometheusStats(absl::string_view path_and_query, Http::HeaderMap&, Buffer::Instance& response, AdminStream&) { + const Http::Utility::QueryParams params = Http::Utility::parseQueryString(path_and_query); + const bool used_only = params.find("usedonly") != params.end(); PrometheusStatsFormatter::statsAsPrometheus(server_.stats().counters(), server_.stats().gauges(), - server_.stats().histograms(), response); + server_.stats().histograms(), response, used_only); return Http::Code::OK; } @@ -705,9 +707,14 @@ std::string PrometheusStatsFormatter::metricName(const std::string& extractedNam uint64_t PrometheusStatsFormatter::statsAsPrometheus( const std::vector& counters, const std::vector& gauges, - const std::vector& histograms, Buffer::Instance& response) { + const std::vector& histograms, Buffer::Instance& response, + const bool used_only) { std::unordered_set metric_type_tracker; for (const auto& counter : counters) { + if (!shouldShowMetric(counter, used_only)) { + continue; + } + const std::string tags = formattedTags(counter->tags()); const std::string metric_name = metricName(counter->tagExtractedName()); if (metric_type_tracker.find(metric_name) == metric_type_tracker.end()) { @@ -718,6 +725,10 @@ uint64_t PrometheusStatsFormatter::statsAsPrometheus( } for (const auto& gauge : gauges) { + if (!shouldShowMetric(gauge, used_only)) { + continue; + } + const std::string tags = formattedTags(gauge->tags()); const std::string metric_name = metricName(gauge->tagExtractedName()); if (metric_type_tracker.find(metric_name) == metric_type_tracker.end()) { @@ -728,6 +739,10 @@ uint64_t PrometheusStatsFormatter::statsAsPrometheus( } for (const auto& histogram : histograms) { + if (!shouldShowMetric(histogram, used_only)) { + continue; + } + const std::string tags = formattedTags(histogram->tags()); const std::string hist_tags = histogram->tags().empty() ? EMPTY_STRING : (tags + ","); diff --git a/source/server/http/admin.h b/source/server/http/admin.h index d9205dba7e0da..05b3c1fa840c5 100644 --- a/source/server/http/admin.h +++ b/source/server/http/admin.h @@ -376,7 +376,7 @@ class PrometheusStatsFormatter { static uint64_t statsAsPrometheus(const std::vector& counters, const std::vector& gauges, const std::vector& histograms, - Buffer::Instance& response); + Buffer::Instance& response, const bool used_only); /** * Format the given tags, returning a string as a comma-separated list * of ="" pairs. @@ -392,6 +392,14 @@ class PrometheusStatsFormatter { * Take a string and sanitize it according to Prometheus conventions. */ static std::string sanitizeName(const std::string& name); + + /* + * Determine whether a metric has never been emitted and choose to + * not show it if we only wanted used metrics. + */ + static bool shouldShowMetric(const std::shared_ptr& metric, const bool used_only) { + return !used_only || metric->used(); + } }; } // namespace Server diff --git a/test/server/http/admin_test.cc b/test/server/http/admin_test.cc index e7ca80fbdf6d1..a13a93629c4a8 100644 --- a/test/server/http/admin_test.cc +++ b/test/server/http/admin_test.cc @@ -1291,7 +1291,7 @@ TEST_F(PrometheusStatsFormatterTest, MetricNameCollison) { Buffer::OwnedImpl response; auto size = - PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response); + PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response, false); EXPECT_EQ(2UL, size); } @@ -1311,7 +1311,7 @@ TEST_F(PrometheusStatsFormatterTest, UniqueMetricName) { Buffer::OwnedImpl response; auto size = - PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response); + PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response, false); EXPECT_EQ(4UL, size); } @@ -1330,7 +1330,7 @@ TEST_F(PrometheusStatsFormatterTest, HistogramWithNoValuesAndNoTags) { Buffer::OwnedImpl response; auto size = - PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response); + PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response, false); EXPECT_EQ(1UL, size); const std::string expected_output = R"EOF(# TYPE envoy_histogram1 histogram @@ -1382,7 +1382,7 @@ TEST_F(PrometheusStatsFormatterTest, OutputWithAllMetricTypes) { Buffer::OwnedImpl response; auto size = - PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response); + PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response, false); EXPECT_EQ(5UL, size); const std::string expected_output = R"EOF(# TYPE envoy_cluster_test_1_upstream_cx_total counter @@ -1421,5 +1421,91 @@ envoy_cluster_test_1_upstream_rq_time_count{key1="value1",key2="value2"} 7 EXPECT_EQ(expected_output, response.toString()); } +TEST_F(PrometheusStatsFormatterTest, OutputWithUsedOnly) { + addCounter("cluster.test_1.upstream_cx_total", {{"a.tag-name", "a.tag-value"}}); + addCounter("cluster.test_2.upstream_cx_total", {{"another_tag_name", "another_tag-value"}}); + addGauge("cluster.test_3.upstream_cx_total", {{"another_tag_name_3", "another_tag_3-value"}}); + addGauge("cluster.test_4.upstream_cx_total", {{"another_tag_name_4", "another_tag_4-value"}}); + + const std::vector h1_values = {50, 20, 30, 70, 100, 5000, 200}; + HistogramWrapper h1_cumulative; + h1_cumulative.setHistogramValues(h1_values); + Stats::HistogramStatisticsImpl h1_cumulative_statistics(h1_cumulative.getHistogram()); + + auto histogram1 = std::make_shared>(); + histogram1->name_ = "cluster.test_1.upstream_rq_time"; + histogram1->used_ = true; + histogram1->tags_ = {Stats::Tag{"key1", "value1"}, Stats::Tag{"key2", "value2"}}; + addHistogram(histogram1); + EXPECT_CALL(*histogram1, cumulativeStatistics()) + .WillOnce(testing::ReturnRef(h1_cumulative_statistics)); + + Buffer::OwnedImpl response; + auto size = + PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, response, true); + EXPECT_EQ(1UL, size); + + const std::string expected_output = R"EOF(# TYPE envoy_cluster_test_1_upstream_rq_time histogram +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="0.5"} 0 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="1"} 0 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="5"} 0 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="10"} 0 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="25"} 1 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="50"} 2 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="100"} 4 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="250"} 6 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="500"} 6 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="1000"} 6 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="2500"} 6 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="5000"} 6 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="10000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="30000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="60000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="300000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="600000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="1800000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="3600000"} 7 +envoy_cluster_test_1_upstream_rq_time_bucket{key1="value1",key2="value2",le="+Inf"} 7 +envoy_cluster_test_1_upstream_rq_time_sum{key1="value1",key2="value2"} 5532 +envoy_cluster_test_1_upstream_rq_time_count{key1="value1",key2="value2"} 7 +)EOF"; + + EXPECT_EQ(expected_output, response.toString()); +} + +TEST_F(PrometheusStatsFormatterTest, OutputWithUsedOnlyHistogram) { + const std::vector h1_values = {}; + HistogramWrapper h1_cumulative; + h1_cumulative.setHistogramValues(h1_values); + Stats::HistogramStatisticsImpl h1_cumulative_statistics(h1_cumulative.getHistogram()); + + auto histogram1 = std::make_shared>(); + histogram1->name_ = "cluster.test_1.upstream_rq_time"; + histogram1->used_ = false; + histogram1->tags_ = {Stats::Tag{"key1", "value1"}, Stats::Tag{"key2", "value2"}}; + addHistogram(histogram1); + + { + const bool used_only = true; + EXPECT_CALL(*histogram1, cumulativeStatistics()).Times(0); + + Buffer::OwnedImpl response; + auto size = PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, + response, used_only); + EXPECT_EQ(0UL, size); + } + + { + const bool used_only = false; + EXPECT_CALL(*histogram1, cumulativeStatistics()) + .WillOnce(testing::ReturnRef(h1_cumulative_statistics)); + + Buffer::OwnedImpl response; + auto size = PrometheusStatsFormatter::statsAsPrometheus(counters_, gauges_, histograms_, + response, used_only); + EXPECT_EQ(1UL, size); + } +} + } // namespace Server } // namespace Envoy From 5a88c95aad954118670d2e4a4994e7dcb51d34e2 Mon Sep 17 00:00:00 2001 From: danzh Date: Fri, 1 Feb 2019 14:01:03 -0500 Subject: [PATCH 03/51] Implement QuicMutex (#5801) Signed-off-by: Dan Zhang --- bazel/external/quiche.BUILD | 16 ++++- bazel/repositories.bzl | 4 ++ bazel/repository_locations.bzl | 6 +- .../quic_listeners/quiche/platform/BUILD | 14 ++++- .../quiche/platform/quic_mutex_impl.h | 60 +++++++++++++++++++ .../quiche/platform/quic_platform_test.cc | 22 +++++++ 6 files changed, 116 insertions(+), 6 deletions(-) create mode 100644 source/extensions/quic_listeners/quiche/platform/quic_mutex_impl.h diff --git a/bazel/external/quiche.BUILD b/bazel/external/quiche.BUILD index 2b0af386def57..0563a6edfea37 100644 --- a/bazel/external/quiche.BUILD +++ b/bazel/external/quiche.BUILD @@ -94,6 +94,19 @@ cc_library( cc_library( name = "quic_platform", + srcs = ["quiche/quic/platform/api/quic_mutex.cc"], + hdrs = [ + "quiche/quic/platform/api/quic_mutex.h", + ], + visibility = ["//visibility:public"], + deps = [ + ":quic_platform_base", + "@envoy//source/extensions/quic_listeners/quiche/platform:quic_platform_impl_lib", + ], +) + +cc_library( + name = "quic_platform_base", hdrs = [ "quiche/quic/platform/api/quic_aligned.h", "quiche/quic/platform/api/quic_arraysize.h", @@ -130,7 +143,6 @@ cc_library( # "quiche/quic/platform/api/quic_mem_slice_span.h", # "quiche/quic/platform/api/quic_mem_slice_storage.h", # "quiche/quic/platform/api/quic_mock_log.h", - # "quiche/quic/platform/api/quic_mutex.h", # "quiche/quic/platform/api/quic_pcc_sender.h", # "quiche/quic/platform/api/quic_reference_counted.h", # "quiche/quic/platform/api/quic_server_stats.h", @@ -149,6 +161,6 @@ cc_library( ], visibility = ["//visibility:public"], deps = [ - "@envoy//source/extensions/quic_listeners/quiche/platform:quic_platform_impl_lib", + "@envoy//source/extensions/quic_listeners/quiche/platform:quic_platform_base_impl_lib", ], ) diff --git a/bazel/repositories.bzl b/bazel/repositories.bzl index 0973e0e42947f..bb817725ac9f8 100644 --- a/bazel/repositories.bzl +++ b/bazel/repositories.bzl @@ -673,6 +673,10 @@ def _com_googlesource_quiche(): name = "quiche_quic_platform", actual = "@com_googlesource_quiche//:quic_platform", ) + native.bind( + name = "quiche_quic_platform_base", + actual = "@com_googlesource_quiche//:quic_platform_base", + ) def _com_github_grpc_grpc(): _repository_impl("com_github_grpc_grpc") diff --git a/bazel/repository_locations.bzl b/bazel/repository_locations.bzl index c85d016d2986b..95a4bfd86e2d6 100644 --- a/bazel/repository_locations.bzl +++ b/bazel/repository_locations.bzl @@ -230,8 +230,8 @@ REPOSITORY_LOCATIONS = dict( urls = ["https://github.com/google/subpar/archive/1.3.0.tar.gz"], ), com_googlesource_quiche = dict( - # Static snapshot of https://quiche.googlesource.com/quiche/+archive/c9b2cecd1d005893114a03c101532017ddfa12cb.tar.gz - sha256 = "c8faea835132103d574cc2769a58e244bee3de02669471330a174f2ffae6fcc3", - urls = ["https://storage.googleapis.com/quiche-envoy-integration/c9b2cecd1d005893114a03c101532017ddfa12cb.tar.gz"], + # Static snapshot of https://quiche.googlesource.com/quiche/+archive/dc5ce1a82e342bfd366a1ccdf2a2717edb46e4ec.tar.gz + sha256 = "ed4aec9af6b251385b720d3a23a22a4264d649806ff95dc0b29dab9f786387a0", + urls = ["https://storage.googleapis.com/quiche-envoy-integration/dc5ce1a82e342bfd366a1ccdf2a2717edb46e4ec.tar.gz"], ), ) diff --git a/source/extensions/quic_listeners/quiche/platform/BUILD b/source/extensions/quic_listeners/quiche/platform/BUILD index 934a5be3f6418..12d7fd4fb1e3a 100644 --- a/source/extensions/quic_listeners/quiche/platform/BUILD +++ b/source/extensions/quic_listeners/quiche/platform/BUILD @@ -38,7 +38,7 @@ envoy_cc_library( ) envoy_cc_library( - name = "quic_platform_impl_lib", + name = "quic_platform_base_impl_lib", hdrs = [ "quic_aligned_impl.h", "quic_arraysize_impl.h", @@ -66,6 +66,18 @@ envoy_cc_library( visibility = ["//visibility:public"], ) +envoy_cc_library( + name = "quic_platform_impl_lib", + hdrs = [ + "quic_mutex_impl.h", + ], + external_deps = [ + "quiche_quic_platform_base", + "abseil_synchronization", + ], + visibility = ["//visibility:public"], +) + envoy_cc_library( name = "spdy_platform_impl_lib", hdrs = [ diff --git a/source/extensions/quic_listeners/quiche/platform/quic_mutex_impl.h b/source/extensions/quic_listeners/quiche/platform/quic_mutex_impl.h new file mode 100644 index 0000000000000..4250eb45e2276 --- /dev/null +++ b/source/extensions/quic_listeners/quiche/platform/quic_mutex_impl.h @@ -0,0 +1,60 @@ +#pragma once + +// NOLINT(namespace-envoy) + +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +#include "absl/synchronization/mutex.h" +#include "absl/synchronization/notification.h" +#include "quiche/quic/platform/api/quic_export.h" + +namespace quic { + +// A class wrapping a non-reentrant mutex. +class LOCKABLE QUIC_EXPORT_PRIVATE QuicLockImpl { +public: + QuicLockImpl() = default; + QuicLockImpl(const QuicLockImpl&) = delete; + QuicLockImpl& operator=(const QuicLockImpl&) = delete; + + // Block until mu_ is free, then acquire it exclusively. + void WriterLock() EXCLUSIVE_LOCK_FUNCTION() { mu_.WriterLock(); } + + // Release mu_. Caller must hold it exclusively. + void WriterUnlock() UNLOCK_FUNCTION() { mu_.WriterUnlock(); } + + // Block until mu_ is free or shared, then acquire a share of it. + void ReaderLock() SHARED_LOCK_FUNCTION() { mu_.ReaderLock(); } + + // Release mu_. Caller could hold it in shared mode. + void ReaderUnlock() UNLOCK_FUNCTION() { mu_.ReaderUnlock(); } + + // Returns immediately if current thread holds mu_ in at least shared + // mode. Otherwise, reports an error by crashing with a diagnostic. + void AssertReaderHeld() const ASSERT_SHARED_LOCK() { mu_.AssertReaderHeld(); } + +private: + absl::Mutex mu_; +}; + +// A Notification allows threads to receive notification of a single occurrence +// of a single event. +class QUIC_EXPORT_PRIVATE QuicNotificationImpl { +public: + QuicNotificationImpl() = default; + QuicNotificationImpl(const QuicNotificationImpl&) = delete; + QuicNotificationImpl& operator=(const QuicNotificationImpl&) = delete; + + bool HasBeenNotified() { return notification_.HasBeenNotified(); } + + void Notify() { notification_.Notify(); } + + void WaitForNotification() { notification_.WaitForNotification(); } + +private: + absl::Notification notification_; +}; + +} // namespace quic diff --git a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc index 42d134e94e422..b13e141ea2221 100644 --- a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc +++ b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc @@ -4,6 +4,7 @@ #include "quiche/quic/platform/api/quic_containers.h" #include "quiche/quic/platform/api/quic_endian.h" #include "quiche/quic/platform/api/quic_estimate_memory_usage.h" +#include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/platform/api/quic_ptr_util.h" #include "quiche/quic/platform/api/quic_string.h" #include "quiche/quic/platform/api/quic_string_piece.h" @@ -93,6 +94,27 @@ TEST(QuicPlatformTest, QuicPtrUtil) { EXPECT_EQ("aaa", *p); } +TEST(QuicPlatformTest, QuicMutex) { + quic::QuicMutex mu; + + quic::QuicWriterMutexLock wmu(&mu); + mu.AssertReaderHeld(); + mu.WriterUnlock(); + { + quic::QuicReaderMutexLock rmu(&mu); + mu.AssertReaderHeld(); + } + mu.WriterLock(); +} + +TEST(QuicPlatformTest, QuicNotification) { + quic::QuicNotification notification; + EXPECT_FALSE(notification.HasBeenNotified()); + notification.Notify(); + notification.WaitForNotification(); + EXPECT_TRUE(notification.HasBeenNotified()); +} + } // namespace Quiche } // namespace QuicListeners } // namespace Extensions From fbcf6bcaac6ac3c2b13f8c51fb1470a25b240abd Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Fri, 1 Feb 2019 16:56:06 -0700 Subject: [PATCH 04/51] http tap: add request/response trailer matching (#5804) 1) Add request/response trailer matching 2) Output request/response trailers 3) Refactor matchers to reduce boilerplate and make it harder to make mistakes when adding new update functions. 4) Split out a match configuration for HTTP request and response into individual things like request headers, request trailers, etc. This will make it easier and more logical to add various types of body matching and wire it up using the existing and/or logic. Signed-off-by: Matt Klein --- api/envoy/data/tap/v2alpha/http.proto | 17 +- api/envoy/service/tap/v2alpha/common.proto | 26 +-- .../configuration/http_filters/tap_filter.rst | 8 +- source/common/router/router.cc | 1 + source/extensions/common/tap/tap_matcher.cc | 99 +++----- source/extensions/common/tap/tap_matcher.h | 215 +++++++++++++----- .../extensions/filters/http/tap/tap_config.h | 14 +- .../filters/http/tap/tap_config_impl.cc | 22 +- .../filters/http/tap/tap_config_impl.h | 7 +- .../extensions/filters/http/tap/tap_filter.cc | 21 +- .../extensions/filters/http/tap/tap_filter.h | 9 +- .../http/tap/tap_filter_integration_test.cc | 179 ++++++++++----- .../filters/http/tap/tap_filter_test.cc | 13 +- 13 files changed, 408 insertions(+), 223 deletions(-) diff --git a/api/envoy/data/tap/v2alpha/http.proto b/api/envoy/data/tap/v2alpha/http.proto index f9c4bb483ad79..92b731c2ec977 100644 --- a/api/envoy/data/tap/v2alpha/http.proto +++ b/api/envoy/data/tap/v2alpha/http.proto @@ -9,9 +9,18 @@ import "envoy/api/v2/core/base.proto"; // A fully buffered HTTP trace message. message HttpBufferedTrace { - // Request headers. - repeated api.v2.core.HeaderValue request_headers = 2; + // HTTP message wrapper. + message Message { + // Message headers. + repeated api.v2.core.HeaderValue headers = 1; - // Response headers. - repeated api.v2.core.HeaderValue response_headers = 3; + // Message trailers. + repeated api.v2.core.HeaderValue trailers = 2; + } + + // Request message. + Message request = 1; + + // Response message. + Message response = 2; } diff --git a/api/envoy/service/tap/v2alpha/common.proto b/api/envoy/service/tap/v2alpha/common.proto index e4bd6d4a0aa55..47f9b53f7e261 100644 --- a/api/envoy/service/tap/v2alpha/common.proto +++ b/api/envoy/service/tap/v2alpha/common.proto @@ -48,23 +48,23 @@ message MatchPredicate { // The match configuration will always match. bool any_match = 4 [(validate.rules).bool.const = true]; - // HTTP request match configuration. - HttpRequestMatch http_request_match = 5; + // HTTP request headers match configuration. + HttpHeadersMatch http_request_headers_match = 5; - // HTTP response match configuration. - HttpResponseMatch http_response_match = 6; - } -} + // HTTP request trailers match configuration. + HttpHeadersMatch http_request_trailers_match = 6; -// HTTP request match configuration. -message HttpRequestMatch { - // HTTP request headers to match. - repeated api.v2.route.HeaderMatcher headers = 1; + // HTTP response headers match configuration. + HttpHeadersMatch http_response_headers_match = 7; + + // HTTP response trailers match configuration. + HttpHeadersMatch http_response_trailers_match = 8; + } } -// HTTP response match configuration. -message HttpResponseMatch { - // HTTP response headers to match. +// HTTP headers match configuration. +message HttpHeadersMatch { + // HTTP headers to match. repeated api.v2.route.HeaderMatcher headers = 1; } diff --git a/docs/root/configuration/http_filters/tap_filter.rst b/docs/root/configuration/http_filters/tap_filter.rst index e447ce5a1ddea..6982a3384a952 100644 --- a/docs/root/configuration/http_filters/tap_filter.rst +++ b/docs/root/configuration/http_filters/tap_filter.rst @@ -65,11 +65,11 @@ An example POST body: match_config: and_match: rules: - - http_request_match: + - http_request_headers_match: headers: - name: foo exact_match: bar - - http_response_match: + - http_response_headers_match: headers: - name: bar exact_match: baz @@ -90,11 +90,11 @@ Another example POST body: match_config: or_match: rules: - - http_request_match: + - http_request_headers_match: headers: - name: foo exact_match: bar - - http_response_match: + - http_response_headers_match: headers: - name: bar exact_match: baz diff --git a/source/common/router/router.cc b/source/common/router/router.cc index 5cab1a9106d5b..af5e8b6faa144 100644 --- a/source/common/router/router.cc +++ b/source/common/router/router.cc @@ -447,6 +447,7 @@ Http::FilterDataStatus Filter::decodeData(Buffer::Instance& data, bool end_strea } Http::FilterTrailersStatus Filter::decodeTrailers(Http::HeaderMap& trailers) { + ENVOY_STREAM_LOG(debug, "router decoding trailers:\n{}", *callbacks_, trailers); downstream_trailers_ = &trailers; upstream_request_->encodeTrailers(trailers); onRequestComplete(); diff --git a/source/extensions/common/tap/tap_matcher.cc b/source/extensions/common/tap/tap_matcher.cc index b97568d4060f8..39114a1229943 100644 --- a/source/extensions/common/tap/tap_matcher.cc +++ b/source/extensions/common/tap/tap_matcher.cc @@ -32,12 +32,21 @@ void buildMatcher(const envoy::service::tap::v2alpha::MatchPredicate& match_conf case envoy::service::tap::v2alpha::MatchPredicate::kAnyMatch: new_matcher = std::make_unique(matchers); break; - case envoy::service::tap::v2alpha::MatchPredicate::kHttpRequestMatch: - new_matcher = std::make_unique(match_config.http_request_match(), matchers); + case envoy::service::tap::v2alpha::MatchPredicate::kHttpRequestHeadersMatch: + new_matcher = std::make_unique( + match_config.http_request_headers_match(), matchers); break; - case envoy::service::tap::v2alpha::MatchPredicate::kHttpResponseMatch: - new_matcher = - std::make_unique(match_config.http_response_match(), matchers); + case envoy::service::tap::v2alpha::MatchPredicate::kHttpRequestTrailersMatch: + new_matcher = std::make_unique( + match_config.http_request_trailers_match(), matchers); + break; + case envoy::service::tap::v2alpha::MatchPredicate::kHttpResponseHeadersMatch: + new_matcher = std::make_unique( + match_config.http_response_headers_match(), matchers); + break; + case envoy::service::tap::v2alpha::MatchPredicate::kHttpResponseTrailersMatch: + new_matcher = std::make_unique( + match_config.http_response_trailers_match(), matchers); break; default: NOT_REACHED_GCOVR_EXCL_LINE; @@ -50,14 +59,19 @@ void buildMatcher(const envoy::service::tap::v2alpha::MatchPredicate& match_conf SetLogicMatcher::SetLogicMatcher( const envoy::service::tap::v2alpha::MatchPredicate::MatchSet& configs, std::vector& matchers, Type type) - : Matcher(matchers), matchers_(matchers), type_(type) { + : LogicMatcherBase(matchers), matchers_(matchers), type_(type) { for (const auto& config : configs.rules()) { indexes_.push_back(matchers_.size()); buildMatcher(config, matchers_); } } -bool SetLogicMatcher::updateLocalStatus(std::vector& statuses) const { +bool SetLogicMatcher::updateLocalStatus(std::vector& statuses, + const UpdateFunctor& functor) const { + for (size_t index : indexes_) { + statuses[index] = functor(*matchers_[index], statuses); + } + auto predicate = [&statuses](size_t index) { return statuses[index]; }; if (type_ == Type::And) { statuses[my_index_] = std::all_of(indexes_.begin(), indexes_.end(), predicate); @@ -69,81 +83,30 @@ bool SetLogicMatcher::updateLocalStatus(std::vector& statuses) const { return statuses[my_index_]; } -bool SetLogicMatcher::onNewStream(std::vector& statuses) const { - for (size_t index : indexes_) { - statuses[index] = matchers_[index]->onNewStream(statuses); - } - - return updateLocalStatus(statuses); -} - -bool SetLogicMatcher::onHttpRequestHeaders(const Http::HeaderMap& request_headers, - std::vector& statuses) const { - for (size_t index : indexes_) { - statuses[index] = matchers_[index]->onHttpRequestHeaders(request_headers, statuses); - } - - return updateLocalStatus(statuses); -} - -bool SetLogicMatcher::onHttpResponseHeaders(const Http::HeaderMap& response_headers, - std::vector& statuses) const { - for (size_t index : indexes_) { - statuses[index] = matchers_[index]->onHttpResponseHeaders(response_headers, statuses); - } - - return updateLocalStatus(statuses); -} - NotMatcher::NotMatcher(const envoy::service::tap::v2alpha::MatchPredicate& config, std::vector& matchers) - : Matcher(matchers), matchers_(matchers), not_index_(matchers.size()) { + : LogicMatcherBase(matchers), matchers_(matchers), not_index_(matchers.size()) { buildMatcher(config, matchers); } -bool NotMatcher::onNewStream(std::vector& statuses) const { - statuses[my_index_] = !matchers_[not_index_]->onNewStream(statuses); - return statuses[my_index_]; -} - -bool NotMatcher::onHttpRequestHeaders(const Http::HeaderMap& request_headers, - std::vector& statuses) const { - statuses[my_index_] = !matchers_[not_index_]->onHttpRequestHeaders(request_headers, statuses); - return statuses[my_index_]; -} - -bool NotMatcher::onHttpResponseHeaders(const Http::HeaderMap& response_headers, - std::vector& statuses) const { - statuses[my_index_] = !matchers_[not_index_]->onHttpResponseHeaders(response_headers, statuses); - return statuses[my_index_]; -} - -HttpRequestMatcher::HttpRequestMatcher(const envoy::service::tap::v2alpha::HttpRequestMatch& config, - const std::vector& matchers) - : Matcher(matchers) { - for (const auto& header_match : config.headers()) { - headers_to_match_.emplace_back(header_match); - } -} - -bool HttpRequestMatcher::onHttpRequestHeaders(const Http::HeaderMap& request_headers, - std::vector& statuses) const { - statuses[my_index_] = Http::HeaderUtility::matchHeaders(request_headers, headers_to_match_); +bool NotMatcher::updateLocalStatus(std::vector& statuses, + const UpdateFunctor& functor) const { + statuses[my_index_] = !functor(*matchers_[not_index_], statuses); return statuses[my_index_]; } -HttpResponseMatcher::HttpResponseMatcher( - const envoy::service::tap::v2alpha::HttpResponseMatch& config, +HttpHeaderMatcherBase::HttpHeaderMatcherBase( + const envoy::service::tap::v2alpha::HttpHeadersMatch& config, const std::vector& matchers) - : Matcher(matchers) { + : SimpleMatcher(matchers) { for (const auto& header_match : config.headers()) { headers_to_match_.emplace_back(header_match); } } -bool HttpResponseMatcher::onHttpResponseHeaders(const Http::HeaderMap& response_headers, - std::vector& statuses) const { - statuses[my_index_] = Http::HeaderUtility::matchHeaders(response_headers, headers_to_match_); +bool HttpHeaderMatcherBase::matchHeaders(const Http::HeaderMap& headers, + std::vector& statuses) const { + statuses[my_index_] = Http::HeaderUtility::matchHeaders(headers, headers_to_match_); return statuses[my_index_]; } diff --git a/source/extensions/common/tap/tap_matcher.h b/source/extensions/common/tap/tap_matcher.h index 0380967c14ddb..622933a96d658 100644 --- a/source/extensions/common/tap/tap_matcher.h +++ b/source/extensions/common/tap/tap_matcher.h @@ -38,6 +38,16 @@ using MatcherPtr = std::unique_ptr; */ class Matcher { public: + /** + * Base class constructor for a matcher. + * @param matchers supplies the match tree vector being built. + */ + Matcher(const std::vector& matchers) + // NOTE: This code assumes that the index for the matcher being constructed has already been + // allocated, which is why my_index_ is set to size() - 1. See buildMatcher() in + // tap_matcher.cc. + : my_index_(matchers.size() - 1) {} + virtual ~Matcher() = default; /** @@ -46,7 +56,7 @@ class Matcher { size_t index() { return my_index_; } /** - * Update match status when a stream is created. This might be an HTTP stream, a TCP connectin, + * Update match status when a stream is created. This might be an HTTP stream, a TCP connection, * etc. This allows any matchers to flip to an initial state of true if applicable. */ virtual bool onNewStream(std::vector& statuses) const PURE; @@ -59,6 +69,16 @@ class Matcher { */ virtual bool onHttpRequestHeaders(const Http::HeaderMap& request_headers, std::vector& statuses) const PURE; + + /** + * Update match status given HTTP request trailers. + * @param request_trailers supplies the request trailers. + * @param statuses supplies the per-stream-request match status vector which must be the same + * size as the match tree vector (see above). + */ + virtual bool onHttpRequestTrailers(const Http::HeaderMap& request_trailers, + std::vector& statuses) const PURE; + /** * Update match status given HTTP response headers. * @param response_headers supplies the response headers. @@ -69,23 +89,22 @@ class Matcher { std::vector& statuses) const PURE; /** - * @return whether given currently available information, the matcher matches. + * Update match status given HTTP response trailers. + * @param response_headers supplies the response trailers. * @param statuses supplies the per-stream-request match status vector which must be the same * size as the match tree vector (see above). */ - bool matches(const std::vector& statuses) const { return statuses[my_index_]; } + virtual bool onHttpResponseTrailers(const Http::HeaderMap& response_trailers, + std::vector& statuses) const PURE; -protected: /** - * Base class constructor for a matcher. - * @param matchers supplies the match tree vector being built. + * @return whether given currently available information, the matcher matches. + * @param statuses supplies the per-stream-request match status vector which must be the same + * size as the match tree vector (see above). */ - Matcher(const std::vector& matchers) - // NOTE: This code assumes that the index for the matcher being constructed has already been - // allocated, which is why my_index_ is set to size() - 1. See buildMatcher() in - // tap_matcher.cc. - : my_index_(matchers.size() - 1) {} + bool matches(const std::vector& statuses) const { return statuses[my_index_]; } +protected: const size_t my_index_; }; @@ -97,25 +116,64 @@ class Matcher { void buildMatcher(const envoy::service::tap::v2alpha::MatchPredicate& match_config, std::vector& matchers); +/** + * Base class for logic matchers that need to forward update calls to child matchers. + */ +class LogicMatcherBase : public Matcher { +public: + using Matcher::Matcher; + + // Extensions::Common::Tap::Matcher + bool onNewStream(std::vector& statuses) const override { + return updateLocalStatus( + statuses, [](Matcher& m, std::vector& statuses) { return m.onNewStream(statuses); }); + } + bool onHttpRequestHeaders(const Http::HeaderMap& request_headers, + std::vector& statuses) const override { + return updateLocalStatus(statuses, [&request_headers](Matcher& m, std::vector& statuses) { + return m.onHttpRequestHeaders(request_headers, statuses); + }); + } + bool onHttpRequestTrailers(const Http::HeaderMap& request_trailers, + std::vector& statuses) const override { + return updateLocalStatus(statuses, + [&request_trailers](Matcher& m, std::vector& statuses) { + return m.onHttpRequestTrailers(request_trailers, statuses); + }); + } + bool onHttpResponseHeaders(const Http::HeaderMap& response_headers, + std::vector& statuses) const override { + return updateLocalStatus(statuses, + [&response_headers](Matcher& m, std::vector& statuses) { + return m.onHttpResponseHeaders(response_headers, statuses); + }); + } + bool onHttpResponseTrailers(const Http::HeaderMap& response_trailers, + std::vector& statuses) const override { + return updateLocalStatus(statuses, + [&response_trailers](Matcher& m, std::vector& statuses) { + return m.onHttpResponseTrailers(response_trailers, statuses); + }); + } + +protected: + using UpdateFunctor = std::function&)>; + virtual bool updateLocalStatus(std::vector& statuses, + const UpdateFunctor& functor) const PURE; +}; + /** * Matcher for implementing set logic. */ -class SetLogicMatcher : public Matcher { +class SetLogicMatcher : public LogicMatcherBase { public: enum class Type { And, Or }; SetLogicMatcher(const envoy::service::tap::v2alpha::MatchPredicate::MatchSet& configs, std::vector& matchers, Type type); - // Extensions::Common::Tap::Matcher - bool onNewStream(std::vector& statuses) const override; - bool onHttpRequestHeaders(const Http::HeaderMap& request_headers, - std::vector& statuses) const override; - bool onHttpResponseHeaders(const Http::HeaderMap& response_headers, - std::vector& statuses) const override; - private: - bool updateLocalStatus(std::vector& statuses) const; + bool updateLocalStatus(std::vector& statuses, const UpdateFunctor& functor) const override; std::vector& matchers_; std::vector indexes_; @@ -125,81 +183,124 @@ class SetLogicMatcher : public Matcher { /** * Not matcher. */ -class NotMatcher : public Matcher { +class NotMatcher : public LogicMatcherBase { public: NotMatcher(const envoy::service::tap::v2alpha::MatchPredicate& config, std::vector& matchers); - // Extensions::Common::Tap::Matcher - bool onNewStream(std::vector& statuses) const override; - bool onHttpRequestHeaders(const Http::HeaderMap& request_headers, - std::vector& statuses) const override; - bool onHttpResponseHeaders(const Http::HeaderMap& response_headers, - std::vector& statuses) const override; - private: + bool updateLocalStatus(std::vector& statuses, const UpdateFunctor& functor) const override; + std::vector& matchers_; const size_t not_index_; }; +/** + * A base class for a matcher that generally wants to return default values, but might override + * a single update function. + */ +class SimpleMatcher : public Matcher { +public: + using Matcher::Matcher; + + // Extensions::Common::Tap::Matcher + bool onNewStream(std::vector& statuses) const { return statuses[my_index_]; } + bool onHttpRequestHeaders(const Http::HeaderMap&, std::vector& statuses) const { + return statuses[my_index_]; + } + bool onHttpRequestTrailers(const Http::HeaderMap&, std::vector& statuses) const { + return statuses[my_index_]; + } + bool onHttpResponseHeaders(const Http::HeaderMap&, std::vector& statuses) const { + return statuses[my_index_]; + } + bool onHttpResponseTrailers(const Http::HeaderMap&, std::vector& statuses) const { + return statuses[my_index_]; + } +}; + /** * Any matcher (always matches). */ -class AnyMatcher : public Matcher { +class AnyMatcher : public SimpleMatcher { public: - AnyMatcher(std::vector& matchers) : Matcher(matchers) {} + using SimpleMatcher::SimpleMatcher; // Extensions::Common::Tap::Matcher bool onNewStream(std::vector& statuses) const override { statuses[my_index_] = true; return true; } - bool onHttpRequestHeaders(const Http::HeaderMap&, std::vector&) const override { - return true; - } - bool onHttpResponseHeaders(const Http::HeaderMap&, std::vector&) const override { - return true; - } }; /** - * HTTP request matcher. + * Base class for the various HTTP header matchers. */ -class HttpRequestMatcher : public Matcher { +class HttpHeaderMatcherBase : public SimpleMatcher { public: - HttpRequestMatcher(const envoy::service::tap::v2alpha::HttpRequestMatch& config, - const std::vector& matchers); + HttpHeaderMatcherBase(const envoy::service::tap::v2alpha::HttpHeadersMatch& config, + const std::vector& matchers); + +protected: + bool matchHeaders(const Http::HeaderMap& headers, std::vector& statuses) const; + + std::vector headers_to_match_; +}; + +/** + * HTTP request headers matcher. + */ +class HttpRequestHeadersMatcher : public HttpHeaderMatcherBase { +public: + using HttpHeaderMatcherBase::HttpHeaderMatcherBase; // Extensions::Common::Tap::Matcher - bool onNewStream(std::vector&) const override { return false; } bool onHttpRequestHeaders(const Http::HeaderMap& request_headers, - std::vector& statuses) const override; - bool onHttpResponseHeaders(const Http::HeaderMap&, std::vector& statuses) const override { - return statuses[my_index_]; + std::vector& statuses) const override { + return matchHeaders(request_headers, statuses); } - -private: - std::vector headers_to_match_; }; /** - * HTTP response matcher. + * HTTP request trailers matcher. */ -class HttpResponseMatcher : public Matcher { +class HttpRequestTrailersMatcher : public HttpHeaderMatcherBase { public: - HttpResponseMatcher(const envoy::service::tap::v2alpha::HttpResponseMatch& config, - const std::vector& matchers); + using HttpHeaderMatcherBase::HttpHeaderMatcherBase; // Extensions::Common::Tap::Matcher - bool onNewStream(std::vector&) const override { return false; } - bool onHttpRequestHeaders(const Http::HeaderMap&, std::vector&) const override { - return false; + bool onHttpRequestTrailers(const Http::HeaderMap& request_trailers, + std::vector& statuses) const override { + return matchHeaders(request_trailers, statuses); } +}; + +/** + * HTTP response headers matcher. + */ +class HttpResponseHeadersMatcher : public HttpHeaderMatcherBase { +public: + using HttpHeaderMatcherBase::HttpHeaderMatcherBase; + + // Extensions::Common::Tap::Matcher bool onHttpResponseHeaders(const Http::HeaderMap& response_headers, - std::vector& statuses) const override; + std::vector& statuses) const override { + return matchHeaders(response_headers, statuses); + } +}; -private: - std::vector headers_to_match_; +/** + * HTTP response trailers matcher. + */ +class HttpResponseTrailersMatcher : public HttpHeaderMatcherBase { +public: + using HttpHeaderMatcherBase::HttpHeaderMatcherBase; + + // Extensions::Common::Tap::Matcher + bool onHttpResponseTrailers(const Http::HeaderMap& response_trailers, + std::vector& statuses) const override { + return matchHeaders(response_trailers, statuses); + } }; } // namespace Tap diff --git a/source/extensions/filters/http/tap/tap_config.h b/source/extensions/filters/http/tap/tap_config.h index ef7e42faa94fd..3444f213b37d9 100644 --- a/source/extensions/filters/http/tap/tap_config.h +++ b/source/extensions/filters/http/tap/tap_config.h @@ -24,17 +24,29 @@ class HttpPerRequestTapper { */ virtual void onRequestHeaders(const Http::HeaderMap& headers) PURE; + /** + * Called when request trailers are received. + */ + virtual void onRequestTrailers(const Http::HeaderMap& trailers) PURE; + /** * Called when response headers are received. */ virtual void onResponseHeaders(const Http::HeaderMap& headers) PURE; + /** + * Called when response trailers are received. + */ + virtual void onResponseTrailers(const Http::HeaderMap& headers) PURE; + /** * Called when the request is being destroyed and is being logged. * @return whether the request was tapped or not. */ virtual bool onDestroyLog(const Http::HeaderMap* request_headers, - const Http::HeaderMap* response_headers) PURE; + const Http::HeaderMap* request_trailers, + const Http::HeaderMap* response_headers, + const Http::HeaderMap* response_trailers) PURE; }; using HttpPerRequestTapperPtr = std::unique_ptr; diff --git a/source/extensions/filters/http/tap/tap_config_impl.cc b/source/extensions/filters/http/tap/tap_config_impl.cc index 1880bf6176a4d..3ed61680a1dd7 100644 --- a/source/extensions/filters/http/tap/tap_config_impl.cc +++ b/source/extensions/filters/http/tap/tap_config_impl.cc @@ -22,10 +22,18 @@ void HttpPerRequestTapperImpl::onRequestHeaders(const Http::HeaderMap& headers) config_->rootMatcher().onHttpRequestHeaders(headers, statuses_); } +void HttpPerRequestTapperImpl::onRequestTrailers(const Http::HeaderMap& trailers) { + config_->rootMatcher().onHttpRequestTrailers(trailers, statuses_); +} + void HttpPerRequestTapperImpl::onResponseHeaders(const Http::HeaderMap& headers) { config_->rootMatcher().onHttpResponseHeaders(headers, statuses_); } +void HttpPerRequestTapperImpl::onResponseTrailers(const Http::HeaderMap& trailers) { + config_->rootMatcher().onHttpResponseTrailers(trailers, statuses_); +} + namespace { Http::HeaderMap::Iterate fillHeaderList(const Http::HeaderEntry& header, void* context) { Protobuf::RepeatedPtrField& header_list = @@ -38,16 +46,24 @@ Http::HeaderMap::Iterate fillHeaderList(const Http::HeaderEntry& header, void* c } // namespace bool HttpPerRequestTapperImpl::onDestroyLog(const Http::HeaderMap* request_headers, - const Http::HeaderMap* response_headers) { + const Http::HeaderMap* request_trailers, + const Http::HeaderMap* response_headers, + const Http::HeaderMap* response_trailers) { if (!config_->rootMatcher().matches(statuses_)) { return false; } auto trace = std::make_shared(); auto& http_trace = *trace->mutable_http_buffered_trace(); - request_headers->iterate(fillHeaderList, http_trace.mutable_request_headers()); + request_headers->iterate(fillHeaderList, http_trace.mutable_request()->mutable_headers()); + if (request_trailers != nullptr) { + request_trailers->iterate(fillHeaderList, http_trace.mutable_request()->mutable_trailers()); + } if (response_headers != nullptr) { - response_headers->iterate(fillHeaderList, http_trace.mutable_response_headers()); + response_headers->iterate(fillHeaderList, http_trace.mutable_response()->mutable_headers()); + } + if (response_trailers != nullptr) { + response_trailers->iterate(fillHeaderList, http_trace.mutable_response()->mutable_trailers()); } ENVOY_LOG(debug, "submitting buffered trace sink"); diff --git a/source/extensions/filters/http/tap/tap_config_impl.h b/source/extensions/filters/http/tap/tap_config_impl.h index 56e465d80acca..8c0fa527188db 100644 --- a/source/extensions/filters/http/tap/tap_config_impl.h +++ b/source/extensions/filters/http/tap/tap_config_impl.h @@ -34,9 +34,12 @@ class HttpPerRequestTapperImpl : public HttpPerRequestTapper, Logger::LoggableonRequestTrailers(trailers); + } + return Http::FilterTrailersStatus::Continue; +} + Http::FilterHeadersStatus Filter::encodeHeaders(Http::HeaderMap& headers, bool) { if (tapper_ != nullptr) { tapper_->onResponseHeaders(headers); @@ -39,9 +48,17 @@ Http::FilterHeadersStatus Filter::encodeHeaders(Http::HeaderMap& headers, bool) return Http::FilterHeadersStatus::Continue; } +Http::FilterTrailersStatus Filter::encodeTrailers(Http::HeaderMap& trailers) { + if (tapper_ != nullptr) { + tapper_->onResponseTrailers(trailers); + } + return Http::FilterTrailersStatus::Continue; +} + void Filter::log(const Http::HeaderMap* request_headers, const Http::HeaderMap* response_headers, - const Http::HeaderMap*, const StreamInfo::StreamInfo&) { - if (tapper_ != nullptr && tapper_->onDestroyLog(request_headers, response_headers)) { + const Http::HeaderMap* response_trailers, const StreamInfo::StreamInfo&) { + if (tapper_ != nullptr && tapper_->onDestroyLog(request_headers, request_trailers_, + response_headers, response_trailers)) { config_->stats().rq_tapped_.inc(); } } diff --git a/source/extensions/filters/http/tap/tap_filter.h b/source/extensions/filters/http/tap/tap_filter.h index 5b05d7128d292..326dcd846c0c0 100644 --- a/source/extensions/filters/http/tap/tap_filter.h +++ b/source/extensions/filters/http/tap/tap_filter.h @@ -86,9 +86,7 @@ class Filter : public Http::StreamFilter, public AccessLog::Instance { Http::FilterDataStatus decodeData(Buffer::Instance&, bool) override { return Http::FilterDataStatus::Continue; } - Http::FilterTrailersStatus decodeTrailers(Http::HeaderMap&) override { - return Http::FilterTrailersStatus::Continue; - } + Http::FilterTrailersStatus decodeTrailers(Http::HeaderMap& trailers) override; void setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) override { HttpTapConfigSharedPtr config = config_->currentConfig(); tapper_ = config ? config->createPerRequestTapper(callbacks.streamId()) : nullptr; @@ -102,9 +100,7 @@ class Filter : public Http::StreamFilter, public AccessLog::Instance { Http::FilterDataStatus encodeData(Buffer::Instance&, bool) override { return Http::FilterDataStatus::Continue; } - Http::FilterTrailersStatus encodeTrailers(Http::HeaderMap&) override { - return Http::FilterTrailersStatus::Continue; - } + Http::FilterTrailersStatus encodeTrailers(Http::HeaderMap& trailers) override; Http::FilterMetadataStatus encodeMetadata(Http::MetadataMap&) override { return Http::FilterMetadataStatus::Continue; } @@ -118,6 +114,7 @@ class Filter : public Http::StreamFilter, public AccessLog::Instance { private: FilterConfigSharedPtr config_; HttpPerRequestTapperPtr tapper_; + const Http::HeaderMap* request_trailers_{}; }; } // namespace TapFilter diff --git a/test/extensions/filters/http/tap/tap_filter_integration_test.cc b/test/extensions/filters/http/tap/tap_filter_integration_test.cc index 26a79ea9c5c83..dc258d3ef67ab 100644 --- a/test/extensions/filters/http/tap/tap_filter_integration_test.cc +++ b/test/extensions/filters/http/tap/tap_filter_integration_test.cc @@ -16,7 +16,11 @@ class TapIntegrationTest : public HttpIntegrationTest, // HTTP/1 on OSX. In this test we close the admin /tap stream when we don't want any // more data, and without immediate close detection we can't have a flake free test. // Thus, we use HTTP/2 for everything here. - : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} + : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) { + + // Also use HTTP/2 for upstream so that we can fully test trailers. + setUpstreamProtocol(FakeHttpConnection::Type::HTTP2); + } void initializeFilter(const std::string& filter_config) { config_helper_.addFilter(filter_config); @@ -36,13 +40,38 @@ class TapIntegrationTest : public HttpIntegrationTest, } void makeRequest(const Http::TestHeaderMapImpl& request_headers, - const Http::TestHeaderMapImpl& response_headers) { - IntegrationStreamDecoderPtr decoder = codec_client_->makeHeaderOnlyRequest(request_headers); + const Http::TestHeaderMapImpl* request_trailers, + const Http::TestHeaderMapImpl& response_headers, + const Http::TestHeaderMapImpl* response_trailers) { + IntegrationStreamDecoderPtr decoder; + if (request_trailers == nullptr) { + decoder = codec_client_->makeHeaderOnlyRequest(request_headers); + } else { + auto result = codec_client_->startRequest(request_headers); + decoder = std::move(result.second); + result.first.encodeTrailers(*request_trailers); + } + waitForNextUpstreamRequest(); - upstream_request_->encodeHeaders(response_headers, true); + + upstream_request_->encodeHeaders(response_headers, response_trailers == nullptr); + if (response_trailers != nullptr) { + upstream_request_->encodeTrailers(*response_trailers); + } + decoder->waitForEndStream(); } + void startAdminRequest(const std::string& admin_request_yaml) { + admin_client_ = makeHttpConnection(makeClientConnection(lookupPort("admin"))); + const Http::TestHeaderMapImpl admin_request_headers{ + {":method", "POST"}, {":path", "/tap"}, {":scheme", "http"}, {":authority", "host"}}; + admin_response_ = admin_client_->makeRequestWithBody(admin_request_headers, admin_request_yaml); + admin_response_->waitForHeaders(); + EXPECT_STREQ("200", admin_response_->headers().Status()->value().c_str()); + EXPECT_FALSE(admin_response_->complete()); + } + const Http::TestHeaderMapImpl request_headers_tap_{{":method", "GET"}, {":path", "/"}, {":scheme", "http"}, @@ -55,6 +84,18 @@ class TapIntegrationTest : public HttpIntegrationTest, const Http::TestHeaderMapImpl response_headers_tap_{{":status", "200"}, {"bar", "baz"}}; const Http::TestHeaderMapImpl response_headers_no_tap_{{":status", "200"}}; + + const std::string admin_filter_config_ = + R"EOF( +name: envoy.filters.http.tap +config: + common_config: + admin_config: + config_id: test_config_id +)EOF"; + + IntegrationCodecClientPtr admin_client_; + IntegrationStreamDecoderPtr admin_response_; }; INSTANTIATE_TEST_SUITE_P(IpVersions, TapIntegrationTest, @@ -84,7 +125,7 @@ name: envoy.filters.http.tap // Initial request/response with tap. codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http"))); - makeRequest(request_headers_tap_, response_headers_no_tap_); + makeRequest(request_headers_tap_, nullptr, response_headers_no_tap_, nullptr); codec_client_->close(); test_server_->waitForCounterGe("http.config_test.downstream_cx_destroy", 1); @@ -101,20 +142,11 @@ name: envoy.filters.http.tap // Verify a basic tap flow using the admin handler. TEST_P(TapIntegrationTest, AdminBasicFlow) { - const std::string filter_config = - R"EOF( -name: envoy.filters.http.tap -config: - common_config: - admin_config: - config_id: test_config_id -)EOF"; - - initializeFilter(filter_config); + initializeFilter(admin_filter_config_); // Initial request/response with no tap. codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http"))); - makeRequest(request_headers_tap_, response_headers_no_tap_); + makeRequest(request_headers_tap_, nullptr, response_headers_no_tap_, nullptr); const std::string admin_request_yaml = R"EOF( @@ -123,11 +155,11 @@ config_id: test_config_id match_config: or_match: rules: - - http_request_match: + - http_request_headers_match: headers: - name: foo exact_match: bar - - http_response_match: + - http_response_headers_match: headers: - name: bar exact_match: baz @@ -137,55 +169,43 @@ config_id: test_config_id )EOF"; // Setup a tap and disconnect it without any request/response. - IntegrationCodecClientPtr admin_client_ = - makeHttpConnection(makeClientConnection(lookupPort("admin"))); - const Http::TestHeaderMapImpl admin_request_headers{ - {":method", "POST"}, {":path", "/tap"}, {":scheme", "http"}, {":authority", "host"}}; - IntegrationStreamDecoderPtr admin_response = - admin_client_->makeRequestWithBody(admin_request_headers, admin_request_yaml); - admin_response->waitForHeaders(); - EXPECT_STREQ("200", admin_response->headers().Status()->value().c_str()); - EXPECT_FALSE(admin_response->complete()); + startAdminRequest(admin_request_yaml); admin_client_->close(); test_server_->waitForGaugeEq("http.admin.downstream_rq_active", 0); // Second request/response with no tap. - makeRequest(request_headers_tap_, response_headers_no_tap_); + makeRequest(request_headers_tap_, nullptr, response_headers_no_tap_, nullptr); // Setup the tap again and leave it open. - admin_client_ = makeHttpConnection(makeClientConnection(lookupPort("admin"))); - admin_response = admin_client_->makeRequestWithBody(admin_request_headers, admin_request_yaml); - admin_response->waitForHeaders(); - EXPECT_STREQ("200", admin_response->headers().Status()->value().c_str()); - EXPECT_FALSE(admin_response->complete()); + startAdminRequest(admin_request_yaml); // Do a request which should tap, matching on request headers. - makeRequest(request_headers_tap_, response_headers_no_tap_); + makeRequest(request_headers_tap_, nullptr, response_headers_no_tap_, nullptr); // Wait for the tap message. - admin_response->waitForBodyData(1); + admin_response_->waitForBodyData(1); envoy::data::tap::v2alpha::BufferedTraceWrapper trace; - MessageUtil::loadFromYaml(admin_response->body(), trace); - EXPECT_EQ(trace.http_buffered_trace().request_headers().size(), 8); - EXPECT_EQ(trace.http_buffered_trace().response_headers().size(), 5); - admin_response->clearBody(); + MessageUtil::loadFromYaml(admin_response_->body(), trace); + EXPECT_EQ(trace.http_buffered_trace().request().headers().size(), 8); + EXPECT_EQ(trace.http_buffered_trace().response().headers().size(), 4); + admin_response_->clearBody(); // Do a request which should not tap. - makeRequest(request_headers_no_tap_, response_headers_no_tap_); + makeRequest(request_headers_no_tap_, nullptr, response_headers_no_tap_, nullptr); // Do a request which should tap, matching on response headers. - makeRequest(request_headers_no_tap_, response_headers_tap_); + makeRequest(request_headers_no_tap_, nullptr, response_headers_tap_, nullptr); // Wait for the tap message. - admin_response->waitForBodyData(1); - MessageUtil::loadFromYaml(admin_response->body(), trace); - EXPECT_EQ(trace.http_buffered_trace().request_headers().size(), 7); + admin_response_->waitForBodyData(1); + MessageUtil::loadFromYaml(admin_response_->body(), trace); + EXPECT_EQ(trace.http_buffered_trace().request().headers().size(), 7); EXPECT_EQ( "http", - findHeader("x-forwarded-proto", trace.http_buffered_trace().request_headers())->value()); - EXPECT_EQ(trace.http_buffered_trace().response_headers().size(), 6); - EXPECT_NE(nullptr, findHeader("date", trace.http_buffered_trace().response_headers())); - EXPECT_EQ("baz", findHeader("bar", trace.http_buffered_trace().response_headers())->value()); + findHeader("x-forwarded-proto", trace.http_buffered_trace().request().headers())->value()); + EXPECT_EQ(trace.http_buffered_trace().response().headers().size(), 5); + EXPECT_NE(nullptr, findHeader("date", trace.http_buffered_trace().response().headers())); + EXPECT_EQ("baz", findHeader("bar", trace.http_buffered_trace().response().headers())->value()); admin_client_->close(); test_server_->waitForGaugeEq("http.admin.downstream_rq_active", 0); @@ -198,11 +218,11 @@ config_id: test_config_id match_config: and_match: rules: - - http_request_match: + - http_request_headers_match: headers: - name: foo exact_match: bar - - http_response_match: + - http_response_headers_match: headers: - name: bar exact_match: baz @@ -211,28 +231,67 @@ config_id: test_config_id - streaming_admin: {} )EOF"; - admin_client_ = makeHttpConnection(makeClientConnection(lookupPort("admin"))); - admin_response = admin_client_->makeRequestWithBody(admin_request_headers, admin_request_yaml2); - admin_response->waitForHeaders(); - EXPECT_STREQ("200", admin_response->headers().Status()->value().c_str()); - EXPECT_FALSE(admin_response->complete()); + startAdminRequest(admin_request_yaml2); // Do a request that matches, but the response does not match. No tap. - makeRequest(request_headers_tap_, response_headers_no_tap_); + makeRequest(request_headers_tap_, nullptr, response_headers_no_tap_, nullptr); // Do a request that doesn't match, but the response does match. No tap. - makeRequest(request_headers_no_tap_, response_headers_tap_); + makeRequest(request_headers_no_tap_, nullptr, response_headers_tap_, nullptr); // Do a request that matches and a response that matches. Should tap. - makeRequest(request_headers_tap_, response_headers_tap_); + makeRequest(request_headers_tap_, nullptr, response_headers_tap_, nullptr); // Wait for the tap message. - admin_response->waitForBodyData(1); - MessageUtil::loadFromYaml(admin_response->body(), trace); + admin_response_->waitForBodyData(1); + MessageUtil::loadFromYaml(admin_response_->body(), trace); admin_client_->close(); EXPECT_EQ(3UL, test_server_->counter("http.config_test.tap.rq_tapped")->value()); } +// Verify both request and response trailer matching works. +TEST_P(TapIntegrationTest, AdminTrailers) { + initializeFilter(admin_filter_config_); + + const std::string admin_request_yaml = + R"EOF( +config_id: test_config_id +tap_config: + match_config: + and_match: + rules: + - http_request_trailers_match: + headers: + - name: foo_trailer + exact_match: bar + - http_response_trailers_match: + headers: + - name: bar_trailer + exact_match: baz + output_config: + sinks: + - streaming_admin: {} +)EOF"; + + startAdminRequest(admin_request_yaml); + + codec_client_ = makeHttpConnection(makeClientConnection(lookupPort("http"))); + const Http::TestHeaderMapImpl request_trailers{{"foo_trailer", "bar"}}; + const Http::TestHeaderMapImpl response_trailers{{"bar_trailer", "baz"}}; + makeRequest(request_headers_no_tap_, &request_trailers, response_headers_no_tap_, + &response_trailers); + + envoy::data::tap::v2alpha::BufferedTraceWrapper trace; + admin_response_->waitForBodyData(1); + MessageUtil::loadFromYaml(admin_response_->body(), trace); + EXPECT_EQ("bar", + findHeader("foo_trailer", trace.http_buffered_trace().request().trailers())->value()); + EXPECT_EQ("baz", + findHeader("bar_trailer", trace.http_buffered_trace().response().trailers())->value()); + + admin_client_->close(); +} + } // namespace } // namespace Envoy diff --git a/test/extensions/filters/http/tap/tap_filter_test.cc b/test/extensions/filters/http/tap/tap_filter_test.cc index e48e13fd94fce..d605488ea68b8 100644 --- a/test/extensions/filters/http/tap/tap_filter_test.cc +++ b/test/extensions/filters/http/tap/tap_filter_test.cc @@ -37,9 +37,13 @@ class MockHttpTapConfig : public HttpTapConfig { class MockHttpPerRequestTapper : public HttpPerRequestTapper { public: MOCK_METHOD1(onRequestHeaders, void(const Http::HeaderMap& headers)); + MOCK_METHOD1(onRequestTrailers, void(const Http::HeaderMap& headers)); MOCK_METHOD1(onResponseHeaders, void(const Http::HeaderMap& headers)); - MOCK_METHOD2(onDestroyLog, bool(const Http::HeaderMap* request_headers, - const Http::HeaderMap* response_headers)); + MOCK_METHOD1(onResponseTrailers, void(const Http::HeaderMap& headers)); + MOCK_METHOD4(onDestroyLog, + bool(const Http::HeaderMap* request_headers, const Http::HeaderMap* request_trailers, + const Http::HeaderMap* response_headers, + const Http::HeaderMap* response_trailers)); }; class TapFilterTest : public testing::Test { @@ -107,6 +111,7 @@ TEST_F(TapFilterTest, Config) { Buffer::OwnedImpl request_body; EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(request_body, false)); Http::TestHeaderMapImpl request_trailers; + EXPECT_CALL(*http_per_request_tapper_, onRequestTrailers(_)); EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->decodeTrailers(request_trailers)); Http::TestHeaderMapImpl response_headers; @@ -117,9 +122,11 @@ TEST_F(TapFilterTest, Config) { Buffer::OwnedImpl response_body; EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->encodeData(response_body, false)); Http::TestHeaderMapImpl response_trailers; + EXPECT_CALL(*http_per_request_tapper_, onResponseTrailers(_)); EXPECT_EQ(Http::FilterTrailersStatus::Continue, filter_->encodeTrailers(response_trailers)); - EXPECT_CALL(*http_per_request_tapper_, onDestroyLog(&request_headers, &response_headers)) + EXPECT_CALL(*http_per_request_tapper_, onDestroyLog(&request_headers, &request_trailers, + &response_headers, &response_trailers)) .WillOnce(Return(true)); filter_->log(&request_headers, &response_headers, &response_trailers, stream_info_); EXPECT_EQ(1UL, filter_config_->stats_.rq_tapped_.value()); From e443bcde5753bb838a5cae55c7a6b13e4d033175 Mon Sep 17 00:00:00 2001 From: Stephan Zuercher Date: Fri, 1 Feb 2019 15:58:57 -0800 Subject: [PATCH 05/51] build: add pedantic spell check to build (#5779) Adds support for fixing errors via the pedantic spell checker. Runs pedantic comment spelling checking during builds. Adds the location where python deps are installed during do_ci.sh (to avoid spurrious format check errors). *Risk Level*: low *Testing*: checks comment spelling *Docs Changes*: n/a *Release Notes*: n/a Signed-off-by: Stephan Zuercher --- .circleci/config.yml | 3 +- ci/do_ci.sh | 7 +- include/envoy/stats/histogram.h | 2 +- include/envoy/stats/symbol_table.h | 4 +- test/common/network/udp_listener_impl_test.cc | 4 +- tools/check_format.py | 2 +- tools/check_spelling_pedantic.py | 464 +++++++++++++----- tools/spelling_dictionary.txt | 3 + 8 files changed, 349 insertions(+), 140 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index decf0b22f3471..290475d9b52a1 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -4,7 +4,7 @@ executors: ubuntu-build: description: "A regular build executor based on ubuntu image" docker: - - image: envoyproxy/envoy-build:111781fa2823535762e9c514db0c5c41a119b4b1 + - image: envoyproxy/envoy-build:698009170e362f9ca0594f2b1927fbbee199bf98 resource_class: xlarge working_directory: /source @@ -127,6 +127,7 @@ jobs: - run: ci/do_circle_ci.sh check_format - run: ci/do_circle_ci.sh check_repositories - run: ci/do_circle_ci.sh check_spelling + - run: ci/do_circle_ci.sh check_spelling_pedantic build_image: docker: - image: circleci/python:3.7 diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 7f4cb02c461b4..5a8085a46fa11 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -7,7 +7,7 @@ set -e build_setup_args="" if [[ "$1" == "fix_format" || "$1" == "check_format" || "$1" == "check_repositories" || \ "$1" == "check_spelling" || "$1" == "fix_spelling" || "$1" == "bazel.clang_tidy" || \ - "$1" == "check_spelling_pedantic" ]]; then + "$1" == "check_spelling_pedantic" || "$1" == "fix_spelling_pedantic" ]]; then build_setup_args="-nofetch" fi @@ -305,6 +305,11 @@ elif [[ "$1" == "check_spelling_pedantic" ]]; then echo "check_spelling_pedantic..." ./tools/check_spelling_pedantic.py check exit 0 +elif [[ "$1" == "fix_spelling_pedantic" ]]; then + cd "${ENVOY_SRCDIR}" + echo "fix_spelling_pedantic..." + ./tools/check_spelling_pedantic.py fix + exit 0 elif [[ "$1" == "docs" ]]; then echo "generating docs..." docs/build.sh diff --git a/include/envoy/stats/histogram.h b/include/envoy/stats/histogram.h index ffd76f274b248..bebba3ff976e5 100644 --- a/include/envoy/stats/histogram.h +++ b/include/envoy/stats/histogram.h @@ -45,7 +45,7 @@ class HistogramStatistics { virtual const std::vector& supportedBuckets() const PURE; /** - * Returns computed bucket values during the period. The vector contains an appoximation + * Returns computed bucket values during the period. The vector contains an approximation * of samples below each quantile bucket defined in supportedBuckets(). This vector is * guaranteed to be the same length as supportedBuckets(). */ diff --git a/include/envoy/stats/symbol_table.h b/include/envoy/stats/symbol_table.h index 3bc6ee4069835..b0efd1cbd75d1 100644 --- a/include/envoy/stats/symbol_table.h +++ b/include/envoy/stats/symbol_table.h @@ -87,7 +87,7 @@ class SymbolTable { * with a corrupt stats set. * * @param stat_name the stat name. - * @return std::string stringifiied stat_name. + * @return std::string stringified stat_name. */ virtual std::string toString(const StatName& stat_name) const PURE; @@ -122,7 +122,7 @@ class SymbolTable { * * This is intended for use doing cached name lookups of scoped stats, where * the scope prefix and the names to combine it with are already in StatName - * form. Using this class, they can be combined without acessingm the + * form. Using this class, they can be combined without accessing the * SymbolTable or, in particular, taking its lock. * * @param stat_names the names to join. diff --git a/test/common/network/udp_listener_impl_test.cc b/test/common/network/udp_listener_impl_test.cc index 3251d1b9775ed..d9262e2dc052b 100644 --- a/test/common/network/udp_listener_impl_test.cc +++ b/test/common/network/udp_listener_impl_test.cc @@ -256,7 +256,7 @@ TEST_P(ListenerImplTest, UdpEcho) { getSocketAddressInfo(*client_socket.get(), server_ip->port(), server_addr, addr_len); ASSERT_GT(addr_len, 0); - // We send 2 packets and exptect it to echo. + // We send 2 packets and expect it to echo. const std::string first("first"); const std::string second("second"); @@ -456,7 +456,7 @@ TEST_P(ListenerImplTest, UdpListenerEnableDisable) { } /** - * Tests UDP listebe's error callback. + * Tests UDP listener's error callback. */ TEST_P(ListenerImplTest, UdpListenerRecvFromError) { // Setup server socket diff --git a/tools/check_format.py b/tools/check_format.py index 6468a275a97a7..f03defe713ee5 100755 --- a/tools/check_format.py +++ b/tools/check_format.py @@ -16,7 +16,7 @@ EXCLUDED_PREFIXES = ("./generated/", "./thirdparty/", "./build", "./.git/", "./bazel-", "./.cache", "./source/extensions/extensions_build_config.bzl", - "./tools/testdata/check_format/") + "./tools/testdata/check_format/", "./tools/pyformat/") SUFFIXES = (".cc", ".h", "BUILD", "WORKSPACE", ".bzl", ".md", ".rst", ".proto") DOCS_SUFFIX = (".md", ".rst") PROTO_SUFFIX = (".proto") diff --git a/tools/check_spelling_pedantic.py b/tools/check_spelling_pedantic.py index 428cfe308bfec..3a6a23938d484 100755 --- a/tools/check_spelling_pedantic.py +++ b/tools/check_spelling_pedantic.py @@ -3,28 +3,35 @@ from __future__ import print_function import argparse +import math import os import re import subprocess import sys -# TODO(zuercher): provide support for fixing errors +from functools import partial + +# Handle function rename between python 2/3. +try: + input = raw_input +except NameError: + pass TOOLS_DIR = os.path.dirname(os.path.realpath(__file__)) -# e.g., // comment OR /* comment */ (single line) +# Single line comments: // comment OR /* comment */ # Limit the characters that may precede // to help filter out some code # mistakenly processed as a comment. INLINE_COMMENT = re.compile(r'(?:^|[^:"])//(.*?)$|/\*+(.*?)\*+/') -# e.g., /* comment */ (multiple lines) +# Multi-line comments: /* comment */ (multiple lines) MULTI_COMMENT_START = re.compile(r'/\*(.*?)$') MULTI_COMMENT_END = re.compile(r'^(.*?)\*/') -# e.g., TODO(username): blah +# Envoy TODO comment style. TODO = re.compile(r'(TODO|NOTE)\s*\(@?[A-Za-z0-9-]+\):?') -# e.g., ignore parameter names in doxygen comments +# Ignore parameter names in doxygen comments. METHOD_DOC = re.compile('@(param\s+\w+|return(\s+const)?\s+\w+)') # Camel Case splitter @@ -38,7 +45,7 @@ # Hex: match 1) longish strings of hex digits (to avoid matching "add" and # other simple words that happen to look like hex), 2) 2 or more two digit # hex numbers separated by colons, 3) "0x" prefixed hex numbers of any length, -# or 4) UUIDs +# or 4) UUIDs. HEX = re.compile(r'(?:^|\s|[(])([A-Fa-f0-9]{8,})(?:$|\s|[.,)])') HEX_SIG = re.compile(r'\W([A-Fa-f0-9]{2}(:[A-Fa-f0-9]{2})+)\W') PREFIXED_HEX = re.compile(r'0x[A-Fa-f0-9]+') @@ -48,13 +55,13 @@ # aspell ignores that anyway. IPV6_ADDR = re.compile(r'\W([A-Fa-f0-9]+:[A-Fa-f0-9:]+/[0-9]{1,3})\W') -# Quoted words: "word", 'word', or *word* +# Quoted words: "word", 'word', or *word*. QUOTED_WORD = re.compile(r'(["\'*])[A-Za-z0-9]+(\1)') -# Command flags (e.g. "-rf") and percent specifiers +# Command flags (e.g. "-rf") and percent specifiers. FLAG = re.compile(r'\W([-%][A-Za-z]+)') -# Bare github users (e.g. @user) +# Bare github users (e.g. @user). USER = re.compile(r'\W(@[A-Za-z0-9-]+)') DEBUG = False @@ -73,17 +80,153 @@ def debug(s): print(s) +class SpellChecker: + """Aspell-based spell checker.""" + + def __init__(self, dictionary_file): + self.dictionary_file = dictionary_file + self.aspell = None + + def start(self): + words = self.load_dictionary() + + # Generate aspell personal dictionary. + pws = os.path.join(TOOLS_DIR, '.aspell.en.pws') + with open(pws, 'w') as f: + f.write("personal_ws-1.1 en %d\n" % (len(words))) + f.writelines(words) + + # Start an aspell process. + aspell_args = ["aspell", "pipe", "--run-together", "--encoding=utf-8", "--personal=" + pws] + self.aspell = subprocess.Popen( + aspell_args, + bufsize=4096, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=True) + + # Read the version line that aspell emits on startup. + self.aspell.stdout.readline() + + def stop(self): + if not self.aspell: + return + + self.aspell.stdin.close() + self.aspell.wait() + self.aspell = None + + def check(self, line): + self.aspell.poll() + if self.aspell.returncode is not None: + print("aspell quit unexpectedly: return code %d" % (self.aspell.returncode)) + sys.exit(2) + + debug("ASPELL< %s" % (line)) + + self.aspell.stdin.write(line + os.linesep) + self.aspell.stdin.flush() + + errors = [] + while True: + result = self.aspell.stdout.readline().strip() + debug("ASPELL> %s" % (result)) + + # Check for end of results. + if result == "": + break + + t = result[0] + if t == "*" or t == "-" or t == "+": + # *: found in dictionary. + # -: found run-together words in dictionary. + # +: found root word in dictionary. + continue + + # & : m1, m2, ... mN, g1, g2, ... + # ? 0 : g1, g2, .... + # # + original, rem = result[2:].split(" ", 1) + + if t == "#": + # Not in dictionary, but no suggestions. + errors.append((original, int(rem), [])) + elif t == '&' or t == '?': + # Near misses and/or guesses. + _, rem = rem.split(" ", 1) # Drop N (may be 0). + o, rem = rem.split(": ", 1) # o is offset from start of line. + suggestions = rem.split(", ") + + errors.append((original, int(o), suggestions)) + else: + print("aspell produced unexpected output: %s" % (result)) + sys.exit(2) + + return errors + + def load_dictionary(self): + # Read the custom dictionary. + words = [] + with open(self.dictionary_file, 'r') as f: + words = f.readlines() + + # Strip comments and blank lines. + words = [w for w in words if len(w.strip()) > 0 and w[0] != "#"] + + # Allow acronyms and abbreviations to be spelled in lowercase. + # (e.g. Convert "HTTP" into "HTTP" and "http" which also matches + # "Http"). + for word in words: + if word.isupper(): + words += word.lower() + + return words + + def add_words(self, additions): + lines = [] + with open(self.dictionary_file, 'r') as f: + lines = f.readlines() + + additions = [w + os.linesep for w in additions] + additions.sort() + + # Insert additions into the lines ignoring comments and blank lines. + idx = 0 + add_idx = 0 + while idx < len(lines) and add_idx < len(additions): + line = lines[idx] + if len(line.strip()) != 0 and line[0] != "#": + c = cmp(additions[add_idx], line) + if c < 0: + lines.insert(idx, additions[add_idx]) + add_idx += 1 + elif c == 0: + add_idx += 1 + idx += 1 + + # Append any remaining additions. + lines += additions[add_idx:] + + with open(self.dictionary_file, 'w') as f: + f.writelines(lines) + + self.stop() + self.start() + + # Split camel case words and run them through the dictionary. Returns # True if they are all spelled correctly, False if word is not camel # case or has a misspelled sub-word. -def check_camel_case(aspell, word): - # Words is not camel case: the previous result stands. +def check_camel_case(checker, word): parts = re.findall(CAMEL_CASE, word) + + # Word is not camel case: the previous result stands. if len(parts) <= 1: return False for part in parts: - if check_comment(aspell, 0, part): + if check_comment(checker, 0, part): # Part of camel case word is misspelled, the result stands. return False @@ -105,10 +248,10 @@ def mask_with_regex(comment, regex, group, secondary=None): return comment -# Checks the comment at offset against the aspell pipe. Result is an array +# Checks the comment at offset against the spell checker. Result is an array # of tuples where each tuple is the misspelled word, it's offset from the # start of the line, and an array of possible replacements. -def check_comment(aspell, offset, comment): +def check_comment(checker, offset, comment): # Replace TODO comments with spaces to preserve string offsets. comment = mask_with_regex(comment, TODO, 0) @@ -135,170 +278,220 @@ def check_comment(aspell, offset, comment): # Github user refs: comment = mask_with_regex(comment, USER, 1) - # Everything got stripped, return early. + # Everything got masked, return early. if comment == "" or comment.strip() == "": return [] - # aspell does not like leading punctuation + # Mask leading punctuation. if not comment[0].isalnum(): comment = ' ' + comment[1:] - errors = [] + errors = checker.check(comment) + + # Fix up offsets relative to the start of the line vs start of the comment. + errors = [(w, o + offset, s) for (w, o, s) in errors] - aspell.poll() - if aspell.returncode is not None: - print("aspell quit unexpectedly: return code %d" % (aspell.returncode)) - sys.exit(1) + # Retry camel case words after splitting them. + errors = [err for err in errors if not check_camel_case(checker, err[0])] + return errors - debug("ASPELL< %s" % (comment)) - aspell.stdin.write(comment + os.linesep) - aspell.stdin.flush() - while True: - result = aspell.stdout.readline().strip() - debug("ASPELL> %s" % (result)) +def print_error(file, line_offset, lines, errors): + # Highlight misspelled words. + line = lines[line_offset] + prefix = "%s:%d:" % (file, line_offset + 1) + for (word, offset, suggestions) in reversed(errors): + line = line[:offset] + red(word) + line[offset + len(word):] - if result == "": - break # handled all results + print("%s%s" % (prefix, line.rstrip())) - t = result[0] - if t == "*" or t == "-" or t == "+": - # *: found in dictionary - # -: found run-together words in dictionary - # +: found root word in dictionary + if MARK: + # Print a caret at the start of each misspelled word. + marks = ' ' * len(prefix) + last = 0 + for (word, offset, suggestions) in errors: + marks += (' ' * (offset - last)) + '^' + last = offset + 1 + print(marks) + + +def print_fix_options(word, suggestions): + print("%s:" % (word)) + print(" a: accept and add to dictionary") + print(" A: accept and add to dictionary as ALLCAPS (for acronyms)") + print(" i: ignore") + print(" r : replace with given word and add to dictionary") + print(" R : replace with given word and add to dictionary as ALLCAPS (for acronyms)") + print(" x: abort") + + col_width = max(len(word) for word in suggestions) + opt_width = int(math.log(len(suggestions), 10)) + 1 + padding = 2 # Two spaces of padding. + delim = 2 # Colon and space after number. + num_cols = int(78 / (col_width + padding + opt_width + delim)) + num_rows = int(len(suggestions) / num_cols + 1) + rows = [""] * num_rows + + indent = " " * padding + for idx, sugg in enumerate(suggestions): + row = idx % len(rows) + row_data = "%d: %s" % (idx, sugg) + + rows[row] += indent + row_data.ljust(col_width + opt_width + delim) + + for row in rows: + print(row) + + +def fix_error(checker, file, line_offset, lines, errors): + print_error(file, line_offset, lines, errors) + + fixed = {} + replacements = [] + additions = [] + for (word, offset, suggestions) in errors: + if word in fixed: + # Same typo was repeated in a line, so just reuse the previous choice. + replacements += [fixed[word]] continue - # & : m1, m2, ... mN, g1, g2, ... - # ? 0 : g1, g2, .... - # # - original, rem = result[2:].split(" ", 1) - - if t == "#": - # Not in dictionary, but no suggestions - errors.append((original, int(rem) + offset, [])) - elif t == '&' or t == '?': - # Near misses and/or guesses - _, rem = rem.split(" ", 1) # drop N (or 0) - o, rem = rem.split(": ", 1) # o is offset from start of comment - suggestions = rem.split(", ") - - errors.append((original, int(o) + offset, suggestions)) - else: - print("aspell produced unexpected output: %s" % (result)) - sys.exit(2) + print_fix_options(word, suggestions) + + replacement = "" + while replacement == "": + try: + choice = input("> ") + except EOFError: + choice = "x" + + add = None + if choice == "x": + print("Spell checking aborted.") + sys.exit(2) + elif choice == "a": + replacement = word + add = word + elif choice == "A": + replacement = word + add = word.upper() + elif choice == "i": + replacement = word + elif choice[:1] == "r" or choice[:1] == "R": + replacement = choice[1:].strip() + if replacement == "": + print("Invalid choice: '%s'. Must specify a replacement (e.g. 'r corrected')." % (choice)) + continue + + if choice[:1] == "R": + if replacement.upper() not in suggestions: + add = replacement.upper() + elif replacement not in suggestions: + add = replacement + elif choice == 's': + for idx, sugg in enumerate(suggestions[:10]): + print("\t%d: %s" % (idx, sugg)) + else: + try: + idx = int(choice) + except ValueError: + idx = -1 + if idx >= 0 and idx < len(suggestions): + replacement = suggestions[idx] + else: + print("Invalid choice: '%s'" % (choice)) + + fixed[word] = replacement + replacements += [replacement] + if add: + additions += [add] + + if len(errors) != len(replacements): + print("Internal error %d errors with %d replacements" % (len(errors), len(replacements))) + sys.exit(2) + + # Perform replacements on the line. + line = lines[line_offset] + for idx in range(len(replacements) - 1, -1, -1): + word, offset, _ = errors[idx] + replacement = replacements[idx] + if word == replacement: + continue - # Retry camel case words after splitting them. - errors = [err for err in errors if not check_camel_case(aspell, err[0])] - return errors + line = line[:offset] + replacement + line[offset + len(word):] + lines[line_offset] = line + + # Update the dictionary. + checker.add_words(additions) -def check_file(aspell, file, lines): +def check_file(checker, file, lines, error_handler): in_comment = False - line_num = 0 - num = 0 - for line in lines: - line_num += 1 + num_comments = 0 + num_errors = 0 + for line_idx, line in enumerate(lines): errors = [] last = 0 if in_comment: mc_end = MULTI_COMMENT_END.search(line) if mc_end is None: # Full line is within a multi-line comment. - errors += check_comment(aspell, 0, line) - num += 1 + errors += check_comment(checker, 0, line) + num_comments += 1 else: # Start of line is the end of a multi-line comment. - errors += check_comment(aspell, 0, mc_end.group(1)) - num += 1 + errors += check_comment(checker, 0, mc_end.group(1)) + num_comments += 1 last = mc_end.end() in_comment = False if not in_comment: for inline in INLINE_COMMENT.finditer(line, last): - # Single-line comment - m = inline.lastindex # 1 or 2 depending on group matched - errors += check_comment(aspell, inline.start(m), inline.group(m)) - num += 1 + # Single-line comment. + m = inline.lastindex # 1 or 2 depending on group matched. + errors += check_comment(checker, inline.start(m), inline.group(m)) + num_comments += 1 last = inline.end(m) if last < len(line): mc_start = MULTI_COMMENT_START.search(line, last) if mc_start is not None: # New multi-lie comment starts at end of line. - errors += check_comment(aspell, mc_start.start(1), mc_start.group(1)) - num += 1 + errors += check_comment(checker, mc_start.start(1), mc_start.group(1)) + num_comments += 1 in_comment = True if errors: - # Highlight misspelled words. - prefix = "%s:%d:" % (file, line_num) - for (word, offset, suggestions) in reversed(errors): - line = line[:offset] + red(word) + line[offset + len(word):] - - print("%s%s" % (prefix, line.rstrip())) - - if MARK: - # Print a caret at the start of each misspelled word. - marks = ' ' * len(prefix) - last = 0 - for (word, offset, suggestions) in errors: - marks += (' ' * (offset - last)) + '^' - last = offset + 1 - print(marks) - - return num - - -def start_aspell(dictionary): - # Read the custom dictionary - words = [] - with open(dictionary, 'r') as f: - words = f.readlines() - - # Strip comments. - words = [w for w in words if len(w) > 0 and w[0] != "#"] - - # Allow acronyms and abbreviations to be spelled in lowercase. - # (e.g. Convert "HTTP"" into "HTTP" and "http" which also matches - # "Http"). - for word in words: - if word.isupper(): - words += word.lower() - - # Generate aspell personal dictionary. - pws = os.path.join(TOOLS_DIR, '.aspell.en.pws') - with open(pws, 'w') as f: - f.write("personal_ws-1.1 en %d\n" % (len(words))) - for word in words: - f.write(word) + num_errors += len(errors) + error_handler(file, line_idx, lines, errors) - # Start an aspell process. - aspell_args = ["aspell", "pipe", "--run-together", "--encoding=utf-8", "--personal=" + pws] - aspell = subprocess.Popen( - aspell_args, - bufsize=4096, - stdin=subprocess.PIPE, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - universal_newlines=True) + return (num_comments, num_errors) - # Read the version line that aspell emits on startup. - aspell.stdout.readline() - return aspell +def execute(files, dictionary_file, fix): + checker = SpellChecker(dictionary_file) + checker.start() -def execute(files, dictionary): - aspell = start_aspell(dictionary) + handler = print_error + if fix: + handler = partial(fix_error, checker) - num = 0 + total_comments = 0 + total_errors = 0 for path in files: with open(path, 'r') as f: lines = f.readlines() - num += check_file(aspell, path, lines) + (num_comments, num_errors) = check_file(checker, path, lines, handler) + total_comments += num_comments + total_errors += num_errors + + if fix and num_errors > 0: + with open(path, 'w') as f: + f.writelines(lines) + + checker.stop() - aspell.stdin.close() - aspell.wait() + print("Checked %d comments, found %d errors." % (total_comments, total_errors)) - print("Checked %d lines of comments" % (num)) + return total_errors == 0 if __name__ == "__main__": @@ -308,7 +501,7 @@ def execute(files, dictionary): parser.add_argument( 'operation_type', type=str, - choices=['check'], + choices=['check', 'fix'], help="specify if the run should 'check' or 'fix' spelling.") parser.add_argument( 'target_paths', type=str, nargs="*", help="specify the files for the script to process.") @@ -341,4 +534,11 @@ def execute(files, dictionary): for root, _, files in os.walk(p): target_paths += [os.path.join(root, f) for f in files if os.path.splitext(f)[1] in exts] - execute(target_paths, args.dictionary) + rv = execute(target_paths, args.dictionary, args.operation_type == 'fix') + + if args.operation_type == 'check': + if not rv: + print("ERROR: spell check failed. Run 'tool/check_spelling_pedantic.py fix'") + sys.exit(1) + + print("PASS") diff --git a/tools/spelling_dictionary.txt b/tools/spelling_dictionary.txt index 5122aeee620a4..f7a4911917f8a 100644 --- a/tools/spelling_dictionary.txt +++ b/tools/spelling_dictionary.txt @@ -148,6 +148,7 @@ Nilsson OCSP OK OOM +OS OSI OSS OSX @@ -587,8 +588,10 @@ rebalancing rebuffer recurse recv +recvmmsg redis redistributions +reentrant refactored refactoring referencee From e8411b02f35bcf3bfa11a7591b105a682b370db8 Mon Sep 17 00:00:00 2001 From: danzh Date: Sat, 2 Feb 2019 20:19:28 -0500 Subject: [PATCH 06/51] Implement QuicStringUtils and QuicStrCat (#5797) Signed-off-by: Dan Zhang --- bazel/external/quiche.BUILD | 19 ++++++++++++--- .../quic_listeners/quiche/platform/BUILD | 2 ++ .../quiche/platform/quic_str_cat_impl.h | 23 +++++++++++++++++++ .../quiche/platform/quic_string_utils_impl.h | 18 +++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 source/extensions/quic_listeners/quiche/platform/quic_str_cat_impl.h create mode 100644 source/extensions/quic_listeners/quiche/platform/quic_string_utils_impl.h diff --git a/bazel/external/quiche.BUILD b/bazel/external/quiche.BUILD index 0563a6edfea37..b287afa1dc695 100644 --- a/bazel/external/quiche.BUILD +++ b/bazel/external/quiche.BUILD @@ -26,6 +26,10 @@ licenses(["notice"]) # Apache 2 # should remain largely the same. load(":genrule_cmd.bzl", "genrule_cmd") +load( + "@envoy//bazel:envoy_build_system.bzl", + "envoy_cc_test", +) src_files = glob([ "**/*.h", @@ -118,9 +122,11 @@ cc_library( "quiche/quic/platform/api/quic_flag_utils.h", "quiche/quic/platform/api/quic_iovec.h", "quiche/quic/platform/api/quic_prefetch.h", + "quiche/quic/platform/api/quic_ptr_util.h", + "quiche/quic/platform/api/quic_str_cat.h", "quiche/quic/platform/api/quic_string.h", "quiche/quic/platform/api/quic_string_piece.h", - "quiche/quic/platform/api/quic_ptr_util.h", + "quiche/quic/platform/api/quic_string_utils.h", "quiche/quic/platform/api/quic_uint128.h", # TODO: uncomment the following files as implementations are added. # "quiche/quic/platform/api/quic_bug_tracker.h", @@ -150,8 +156,6 @@ cc_library( # "quiche/quic/platform/api/quic_sleep.h", # "quiche/quic/platform/api/quic_socket_address.h", # "quiche/quic/platform/api/quic_stack_trace.h", - # "quiche/quic/platform/api/quic_str_cat.h", - # "quiche/quic/platform/api/quic_string_utils.h", # "quiche/quic/platform/api/quic_test.h", # "quiche/quic/platform/api/quic_test_loopback.h", # "quiche/quic/platform/api/quic_test_mem_slice_vector.h", @@ -164,3 +168,12 @@ cc_library( "@envoy//source/extensions/quic_listeners/quiche/platform:quic_platform_base_impl_lib", ], ) + +envoy_cc_test( + name = "quic_platform_test", + srcs = ["quiche/quic/platform/api/quic_string_utils_test.cc"], + repository = "@envoy", + deps = [ + ":quic_platform", + ], +) diff --git a/source/extensions/quic_listeners/quiche/platform/BUILD b/source/extensions/quic_listeners/quiche/platform/BUILD index 12d7fd4fb1e3a..8687dd1cb0b6f 100644 --- a/source/extensions/quic_listeners/quiche/platform/BUILD +++ b/source/extensions/quic_listeners/quiche/platform/BUILD @@ -70,6 +70,8 @@ envoy_cc_library( name = "quic_platform_impl_lib", hdrs = [ "quic_mutex_impl.h", + "quic_str_cat_impl.h", + "quic_string_utils_impl.h", ], external_deps = [ "quiche_quic_platform_base", diff --git a/source/extensions/quic_listeners/quiche/platform/quic_str_cat_impl.h b/source/extensions/quic_listeners/quiche/platform/quic_str_cat_impl.h new file mode 100644 index 0000000000000..f689f40a6204a --- /dev/null +++ b/source/extensions/quic_listeners/quiche/platform/quic_str_cat_impl.h @@ -0,0 +1,23 @@ +#pragma once + +#include "absl/strings/str_cat.h" +#include "fmt/printf.h" +#include "quiche/quic/platform/api/quic_string.h" + +// NOLINT(namespace-envoy) + +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +namespace quic { + +template inline QuicString QuicStrCatImpl(const Args&... args) { + return absl::StrCat(args...); +} + +template inline QuicString QuicStringPrintfImpl(const Args&... args) { + return fmt::sprintf(std::forward(args)...); +} + +} // namespace quic diff --git a/source/extensions/quic_listeners/quiche/platform/quic_string_utils_impl.h b/source/extensions/quic_listeners/quiche/platform/quic_string_utils_impl.h new file mode 100644 index 0000000000000..b3ab8277df196 --- /dev/null +++ b/source/extensions/quic_listeners/quiche/platform/quic_string_utils_impl.h @@ -0,0 +1,18 @@ +#pragma once + +#include "absl/strings/str_cat.h" +#include "quiche/quic/platform/api/quic_string.h" + +// NOLINT(namespace-envoy) + +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +namespace quic { + +template inline void QuicStrAppendImpl(QuicString* output, const Args&... args) { + absl::StrAppend(output, args...); +} + +} // namespace quic From f54d222a466a597e5980961e34432b38b4dc8b58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Guti=C3=A9rrez=20Segal=C3=A9s?= Date: Sun, 3 Feb 2019 14:17:47 -0800 Subject: [PATCH 07/51] Fix setReference() call in hystrix stats sink (#5815) Per: https://github.com/envoyproxy/envoy/blob/master/include/envoy/http/header_map.h#L148 `setReference()` needs a std::string ref that will live beyond the lifetime of a request/response, but it's currently receiving a string literal which is used to construct a temporary std::string. So instead pass an integer. Signed-off-by: Raul Gutierrez Segales --- source/extensions/stat_sinks/hystrix/hystrix.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/extensions/stat_sinks/hystrix/hystrix.cc b/source/extensions/stat_sinks/hystrix/hystrix.cc index 6c05d4a66c27f..f3a860032ba33 100644 --- a/source/extensions/stat_sinks/hystrix/hystrix.cc +++ b/source/extensions/stat_sinks/hystrix/hystrix.cc @@ -290,7 +290,7 @@ Http::Code HystrixSink::handlerHystrixEventStream(absl::string_view, AccessControlAllowHeadersValue.AllowHeadersHystrix); response_headers.insertAccessControlAllowOrigin().value().setReference( Http::Headers::get().AccessControlAllowOriginValue.All); - response_headers.insertNoChunks().value().setReference("0"); + response_headers.insertNoChunks().value().setInteger(0); Http::StreamDecoderFilterCallbacks& stream_decoder_filter_callbacks = admin_stream.getDecoderFilterCallbacks(); From cb3ac04e2b096eb447b3ec2ba58ae175c91da542 Mon Sep 17 00:00:00 2001 From: Joshua Marantz Date: Mon, 4 Feb 2019 00:08:31 -0500 Subject: [PATCH 08/51] test: add a common test base class (#5811) Signed-off-by: Joshua Marantz --- bazel/envoy_build_system.bzl | 1 + .../access_log/access_log_formatter_test.cc | 2 +- .../common/access_log/access_log_impl_test.cc | 4 ++-- .../access_log_manager_impl_test.cc | 2 +- test/common/buffer/buffer_test.cc | 3 +-- test/common/buffer/owned_impl_test.cc | 4 ++-- test/common/buffer/utility.h | 2 +- test/common/buffer/watermark_buffer_test.cc | 4 ++-- .../buffer/zero_copy_input_stream_test.cc | 4 ++-- test/common/common/assert_test.cc | 3 +-- test/common/common/backoff_strategy_test.cc | 3 +-- test/common/common/base64_test.cc | 3 +-- .../common/block_memory_hash_set_test.cc | 5 +++-- test/common/common/callback_impl_test.cc | 4 +++- test/common/common/cleanup_test.cc | 2 +- test/common/common/fmt_test.cc | 3 ++- test/common/common/hash_test.cc | 2 +- test/common/common/hex_test.cc | 2 +- test/common/common/lock_guard_test.cc | 4 ++-- test/common/common/log_macros_test.cc | 2 +- test/common/common/matchers_test.cc | 2 +- test/common/common/mutex_tracer_test.cc | 4 ++-- .../common/perf_annotation_disabled_test.cc | 2 +- test/common/common/perf_annotation_test.cc | 4 ++-- test/common/common/phantom_test.cc | 2 +- test/common/common/stack_array_test.cc | 3 ++- test/common/common/to_lower_table_test.cc | 2 +- test/common/common/token_bucket_impl_test.cc | 5 ++--- test/common/common/utility_test.cc | 2 +- .../compressor/zlib_compressor_impl_test.cc | 5 ++--- .../config/config_provider_impl_test.cc | 4 ++-- .../filesystem_subscription_impl_test.cc | 5 ++--- .../filesystem_subscription_test_harness.h | 2 +- test/common/config/filter_json_test.cc | 3 +-- test/common/config/grpc_mux_impl_test.cc | 4 ++-- .../config/grpc_subscription_impl_test.cc | 5 ++--- .../config/grpc_subscription_test_harness.h | 2 +- .../config/http_subscription_impl_test.cc | 5 ++--- .../config/http_subscription_test_harness.h | 2 +- test/common/config/metadata_test.cc | 5 ++--- test/common/config/rds_json_test.cc | 3 ++- .../config/subscription_factory_test.cc | 4 ++-- test/common/config/subscription_impl_test.cc | 2 +- .../common/config/subscription_test_harness.h | 2 +- test/common/config/utility_test.cc | 2 +- test/common/crypto/utility_test.cc | 2 +- .../zlib_decompressor_impl_test.cc | 5 ++--- .../event/dispatched_thread_impl_test.cc | 4 ++-- test/common/event/dispatcher_impl_test.cc | 4 ++-- test/common/event/file_event_impl_test.cc | 7 +++---- test/common/filesystem/directory_test.cc | 4 ++-- .../common/filesystem/filesystem_impl_test.cc | 4 ++-- test/common/filesystem/watcher_impl_test.cc | 4 ++-- test/common/grpc/async_client_impl_test.cc | 4 ++-- .../grpc/async_client_manager_impl_test.cc | 4 ++-- test/common/grpc/codec_test.cc | 3 +-- test/common/grpc/common_test.cc | 3 +-- .../grpc/google_async_client_impl_test.cc | 4 ++-- test/common/grpc/google_grpc_creds_test.cc | 5 ++--- test/common/grpc/grpc_client_integration.h | 7 +++---- test/common/html/utility_test.cc | 2 +- test/common/http/async_client_impl_test.cc | 4 ++-- test/common/http/codec_client_test.cc | 6 +++--- test/common/http/codes_test.cc | 6 +++--- test/common/http/conn_manager_impl_test.cc | 4 ++-- test/common/http/conn_manager_utility_test.cc | 4 ++-- test/common/http/date_provider_impl_test.cc | 2 +- test/common/http/header_map_impl_test.cc | 3 +-- test/common/http/header_utility_test.cc | 3 +-- test/common/http/http1/codec_impl_test.cc | 6 +++--- test/common/http/http1/conn_pool_test.cc | 4 ++-- test/common/http/http2/codec_impl_test.cc | 4 ++-- test/common/http/http2/conn_pool_test.cc | 4 ++-- .../http2/metadata_encoder_decoder_test.cc | 5 +++-- test/common/http/user_agent_test.cc | 3 +-- test/common/http/utility_test.cc | 3 +-- test/common/json/config_schemas_test.cc | 4 ++-- test/common/json/json_loader_test.cc | 5 ++--- test/common/memory/debug_test.cc | 2 +- test/common/network/address_impl_test.cc | 7 +++---- test/common/network/cidr_range_test.cc | 2 +- test/common/network/connection_impl_test.cc | 12 +++++------ test/common/network/dns_impl_test.cc | 6 +++--- .../network/filter_manager_impl_test.cc | 4 ++-- test/common/network/lc_trie_test.cc | 5 ++--- .../common/network/listen_socket_impl_test.cc | 5 ++--- test/common/network/listener_impl_test.cc | 6 +++--- test/common/network/resolver_impl_test.cc | 5 ++--- .../network/socket_option_factory_test.cc | 5 ++--- test/common/network/socket_option_test.h | 5 ++--- test/common/network/udp_listener_impl_test.cc | 4 ++-- test/common/network/utility_test.cc | 5 ++--- test/common/protobuf/utility_test.cc | 7 +++---- test/common/router/config_impl_test.cc | 20 +++++++++--------- test/common/router/header_formatter_test.cc | 4 ++-- test/common/router/rds_impl_test.cc | 4 ++-- test/common/router/retry_state_impl_test.cc | 4 ++-- test/common/router/router_ratelimit_test.cc | 6 +++--- test/common/router/router_test.cc | 4 ++-- .../common/router/router_upstream_log_test.cc | 4 ++-- test/common/router/shadow_writer_impl_test.cc | 4 ++-- .../router/string_accessor_impl_test.cc | 3 ++- test/common/runtime/runtime_impl_test.cc | 6 +++--- test/common/runtime/uuid_util_test.cc | 2 +- test/common/secret/sds_api_test.cc | 4 ++-- .../common/secret/secret_manager_impl_test.cc | 4 ++-- .../singleton/threadsafe_singleton_test.cc | 3 +-- test/common/stats/heap_stat_data_test.cc | 3 +-- test/common/stats/isolated_store_impl_test.cc | 3 ++- test/common/stats/raw_stat_data_test.cc | 5 ++--- test/common/stats/source_impl_test.cc | 3 +-- test/common/stats/stats_matcher_impl_test.cc | 5 ++--- test/common/stats/symbol_table_impl_test.cc | 4 ++-- test/common/stats/tag_extractor_impl_test.cc | 3 +-- test/common/stats/tag_producer_impl_test.cc | 3 +-- test/common/stats/thread_local_store_test.cc | 6 +++--- .../stream_info/filter_state_impl_test.cc | 5 ++--- .../stream_info/stream_info_impl_test.cc | 4 ++-- test/common/stream_info/utility_test.cc | 2 +- test/common/tcp/conn_pool_test.cc | 6 +++--- test/common/tcp_proxy/tcp_proxy_test.cc | 6 +++--- .../thread/thread_factory_singleton_test.cc | 5 +++-- .../thread_local/thread_local_impl_test.cc | 2 +- test/common/tracing/http_tracer_impl_test.cc | 4 ++-- test/common/upstream/cds_api_impl_test.cc | 4 ++-- .../upstream/cluster_manager_impl_test.cc | 6 +++--- test/common/upstream/edf_scheduler_test.cc | 2 +- test/common/upstream/eds_test.cc | 4 ++-- test/common/upstream/hds_test.cc | 4 ++-- .../upstream/health_checker_impl_test.cc | 10 ++++----- test/common/upstream/host_utility_test.cc | 3 +-- .../upstream/load_balancer_impl_test.cc | 4 ++-- .../upstream/load_balancer_simulation_test.cc | 4 ++-- .../upstream/load_stats_reporter_test.cc | 4 ++-- .../upstream/logical_dns_cluster_test.cc | 4 ++-- test/common/upstream/maglev_lb_test.cc | 2 +- .../upstream/original_dst_cluster_test.cc | 4 ++-- .../upstream/outlier_detection_impl_test.cc | 4 ++-- .../upstream/resource_manager_impl_test.cc | 2 +- test/common/upstream/ring_hash_lb_test.cc | 4 ++-- test/common/upstream/subset_lb_test.cc | 4 ++-- test/common/upstream/upstream_impl_test.cc | 14 ++++++------- test/config/utility.cc | 2 +- test/config_test/config_test.cc | 2 +- test/config_test/example_configs_test.cc | 3 +-- test/coverage/gcc_only_test/gcc_only_test.cc | 2 +- test/exe/main_common_test.cc | 5 ++--- test/exe/signals_test.cc | 3 +-- test/exe/terminate_handler_test.cc | 3 +-- .../access_loggers/file/config_test.cc | 2 +- .../access_loggers/http_grpc/config_test.cc | 4 ++-- .../http_grpc/grpc_access_log_impl_test.cc | 4 ++-- .../grpc_access_log_integration_test.cc | 3 +-- test/extensions/common/tap/admin_test.cc | 5 ++--- .../extensions/common/tap/tap_matcher_test.cc | 5 ++--- .../ext_authz/check_request_utils_test.cc | 4 ++-- .../ext_authz/ext_authz_grpc_impl_test.cc | 4 ++-- .../ext_authz/ext_authz_http_impl_test.cc | 4 ++-- .../extensions/filters/common/lua/lua_test.cc | 2 +- .../filters/common/lua/lua_wrappers.h | 2 +- .../common/ratelimit/ratelimit_impl_test.cc | 4 ++-- .../filters/common/rbac/engine_impl_test.cc | 2 +- .../filters/common/rbac/matchers_test.cc | 2 +- .../filters/http/buffer/buffer_filter_test.cc | 4 ++-- .../filters/http/buffer/config_test.cc | 2 +- .../http/common/aws/signer_impl_test.cc | 2 +- .../filters/http/common/aws/utility_test.cc | 3 +-- .../filters/http/common/jwks_fetcher_test.cc | 2 +- .../http/cors/cors_filter_integration_test.cc | 5 ++--- .../filters/http/cors/cors_filter_test.cc | 4 ++-- .../filters/http/dynamo/config_test.cc | 2 +- .../filters/http/dynamo/dynamo_filter_test.cc | 4 ++-- .../http/dynamo/dynamo_request_parser_test.cc | 3 +-- .../http/dynamo/dynamo_utility_test.cc | 2 +- .../filters/http/ext_authz/config_test.cc | 2 +- .../filters/http/ext_authz/ext_authz_test.cc | 8 +++---- .../filters/http/fault/config_test.cc | 2 +- .../filters/http/fault/fault_filter_test.cc | 4 ++-- .../http/grpc_http1_bridge/config_test.cc | 2 +- .../http1_bridge_filter_test.cc | 4 ++-- .../reverse_bridge_integration_test.cc | 4 ++-- .../reverse_bridge_test.cc | 4 ++-- .../http/grpc_json_transcoder/config_test.cc | 2 +- .../grpc_json_transcoder_integration_test.cc | 7 +++---- .../json_transcoder_filter_test.cc | 8 +++---- .../transcoder_input_stream_test.cc | 4 ++-- .../filters/http/grpc_web/config_test.cc | 2 +- .../http/grpc_web/grpc_web_filter_test.cc | 4 ++-- .../http/gzip/gzip_filter_integration_test.cc | 5 ++--- .../filters/http/gzip/gzip_filter_test.cc | 5 ++--- .../header_to_metadata_filter_test.cc | 4 ++-- .../filters/http/health_check/config_test.cc | 2 +- .../http/health_check/health_check_test.cc | 4 ++-- .../http/ip_tagging/ip_tagging_filter_test.cc | 4 ++-- .../http/jwt_authn/all_verifier_test.cc | 2 +- .../http/jwt_authn/authenticator_test.cc | 5 ++--- .../filters/http/jwt_authn/extractor_test.cc | 2 +- .../http/jwt_authn/filter_factory_test.cc | 2 +- .../filters/http/jwt_authn/filter_test.cc | 4 ++-- .../http/jwt_authn/group_verifier_test.cc | 2 +- .../filters/http/jwt_authn/jwks_cache_test.cc | 2 +- .../filters/http/jwt_authn/matcher_test.cc | 2 +- .../http/jwt_authn/provider_verifier_test.cc | 2 +- .../filters/http/lua/config_test.cc | 2 +- .../filters/http/lua/lua_filter_test.cc | 2 +- .../filters/http/lua/lua_integration_test.cc | 5 ++--- .../filters/http/ratelimit/config_test.cc | 2 +- .../filters/http/ratelimit/ratelimit_test.cc | 4 ++-- .../filters/http/rbac/config_test.cc | 2 +- .../filters/http/rbac/rbac_filter_test.cc | 2 +- .../filters/http/router/config_test.cc | 2 +- .../filters/http/squash/config_test.cc | 2 +- .../squash/squash_filter_integration_test.cc | 2 +- .../filters/http/squash/squash_filter_test.cc | 4 ++-- .../http/tap/tap_filter_integration_test.cc | 4 ++-- .../filters/http/tap/tap_filter_test.cc | 4 ++-- .../listener/original_src/config_test.cc | 4 ++-- .../original_src_config_factory_test.cc | 2 +- .../original_src_socket_option_test.cc | 4 ++-- .../original_src/original_src_test.cc | 4 ++-- .../proxy_protocol/proxy_protocol_test.cc | 6 +++--- .../tls_inspector/tls_inspector_benchmark.cc | 2 +- .../tls_inspector/tls_inspector_test.cc | 4 ++-- .../client_ssl_auth/client_ssl_auth_test.cc | 4 ++-- .../network/client_ssl_auth/config_test.cc | 4 ++-- .../network/dubbo_proxy/config_test.cc | 2 +- .../dubbo_proxy/dubbo_protocol_impl_test.cc | 2 +- .../network/dubbo_proxy/filter_test.cc | 4 ++-- .../hessian_deserializer_impl_test.cc | 2 +- .../network/dubbo_proxy/hessian_utils_test.cc | 3 +-- .../network/dubbo_proxy/metadata_test.cc | 2 +- .../filters/network/dubbo_proxy/mocks.cc | 2 +- .../network/dubbo_proxy/route_matcher_test.cc | 2 +- .../filters/network/ext_authz/config_test.cc | 2 +- .../network/ext_authz/ext_authz_test.cc | 4 ++-- .../http_connection_manager/config_test.cc | 4 ++-- .../network/mongo_proxy/bson_impl_test.cc | 3 +-- .../network/mongo_proxy/codec_impl_test.cc | 4 ++-- .../network/mongo_proxy/config_test.cc | 2 +- .../filters/network/mongo_proxy/proxy_test.cc | 4 ++-- .../network/mongo_proxy/utility_test.cc | 2 +- .../network/mysql_proxy/mysql_codec_test.cc | 5 +++-- .../network/mysql_proxy/mysql_command_test.cc | 5 +++-- .../network/mysql_proxy/mysql_filter_test.cc | 4 ++-- .../mysql_proxy/mysql_integration_test.cc | 4 ++-- .../filters/network/ratelimit/config_test.cc | 2 +- .../network/ratelimit/ratelimit_test.cc | 4 ++-- .../filters/network/rbac/config_test.cc | 4 ++-- .../filters/network/rbac/filter_test.cc | 2 +- .../filters/network/rbac/integration_test.cc | 2 +- .../network/redis_proxy/codec_impl_test.cc | 5 ++--- .../redis_proxy/command_splitter_impl_test.cc | 4 ++-- .../network/redis_proxy/config_test.cc | 2 +- .../redis_proxy/conn_pool_impl_test.cc | 6 +++--- .../filters/network/redis_proxy/mocks.cc | 3 ++- .../network/redis_proxy/proxy_filter_test.cc | 6 +++--- .../network/sni_cluster/sni_cluster_test.cc | 2 +- .../filters/network/tcp_proxy/config_test.cc | 4 ++-- .../thrift_proxy/app_exception_impl_test.cc | 2 +- .../thrift_proxy/auto_protocol_impl_test.cc | 4 ++-- .../thrift_proxy/auto_transport_impl_test.cc | 2 +- .../thrift_proxy/binary_protocol_impl_test.cc | 5 ++--- .../thrift_proxy/buffer_helper_test.cc | 3 +-- .../compact_protocol_impl_test.cc | 8 +++---- .../network/thrift_proxy/config_test.cc | 8 +++---- .../network/thrift_proxy/conn_manager_test.cc | 4 ++-- .../network/thrift_proxy/conn_state_test.cc | 2 +- .../network/thrift_proxy/decoder_test.cc | 13 ++++++------ .../filters/ratelimit/config_test.cc | 2 +- .../filters/ratelimit/ratelimit_test.cc | 4 ++-- .../framed_transport_impl_test.cc | 3 +-- .../header_transport_impl_test.cc | 2 +- .../network/thrift_proxy/integration_test.cc | 8 +++---- .../network/thrift_proxy/metadata_test.cc | 3 +-- .../filters/network/thrift_proxy/mocks.cc | 2 +- .../thrift_proxy/route_matcher_test.cc | 3 +-- .../thrift_proxy/router_ratelimit_test.cc | 6 +++--- .../network/thrift_proxy/router_test.cc | 9 ++++---- .../thrift_proxy/thrift_object_impl_test.cc | 7 +++---- .../translation_integration_test.cc | 9 ++++---- .../twitter_protocol_impl_test.cc | 5 ++--- .../unframed_transport_impl_test.cc | 3 +-- .../filters/network/thrift_proxy/utility.h | 4 ++-- .../health_checkers/redis/redis_test.cc | 2 +- .../quic_listeners/quiche/dummy_test.cc | 3 ++- .../quiche/platform/http2_platform_test.cc | 3 ++- .../quiche/platform/quic_platform_test.cc | 3 ++- .../quiche/platform/spdy_platform_test.cc | 3 ++- .../fixed_heap/config_test.cc | 3 +-- .../fixed_heap/fixed_heap_monitor_test.cc | 3 ++- .../injected_resource/config_test.cc | 3 +-- .../injected_resource_monitor_test.cc | 4 ++-- .../retry/host/previous_hosts/config_test.cc | 2 +- .../previous_priorities/config_test.cc | 4 ++-- .../stats_sinks/common/statsd/statsd_test.cc | 4 ++-- .../common/statsd/udp_statsd_test.cc | 6 +++--- .../stats_sinks/dog_statsd/config_test.cc | 4 ++-- .../stats_sinks/hystrix/config_test.cc | 2 +- .../stats_sinks/hystrix/hystrix_test.cc | 4 ++-- .../grpc_metrics_service_impl_test.cc | 4 ++-- .../metrics_service_integration_test.cc | 3 +-- .../stats_sinks/statsd/config_test.cc | 6 +++--- .../common/ot/opentracing_driver_impl_test.cc | 4 ++-- .../extensions/tracers/datadog/config_test.cc | 2 +- .../datadog/datadog_tracer_impl_test.cc | 4 ++-- .../tracers/dynamic_ot/config_test.cc | 2 +- .../dynamic_opentracing_driver_impl_test.cc | 4 ++-- .../tracers/lightstep/config_test.cc | 2 +- .../lightstep/lightstep_tracer_impl_test.cc | 4 ++-- test/extensions/tracers/zipkin/config_test.cc | 2 +- .../tracers/zipkin/span_buffer_test.cc | 3 +-- .../zipkin/span_context_extractor_test.cc | 3 +-- test/extensions/tracers/zipkin/tracer_test.cc | 4 ++-- test/extensions/tracers/zipkin/util_test.cc | 3 +-- .../tracers/zipkin/zipkin_core_types_test.cc | 3 +-- .../tracers/zipkin/zipkin_tracer_impl_test.cc | 4 ++-- .../alts/alts_integration_test.cc | 4 ++-- .../transport_sockets/alts/config_test.cc | 2 +- .../noop_transport_socket_callbacks_test.cc | 5 ++--- .../alts/tsi_frame_protector_test.cc | 5 +++-- .../alts/tsi_handshaker_test.cc | 4 ++-- .../transport_sockets/alts/tsi_socket_test.cc | 6 +++--- .../tls/context_impl_test.cc | 2 +- .../transport_sockets/tls/ssl_certs_test.h | 5 ++--- .../transport_sockets/tls/ssl_socket_test.cc | 2 +- .../transport_sockets/tls/ssl_test_utility.h | 2 +- .../transport_sockets/tls/utility_test.cc | 2 +- test/fuzz/main.cc | 5 ++--- test/integration/ads_integration_test.cc | 3 +-- test/integration/cds_integration_test.cc | 2 +- test/integration/echo_integration_test.cc | 2 +- test/integration/eds_integration_test.cc | 5 ++--- test/integration/hds_integration_test.cc | 4 ++-- test/integration/header_integration_test.cc | 9 ++++---- test/integration/http2_integration_test.cc | 3 +-- test/integration/http2_integration_test.h | 5 ++--- .../http2_upstream_integration_test.cc | 3 +-- .../http2_upstream_integration_test.h | 5 ++--- test/integration/http_integration.cc | 3 +-- test/integration/http_protocol_integration.h | 7 +++---- test/integration/integration.cc | 3 +-- test/integration/integration_admin_test.cc | 6 +++--- test/integration/integration_admin_test.h | 3 +-- test/integration/integration_test.cc | 3 +-- test/integration/integration_test.h | 5 ++--- .../load_stats_integration_test.cc | 5 ++--- .../proxy_proto_integration_test.cc | 2 +- .../proxy_proto_integration_test.h | 5 ++--- .../integration/ratelimit_integration_test.cc | 3 +-- .../sds_dynamic_integration_test.cc | 2 +- .../sds_static_integration_test.cc | 12 +++++------ test/integration/server.cc | 2 +- test/integration/ssl_integration_test.cc | 8 +++---- test/integration/ssl_integration_test.h | 4 ++-- test/integration/ssl_utility.cc | 3 +-- test/integration/stats_integration_test.cc | 5 ++--- .../tcp_conn_pool_integration_test.cc | 2 +- .../integration/tcp_proxy_integration_test.cc | 3 +-- test/integration/tcp_proxy_integration_test.h | 5 ++--- test/integration/uds_integration_test.cc | 3 +-- test/integration/uds_integration_test.h | 7 +++---- .../integration/websocket_integration_test.cc | 2 +- test/integration/websocket_integration_test.h | 3 +-- test/integration/xds_integration_test.cc | 5 ++--- test/integration/xfcc_integration_test.cc | 2 +- test/integration/xfcc_integration_test.h | 4 ++-- test/mocks/access_log/mocks.cc | 3 ++- test/mocks/api/mocks.cc | 3 ++- test/mocks/common.h | 1 + test/mocks/event/mocks.cc | 3 ++- test/mocks/http/mocks.cc | 3 ++- test/mocks/init/mocks.cc | 3 ++- test/mocks/local_info/mocks.cc | 3 ++- test/mocks/network/mocks.cc | 2 +- test/mocks/router/mocks.cc | 3 ++- test/mocks/runtime/mocks.cc | 3 ++- test/mocks/secret/mocks.h | 3 ++- test/mocks/server/mocks.cc | 3 ++- test/mocks/server/mocks.h | 2 +- test/mocks/stats/mocks.cc | 3 ++- test/mocks/stream_info/mocks.cc | 3 ++- test/mocks/thread_local/mocks.cc | 3 ++- test/mocks/tracing/mocks.cc | 3 ++- test/mocks/upstream/cluster_info.h | 2 +- test/mocks/upstream/mocks.cc | 3 ++- test/mocks/upstream/mocks.h | 2 +- test/server/backtrace_test.cc | 2 +- .../config_validation/dispatcher_test.cc | 2 +- test/server/config_validation/server_test.cc | 2 +- test/server/configuration_impl_test.cc | 4 ++-- test/server/connection_handler_test.cc | 4 ++-- test/server/drain_manager_impl_test.cc | 4 ++-- test/server/guarddog_impl_test.cc | 4 ++-- test/server/hot_restart_impl_test.cc | 4 ++-- test/server/http/admin_test.cc | 10 ++++----- test/server/http/config_tracker_impl_test.cc | 2 +- test/server/init_manager_impl_test.cc | 2 +- test/server/lds_api_test.cc | 2 +- test/server/listener_manager_impl_test.cc | 4 ++-- test/server/options_impl_test.cc | 4 ++-- test/server/overload_manager_impl_test.cc | 4 ++-- test/server/server_test.cc | 7 +++---- test/server/worker_impl_test.cc | 5 ++--- test/test_common/BUILD | 12 ++++++++++- test/test_common/environment.cc | 2 +- test/test_common/global_test.cc | 5 ++--- test/test_common/network_utility_test.cc | 5 ++--- test/test_common/registry.h | 2 +- .../test_common/simulated_time_system_test.cc | 4 ++-- test/test_common/test_base.cc | 19 +++++++++++++++++ test/test_common/test_base.h | 21 +++++++++++++++++++ test/test_common/test_time_system_test.cc | 5 ++--- test/test_common/utility.cc | 2 +- test/test_common/utility.h | 4 ++-- test/test_common/utility_test.cc | 3 +-- test/test_runner.h | 11 ++++------ .../config_load_check/config_load_check.cc | 3 +-- tools/check_format.py | 5 +++++ 418 files changed, 795 insertions(+), 824 deletions(-) create mode 100644 test/test_common/test_base.cc create mode 100644 test/test_common/test_base.h diff --git a/bazel/envoy_build_system.bzl b/bazel/envoy_build_system.bzl index 3954d2492177d..a244d8be7a94d 100644 --- a/bazel/envoy_build_system.bzl +++ b/bazel/envoy_build_system.bzl @@ -432,6 +432,7 @@ def envoy_cc_test_library( deps = deps + [envoy_external_dep_path(dep) for dep in external_deps] + [ envoy_external_dep_path("googletest"), repository + "//test/test_common:printers_includes", + repository + "//test/test_common:test_base", ], tags = tags, alwayslink = 1, diff --git a/test/common/access_log/access_log_formatter_test.cc b/test/common/access_log/access_log_formatter_test.cc index 06273f2fe486d..38a81cd2c6d3f 100644 --- a/test/common/access_log/access_log_formatter_test.cc +++ b/test/common/access_log/access_log_formatter_test.cc @@ -11,10 +11,10 @@ #include "test/mocks/stream_info/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Const; diff --git a/test/common/access_log/access_log_impl_test.cc b/test/common/access_log/access_log_impl_test.cc index 378617adb5bac..a5c13c589c2af 100644 --- a/test/common/access_log/access_log_impl_test.cc +++ b/test/common/access_log/access_log_impl_test.cc @@ -20,10 +20,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -48,7 +48,7 @@ envoy::config::filter::accesslog::v2::AccessLog parseAccessLogFromV2Yaml(const s return access_log; } -class AccessLogImplTest : public testing::Test { +class AccessLogImplTest : public TestBase { public: AccessLogImplTest() : file_(new Filesystem::MockFile()) { ON_CALL(context_, runtime()).WillByDefault(ReturnRef(runtime_)); diff --git a/test/common/access_log/access_log_manager_impl_test.cc b/test/common/access_log/access_log_manager_impl_test.cc index 06838ee9df287..cde2c1a0fb8fc 100644 --- a/test/common/access_log/access_log_manager_impl_test.cc +++ b/test/common/access_log/access_log_manager_impl_test.cc @@ -7,9 +7,9 @@ #include "test/mocks/api/mocks.h" #include "test/mocks/event/mocks.h" #include "test/mocks/filesystem/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; diff --git a/test/common/buffer/buffer_test.cc b/test/common/buffer/buffer_test.cc index c70ea116bdfbc..f9574b5ecc66f 100644 --- a/test/common/buffer/buffer_test.cc +++ b/test/common/buffer/buffer_test.cc @@ -6,10 +6,9 @@ #include "test/common/buffer/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Buffer { namespace { diff --git a/test/common/buffer/owned_impl_test.cc b/test/common/buffer/owned_impl_test.cc index 227f932846620..aad9ada564907 100644 --- a/test/common/buffer/owned_impl_test.cc +++ b/test/common/buffer/owned_impl_test.cc @@ -2,11 +2,11 @@ #include "common/buffer/buffer_impl.h" #include "test/mocks/api/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "absl/strings/str_cat.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; @@ -15,7 +15,7 @@ namespace Envoy { namespace Buffer { namespace { -class OwnedImplTest : public testing::Test { +class OwnedImplTest : public TestBase { public: OwnedImplTest() {} diff --git a/test/common/buffer/utility.h b/test/common/buffer/utility.h index 868427de465ad..1670a2da040ea 100644 --- a/test/common/buffer/utility.h +++ b/test/common/buffer/utility.h @@ -4,7 +4,7 @@ #include "common/buffer/buffer_impl.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Buffer { diff --git a/test/common/buffer/watermark_buffer_test.cc b/test/common/buffer/watermark_buffer_test.cc index e7f45ea56b8f3..18efc42460822 100644 --- a/test/common/buffer/watermark_buffer_test.cc +++ b/test/common/buffer/watermark_buffer_test.cc @@ -3,7 +3,7 @@ #include "common/buffer/buffer_impl.h" #include "common/buffer/watermark_buffer.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Buffer { @@ -11,7 +11,7 @@ namespace { const char TEN_BYTES[] = "0123456789"; -class WatermarkBufferTest : public testing::Test { +class WatermarkBufferTest : public TestBase { public: WatermarkBufferTest() { buffer_.setWatermarks(5, 10); } diff --git a/test/common/buffer/zero_copy_input_stream_test.cc b/test/common/buffer/zero_copy_input_stream_test.cc index 69070f1cc0262..1a748fe1146b6 100644 --- a/test/common/buffer/zero_copy_input_stream_test.cc +++ b/test/common/buffer/zero_copy_input_stream_test.cc @@ -1,13 +1,13 @@ #include "common/buffer/buffer_impl.h" #include "common/buffer/zero_copy_input_stream_impl.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Buffer { namespace { -class ZeroCopyInputStreamTest : public testing::Test { +class ZeroCopyInputStreamTest : public TestBase { public: ZeroCopyInputStreamTest() { Buffer::OwnedImpl buffer{"abcd"}; diff --git a/test/common/common/assert_test.cc b/test/common/common/assert_test.cc index 44d65b4957666..078e085144b63 100644 --- a/test/common/common/assert_test.cc +++ b/test/common/common/assert_test.cc @@ -1,8 +1,7 @@ #include "common/common/assert.h" #include "test/test_common/logging.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/common/common/backoff_strategy_test.cc b/test/common/common/backoff_strategy_test.cc index 010768349983d..3396c166a1ad2 100644 --- a/test/common/common/backoff_strategy_test.cc +++ b/test/common/common/backoff_strategy_test.cc @@ -1,8 +1,7 @@ #include "common/common/backoff_strategy.h" #include "test/mocks/runtime/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::NiceMock; using testing::Return; diff --git a/test/common/common/base64_test.cc b/test/common/common/base64_test.cc index 74cbbd44132cf..257ad00603260 100644 --- a/test/common/common/base64_test.cc +++ b/test/common/common/base64_test.cc @@ -4,8 +4,7 @@ #include "common/common/base64.h" #include "test/test_common/printers.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { TEST(Base64Test, EmptyBufferEncode) { diff --git a/test/common/common/block_memory_hash_set_test.cc b/test/common/common/block_memory_hash_set_test.cc index 37b4957feca1f..fbeb56f7c38d9 100644 --- a/test/common/common/block_memory_hash_set_test.cc +++ b/test/common/common/block_memory_hash_set_test.cc @@ -9,13 +9,14 @@ #include "common/common/hash.h" #include "common/stats/stats_options_impl.h" +#include "test/test_common/test_base.h" + #include "absl/strings/string_view.h" -#include "gtest/gtest.h" namespace Envoy { // Tests BlockMemoryHashSet. -class BlockMemoryHashSetTest : public testing::Test { +class BlockMemoryHashSetTest : public TestBase { protected: // TestValue that doesn't define a hash. struct TestValueBase { diff --git a/test/common/common/callback_impl_test.cc b/test/common/common/callback_impl_test.cc index 6f5d6afe48545..72ea44c63b81e 100644 --- a/test/common/common/callback_impl_test.cc +++ b/test/common/common/callback_impl_test.cc @@ -1,5 +1,7 @@ #include "common/common/callback_impl.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" using testing::InSequence; @@ -7,7 +9,7 @@ using testing::InSequence; namespace Envoy { namespace Common { -class CallbackManagerTest : public testing::Test { +class CallbackManagerTest : public TestBase { public: MOCK_METHOD1(called, void(int arg)); }; diff --git a/test/common/common/cleanup_test.cc b/test/common/common/cleanup_test.cc index 742f279dc530c..f702f70f4bdc9 100644 --- a/test/common/common/cleanup_test.cc +++ b/test/common/common/cleanup_test.cc @@ -1,6 +1,6 @@ #include "common/common/cleanup.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/common/common/fmt_test.cc b/test/common/common/fmt_test.cc index f5b8fd45d9536..6ec59c26b2701 100644 --- a/test/common/common/fmt_test.cc +++ b/test/common/common/fmt_test.cc @@ -1,8 +1,9 @@ #include "common/common/fmt.h" #include "common/common/logger.h" +#include "test/test_common/test_base.h" + #include "absl/strings/string_view.h" -#include "gtest/gtest.h" namespace Envoy { diff --git a/test/common/common/hash_test.cc b/test/common/common/hash_test.cc index e1fcafc5ea971..8d131ea7ca9ff 100644 --- a/test/common/common/hash_test.cc +++ b/test/common/common/hash_test.cc @@ -1,6 +1,6 @@ #include "common/common/hash.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { TEST(Hash, xxHash) { diff --git a/test/common/common/hex_test.cc b/test/common/common/hex_test.cc index 06a06469edc1c..4fe426a25fb93 100644 --- a/test/common/common/hex_test.cc +++ b/test/common/common/hex_test.cc @@ -5,7 +5,7 @@ #include "common/common/hex.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { TEST(Hex, SimpleEncode) { diff --git a/test/common/common/lock_guard_test.cc b/test/common/common/lock_guard_test.cc index 55f505f9ab584..ee9073391a5d5 100644 --- a/test/common/common/lock_guard_test.cc +++ b/test/common/common/lock_guard_test.cc @@ -1,12 +1,12 @@ #include "common/common/lock_guard.h" #include "common/common/thread.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Thread { -class ThreadTest : public testing::Test { +class ThreadTest : public TestBase { protected: ThreadTest() : a_(0), b_(0) {} int a_ GUARDED_BY(a_mutex_); diff --git a/test/common/common/log_macros_test.cc b/test/common/common/log_macros_test.cc index 8d683910bb6b7..82fdfeca05ec2 100644 --- a/test/common/common/log_macros_test.cc +++ b/test/common/common/log_macros_test.cc @@ -5,9 +5,9 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/network/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { diff --git a/test/common/common/matchers_test.cc b/test/common/common/matchers_test.cc index d5b509a89082a..43c24e132109c 100644 --- a/test/common/common/matchers_test.cc +++ b/test/common/common/matchers_test.cc @@ -7,7 +7,7 @@ #include "common/config/metadata.h" #include "common/protobuf/protobuf.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Matcher { diff --git a/test/common/common/mutex_tracer_test.cc b/test/common/common/mutex_tracer_test.cc index 042b0469f1994..a8ccee205a047 100644 --- a/test/common/common/mutex_tracer_test.cc +++ b/test/common/common/mutex_tracer_test.cc @@ -5,13 +5,13 @@ #include "common/common/mutex_tracer_impl.h" #include "test/test_common/contention.h" +#include "test/test_common/test_base.h" #include "absl/synchronization/mutex.h" -#include "gtest/gtest.h" namespace Envoy { -class MutexTracerTest : public testing::Test { +class MutexTracerTest : public TestBase { protected: void SetUp() override { tracer_.reset(); } diff --git a/test/common/common/perf_annotation_disabled_test.cc b/test/common/common/perf_annotation_disabled_test.cc index 8109cad634578..fe6ecc663a2b2 100644 --- a/test/common/common/perf_annotation_disabled_test.cc +++ b/test/common/common/perf_annotation_disabled_test.cc @@ -6,7 +6,7 @@ #include "common/common/perf_annotation.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/common/common/perf_annotation_test.cc b/test/common/common/perf_annotation_test.cc index c8498a72096ef..6a479009b25f0 100644 --- a/test/common/common/perf_annotation_test.cc +++ b/test/common/common/perf_annotation_test.cc @@ -9,11 +9,11 @@ #include "common/common/perf_annotation.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { -class PerfAnnotationTest : public testing::Test { +class PerfAnnotationTest : public TestBase { protected: void TearDown() override { PERF_CLEAR(); } }; diff --git a/test/common/common/phantom_test.cc b/test/common/common/phantom_test.cc index 6ec0ed1850683..fbdfd42a5df0c 100644 --- a/test/common/common/phantom_test.cc +++ b/test/common/common/phantom_test.cc @@ -1,6 +1,6 @@ #include "common/common/phantom.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/common/common/stack_array_test.cc b/test/common/common/stack_array_test.cc index fa857f77b05f5..04a98c9d31596 100644 --- a/test/common/common/stack_array_test.cc +++ b/test/common/common/stack_array_test.cc @@ -1,7 +1,8 @@ #include "common/common/stack_array.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { diff --git a/test/common/common/to_lower_table_test.cc b/test/common/common/to_lower_table_test.cc index 3004f852aa200..a20c6cebdd5a4 100644 --- a/test/common/common/to_lower_table_test.cc +++ b/test/common/common/to_lower_table_test.cc @@ -1,6 +1,6 @@ #include "common/common/to_lower_table.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { TEST(ToLowerTableTest, All) { diff --git a/test/common/common/token_bucket_impl_test.cc b/test/common/common/token_bucket_impl_test.cc index 5d4e811e473e8..5d575377769d1 100644 --- a/test/common/common/token_bucket_impl_test.cc +++ b/test/common/common/token_bucket_impl_test.cc @@ -3,12 +3,11 @@ #include "common/common/token_bucket_impl.h" #include "test/test_common/simulated_time_system.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { -class TokenBucketImplTest : public testing::Test { +class TokenBucketImplTest : public TestBase { protected: Event::SimulatedTimeSystem time_system_; }; diff --git a/test/common/common/utility_test.cc b/test/common/common/utility_test.cc index 2946b52189103..3e83544a04c00 100644 --- a/test/common/common/utility_test.cc +++ b/test/common/common/utility_test.cc @@ -8,13 +8,13 @@ #include "common/common/utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::ContainerEq; diff --git a/test/common/compressor/zlib_compressor_impl_test.cc b/test/common/compressor/zlib_compressor_impl_test.cc index 8d07331995a1e..c1fd72b5cd50d 100644 --- a/test/common/compressor/zlib_compressor_impl_test.cc +++ b/test/common/compressor/zlib_compressor_impl_test.cc @@ -3,15 +3,14 @@ #include "common/common/stack_array.h" #include "common/compressor/zlib_compressor_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Compressor { namespace { -class ZlibCompressorImplTest : public testing::Test { +class ZlibCompressorImplTest : public TestBase { protected: void expectValidFlushedBuffer(const Buffer::OwnedImpl& output_buffer) { uint64_t num_comp_slices = output_buffer.getRawSlices(nullptr, 0); diff --git a/test/common/config/config_provider_impl_test.cc b/test/common/config/config_provider_impl_test.cc index 4704f1aa82b06..1f355769cda58 100644 --- a/test/common/config/config_provider_impl_test.cc +++ b/test/common/config/config_provider_impl_test.cc @@ -6,9 +6,9 @@ #include "test/common/config/dummy_config.pb.h" #include "test/mocks/server/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Config { @@ -205,7 +205,7 @@ DummyConfigSubscription::DummyConfigSubscription( "DummyDS", manager_identifier, config_provider_manager, factory_context.timeSource(), factory_context.timeSource().systemTime(), factory_context.localInfo()) {} -class ConfigProviderImplTest : public testing::Test { +class ConfigProviderImplTest : public TestBase { public: ConfigProviderImplTest() { EXPECT_CALL(factory_context_.admin_.config_tracker_, add_("dummy", _)); diff --git a/test/common/config/filesystem_subscription_impl_test.cc b/test/common/config/filesystem_subscription_impl_test.cc index b76d6de62a7b6..c1582b0f45574 100644 --- a/test/common/config/filesystem_subscription_impl_test.cc +++ b/test/common/config/filesystem_subscription_impl_test.cc @@ -2,9 +2,9 @@ #include "test/mocks/event/mocks.h" #include "test/mocks/filesystem/mocks.h" #include "test/test_common/logging.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using ::testing::Throw; @@ -12,8 +12,7 @@ namespace Envoy { namespace Config { namespace { -class FilesystemSubscriptionImplTest : public FilesystemSubscriptionTestHarness, - public testing::Test {}; +class FilesystemSubscriptionImplTest : public FilesystemSubscriptionTestHarness, public TestBase {}; // Validate that the client can recover from bad JSON responses. TEST_F(FilesystemSubscriptionImplTest, BadJsonRecovery) { diff --git a/test/common/config/filesystem_subscription_test_harness.h b/test/common/config/filesystem_subscription_test_harness.h index ef402e6573448..f78b0ef199d55 100644 --- a/test/common/config/filesystem_subscription_test_harness.h +++ b/test/common/config/filesystem_subscription_test_harness.h @@ -11,11 +11,11 @@ #include "test/common/config/subscription_test_harness.h" #include "test/mocks/config/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/common/config/filter_json_test.cc b/test/common/config/filter_json_test.cc index 8cec55f45609a..beb6a7e4de3dd 100644 --- a/test/common/config/filter_json_test.cc +++ b/test/common/config/filter_json_test.cc @@ -5,10 +5,9 @@ #include "common/config/filter_json.h" #include "common/json/json_loader.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Config { namespace { diff --git a/test/common/config/grpc_mux_impl_test.cc b/test/common/config/grpc_mux_impl_test.cc index d20d699fbdec6..b8c58b5443fea 100644 --- a/test/common/config/grpc_mux_impl_test.cc +++ b/test/common/config/grpc_mux_impl_test.cc @@ -18,11 +18,11 @@ #include "test/mocks/runtime/mocks.h" #include "test/test_common/logging.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtLeast; @@ -38,7 +38,7 @@ namespace { // We test some mux specific stuff below, other unit test coverage for singleton use of GrpcMuxImpl // is provided in [grpc_]subscription_impl_test.cc. -class GrpcMuxImplTestBase : public testing::Test { +class GrpcMuxImplTestBase : public TestBase { public: GrpcMuxImplTestBase() : async_client_(new Grpc::MockAsyncClient()) {} diff --git a/test/common/config/grpc_subscription_impl_test.cc b/test/common/config/grpc_subscription_impl_test.cc index 3dd94aea5f4f1..1c2f1c987e87b 100644 --- a/test/common/config/grpc_subscription_impl_test.cc +++ b/test/common/config/grpc_subscription_impl_test.cc @@ -1,6 +1,5 @@ #include "test/common/config/grpc_subscription_test_harness.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::InSequence; @@ -8,7 +7,7 @@ namespace Envoy { namespace Config { namespace { -class GrpcSubscriptionImplTest : public GrpcSubscriptionTestHarness, public testing::Test {}; +class GrpcSubscriptionImplTest : public GrpcSubscriptionTestHarness, public TestBase {}; // Validate that stream creation results in a timer based retry and can recover. TEST_F(GrpcSubscriptionImplTest, StreamCreationFailure) { diff --git a/test/common/config/grpc_subscription_test_harness.h b/test/common/config/grpc_subscription_test_harness.h index c6316aab957ce..a9e2c0eed41db 100644 --- a/test/common/config/grpc_subscription_test_harness.h +++ b/test/common/config/grpc_subscription_test_harness.h @@ -14,10 +14,10 @@ #include "test/mocks/grpc/mocks.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/common/config/http_subscription_impl_test.cc b/test/common/config/http_subscription_impl_test.cc index 8a275347ec0b5..05d5c19cf5cda 100644 --- a/test/common/config/http_subscription_impl_test.cc +++ b/test/common/config/http_subscription_impl_test.cc @@ -1,14 +1,13 @@ #include #include "test/common/config/http_subscription_test_harness.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Config { namespace { -class HttpSubscriptionImplTest : public HttpSubscriptionTestHarness, public testing::Test {}; +class HttpSubscriptionImplTest : public HttpSubscriptionTestHarness, public TestBase {}; // Validate that the client can recover from a remote fetch failure. TEST_F(HttpSubscriptionImplTest, OnRequestReset) { diff --git a/test/common/config/http_subscription_test_harness.h b/test/common/config/http_subscription_test_harness.h index 762f28454b253..d847994b081f2 100644 --- a/test/common/config/http_subscription_test_harness.h +++ b/test/common/config/http_subscription_test_harness.h @@ -17,10 +17,10 @@ #include "test/mocks/local_info/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/common/config/metadata_test.cc b/test/common/config/metadata_test.cc index 28d5cb67b4a83..bfc208841fcfa 100644 --- a/test/common/config/metadata_test.cc +++ b/test/common/config/metadata_test.cc @@ -5,10 +5,9 @@ #include "common/protobuf/utility.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Config { namespace { @@ -48,7 +47,7 @@ TEST(MetadataTest, MetadataValuePath) { ProtobufWkt::Value::KindCase::KIND_NOT_SET); } -class TypedMetadataTest : public testing::Test { +class TypedMetadataTest : public TestBase { public: TypedMetadataTest() : registered_factory_(foo_factory_) {} diff --git a/test/common/config/rds_json_test.cc b/test/common/config/rds_json_test.cc index 0b099bbe33e38..262871c750b72 100644 --- a/test/common/config/rds_json_test.cc +++ b/test/common/config/rds_json_test.cc @@ -3,8 +3,9 @@ #include "common/config/rds_json.h" #include "common/json/json_loader.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/common/config/subscription_factory_test.cc b/test/common/config/subscription_factory_test.cc index e689f68fc4bfb..0daf82b123fca 100644 --- a/test/common/config/subscription_factory_test.cc +++ b/test/common/config/subscription_factory_test.cc @@ -14,10 +14,10 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using ::testing::_; using ::testing::Invoke; @@ -26,7 +26,7 @@ using ::testing::Return; namespace Envoy { namespace Config { -class SubscriptionFactoryTest : public ::testing::Test { +class SubscriptionFactoryTest : public TestBase { public: SubscriptionFactoryTest() : http_request_(&cm_.async_client_), api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/config/subscription_impl_test.cc b/test/common/config/subscription_impl_test.cc index 85b07333306ae..503f469fe8bb1 100644 --- a/test/common/config/subscription_impl_test.cc +++ b/test/common/config/subscription_impl_test.cc @@ -15,7 +15,7 @@ enum class SubscriptionType { Filesystem, }; -class SubscriptionImplTest : public testing::TestWithParam { +class SubscriptionImplTest : public TestBaseWithParam { public: SubscriptionImplTest() { switch (GetParam()) { diff --git a/test/common/config/subscription_test_harness.h b/test/common/config/subscription_test_harness.h index 0df305a00f581..16d1841217898 100644 --- a/test/common/config/subscription_test_harness.h +++ b/test/common/config/subscription_test_harness.h @@ -3,9 +3,9 @@ #include "common/config/utility.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Config { diff --git a/test/common/config/utility_test.cc b/test/common/config/utility_test.cc index c52d2c8118134..c3ebc97e5d235 100644 --- a/test/common/config/utility_test.cc +++ b/test/common/config/utility_test.cc @@ -14,10 +14,10 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtLeast; diff --git a/test/common/crypto/utility_test.cc b/test/common/crypto/utility_test.cc index 46c6852102441..e3730caab9593 100644 --- a/test/common/crypto/utility_test.cc +++ b/test/common/crypto/utility_test.cc @@ -2,7 +2,7 @@ #include "common/common/hex.h" #include "common/crypto/utility.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Common { diff --git a/test/common/decompressor/zlib_decompressor_impl_test.cc b/test/common/decompressor/zlib_decompressor_impl_test.cc index bb715643e1239..3dfa3600966a4 100644 --- a/test/common/decompressor/zlib_decompressor_impl_test.cc +++ b/test/common/decompressor/zlib_decompressor_impl_test.cc @@ -3,15 +3,14 @@ #include "common/compressor/zlib_compressor_impl.h" #include "common/decompressor/zlib_decompressor_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Decompressor { namespace { -class ZlibDecompressorImplTest : public testing::Test { +class ZlibDecompressorImplTest : public TestBase { protected: void drainBuffer(Buffer::OwnedImpl& buffer) { buffer.drain(buffer.length()); } diff --git a/test/common/event/dispatched_thread_impl_test.cc b/test/common/event/dispatched_thread_impl_test.cc index cf0717371c3a3..1971ee014621a 100644 --- a/test/common/event/dispatched_thread_impl_test.cc +++ b/test/common/event/dispatched_thread_impl_test.cc @@ -9,11 +9,11 @@ #include "test/mocks/common.h" #include "test/mocks/server/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::InSequence; using testing::NiceMock; @@ -21,7 +21,7 @@ using testing::NiceMock; namespace Envoy { namespace Event { -class DispatchedThreadTest : public testing::Test { +class DispatchedThreadTest : public TestBase { protected: DispatchedThreadTest() : config_(1000, 1000, 1000, 1000), api_(Api::createApiForTest(fakestats_)), diff --git a/test/common/event/dispatcher_impl_test.cc b/test/common/event/dispatcher_impl_test.cc index 1d2d6b54a5331..da48fa793e17c 100644 --- a/test/common/event/dispatcher_impl_test.cc +++ b/test/common/event/dispatcher_impl_test.cc @@ -8,11 +8,11 @@ #include "common/stats/isolated_store_impl.h" #include "test/mocks/common.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::InSequence; @@ -61,7 +61,7 @@ TEST(DeferredDeleteTest, DeferredDelete) { dispatcher.clearDeferredDeleteList(); } -class DispatcherImplTest : public ::testing::Test { +class DispatcherImplTest : public TestBase { protected: DispatcherImplTest() : api_(Api::createApiForTest(stat_store_)), diff --git a/test/common/event/file_event_impl_test.cc b/test/common/event/file_event_impl_test.cc index 8b8dc3fe415bc..cb8bec642bf66 100644 --- a/test/common/event/file_event_impl_test.cc +++ b/test/common/event/file_event_impl_test.cc @@ -7,15 +7,14 @@ #include "test/mocks/common.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Event { -class FileEventImplTest : public testing::Test { +class FileEventImplTest : public TestBase { public: FileEventImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} @@ -41,7 +40,7 @@ class FileEventImplTest : public testing::Test { DispatcherImpl dispatcher_; }; -class FileEventImplActivateTest : public testing::TestWithParam {}; +class FileEventImplActivateTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, FileEventImplActivateTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), diff --git a/test/common/filesystem/directory_test.cc b/test/common/filesystem/directory_test.cc index 5536f77d72863..9eb3f0d3ddd73 100644 --- a/test/common/filesystem/directory_test.cc +++ b/test/common/filesystem/directory_test.cc @@ -6,10 +6,10 @@ #include "common/filesystem/directory.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Filesystem { @@ -18,7 +18,7 @@ namespace Filesystem { // as it looks like some versions of libstdc++ have a bug in // std::experimental::filesystem::remove_all where it fails with nested directories: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71313 -class DirectoryTest : public testing::Test { +class DirectoryTest : public TestBase { public: DirectoryTest() : dir_path_(TestEnvironment::temporaryPath("envoy_test")) { files_to_remove_.push(dir_path_); diff --git a/test/common/filesystem/filesystem_impl_test.cc b/test/common/filesystem/filesystem_impl_test.cc index 4e4558c835919..3bc30c6a14c7c 100644 --- a/test/common/filesystem/filesystem_impl_test.cc +++ b/test/common/filesystem/filesystem_impl_test.cc @@ -13,11 +13,11 @@ #include "test/mocks/event/mocks.h" #include "test/mocks/filesystem/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -30,7 +30,7 @@ using testing::Throw; namespace Envoy { -class FileSystemImplTest : public testing::Test { +class FileSystemImplTest : public TestBase { protected: FileSystemImplTest() : file_system_(std::chrono::milliseconds(10000), Thread::threadFactoryForTest(), diff --git a/test/common/filesystem/watcher_impl_test.cc b/test/common/filesystem/watcher_impl_test.cc index 0f90304f001f7..a7ab6895f702f 100644 --- a/test/common/filesystem/watcher_impl_test.cc +++ b/test/common/filesystem/watcher_impl_test.cc @@ -7,16 +7,16 @@ #include "common/stats/isolated_store_impl.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Filesystem { -class WatcherImplTest : public testing::Test { +class WatcherImplTest : public TestBase { protected: WatcherImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} diff --git a/test/common/grpc/async_client_impl_test.cc b/test/common/grpc/async_client_impl_test.cc index 94a33c83fd683..f12ff49921378 100644 --- a/test/common/grpc/async_client_impl_test.cc +++ b/test/common/grpc/async_client_impl_test.cc @@ -4,10 +4,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/proto/helloworld.pb.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -19,7 +19,7 @@ namespace Envoy { namespace Grpc { namespace { -class EnvoyAsyncClientImplTest : public testing::Test { +class EnvoyAsyncClientImplTest : public TestBase { public: EnvoyAsyncClientImplTest() : method_descriptor_(helloworld::Greeter::descriptor()->FindMethodByName("SayHello")) { diff --git a/test/common/grpc/async_client_manager_impl_test.cc b/test/common/grpc/async_client_manager_impl_test.cc index c047970fc9682..8d3c15f0a9fdc 100644 --- a/test/common/grpc/async_client_manager_impl_test.cc +++ b/test/common/grpc/async_client_manager_impl_test.cc @@ -4,11 +4,11 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using ::testing::Return; @@ -16,7 +16,7 @@ namespace Envoy { namespace Grpc { namespace { -class AsyncClientManagerImplTest : public testing::Test { +class AsyncClientManagerImplTest : public TestBase { public: AsyncClientManagerImplTest() : api_(Api::createApiForTest(api_stats_store_)) {} diff --git a/test/common/grpc/codec_test.cc b/test/common/grpc/codec_test.cc index 99a9d2f599731..e0e6be57502d5 100644 --- a/test/common/grpc/codec_test.cc +++ b/test/common/grpc/codec_test.cc @@ -8,8 +8,7 @@ #include "test/proto/helloworld.pb.h" #include "test/test_common/printers.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Grpc { diff --git a/test/common/grpc/common_test.cc b/test/common/grpc/common_test.cc index 290328a53941a..34a582d35c937 100644 --- a/test/common/grpc/common_test.cc +++ b/test/common/grpc/common_test.cc @@ -5,10 +5,9 @@ #include "test/mocks/upstream/mocks.h" #include "test/proto/helloworld.pb.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Grpc { diff --git a/test/common/grpc/google_async_client_impl_test.cc b/test/common/grpc/google_async_client_impl_test.cc index abbc914c8c687..761ce43fbd61c 100644 --- a/test/common/grpc/google_async_client_impl_test.cc +++ b/test/common/grpc/google_async_client_impl_test.cc @@ -8,11 +8,11 @@ #include "test/mocks/grpc/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/proto/helloworld.pb.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; @@ -44,7 +44,7 @@ class MockStubFactory : public GoogleStubFactory { std::shared_ptr shared_stub_{stub_}; }; -class EnvoyGoogleAsyncClientImplTest : public testing::Test { +class EnvoyGoogleAsyncClientImplTest : public TestBase { public: EnvoyGoogleAsyncClientImplTest() : stats_store_(new Stats::IsolatedStoreImpl), api_(Api::createApiForTest(*stats_store_)), diff --git a/test/common/grpc/google_grpc_creds_test.cc b/test/common/grpc/google_grpc_creds_test.cc index a9eeb2a550024..1bbb3bd353401 100644 --- a/test/common/grpc/google_grpc_creds_test.cc +++ b/test/common/grpc/google_grpc_creds_test.cc @@ -2,10 +2,9 @@ #include "test/common/grpc/utility.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Grpc { namespace { @@ -15,7 +14,7 @@ namespace { // of getting at the underlying state, we can at best just make sure we don't // crash, compare with nullptr and/or look at vector lengths. -class CredsUtilityTest : public testing::Test { +class CredsUtilityTest : public TestBase { public: CredsUtilityTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/grpc/grpc_client_integration.h b/test/common/grpc/grpc_client_integration.h index a2c1ac2ca3f19..ee664f4f2f599 100644 --- a/test/common/grpc/grpc_client_integration.h +++ b/test/common/grpc/grpc_client_integration.h @@ -2,10 +2,9 @@ #include "common/common/assert.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Grpc { @@ -39,11 +38,11 @@ class BaseGrpcClientIntegrationParamTest { class GrpcClientIntegrationParamTest : public BaseGrpcClientIntegrationParamTest, - public testing::TestWithParam> { + public TestBaseWithParam> { public: ~GrpcClientIntegrationParamTest() {} static std::string protocolTestParamsToString( - const testing::TestParamInfo>& p) { + const ::testing::TestParamInfo>& p) { return absl::StrCat( (std::get<0>(p.param) == Network::Address::IpVersion::v4 ? "IPv4_" : "IPv6_"), (std::get<1>(p.param) == ClientType::GoogleGrpc ? "GoogleGrpc" : "EnvoyGrpc")); diff --git a/test/common/html/utility_test.cc b/test/common/html/utility_test.cc index 251e3508a9cb1..d4954b9bf9a3f 100644 --- a/test/common/html/utility_test.cc +++ b/test/common/html/utility_test.cc @@ -1,6 +1,6 @@ #include "common/html/utility.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Html { diff --git a/test/common/http/async_client_impl_test.cc b/test/common/http/async_client_impl_test.cc index ba6115bedc04d..67f6b1291ea3d 100644 --- a/test/common/http/async_client_impl_test.cc +++ b/test/common/http/async_client_impl_test.cc @@ -19,9 +19,9 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -34,7 +34,7 @@ namespace Envoy { namespace Http { namespace { -class AsyncClientImplTest : public testing::Test { +class AsyncClientImplTest : public TestBase { public: AsyncClientImplTest() : client_(cm_.thread_local_cluster_.cluster_.info_, stats_store_, dispatcher_, local_info_, diff --git a/test/common/http/codec_client_test.cc b/test/common/http/codec_client_test.cc index 2fcddd36f2552..0871311e6fbb1 100644 --- a/test/common/http/codec_client_test.cc +++ b/test/common/http/codec_client_test.cc @@ -18,11 +18,11 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtMost; @@ -38,7 +38,7 @@ using testing::Throw; namespace Envoy { namespace Http { -class CodecClientTest : public testing::Test { +class CodecClientTest : public TestBase { public: CodecClientTest() { connection_ = new NiceMock(); @@ -259,7 +259,7 @@ TEST_F(CodecClientTest, WatermarkPassthrough) { } // Test the codec getting input from a real TCP connection. -class CodecNetworkTest : public testing::TestWithParam { +class CodecNetworkTest : public TestBaseWithParam { public: CodecNetworkTest() : api_(Api::createApiForTest(stats_store_)) { dispatcher_ = std::make_unique(test_time_.timeSystem(), *api_); diff --git a/test/common/http/codes_test.cc b/test/common/http/codes_test.cc index b209d6ce74e32..598bd008f6ff6 100644 --- a/test/common/http/codes_test.cc +++ b/test/common/http/codes_test.cc @@ -11,10 +11,10 @@ #include "test/mocks/stats/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Property; @@ -22,7 +22,7 @@ using testing::Property; namespace Envoy { namespace Http { -class CodeUtilityTest : public testing::Test { +class CodeUtilityTest : public TestBase { public: void addResponse(uint64_t code, bool canary, bool internal_request, const std::string& request_vhost_name = EMPTY_STRING, @@ -235,7 +235,7 @@ TEST(CodeUtilityResponseTimingTest, All) { code_stats.chargeResponseTiming(info); } -class CodeStatsTest : public testing::Test { +class CodeStatsTest : public TestBase { protected: absl::string_view stripTrailingDot(absl::string_view prefix) { return CodeStatsImpl::stripTrailingDot(prefix); diff --git a/test/common/http/conn_manager_impl_test.cc b/test/common/http/conn_manager_impl_test.cc index dd73d03349228..527bb7b86578f 100644 --- a/test/common/http/conn_manager_impl_test.cc +++ b/test/common/http/conn_manager_impl_test.cc @@ -39,10 +39,10 @@ #include "test/mocks/upstream/cluster_info.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -60,7 +60,7 @@ using testing::Sequence; namespace Envoy { namespace Http { -class HttpConnectionManagerImplTest : public testing::Test, public ConnectionManagerConfig { +class HttpConnectionManagerImplTest : public TestBase, public ConnectionManagerConfig { public: struct RouteConfigProvider : public Router::RouteConfigProvider { RouteConfigProvider(TimeSource& time_source) : time_source_(time_source) {} diff --git a/test/common/http/conn_manager_utility_test.cc b/test/common/http/conn_manager_utility_test.cc index 3d9335d96b2e5..6ede90b769f41 100644 --- a/test/common/http/conn_manager_utility_test.cc +++ b/test/common/http/conn_manager_utility_test.cc @@ -13,10 +13,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/ssl/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -82,7 +82,7 @@ class MockConnectionManagerConfig : public ConnectionManagerConfig { std::make_unique(); }; -class ConnectionManagerUtilityTest : public testing::Test { +class ConnectionManagerUtilityTest : public TestBase { public: ConnectionManagerUtilityTest() { ON_CALL(config_, userAgent()).WillByDefault(ReturnRef(user_agent_)); diff --git a/test/common/http/date_provider_impl_test.cc b/test/common/http/date_provider_impl_test.cc index ea037ee0f8d9f..352554cd520e7 100644 --- a/test/common/http/date_provider_impl_test.cc +++ b/test/common/http/date_provider_impl_test.cc @@ -6,9 +6,9 @@ #include "test/mocks/event/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; diff --git a/test/common/http/header_map_impl_test.cc b/test/common/http/header_map_impl_test.cc index c8ffe6d455681..dfdb515af7fd1 100644 --- a/test/common/http/header_map_impl_test.cc +++ b/test/common/http/header_map_impl_test.cc @@ -4,10 +4,9 @@ #include "common/http/header_map_impl.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using ::testing::InSequence; namespace Envoy { diff --git a/test/common/http/header_utility_test.cc b/test/common/http/header_utility_test.cc index 0d8c82d134245..b65439f7de714 100644 --- a/test/common/http/header_utility_test.cc +++ b/test/common/http/header_utility_test.cc @@ -7,10 +7,9 @@ #include "common/http/header_utility.h" #include "common/json/json_loader.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Http { diff --git a/test/common/http/http1/codec_impl_test.cc b/test/common/http/http1/codec_impl_test.cc index 3fcd623377298..74fb6280b8264 100644 --- a/test/common/http/http1/codec_impl_test.cc +++ b/test/common/http/http1/codec_impl_test.cc @@ -13,9 +13,9 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/network/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -28,7 +28,7 @@ namespace Envoy { namespace Http { namespace Http1 { -class Http1ServerConnectionImplTest : public ::testing::Test { +class Http1ServerConnectionImplTest : public TestBase { public: void initialize() { codec_ = std::make_unique(connection_, callbacks_, codec_settings_); @@ -671,7 +671,7 @@ TEST_F(Http1ServerConnectionImplTest, WatermarkTest) { ->onUnderlyingConnectionBelowWriteBufferLowWatermark(); } -class Http1ClientConnectionImplTest : public testing::Test { +class Http1ClientConnectionImplTest : public TestBase { public: void initialize() { codec_ = std::make_unique(connection_, callbacks_); } diff --git a/test/common/http/http1/conn_pool_test.cc b/test/common/http/http1/conn_pool_test.cc index ddcd230d50011..40c3994e9688a 100644 --- a/test/common/http/http1/conn_pool_test.cc +++ b/test/common/http/http1/conn_pool_test.cc @@ -17,11 +17,11 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -124,7 +124,7 @@ class ConnPoolImplForTest : public ConnPoolImpl { /** * Test fixture for all connection pool tests. */ -class Http1ConnPoolImplTest : public testing::Test { +class Http1ConnPoolImplTest : public TestBase { public: Http1ConnPoolImplTest() : upstream_ready_timer_(new NiceMock(&dispatcher_)), diff --git a/test/common/http/http2/codec_impl_test.cc b/test/common/http/http2/codec_impl_test.cc index ea41227ac65e9..a20bfda08d15f 100644 --- a/test/common/http/http2/codec_impl_test.cc +++ b/test/common/http/http2/codec_impl_test.cc @@ -12,10 +12,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/network/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -51,7 +51,7 @@ class TestClientConnectionImpl : public ClientConnectionImpl { using ClientConnectionImpl::getStream; }; -class Http2CodecImplTest : public testing::TestWithParam { +class Http2CodecImplTest : public TestBaseWithParam { public: struct ConnectionWrapper { void dispatch(const Buffer::Instance& data, ConnectionImpl& connection) { diff --git a/test/common/http/http2/conn_pool_test.cc b/test/common/http/http2/conn_pool_test.cc index 9e67df328a16b..0402277c88f00 100644 --- a/test/common/http/http2/conn_pool_test.cc +++ b/test/common/http/http2/conn_pool_test.cc @@ -15,10 +15,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -54,7 +54,7 @@ class TestConnPoolImpl : public ConnPoolImpl { class ActiveTestRequest; -class Http2ConnPoolImplTest : public testing::Test { +class Http2ConnPoolImplTest : public TestBase { public: struct TestCodecClient { Http::MockClientConnection* codec_; diff --git a/test/common/http/http2/metadata_encoder_decoder_test.cc b/test/common/http/http2/metadata_encoder_decoder_test.cc index e65d27229c7ae..10e1023bbf5ba 100644 --- a/test/common/http/http2/metadata_encoder_decoder_test.cc +++ b/test/common/http/http2/metadata_encoder_decoder_test.cc @@ -4,8 +4,9 @@ #include "common/http/http2/metadata_encoder.h" #include "common/runtime/runtime_impl.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "nghttp2/nghttp2.h" // A global variable in nghttp2 to disable preface and initial settings for tests. @@ -80,7 +81,7 @@ static ssize_t send_callback(nghttp2_session* session, const uint8_t* buf, size_ } } // namespace -class MetadataEncoderDecoderTest : public ::testing::Test { +class MetadataEncoderDecoderTest : public TestBase { public: void initialize(MetadataCallback cb) { decoder_ = std::make_unique(cb); diff --git a/test/common/http/user_agent_test.cc b/test/common/http/user_agent_test.cc index d69b99c840513..d5a5a04a2f2e6 100644 --- a/test/common/http/user_agent_test.cc +++ b/test/common/http/user_agent_test.cc @@ -5,10 +5,9 @@ #include "test/mocks/stats/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::_; using testing::NiceMock; using testing::Property; diff --git a/test/common/http/utility_test.cc b/test/common/http/utility_test.cc index 06a737da93ef5..bd825d86acce3 100644 --- a/test/common/http/utility_test.cc +++ b/test/common/http/utility_test.cc @@ -10,10 +10,9 @@ #include "test/mocks/http/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::_; using testing::Invoke; using testing::InvokeWithoutArgs; diff --git a/test/common/json/config_schemas_test.cc b/test/common/json/config_schemas_test.cc index 703c1afa712dd..5a4d6eba6dc8d 100644 --- a/test/common/json/config_schemas_test.cc +++ b/test/common/json/config_schemas_test.cc @@ -7,10 +7,10 @@ #include "common/stats/isolated_store_impl.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; @@ -27,7 +27,7 @@ std::vector generateTestInputs() { return file_list; } -class ConfigSchemasTest : public ::testing::TestWithParam { +class ConfigSchemasTest : public TestBaseWithParam { protected: ConfigSchemasTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/json/json_loader_test.cc b/test/common/json/json_loader_test.cc index 82659a950c12e..2846fa4f0a556 100644 --- a/test/common/json/json_loader_test.cc +++ b/test/common/json/json_loader_test.cc @@ -4,14 +4,13 @@ #include "common/json/json_loader.h" #include "common/stats/isolated_store_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Json { -class JsonLoaderTest : public testing::Test { +class JsonLoaderTest : public TestBase { protected: JsonLoaderTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/memory/debug_test.cc b/test/common/memory/debug_test.cc index 6dfeca6cd67ed..694a4cfa89cc1 100644 --- a/test/common/memory/debug_test.cc +++ b/test/common/memory/debug_test.cc @@ -1,6 +1,6 @@ #include "common/memory/stats.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Memory { diff --git a/test/common/network/address_impl_test.cc b/test/common/network/address_impl_test.cc index c64538942915e..8cae44fe9589a 100644 --- a/test/common/network/address_impl_test.cc +++ b/test/common/network/address_impl_test.cc @@ -18,10 +18,9 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Network { namespace Address { @@ -107,7 +106,7 @@ void testSocketBindAndConnect(Network::Address::IpVersion ip_version, bool v6onl } } // namespace -class AddressImplSocketTest : public testing::TestWithParam {}; +class AddressImplSocketTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, AddressImplSocketTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); @@ -431,7 +430,7 @@ struct TestCase { uint32_t port_; // Ignored for Pipe }; -class MixedAddressTest : public testing::TestWithParam<::testing::tuple> { +class MixedAddressTest : public TestBaseWithParam<::testing::tuple> { public: protected: InstanceConstSharedPtr testCaseToInstance(const struct TestCase& test_case) { diff --git a/test/common/network/cidr_range_test.cc b/test/common/network/cidr_range_test.cc index 3636c530f97ac..e9df0bddb6649 100644 --- a/test/common/network/cidr_range_test.cc +++ b/test/common/network/cidr_range_test.cc @@ -11,7 +11,7 @@ #include "common/network/cidr_range.h" #include "common/network/utility.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" // We are adding things into the std namespace. // Note that this is technically undefined behavior! diff --git a/test/common/network/connection_impl_test.cc b/test/common/network/connection_impl_test.cc index 2f329456e17d1..9f8667b030829 100644 --- a/test/common/network/connection_impl_test.cc +++ b/test/common/network/connection_impl_test.cc @@ -22,10 +22,10 @@ #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -72,7 +72,7 @@ TEST(ConnectionImplUtility, updateBufferStats) { ConnectionImplUtility::updateBufferStats(3, 3, previous_total, counter, gauge); } -class ConnectionImplDeathTest : public testing::TestWithParam {}; +class ConnectionImplDeathTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, ConnectionImplDeathTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); @@ -90,7 +90,7 @@ TEST_P(ConnectionImplDeathTest, BadFd) { ".*assert failure: ioHandle\\(\\).fd\\(\\) != -1.*"); } -class ConnectionImplTest : public testing::TestWithParam { +class ConnectionImplTest : public TestBaseWithParam { public: ConnectionImplTest() : api_(Api::createApiForTest(stats_store_)) {} @@ -1229,7 +1229,7 @@ class FakeReadFilter : public Network::ReadFilter { private: ReadFilterCallbacks* callbacks_{nullptr}; }; -class MockTransportConnectionImplTest : public testing::Test { +class MockTransportConnectionImplTest : public TestBase { public: MockTransportConnectionImplTest() { EXPECT_CALL(dispatcher_.buffer_factory_, create_(_, _)) @@ -1643,7 +1643,7 @@ TEST_P(ReadBufferLimitTest, SomeLimit) { readBufferLimitTest(read_buffer_limit, read_buffer_limit - 1 + 16384); } -class TcpClientConnectionImplTest : public testing::TestWithParam { +class TcpClientConnectionImplTest : public TestBaseWithParam { protected: TcpClientConnectionImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(time_system_, *api_) {} @@ -1688,7 +1688,7 @@ TEST_P(TcpClientConnectionImplTest, BadConnectConnRefused) { dispatcher_.run(Event::Dispatcher::RunType::Block); } -class PipeClientConnectionImplTest : public testing::Test { +class PipeClientConnectionImplTest : public TestBase { protected: PipeClientConnectionImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(time_system_, *api_) {} diff --git a/test/common/network/dns_impl_test.cc b/test/common/network/dns_impl_test.cc index 3e74ab3511636..37cf0080bbc20 100644 --- a/test/common/network/dns_impl_test.cc +++ b/test/common/network/dns_impl_test.cc @@ -26,12 +26,12 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "ares.h" #include "ares_dns.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -323,7 +323,7 @@ class DnsResolverImplPeer { DnsResolverImpl* resolver_; }; -class DnsImplConstructor : public testing::Test { +class DnsImplConstructor : public TestBase { protected: DnsImplConstructor() : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} @@ -405,7 +405,7 @@ TEST_F(DnsImplConstructor, BadCustomResolvers) { "DNS resolver 'foo' is not an IP address"); } -class DnsImplTest : public testing::TestWithParam { +class DnsImplTest : public TestBaseWithParam { public: DnsImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} diff --git a/test/common/network/filter_manager_impl_test.cc b/test/common/network/filter_manager_impl_test.cc index 5f5f1a63db88a..54d12d38debcd 100644 --- a/test/common/network/filter_manager_impl_test.cc +++ b/test/common/network/filter_manager_impl_test.cc @@ -20,9 +20,9 @@ #include "test/mocks/upstream/host.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -34,7 +34,7 @@ using testing::WithArgs; namespace Envoy { namespace Network { -class NetworkFilterManagerTest : public testing::Test, public BufferSource { +class NetworkFilterManagerTest : public TestBase, public BufferSource { public: StreamBuffer getReadBuffer() override { return {read_buffer_, read_end_stream_}; } StreamBuffer getWriteBuffer() override { return {write_buffer_, write_end_stream_}; } diff --git a/test/common/network/lc_trie_test.cc b/test/common/network/lc_trie_test.cc index 75b93e2dee1aa..d7383b952f7a8 100644 --- a/test/common/network/lc_trie_test.cc +++ b/test/common/network/lc_trie_test.cc @@ -5,15 +5,14 @@ #include "common/network/cidr_range.h" #include "common/network/lc_trie.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Network { namespace LcTrie { -class LcTrieTest : public testing::Test { +class LcTrieTest : public TestBase { public: void setup(const std::vector>& cidr_range_strings, bool exclusive = false, double fill_factor = 0, uint32_t root_branch_factor = 0) { diff --git a/test/common/network/listen_socket_impl_test.cc b/test/common/network/listen_socket_impl_test.cc index 8a4d787d8eb5c..285a829f76fcb 100644 --- a/test/common/network/listen_socket_impl_test.cc +++ b/test/common/network/listen_socket_impl_test.cc @@ -5,10 +5,9 @@ #include "test/mocks/network/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::_; using testing::Return; @@ -16,7 +15,7 @@ namespace Envoy { namespace Network { template -class ListenSocketImplTest : public testing::TestWithParam { +class ListenSocketImplTest : public TestBaseWithParam { protected: ListenSocketImplTest() : version_(GetParam()) {} const Address::IpVersion version_; diff --git a/test/common/network/listener_impl_test.cc b/test/common/network/listener_impl_test.cc index 2e04093199970..0e20d0f103635 100644 --- a/test/common/network/listener_impl_test.cc +++ b/test/common/network/listener_impl_test.cc @@ -6,11 +6,11 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -55,7 +55,7 @@ static void errorCallbackTest(Address::IpVersion version) { dispatcher.run(Event::Dispatcher::RunType::Block); } -class ListenerImplDeathTest : public testing::TestWithParam {}; +class ListenerImplDeathTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, ListenerImplDeathTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); @@ -73,7 +73,7 @@ class TestListenerImpl : public ListenerImpl { MOCK_METHOD1(getLocalAddress, Address::InstanceConstSharedPtr(int fd)); }; -class ListenerImplTest : public testing::TestWithParam { +class ListenerImplTest : public TestBaseWithParam { protected: ListenerImplTest() : version_(GetParam()), diff --git a/test/common/network/resolver_impl_test.cc b/test/common/network/resolver_impl_test.cc index 3a7496ea09b5c..e47534d03a0c6 100644 --- a/test/common/network/resolver_impl_test.cc +++ b/test/common/network/resolver_impl_test.cc @@ -14,14 +14,13 @@ #include "test/mocks/network/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Network { namespace Address { -class IpResolverTest : public testing::Test { +class IpResolverTest : public TestBase { public: Resolver* resolver_{Registry::FactoryRegistry::getFactory("envoy.ip")}; }; diff --git a/test/common/network/socket_option_factory_test.cc b/test/common/network/socket_option_factory_test.cc index 7ba8f53d1e518..4529316408e28 100644 --- a/test/common/network/socket_option_factory_test.cc +++ b/test/common/network/socket_option_factory_test.cc @@ -4,16 +4,15 @@ #include "test/mocks/api/mocks.h" #include "test/mocks/network/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" -#include "gtest/gtest.h" - using testing::_; namespace Envoy { namespace Network { -class SocketOptionFactoryTest : public testing::Test { +class SocketOptionFactoryTest : public TestBase { public: SocketOptionFactoryTest() = default; diff --git a/test/common/network/socket_option_test.h b/test/common/network/socket_option_test.h index fb218b015c3e1..0399ba981ca02 100644 --- a/test/common/network/socket_option_test.h +++ b/test/common/network/socket_option_test.h @@ -6,10 +6,9 @@ #include "test/mocks/api/mocks.h" #include "test/mocks/network/mocks.h" #include "test/test_common/logging.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" -#include "gtest/gtest.h" - using testing::_; using testing::Invoke; using testing::NiceMock; @@ -19,7 +18,7 @@ namespace Envoy { namespace Network { namespace { -class SocketOptionTest : public testing::Test { +class SocketOptionTest : public TestBase { public: SocketOptionTest() { socket_.local_address_.reset(); } diff --git a/test/common/network/udp_listener_impl_test.cc b/test/common/network/udp_listener_impl_test.cc index d9262e2dc052b..6c9e9b1926529 100644 --- a/test/common/network/udp_listener_impl_test.cc +++ b/test/common/network/udp_listener_impl_test.cc @@ -10,11 +10,11 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -36,7 +36,7 @@ class TestUdpListenerImpl : public UdpListenerImpl { } }; -class ListenerImplTest : public testing::TestWithParam { +class ListenerImplTest : public TestBaseWithParam { protected: ListenerImplTest() : version_(GetParam()), diff --git a/test/common/network/utility_test.cc b/test/common/network/utility_test.cc index 675093150d30e..91007b4b62c7d 100644 --- a/test/common/network/utility_test.cc +++ b/test/common/network/utility_test.cc @@ -11,10 +11,9 @@ #include "test/mocks/network/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Network { @@ -154,7 +153,7 @@ TEST(NetworkUtility, ParseInternetAddressAndPort) { EXPECT_EQ("[::1]:0", Utility::parseInternetAddressAndPort("[::1]:0")->asString()); } -class NetworkUtilityGetLocalAddress : public testing::TestWithParam {}; +class NetworkUtilityGetLocalAddress : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, NetworkUtilityGetLocalAddress, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), diff --git a/test/common/protobuf/utility_test.cc b/test/common/protobuf/utility_test.cc index bdedbed7f78ff..58d4c00d2d12c 100644 --- a/test/common/protobuf/utility_test.cc +++ b/test/common/protobuf/utility_test.cc @@ -8,13 +8,12 @@ #include "common/stats/isolated_store_impl.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { -class ProtobufUtilityTest : public testing::Test { +class ProtobufUtilityTest : public TestBase { protected: ProtobufUtilityTest() : api_(Api::createApiForTest(stats_store_)) {} @@ -338,7 +337,7 @@ TEST(DurationUtilTest, OutOfRange) { } } -class TimestampUtilTest : public ::testing::Test, public ::testing::WithParamInterface {}; +class TimestampUtilTest : public TestBase, public ::testing::WithParamInterface {}; TEST_P(TimestampUtilTest, SystemClockToTimestampTest) { // Generate an input time_point, diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index 96499d1ee066d..40a2a9636a417 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -24,10 +24,10 @@ #include "test/test_common/environment.h" #include "test/test_common/printers.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ContainerEq; @@ -111,7 +111,7 @@ class ConfigImplTestBase { NiceMock factory_context_; }; -class RouteMatcherTest : public testing::Test, public ConfigImplTestBase {}; +class RouteMatcherTest : public TestBase, public ConfigImplTestBase {}; TEST_F(RouteMatcherTest, TestRoutes) { const std::string json = R"EOF( @@ -1382,7 +1382,7 @@ TEST_F(RouteMatcherTest, InvalidQueryParamMatchedRoutingConfig) { EnvoyException, "Invalid regex"); } -class RouterMatcherHashPolicyTest : public testing::Test, public ConfigImplTestBase { +class RouterMatcherHashPolicyTest : public TestBase, public ConfigImplTestBase { protected: RouterMatcherHashPolicyTest() : add_cookie_nop_( @@ -2220,7 +2220,7 @@ TEST_F(RouteMatcherTest, Shadow) { .runtimeKey()); } -class RouteConfigurationV2 : public testing::Test, public ConfigImplTestBase {}; +class RouteConfigurationV2 : public TestBase, public ConfigImplTestBase {}; TEST_F(RouteConfigurationV2, RequestMirrorPolicy) { const std::string yaml = R"EOF( @@ -3629,7 +3629,7 @@ TEST(NullConfigImplTest, All) { EXPECT_EQ("", config.name()); } -class BadHttpRouteConfigurationsTest : public testing::Test, public ConfigImplTestBase {}; +class BadHttpRouteConfigurationsTest : public TestBase, public ConfigImplTestBase {}; TEST_F(BadHttpRouteConfigurationsTest, BadRouteConfig) { const std::string json = R"EOF( @@ -3875,7 +3875,7 @@ TEST_F(RouteMatcherTest, TestOpaqueConfig) { EXPECT_EQ(opaque_config.find("name2")->second, "value2"); } -class RoutePropertyTest : public testing::Test, public ConfigImplTestBase {}; +class RoutePropertyTest : public TestBase, public ConfigImplTestBase {}; TEST_F(RoutePropertyTest, excludeVHRateLimits) { std::string json = R"EOF( @@ -4225,7 +4225,7 @@ TEST_F(RouteMatcherTest, Decorator) { } } -class CustomRequestHeadersTest : public testing::Test, public ConfigImplTestBase {}; +class CustomRequestHeadersTest : public TestBase, public ConfigImplTestBase {}; TEST_F(CustomRequestHeadersTest, AddNewHeader) { const std::string json = R"EOF( @@ -4406,7 +4406,7 @@ TEST(MetadataMatchCriteriaImpl, Merge) { EXPECT_EQ((*it)->value().value().string_value(), "override3"); } -class RouteEntryMetadataMatchTest : public testing::Test, public ConfigImplTestBase {}; +class RouteEntryMetadataMatchTest : public TestBase, public ConfigImplTestBase {}; TEST_F(RouteEntryMetadataMatchTest, ParsesMetadata) { auto route_config = envoy::api::v2::RouteConfiguration(); @@ -4518,7 +4518,7 @@ TEST_F(RouteEntryMetadataMatchTest, ParsesMetadata) { } } -class ConfigUtilityTest : public testing::Test, public ConfigImplTestBase {}; +class ConfigUtilityTest : public TestBase, public ConfigImplTestBase {}; TEST_F(ConfigUtilityTest, ParseResponseCode) { const std::vector< @@ -5247,7 +5247,7 @@ name: RetriableStatusCodes EXPECT_NE(predicates1, predicates2); } -class PerFilterConfigsTest : public testing::Test, public ConfigImplTestBase { +class PerFilterConfigsTest : public TestBase, public ConfigImplTestBase { public: PerFilterConfigsTest() : factory_(), registered_factory_(factory_), default_factory_(), diff --git a/test/common/router/header_formatter_test.cc b/test/common/router/header_formatter_test.cc index 327a9e8076640..58a8c9b37d350 100644 --- a/test/common/router/header_formatter_test.cc +++ b/test/common/router/header_formatter_test.cc @@ -15,10 +15,10 @@ #include "test/common/stream_info/test_int_accessor.h" #include "test/mocks/http/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::Return; @@ -33,7 +33,7 @@ static envoy::api::v2::route::Route parseRouteFromV2Yaml(const std::string& yaml return route; } -class StreamInfoHeaderFormatterTest : public testing::Test { +class StreamInfoHeaderFormatterTest : public TestBase { public: void testFormatting(const Envoy::StreamInfo::MockStreamInfo& stream_info, const std::string& variable, const std::string& expected_output) { diff --git a/test/common/router/rds_impl_test.cc b/test/common/router/rds_impl_test.cc index 7fa8cac0dc856..19171f44d5e01 100644 --- a/test/common/router/rds_impl_test.cc +++ b/test/common/router/rds_impl_test.cc @@ -21,10 +21,10 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -47,7 +47,7 @@ parseHttpConnectionManagerFromJson(const std::string& json_string, const Stats:: return http_connection_manager; } -class RdsTestBase : public testing::Test { +class RdsTestBase : public TestBase { public: RdsTestBase() : request_(&factory_context_.cluster_manager_.async_client_) {} diff --git a/test/common/router/retry_state_impl_test.cc b/test/common/router/retry_state_impl_test.cc index 61acbeaf199b4..f418c98922ca5 100644 --- a/test/common/router/retry_state_impl_test.cc +++ b/test/common/router/retry_state_impl_test.cc @@ -11,10 +11,10 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -23,7 +23,7 @@ using testing::Return; namespace Envoy { namespace Router { -class RouterRetryStateImplTest : public testing::Test { +class RouterRetryStateImplTest : public TestBase { public: RouterRetryStateImplTest() : callback_([this]() -> void { callback_ready_.ready(); }) { ON_CALL(runtime_.snapshot_, featureEnabled("upstream.use_retry", 100)) diff --git a/test/common/router/router_ratelimit_test.cc b/test/common/router/router_ratelimit_test.cc index ae5a104aec3ff..9ec8c79c1903f 100644 --- a/test/common/router/router_ratelimit_test.cc +++ b/test/common/router/router_ratelimit_test.cc @@ -14,10 +14,10 @@ #include "test/mocks/router/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -97,7 +97,7 @@ static Http::TestHeaderMapImpl genHeaders(const std::string& host, const std::st return Http::TestHeaderMapImpl{{":authority", host}, {":path", path}, {":method", method}}; } -class RateLimitConfiguration : public testing::Test { +class RateLimitConfiguration : public TestBase { public: void SetUpTest(const std::string json) { envoy::api::v2::RouteConfiguration route_config; @@ -343,7 +343,7 @@ TEST_F(RateLimitConfiguration, Stages) { EXPECT_TRUE(rate_limits.empty()); } -class RateLimitPolicyEntryTest : public testing::Test { +class RateLimitPolicyEntryTest : public TestBase { public: void SetUpTest(const std::string json) { rate_limit_entry_ = std::make_unique(parseRateLimitFromJson(json)); diff --git a/test/common/router/router_test.cc b/test/common/router/router_test.cc index c237bebacde07..ce54d1c0c3537 100644 --- a/test/common/router/router_test.cc +++ b/test/common/router/router_test.cc @@ -24,11 +24,11 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AssertionFailure; @@ -74,7 +74,7 @@ class TestFilter : public Filter { bool reject_all_hosts_ = false; }; -class RouterTestBase : public testing::Test { +class RouterTestBase : public TestBase { public: RouterTestBase(bool start_child_span, bool suppress_envoy_headers) : shadow_writer_(new MockShadowWriter()), diff --git a/test/common/router/router_upstream_log_test.cc b/test/common/router/router_upstream_log_test.cc index 64210156df153..8bf7069a6e14b 100644 --- a/test/common/router/router_upstream_log_test.cc +++ b/test/common/router/router_upstream_log_test.cc @@ -16,11 +16,11 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/server/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/types/optional.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -72,7 +72,7 @@ class TestFilter : public Filter { MockRetryState* retry_state_{}; }; -class RouterUpstreamLogTest : public testing::Test { +class RouterUpstreamLogTest : public TestBase { public: RouterUpstreamLogTest() {} diff --git a/test/common/router/shadow_writer_impl_test.cc b/test/common/router/shadow_writer_impl_test.cc index adf0cf593ea20..eb2859ca56446 100644 --- a/test/common/router/shadow_writer_impl_test.cc +++ b/test/common/router/shadow_writer_impl_test.cc @@ -6,9 +6,9 @@ #include "common/router/shadow_writer_impl.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -18,7 +18,7 @@ using testing::Return; namespace Envoy { namespace Router { -class ShadowWriterImplTest : public testing::Test { +class ShadowWriterImplTest : public TestBase { public: void expectShadowWriter(absl::string_view host, absl::string_view shadowed_host) { Http::MessagePtr message(new Http::RequestMessageImpl()); diff --git a/test/common/router/string_accessor_impl_test.cc b/test/common/router/string_accessor_impl_test.cc index 4138980f8b362..6cfe54ad8c420 100644 --- a/test/common/router/string_accessor_impl_test.cc +++ b/test/common/router/string_accessor_impl_test.cc @@ -1,7 +1,8 @@ #include "common/router/string_accessor_impl.h" +#include "test/test_common/test_base.h" + #include "absl/strings/string_view.h" -#include "gtest/gtest.h" namespace Envoy { namespace Router { diff --git a/test/common/runtime/runtime_impl_test.cc b/test/common/runtime/runtime_impl_test.cc index 74a5f7b0c8b71..aa99434d3bef4 100644 --- a/test/common/runtime/runtime_impl_test.cc +++ b/test/common/runtime/runtime_impl_test.cc @@ -9,9 +9,9 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -63,7 +63,7 @@ TEST(UUID, sanityCheckOfUniqueness) { EXPECT_EQ(num_of_uuids, uuids.size()); } -class DiskBackedLoaderImplTest : public testing::Test { +class DiskBackedLoaderImplTest : public TestBase { protected: DiskBackedLoaderImplTest() : api_(Api::createApiForTest(store)) {} @@ -260,7 +260,7 @@ TEST(LoaderImplTest, All) { testNewOverrides(loader, store); } -class DiskLayerTest : public testing::Test { +class DiskLayerTest : public TestBase { protected: DiskLayerTest() : api_(Api::createApiForTest(store_)) {} diff --git a/test/common/runtime/uuid_util_test.cc b/test/common/runtime/uuid_util_test.cc index 8596783038a53..fff1b87b6651f 100644 --- a/test/common/runtime/uuid_util_test.cc +++ b/test/common/runtime/uuid_util_test.cc @@ -3,7 +3,7 @@ #include "common/runtime/runtime_impl.h" #include "common/runtime/uuid_util.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { TEST(UUIDUtilsTest, mod) { diff --git a/test/common/secret/sds_api_test.cc b/test/common/secret/sds_api_test.cc index 7c11e3730f36e..39808f24d432d 100644 --- a/test/common/secret/sds_api_test.cc +++ b/test/common/secret/sds_api_test.cc @@ -13,10 +13,10 @@ #include "test/mocks/secret/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using ::testing::_; using ::testing::Invoke; @@ -26,7 +26,7 @@ namespace Envoy { namespace Secret { namespace { -class SdsApiTest : public testing::Test { +class SdsApiTest : public TestBase { protected: SdsApiTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/secret/secret_manager_impl_test.cc b/test/common/secret/secret_manager_impl_test.cc index 8b50f6678ecb7..7b3aa38238f66 100644 --- a/test/common/secret/secret_manager_impl_test.cc +++ b/test/common/secret/secret_manager_impl_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::Return; using testing::ReturnRef; @@ -22,7 +22,7 @@ namespace Envoy { namespace Secret { namespace { -class SecretManagerImplTest : public testing::Test { +class SecretManagerImplTest : public TestBase { protected: SecretManagerImplTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/singleton/threadsafe_singleton_test.cc b/test/common/singleton/threadsafe_singleton_test.cc index a9172aceade76..984e95c25ff0c 100644 --- a/test/common/singleton/threadsafe_singleton_test.cc +++ b/test/common/singleton/threadsafe_singleton_test.cc @@ -5,11 +5,10 @@ #include "common/singleton/threadsafe_singleton.h" #include "common/stats/isolated_store_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { class TestSingleton { diff --git a/test/common/stats/heap_stat_data_test.cc b/test/common/stats/heap_stat_data_test.cc index eac2c123ff2bb..6293df616a4e1 100644 --- a/test/common/stats/heap_stat_data_test.cc +++ b/test/common/stats/heap_stat_data_test.cc @@ -4,8 +4,7 @@ #include "common/stats/stats_options_impl.h" #include "test/test_common/logging.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Stats { diff --git a/test/common/stats/isolated_store_impl_test.cc b/test/common/stats/isolated_store_impl_test.cc index b2aaa80693fdd..ffb2069094221 100644 --- a/test/common/stats/isolated_store_impl_test.cc +++ b/test/common/stats/isolated_store_impl_test.cc @@ -4,9 +4,10 @@ #include "common/stats/isolated_store_impl.h" +#include "test/test_common/test_base.h" + #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" -#include "gtest/gtest.h" namespace Envoy { namespace Stats { diff --git a/test/common/stats/raw_stat_data_test.cc b/test/common/stats/raw_stat_data_test.cc index 3b7b5575bfa73..d04421d105534 100644 --- a/test/common/stats/raw_stat_data_test.cc +++ b/test/common/stats/raw_stat_data_test.cc @@ -4,14 +4,13 @@ #include "common/stats/stats_options_impl.h" #include "test/test_common/logging.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Stats { -class RawStatDataTest : public testing::Test { +class RawStatDataTest : public TestBase { public: RawStatDataTest() : allocator_(stats_options_) {} diff --git a/test/common/stats/source_impl_test.cc b/test/common/stats/source_impl_test.cc index 8668626534c7a..a3a8bdec9bef8 100644 --- a/test/common/stats/source_impl_test.cc +++ b/test/common/stats/source_impl_test.cc @@ -3,8 +3,7 @@ #include "common/stats/source_impl.h" #include "test/mocks/stats/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::NiceMock; using testing::ReturnPointee; diff --git a/test/common/stats/stats_matcher_impl_test.cc b/test/common/stats/stats_matcher_impl_test.cc index 485560f2b702f..b70db7f78ec95 100644 --- a/test/common/stats/stats_matcher_impl_test.cc +++ b/test/common/stats/stats_matcher_impl_test.cc @@ -2,17 +2,16 @@ #include "common/stats/stats_matcher_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::IsFalse; using testing::IsTrue; namespace Envoy { namespace Stats { -class StatsMatcherTest : public testing::Test { +class StatsMatcherTest : public TestBase { protected: envoy::type::matcher::StringMatcher* inclusionList() { return stats_config_.mutable_stats_matcher()->mutable_inclusion_list()->add_patterns(); diff --git a/test/common/stats/symbol_table_impl_test.cc b/test/common/stats/symbol_table_impl_test.cc index 6b91a15236f41..571f2665d9471 100644 --- a/test/common/stats/symbol_table_impl_test.cc +++ b/test/common/stats/symbol_table_impl_test.cc @@ -7,10 +7,10 @@ #include "test/common/stats/stat_test_utility.h" #include "test/test_common/logging.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/synchronization/blocking_counter.h" -#include "gtest/gtest.h" namespace Envoy { namespace Stats { @@ -28,7 +28,7 @@ enum class SymbolTableType { Fake, }; -class StatNameTest : public testing::TestWithParam { +class StatNameTest : public TestBaseWithParam { protected: StatNameTest() { switch (GetParam()) { diff --git a/test/common/stats/tag_extractor_impl_test.cc b/test/common/stats/tag_extractor_impl_test.cc index 4fe93839194b6..d47b8610cee89 100644 --- a/test/common/stats/tag_extractor_impl_test.cc +++ b/test/common/stats/tag_extractor_impl_test.cc @@ -7,10 +7,9 @@ #include "common/stats/tag_extractor_impl.h" #include "common/stats/tag_producer_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Stats { diff --git a/test/common/stats/tag_producer_impl_test.cc b/test/common/stats/tag_producer_impl_test.cc index d97819ed4e9c6..965003f09d9dd 100644 --- a/test/common/stats/tag_producer_impl_test.cc +++ b/test/common/stats/tag_producer_impl_test.cc @@ -3,10 +3,9 @@ #include "common/config/well_known_names.h" #include "common/stats/tag_producer_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Stats { diff --git a/test/common/stats/thread_local_store_test.cc b/test/common/stats/thread_local_store_test.cc index 7d69bf0abae53..f13ed96ca61ce 100644 --- a/test/common/stats/thread_local_store_test.cc +++ b/test/common/stats/thread_local_store_test.cc @@ -17,11 +17,11 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/test_common/logging.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/str_split.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -33,7 +33,7 @@ using testing::Return; namespace Envoy { namespace Stats { -class StatsThreadLocalStoreTest : public testing::Test { +class StatsThreadLocalStoreTest : public TestBase { public: void SetUp() override { alloc_ = std::make_unique(options_); @@ -71,7 +71,7 @@ class HistogramWrapper { histogram_t* histogram_; }; -class HistogramTest : public testing::Test { +class HistogramTest : public TestBase { public: typedef std::map NameHistogramMap; diff --git a/test/common/stream_info/filter_state_impl_test.cc b/test/common/stream_info/filter_state_impl_test.cc index 56fbbd91d00d1..779077a4b94bf 100644 --- a/test/common/stream_info/filter_state_impl_test.cc +++ b/test/common/stream_info/filter_state_impl_test.cc @@ -2,10 +2,9 @@ #include "common/stream_info/filter_state_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace StreamInfo { namespace { @@ -44,7 +43,7 @@ class SimpleType : public FilterState::Object { int value_; }; -class FilterStateImplTest : public testing::Test { +class FilterStateImplTest : public TestBase { public: FilterStateImplTest() { resetFilterState(); } diff --git a/test/common/stream_info/stream_info_impl_test.cc b/test/common/stream_info/stream_info_impl_test.cc index 62a62166040b9..d094e623ba0d6 100644 --- a/test/common/stream_info/stream_info_impl_test.cc +++ b/test/common/stream_info/stream_info_impl_test.cc @@ -12,9 +12,9 @@ #include "test/common/stream_info/test_int_accessor.h" #include "test/mocks/router/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace StreamInfo { @@ -27,7 +27,7 @@ std::chrono::nanoseconds checkDuration(std::chrono::nanoseconds last, return timing.value(); } -class StreamInfoImplTest : public testing::Test { +class StreamInfoImplTest : public TestBase { protected: DangerousDeprecatedTestTime test_time_; }; diff --git a/test/common/stream_info/utility_test.cc b/test/common/stream_info/utility_test.cc index 51781b85df801..e96ddd17eab3f 100644 --- a/test/common/stream_info/utility_test.cc +++ b/test/common/stream_info/utility_test.cc @@ -2,9 +2,9 @@ #include "common/stream_info/utility.h" #include "test/mocks/stream_info/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/common/tcp/conn_pool_test.cc b/test/common/tcp/conn_pool_test.cc index b3f26916eabad..84f4cd72db6b3 100644 --- a/test/common/tcp/conn_pool_test.cc +++ b/test/common/tcp/conn_pool_test.cc @@ -12,10 +12,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -152,7 +152,7 @@ class ConnPoolImplForTest : public ConnPoolImpl { /** * Test fixture for connection pool tests. */ -class TcpConnPoolImplTest : public testing::Test { +class TcpConnPoolImplTest : public TestBase { public: TcpConnPoolImplTest() : upstream_ready_timer_(new NiceMock(&dispatcher_)), @@ -175,7 +175,7 @@ class TcpConnPoolImplTest : public testing::Test { /** * Test fixture for connection pool destructor tests. */ -class TcpConnPoolImplDestructorTest : public testing::Test { +class TcpConnPoolImplDestructorTest : public TestBase { public: TcpConnPoolImplDestructorTest() : upstream_ready_timer_(new NiceMock(&dispatcher_)), diff --git a/test/common/tcp_proxy/tcp_proxy_test.cc b/test/common/tcp_proxy/tcp_proxy_test.cc index cb04f0bb5c126..9f1dced174f20 100644 --- a/test/common/tcp_proxy/tcp_proxy_test.cc +++ b/test/common/tcp_proxy/tcp_proxy_test.cc @@ -25,9 +25,9 @@ #include "test/mocks/upstream/host.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -346,7 +346,7 @@ TEST(ConfigTest, AccessLogConfig) { EXPECT_EQ(2, config_obj.accessLogs().size()); } -class TcpProxyTest : public testing::Test { +class TcpProxyTest : public TestBase { public: TcpProxyTest() { ON_CALL(*factory_context_.access_log_manager_.file_, write(_)) @@ -1076,7 +1076,7 @@ TEST_F(TcpProxyTest, UpstreamFlushReceiveUpstreamData) { upstream_callbacks_->onUpstreamData(buffer, false); } -class TcpProxyRoutingTest : public testing::Test { +class TcpProxyRoutingTest : public TestBase { public: TcpProxyRoutingTest() { std::string json = R"EOF( diff --git a/test/common/thread/thread_factory_singleton_test.cc b/test/common/thread/thread_factory_singleton_test.cc index d50fc69ee417c..dd474ce520f8a 100644 --- a/test/common/thread/thread_factory_singleton_test.cc +++ b/test/common/thread/thread_factory_singleton_test.cc @@ -2,14 +2,15 @@ #include "common/common/assert.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Thread { namespace { -class ThreadFactorySingletonTest : public testing::Test { +class ThreadFactorySingletonTest : public TestBase { protected: ThreadFactorySingletonTest() : run_tid_(Envoy::Thread::ThreadFactorySingleton::get().currentThreadId()) {} diff --git a/test/common/thread_local/thread_local_impl_test.cc b/test/common/thread_local/thread_local_impl_test.cc index 0f67f18c50220..49e228030d1a4 100644 --- a/test/common/thread_local/thread_local_impl_test.cc +++ b/test/common/thread_local/thread_local_impl_test.cc @@ -23,7 +23,7 @@ class TestThreadLocalObject : public ThreadLocalObject { MOCK_METHOD0(onDestroy, void()); }; -class ThreadLocalInstanceImplTest : public testing::Test { +class ThreadLocalInstanceImplTest : public TestBase { public: ThreadLocalInstanceImplTest() { tls_.registerThread(main_dispatcher_, true); diff --git a/test/common/tracing/http_tracer_impl_test.cc b/test/common/tracing/http_tracer_impl_test.cc index ac5ad1a0ddc90..c0790a1651c23 100644 --- a/test/common/tracing/http_tracer_impl_test.cc +++ b/test/common/tracing/http_tracer_impl_test.cc @@ -18,10 +18,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -323,7 +323,7 @@ TEST(HttpNullTracerTest, BasicFunctionality) { EXPECT_NE(nullptr, span_ptr->spawnChild(config, "foo", SystemTime())); } -class HttpTracerImplTest : public testing::Test { +class HttpTracerImplTest : public TestBase { public: HttpTracerImplTest() { driver_ = new MockDriver(); diff --git a/test/common/upstream/cds_api_impl_test.cc b/test/common/upstream/cds_api_impl_test.cc index 3c58882352941..205611fb88c52 100644 --- a/test/common/upstream/cds_api_impl_test.cc +++ b/test/common/upstream/cds_api_impl_test.cc @@ -12,10 +12,10 @@ #include "test/mocks/local_info/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -26,7 +26,7 @@ using testing::ReturnRef; namespace Envoy { namespace Upstream { -class CdsApiImplTest : public testing::Test { +class CdsApiImplTest : public TestBase { protected: CdsApiImplTest() : request_(&cm_.async_client_), api_(Api::createApiForTest(store_)) {} diff --git a/test/common/upstream/cluster_manager_impl_test.cc b/test/common/upstream/cluster_manager_impl_test.cc index f03f9b7901c91..ade2b7b5e399e 100644 --- a/test/common/upstream/cluster_manager_impl_test.cc +++ b/test/common/upstream/cluster_manager_impl_test.cc @@ -30,11 +30,11 @@ #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -163,7 +163,7 @@ envoy::config::bootstrap::v2::Bootstrap parseBootstrapFromV2Yaml(const std::stri return bootstrap; } -class ClusterManagerImplTest : public testing::Test { +class ClusterManagerImplTest : public TestBase { public: ClusterManagerImplTest() : api_(Api::createApiForTest(stats_store_)) {} @@ -2336,7 +2336,7 @@ TEST_F(ClusterManagerImplTest, MergedUpdatesDestroyedOnUpdate) { EXPECT_EQ(0, factory_.stats_.gauge("cluster_manager.warming_clusters").value()); } -class ClusterManagerInitHelperTest : public testing::Test { +class ClusterManagerInitHelperTest : public TestBase { public: MOCK_METHOD1(onClusterInit, void(Cluster& cluster)); diff --git a/test/common/upstream/edf_scheduler_test.cc b/test/common/upstream/edf_scheduler_test.cc index ddb39bf847a05..9962b6f5cd6d2 100644 --- a/test/common/upstream/edf_scheduler_test.cc +++ b/test/common/upstream/edf_scheduler_test.cc @@ -1,6 +1,6 @@ #include "common/upstream/edf_scheduler.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Upstream { diff --git a/test/common/upstream/eds_test.cc b/test/common/upstream/eds_test.cc index 8a729e80378a4..be98cdf9f97eb 100644 --- a/test/common/upstream/eds_test.cc +++ b/test/common/upstream/eds_test.cc @@ -15,10 +15,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/ssl/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; @@ -27,7 +27,7 @@ using testing::ReturnRef; namespace Envoy { namespace Upstream { -class EdsTest : public testing::Test { +class EdsTest : public TestBase { protected: EdsTest() : api_(Api::createApiForTest(stats_)) { resetCluster(); } diff --git a/test/common/upstream/hds_test.cc b/test/common/upstream/hds_test.cc index 2f2963891d6ba..501aa9aa76929 100644 --- a/test/common/upstream/hds_test.cc +++ b/test/common/upstream/hds_test.cc @@ -15,10 +15,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtLeast; @@ -42,7 +42,7 @@ class HdsDelegateFriend { }; }; -class HdsTest : public testing::Test { +class HdsTest : public TestBase { protected: HdsTest() : retry_timer_(new Event::MockTimer()), server_response_timer_(new Event::MockTimer()), diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index e930588f9d4a3..bf7e3b2c65751 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -24,10 +24,10 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -101,7 +101,7 @@ class TestHttpHealthCheckerImpl : public HttpHealthCheckerImpl { Http::CodecClient::Type codecClientType() { return codec_client_type_; } }; -class HttpHealthCheckerImplTest : public testing::Test { +class HttpHealthCheckerImplTest : public TestBase { public: struct TestSession { TestSession() {} @@ -1969,7 +1969,7 @@ TEST(TcpHealthCheckMatcher, match) { EXPECT_TRUE(TcpHealthCheckMatcher::match(segments, buffer)); } -class TcpHealthCheckerImplTest : public testing::Test { +class TcpHealthCheckerImplTest : public TestBase { public: TcpHealthCheckerImplTest() : cluster_(new NiceMock()), event_logger_(new MockHealthCheckEventLogger()) {} @@ -2753,7 +2753,7 @@ class GrpcHealthCheckerImplTestBase { std::list codec_index_{}; }; -class GrpcHealthCheckerImplTest : public GrpcHealthCheckerImplTestBase, public testing::Test {}; +class GrpcHealthCheckerImplTest : public GrpcHealthCheckerImplTestBase, public TestBase {}; // Test single host check success. TEST_F(GrpcHealthCheckerImplTest, Success) { testSingleHostSuccess(absl::nullopt); } @@ -3382,7 +3382,7 @@ TEST_F(GrpcHealthCheckerImplTest, GoAwayBetweenChecks) { class BadResponseGrpcHealthCheckerImplTest : public GrpcHealthCheckerImplTestBase, - public testing::TestWithParam {}; + public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P( BadResponse, BadResponseGrpcHealthCheckerImplTest, diff --git a/test/common/upstream/host_utility_test.cc b/test/common/upstream/host_utility_test.cc index f6c37823d051a..ce26ba708725e 100644 --- a/test/common/upstream/host_utility_test.cc +++ b/test/common/upstream/host_utility_test.cc @@ -4,8 +4,7 @@ #include "test/common/upstream/utility.h" #include "test/mocks/upstream/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Upstream { diff --git a/test/common/upstream/load_balancer_impl_test.cc b/test/common/upstream/load_balancer_impl_test.cc index 3d624e6c43965..5d59c4806a1aa 100644 --- a/test/common/upstream/load_balancer_impl_test.cc +++ b/test/common/upstream/load_balancer_impl_test.cc @@ -11,9 +11,9 @@ #include "test/common/upstream/utility.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::ElementsAre; using testing::NiceMock; @@ -23,7 +23,7 @@ using testing::ReturnRef; namespace Envoy { namespace Upstream { -class LoadBalancerTestBase : public ::testing::TestWithParam { +class LoadBalancerTestBase : public TestBaseWithParam { protected: // Run all tests against both priority 0 and priority 1 host sets, to ensure // all the load balancers have equivalent functonality for failover host sets. diff --git a/test/common/upstream/load_balancer_simulation_test.cc b/test/common/upstream/load_balancer_simulation_test.cc index 7474b90727514..14267d825b685 100644 --- a/test/common/upstream/load_balancer_simulation_test.cc +++ b/test/common/upstream/load_balancer_simulation_test.cc @@ -11,9 +11,9 @@ #include "test/common/upstream/utility.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::Return; @@ -90,7 +90,7 @@ TEST(DISABLED_LeastRequestLoadBalancerWeightTest, Weight) { /** * This test is for simulation only and should not be run as part of unit tests. */ -class DISABLED_SimulationTest : public testing::Test { +class DISABLED_SimulationTest : public TestBase { public: DISABLED_SimulationTest() : stats_(ClusterInfoImpl::generateStats(stats_store_)) { ON_CALL(runtime_.snapshot_, getInteger("upstream.healthy_panic_threshold", 50U)) diff --git a/test/common/upstream/load_stats_reporter_test.cc b/test/common/upstream/load_stats_reporter_test.cc index beed927a71704..f860248996989 100644 --- a/test/common/upstream/load_stats_reporter_test.cc +++ b/test/common/upstream/load_stats_reporter_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/local_info/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -26,7 +26,7 @@ using testing::Return; namespace Envoy { namespace Upstream { -class LoadStatsReporterTest : public testing::Test { +class LoadStatsReporterTest : public TestBase { public: LoadStatsReporterTest() : retry_timer_(new Event::MockTimer()), response_timer_(new Event::MockTimer()), diff --git a/test/common/upstream/logical_dns_cluster_test.cc b/test/common/upstream/logical_dns_cluster_test.cc index 0c27abdc0fdfe..9d55f81d1e5ed 100644 --- a/test/common/upstream/logical_dns_cluster_test.cc +++ b/test/common/upstream/logical_dns_cluster_test.cc @@ -21,10 +21,10 @@ #include "test/mocks/ssl/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -35,7 +35,7 @@ namespace Upstream { enum class ConfigType { V2_YAML, V1_JSON }; -class LogicalDnsClusterTest : public testing::Test { +class LogicalDnsClusterTest : public TestBase { protected: LogicalDnsClusterTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/common/upstream/maglev_lb_test.cc b/test/common/upstream/maglev_lb_test.cc index b0208e9836195..34f196251da7f 100644 --- a/test/common/upstream/maglev_lb_test.cc +++ b/test/common/upstream/maglev_lb_test.cc @@ -20,7 +20,7 @@ class TestLoadBalancerContext : public LoadBalancerContextBase { // Note: ThreadAwareLoadBalancer base is heavily tested by RingHashLoadBalancerTest. Only basic // functionality is covered here. -class MaglevLoadBalancerTest : public ::testing::Test { +class MaglevLoadBalancerTest : public TestBase { public: MaglevLoadBalancerTest() : stats_(ClusterInfoImpl::generateStats(stats_store_)) {} diff --git a/test/common/upstream/original_dst_cluster_test.cc b/test/common/upstream/original_dst_cluster_test.cc index dc6e51e3f8771..f052e5d56a21b 100644 --- a/test/common/upstream/original_dst_cluster_test.cc +++ b/test/common/upstream/original_dst_cluster_test.cc @@ -22,10 +22,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/ssl/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -57,7 +57,7 @@ class TestLoadBalancerContext : public LoadBalancerContextBase { Http::HeaderMapPtr downstream_headers_; }; -class OriginalDstClusterTest : public testing::Test { +class OriginalDstClusterTest : public TestBase { public: // cleanup timer must be created before the cluster (in setup()), so that we can set expectations // on it. Ownership is transferred to the cluster at the cluster constructor, so the cluster will diff --git a/test/common/upstream/outlier_detection_impl_test.cc b/test/common/upstream/outlier_detection_impl_test.cc index 5a85a50ac3464..c55da17c86190 100644 --- a/test/common/upstream/outlier_detection_impl_test.cc +++ b/test/common/upstream/outlier_detection_impl_test.cc @@ -16,10 +16,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "absl/types/optional.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -56,7 +56,7 @@ class CallbackChecker { MOCK_METHOD1(check, void(HostSharedPtr host)); }; -class OutlierDetectorImplTest : public testing::Test { +class OutlierDetectorImplTest : public TestBase { public: OutlierDetectorImplTest() { ON_CALL(runtime_.snapshot_, featureEnabled("outlier_detection.enforcing_consecutive_5xx", 100)) diff --git a/test/common/upstream/resource_manager_impl_test.cc b/test/common/upstream/resource_manager_impl_test.cc index 73610ab81c5fb..c726700ad77a0 100644 --- a/test/common/upstream/resource_manager_impl_test.cc +++ b/test/common/upstream/resource_manager_impl_test.cc @@ -5,9 +5,9 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/common/upstream/ring_hash_lb_test.cc b/test/common/upstream/ring_hash_lb_test.cc index 0ef94dd3dd00b..8f6e5234380a7 100644 --- a/test/common/upstream/ring_hash_lb_test.cc +++ b/test/common/upstream/ring_hash_lb_test.cc @@ -12,9 +12,9 @@ #include "test/common/upstream/utility.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -33,7 +33,7 @@ class TestLoadBalancerContext : public LoadBalancerContextBase { absl::optional hash_key_; }; -class RingHashLoadBalancerTest : public ::testing::TestWithParam { +class RingHashLoadBalancerTest : public TestBaseWithParam { public: RingHashLoadBalancerTest() : stats_(ClusterInfoImpl::generateStats(stats_store_)) {} diff --git a/test/common/upstream/subset_lb_test.cc b/test/common/upstream/subset_lb_test.cc index 49b29a98be673..a7447a226d54a 100644 --- a/test/common/upstream/subset_lb_test.cc +++ b/test/common/upstream/subset_lb_test.cc @@ -17,10 +17,10 @@ #include "test/mocks/filesystem/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "absl/types/optional.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::EndsWith; @@ -106,7 +106,7 @@ class TestLoadBalancerContext : public LoadBalancerContextBase { enum UpdateOrder { REMOVES_FIRST, SIMULTANEOUS }; -class SubsetLoadBalancerTest : public testing::TestWithParam { +class SubsetLoadBalancerTest : public TestBaseWithParam { public: SubsetLoadBalancerTest() : stats_(ClusterInfoImpl::generateStats(stats_store_)) { stats_.max_host_weight_.set(1UL); diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index efa170dc6e2a3..a84e7b834b985 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -28,10 +28,10 @@ #include "test/mocks/ssl/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ContainerEq; @@ -134,7 +134,7 @@ std::vector generateStrictDnsParams() { return dns_config; } -class StrictDnsParamTest : public testing::TestWithParam, +class StrictDnsParamTest : public TestBaseWithParam, public UpstreamImplTestBase {}; INSTANTIATE_TEST_SUITE_P(DnsParam, StrictDnsParamTest, @@ -176,7 +176,7 @@ TEST_P(StrictDnsParamTest, ImmediateResolve) { EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); } -class StrictDnsClusterImplTest : public testing::Test, public UpstreamImplTestBase { +class StrictDnsClusterImplTest : public TestBase, public UpstreamImplTestBase { protected: std::shared_ptr dns_resolver_ = std::make_shared(); @@ -846,7 +846,7 @@ TEST(HostImplTest, HealthFlags) { EXPECT_EQ(Host::Health::Degraded, host->health()); } -class StaticClusterImplTest : public testing::Test, public UpstreamImplTestBase {}; +class StaticClusterImplTest : public TestBase, public UpstreamImplTestBase {}; TEST_F(StaticClusterImplTest, InitialHosts) { const std::string yaml = R"EOF( @@ -1446,7 +1446,7 @@ TEST_F(StaticClusterImplTest, SourceAddressPriority) { } } -class ClusterImplTest : public testing::Test, public UpstreamImplTestBase {}; +class ClusterImplTest : public TestBase, public UpstreamImplTestBase {}; // Test that the correct feature() is set when close_connections_on_host_health_failure is // configured. @@ -1532,7 +1532,7 @@ TEST(PrioritySet, Extend) { } } -class ClusterInfoImplTest : public testing::Test { +class ClusterInfoImplTest : public TestBase { public: ClusterInfoImplTest() : api_(Api::createApiForTest(stats_)) {} @@ -1976,7 +1976,7 @@ TEST(HostsPerLocalityImpl, Filter) { } } -class HostSetImplLocalityTest : public ::testing::Test { +class HostSetImplLocalityTest : public TestBase { public: LocalityWeightsConstSharedPtr locality_weights_; HostSetImpl host_set_{0, kDefaultOverProvisioningFactor}; diff --git a/test/config/utility.cc b/test/config/utility.cc index 467fa9d8b7fbd..4f1e353372d7a 100644 --- a/test/config/utility.cc +++ b/test/config/utility.cc @@ -12,10 +12,10 @@ #include "test/config/integration/certs/clientcert_hash.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/str_replace.h" -#include "gtest/gtest.h" namespace Envoy { diff --git a/test/config_test/config_test.cc b/test/config_test/config_test.cc index f2a83ab1196b8..f7efcaab48630 100644 --- a/test/config_test/config_test.cc +++ b/test/config_test/config_test.cc @@ -14,11 +14,11 @@ #include "test/integration/server.h" #include "test/mocks/server/mocks.h" #include "test/mocks/ssl/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/config_test/example_configs_test.cc b/test/config_test/example_configs_test.cc index ca85b6f1ecad2..6f4c7fe4428b8 100644 --- a/test/config_test/example_configs_test.cc +++ b/test/config_test/example_configs_test.cc @@ -1,9 +1,8 @@ #include "test/config_test/config_test.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { TEST(ExampleConfigsTest, All) { TestEnvironment::exec( diff --git a/test/coverage/gcc_only_test/gcc_only_test.cc b/test/coverage/gcc_only_test/gcc_only_test.cc index 31346323d20e4..ced70a1e7213f 100644 --- a/test/coverage/gcc_only_test/gcc_only_test.cc +++ b/test/coverage/gcc_only_test/gcc_only_test.cc @@ -1,4 +1,4 @@ -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/exe/main_common_test.cc b/test/exe/main_common_test.cc index 54f8ef9d10e25..0040171dbe53d 100644 --- a/test/exe/main_common_test.cc +++ b/test/exe/main_common_test.cc @@ -11,10 +11,9 @@ #include "test/test_common/contention.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - #ifdef ENVOY_HANDLE_SIGNALS #include "exe/signal_action.h" #endif @@ -32,7 +31,7 @@ namespace Envoy { * an argv array that is terminated with nullptr. Identifies the config * file relative to $TEST_RUNDIR. */ -class MainCommonTest : public testing::TestWithParam { +class MainCommonTest : public TestBaseWithParam { protected: MainCommonTest() : config_file_(TestEnvironment::temporaryFileSubstitute( diff --git a/test/exe/signals_test.cc b/test/exe/signals_test.cc index eb07fe61370a5..99ff8fa73cb9d 100644 --- a/test/exe/signals_test.cc +++ b/test/exe/signals_test.cc @@ -3,10 +3,9 @@ #include "exe/signal_action.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { #if defined(__has_feature) #if __has_feature(address_sanitizer) diff --git a/test/exe/terminate_handler_test.cc b/test/exe/terminate_handler_test.cc index f37774352b3a3..bb84c26ffd41c 100644 --- a/test/exe/terminate_handler_test.cc +++ b/test/exe/terminate_handler_test.cc @@ -1,9 +1,8 @@ #include "exe/terminate_handler.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { TEST(TerminateHandlerDeathTest, HandlerInstalledTest) { diff --git a/test/extensions/access_loggers/file/config_test.cc b/test/extensions/access_loggers/file/config_test.cc index 14e35b40c72fe..b309c55d3c1ad 100644 --- a/test/extensions/access_loggers/file/config_test.cc +++ b/test/extensions/access_loggers/file/config_test.cc @@ -9,9 +9,9 @@ #include "extensions/access_loggers/well_known_names.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/access_loggers/http_grpc/config_test.cc b/test/extensions/access_loggers/http_grpc/config_test.cc index b337fe4cf9d43..5bf1e1134ed0f 100644 --- a/test/extensions/access_loggers/http_grpc/config_test.cc +++ b/test/extensions/access_loggers/http_grpc/config_test.cc @@ -6,9 +6,9 @@ #include "extensions/access_loggers/well_known_names.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -19,7 +19,7 @@ namespace Extensions { namespace AccessLoggers { namespace HttpGrpc { -class HttpGrpcAccessLogConfigTest : public testing::Test { +class HttpGrpcAccessLogConfigTest : public TestBase { public: void SetUp() override { factory_ = diff --git a/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc b/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc index 1b5aed984b6e0..ebc8fe6482600 100644 --- a/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc +++ b/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc @@ -22,7 +22,7 @@ namespace Extensions { namespace AccessLoggers { namespace HttpGrpc { -class GrpcAccessLogStreamerImplTest : public testing::Test { +class GrpcAccessLogStreamerImplTest : public TestBase { public: typedef Grpc::MockAsyncStream MockAccessLogStream; typedef Grpc::TypedAsyncStreamCallbacks @@ -112,7 +112,7 @@ class MockGrpcAccessLogStreamer : public GrpcAccessLogStreamer { const std::string& log_name)); }; -class HttpGrpcAccessLogTest : public testing::Test { +class HttpGrpcAccessLogTest : public TestBase { public: void init() { ON_CALL(*filter_, evaluate(_, _)).WillByDefault(Return(true)); diff --git a/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc b/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc index 59b5b1b3f92ec..16015e13764cd 100644 --- a/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc +++ b/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc @@ -8,10 +8,9 @@ #include "test/common/grpc/grpc_client_integration.h" #include "test/integration/http_integration.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::AssertionResult; namespace Envoy { diff --git a/test/extensions/common/tap/admin_test.cc b/test/extensions/common/tap/admin_test.cc index 8af5250432135..665e137cfcac9 100644 --- a/test/extensions/common/tap/admin_test.cc +++ b/test/extensions/common/tap/admin_test.cc @@ -1,8 +1,7 @@ #include "extensions/common/tap/admin.h" #include "test/mocks/server/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::_; using testing::Return; @@ -22,7 +21,7 @@ class MockExtensionConfig : public ExtensionConfig { void(envoy::service::tap::v2alpha::TapConfig&& proto_config, Sink* admin_streamer)); }; -class AdminHandlerTest : public testing::Test { +class AdminHandlerTest : public TestBase { public: AdminHandlerTest() { EXPECT_CALL(admin_, addHandler("/tap", "tap filter control", _, true, true)) diff --git a/test/extensions/common/tap/tap_matcher_test.cc b/test/extensions/common/tap/tap_matcher_test.cc index e7265f221952f..214e3166b87f7 100644 --- a/test/extensions/common/tap/tap_matcher_test.cc +++ b/test/extensions/common/tap/tap_matcher_test.cc @@ -2,17 +2,16 @@ #include "extensions/common/tap/tap_matcher.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace Common { namespace Tap { namespace { -class TapMatcherTest : public testing::Test { +class TapMatcherTest : public TestBase { public: std::vector matchers_; std::vector statuses_; diff --git a/test/extensions/filters/common/ext_authz/check_request_utils_test.cc b/test/extensions/filters/common/ext_authz/check_request_utils_test.cc index f03291fb2f499..01aef6d695655 100644 --- a/test/extensions/filters/common/ext_authz/check_request_utils_test.cc +++ b/test/extensions/filters/common/ext_authz/check_request_utils_test.cc @@ -7,9 +7,9 @@ #include "test/mocks/ssl/mocks.h" #include "test/mocks/stream_info/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::Return; using testing::ReturnPointee; @@ -21,7 +21,7 @@ namespace Filters { namespace Common { namespace ExtAuthz { -class CheckRequestUtilsTest : public testing::Test { +class CheckRequestUtilsTest : public TestBase { public: CheckRequestUtilsTest() { addr_ = std::make_shared("1.2.3.4", 1111); diff --git a/test/extensions/filters/common/ext_authz/ext_authz_grpc_impl_test.cc b/test/extensions/filters/common/ext_authz/ext_authz_grpc_impl_test.cc index 7c74aca575c22..ef56a5bdacd87 100644 --- a/test/extensions/filters/common/ext_authz/ext_authz_grpc_impl_test.cc +++ b/test/extensions/filters/common/ext_authz/ext_authz_grpc_impl_test.cc @@ -9,9 +9,9 @@ #include "test/extensions/filters/common/ext_authz/test_common.h" #include "test/mocks/grpc/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -28,7 +28,7 @@ namespace Filters { namespace Common { namespace ExtAuthz { -class ExtAuthzGrpcClientTest : public testing::Test { +class ExtAuthzGrpcClientTest : public TestBase { public: ExtAuthzGrpcClientTest() : async_client_(new Grpc::MockAsyncClient()), timeout_(10), diff --git a/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc b/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc index 57a332ec78ccd..4a529ccce0a06 100644 --- a/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc +++ b/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc @@ -10,9 +10,9 @@ #include "test/extensions/filters/common/ext_authz/mocks.h" #include "test/extensions/filters/common/ext_authz/test_common.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AllOf; @@ -30,7 +30,7 @@ namespace Filters { namespace Common { namespace ExtAuthz { -class ExtAuthzHttpClientTest : public testing::Test { +class ExtAuthzHttpClientTest : public TestBase { public: ExtAuthzHttpClientTest() : cm_{}, async_client_{}, diff --git a/test/extensions/filters/common/lua/lua_test.cc b/test/extensions/filters/common/lua/lua_test.cc index 720c1794b78a2..4d81601c290d0 100644 --- a/test/extensions/filters/common/lua/lua_test.cc +++ b/test/extensions/filters/common/lua/lua_test.cc @@ -33,7 +33,7 @@ class TestObject : public BaseLuaObject { int TestObject::luaTestCall(lua_State* state) { return doTestCall(state); } -class LuaTest : public testing::Test { +class LuaTest : public TestBase { public: LuaTest() : yield_callback_([this]() { on_yield_.ready(); }) {} diff --git a/test/extensions/filters/common/lua/lua_wrappers.h b/test/extensions/filters/common/lua/lua_wrappers.h index e1e7a41f1d0fe..a48bc2880d2e7 100644 --- a/test/extensions/filters/common/lua/lua_wrappers.h +++ b/test/extensions/filters/common/lua/lua_wrappers.h @@ -14,7 +14,7 @@ namespace Filters { namespace Common { namespace Lua { -template class LuaWrappersTestBase : public testing::Test { +template class LuaWrappersTestBase : public TestBase { public: virtual void setup(const std::string& code) { coroutine_.reset(); diff --git a/test/extensions/filters/common/ratelimit/ratelimit_impl_test.cc b/test/extensions/filters/common/ratelimit/ratelimit_impl_test.cc index a2db5f48367c0..6b21bd4f69bcf 100644 --- a/test/extensions/filters/common/ratelimit/ratelimit_impl_test.cc +++ b/test/extensions/filters/common/ratelimit/ratelimit_impl_test.cc @@ -14,10 +14,10 @@ #include "test/mocks/grpc/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtLeast; @@ -41,7 +41,7 @@ class MockRequestCallbacks : public RequestCallbacks { MOCK_METHOD2(complete_, void(LimitStatus status, const Http::HeaderMap* headers)); }; -class RateLimitGrpcClientTest : public testing::Test { +class RateLimitGrpcClientTest : public TestBase { public: RateLimitGrpcClientTest() : async_client_(new Grpc::MockAsyncClient()), diff --git a/test/extensions/filters/common/rbac/engine_impl_test.cc b/test/extensions/filters/common/rbac/engine_impl_test.cc index 5f86e76785132..cab08a096eebb 100644 --- a/test/extensions/filters/common/rbac/engine_impl_test.cc +++ b/test/extensions/filters/common/rbac/engine_impl_test.cc @@ -4,9 +4,9 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/ssl/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Const; diff --git a/test/extensions/filters/common/rbac/matchers_test.cc b/test/extensions/filters/common/rbac/matchers_test.cc index d38b17a86803f..95438862b4826 100644 --- a/test/extensions/filters/common/rbac/matchers_test.cc +++ b/test/extensions/filters/common/rbac/matchers_test.cc @@ -4,9 +4,9 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/ssl/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Const; diff --git a/test/extensions/filters/http/buffer/buffer_filter_test.cc b/test/extensions/filters/http/buffer/buffer_filter_test.cc index 34c1bd05298b6..4a6ff63dcb64b 100644 --- a/test/extensions/filters/http/buffer/buffer_filter_test.cc +++ b/test/extensions/filters/http/buffer/buffer_filter_test.cc @@ -12,9 +12,9 @@ #include "test/mocks/buffer/mocks.h" #include "test/mocks/http/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -28,7 +28,7 @@ namespace Extensions { namespace HttpFilters { namespace BufferFilter { -class BufferFilterTest : public testing::Test { +class BufferFilterTest : public TestBase { public: BufferFilterConfigSharedPtr setupConfig() { envoy::config::filter::http::buffer::v2::Buffer proto_config; diff --git a/test/extensions/filters/http/buffer/config_test.cc b/test/extensions/filters/http/buffer/config_test.cc index 98e87a8d66fd9..63b3ea3dff537 100644 --- a/test/extensions/filters/http/buffer/config_test.cc +++ b/test/extensions/filters/http/buffer/config_test.cc @@ -4,9 +4,9 @@ #include "extensions/filters/http/buffer/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/filters/http/common/aws/signer_impl_test.cc b/test/extensions/filters/http/common/aws/signer_impl_test.cc index 7d8d7331bc3d5..e877d764c19b4 100644 --- a/test/extensions/filters/http/common/aws/signer_impl_test.cc +++ b/test/extensions/filters/http/common/aws/signer_impl_test.cc @@ -17,7 +17,7 @@ namespace HttpFilters { namespace Common { namespace Aws { -class SignerImplTest : public testing::Test { +class SignerImplTest : public TestBase { public: SignerImplTest() : credentials_provider_(new NiceMock()), diff --git a/test/extensions/filters/http/common/aws/utility_test.cc b/test/extensions/filters/http/common/aws/utility_test.cc index 802e06036d3f5..eaf0b483b7933 100644 --- a/test/extensions/filters/http/common/aws/utility_test.cc +++ b/test/extensions/filters/http/common/aws/utility_test.cc @@ -1,9 +1,8 @@ #include "extensions/filters/http/common/aws/utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::ElementsAre; using testing::Pair; diff --git a/test/extensions/filters/http/common/jwks_fetcher_test.cc b/test/extensions/filters/http/common/jwks_fetcher_test.cc index 46ce0063b1c0e..a1bc4a2d74edf 100644 --- a/test/extensions/filters/http/common/jwks_fetcher_test.cc +++ b/test/extensions/filters/http/common/jwks_fetcher_test.cc @@ -49,7 +49,7 @@ cluster: pubkey_cluster seconds: 5 )"; -class JwksFetcherTest : public ::testing::Test { +class JwksFetcherTest : public TestBase { public: void SetUp() { MessageUtil::loadFromYaml(JwksUri, uri_); } HttpUri uri_; diff --git a/test/extensions/filters/http/cors/cors_filter_integration_test.cc b/test/extensions/filters/http/cors/cors_filter_integration_test.cc index d1008ece992fb..b5880df48a807 100644 --- a/test/extensions/filters/http/cors/cors_filter_integration_test.cc +++ b/test/extensions/filters/http/cors/cors_filter_integration_test.cc @@ -1,13 +1,12 @@ #include "test/integration/http_integration.h" #include "test/mocks/http/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { class CorsFilterIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: CorsFilterIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/cors/cors_filter_test.cc b/test/extensions/filters/http/cors/cors_filter_test.cc index 1558eb3462abd..e2dc13fb0a53b 100644 --- a/test/extensions/filters/http/cors/cors_filter_test.cc +++ b/test/extensions/filters/http/cors/cors_filter_test.cc @@ -6,9 +6,9 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -24,7 +24,7 @@ namespace Extensions { namespace HttpFilters { namespace Cors { -class CorsFilterTest : public testing::Test { +class CorsFilterTest : public TestBase { public: CorsFilterTest() : config_(new CorsFilterConfig("test.", stats_)), filter_(config_) { cors_policy_ = std::make_unique(); diff --git a/test/extensions/filters/http/dynamo/config_test.cc b/test/extensions/filters/http/dynamo/config_test.cc index f4fba1ccf90db..1e13225ddeafc 100644 --- a/test/extensions/filters/http/dynamo/config_test.cc +++ b/test/extensions/filters/http/dynamo/config_test.cc @@ -1,9 +1,9 @@ #include "extensions/filters/http/dynamo/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/http/dynamo/dynamo_filter_test.cc b/test/extensions/filters/http/dynamo/dynamo_filter_test.cc index 204eba44f9c75..e78590c2e44ba 100644 --- a/test/extensions/filters/http/dynamo/dynamo_filter_test.cc +++ b/test/extensions/filters/http/dynamo/dynamo_filter_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -26,7 +26,7 @@ namespace Extensions { namespace HttpFilters { namespace Dynamo { -class DynamoFilterTest : public testing::Test { +class DynamoFilterTest : public TestBase { public: void setup(bool enabled) { ON_CALL(loader_.snapshot_, featureEnabled("dynamodb.filter_enabled", 100)) diff --git a/test/extensions/filters/http/dynamo/dynamo_request_parser_test.cc b/test/extensions/filters/http/dynamo/dynamo_request_parser_test.cc index 330baed379f43..f9a61b116af53 100644 --- a/test/extensions/filters/http/dynamo/dynamo_request_parser_test.cc +++ b/test/extensions/filters/http/dynamo/dynamo_request_parser_test.cc @@ -7,10 +7,9 @@ #include "extensions/filters/http/dynamo/dynamo_request_parser.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace HttpFilters { diff --git a/test/extensions/filters/http/dynamo/dynamo_utility_test.cc b/test/extensions/filters/http/dynamo/dynamo_utility_test.cc index 83014009e7d8c..1834bee14db92 100644 --- a/test/extensions/filters/http/dynamo/dynamo_utility_test.cc +++ b/test/extensions/filters/http/dynamo/dynamo_utility_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/http/dynamo/dynamo_utility.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/filters/http/ext_authz/config_test.cc b/test/extensions/filters/http/ext_authz/config_test.cc index d6043f785588e..a16d7ad9acb29 100644 --- a/test/extensions/filters/http/ext_authz/config_test.cc +++ b/test/extensions/filters/http/ext_authz/config_test.cc @@ -4,9 +4,9 @@ #include "extensions/filters/http/ext_authz/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/http/ext_authz/ext_authz_test.cc b/test/extensions/filters/http/ext_authz/ext_authz_test.cc index 97c55dc9676c6..b064f78ade3d1 100644 --- a/test/extensions/filters/http/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/http/ext_authz/ext_authz_test.cc @@ -25,10 +25,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -36,7 +36,6 @@ using testing::Invoke; using testing::NiceMock; using testing::Return; using testing::ReturnRef; -using testing::TestWithParam; using testing::Values; using testing::WithArgs; @@ -82,12 +81,11 @@ template class HttpFilterTestBase : public T { } }; -class HttpFilterTest : public HttpFilterTestBase {}; +class HttpFilterTest : public HttpFilterTestBase {}; typedef envoy::config::filter::http::ext_authz::v2::ExtAuthz CreateFilterConfigFunc(); -class HttpFilterTestParam - : public HttpFilterTestBase> { +class HttpFilterTestParam : public HttpFilterTestBase> { public: virtual void SetUp() override { initialize(""); } }; diff --git a/test/extensions/filters/http/fault/config_test.cc b/test/extensions/filters/http/fault/config_test.cc index cac94593579a4..82bce8efd16ee 100644 --- a/test/extensions/filters/http/fault/config_test.cc +++ b/test/extensions/filters/http/fault/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/http/fault/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/http/fault/fault_filter_test.cc b/test/extensions/filters/http/fault/fault_filter_test.cc index 36963bdc285d4..18d464e20e20e 100644 --- a/test/extensions/filters/http/fault/fault_filter_test.cc +++ b/test/extensions/filters/http/fault/fault_filter_test.cc @@ -18,10 +18,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -36,7 +36,7 @@ namespace Extensions { namespace HttpFilters { namespace Fault { -class FaultFilterTest : public testing::Test { +class FaultFilterTest : public TestBase { public: const std::string fixed_delay_and_abort_nodes_json = R"EOF( { diff --git a/test/extensions/filters/http/grpc_http1_bridge/config_test.cc b/test/extensions/filters/http/grpc_http1_bridge/config_test.cc index 62eac3c9ed090..101aa36ff2873 100644 --- a/test/extensions/filters/http/grpc_http1_bridge/config_test.cc +++ b/test/extensions/filters/http/grpc_http1_bridge/config_test.cc @@ -1,9 +1,9 @@ #include "extensions/filters/http/grpc_http1_bridge/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc b/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc index 49bb87f4e868e..ac3bc03983821 100644 --- a/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc +++ b/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc @@ -6,10 +6,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -22,7 +22,7 @@ namespace Extensions { namespace HttpFilters { namespace GrpcHttp1Bridge { -class GrpcHttp1BridgeFilterTest : public testing::Test { +class GrpcHttp1BridgeFilterTest : public TestBase { public: GrpcHttp1BridgeFilterTest() : filter_() { filter_.setDecoderFilterCallbacks(decoder_callbacks_); diff --git a/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc b/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc index e46b5c84e75fc..eb07083c764ec 100644 --- a/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc +++ b/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc @@ -6,10 +6,10 @@ #include "test/integration/http_integration.h" #include "test/mocks/http/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" -#include "gtest/gtest.h" using Envoy::Http::HeaderValueOf; @@ -18,7 +18,7 @@ namespace Envoy { // Tests a downstream HTTP2 client sending gRPC requests that are converted into HTTP/1.1 for a // HTTP1 upstream. class ReverseBridgeIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: ReverseBridgeIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_test.cc b/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_test.cc index c9fc1527d05e6..8e36ee5ad7573 100644 --- a/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_test.cc +++ b/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_test.cc @@ -12,10 +12,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using Envoy::Http::HeaderValueOf; using testing::_; @@ -27,7 +27,7 @@ namespace Extensions { namespace HttpFilters { namespace GrpcHttp1ReverseBridge { -class ReverseBridgeTest : public testing::Test { +class ReverseBridgeTest : public TestBase { protected: void initialize(bool withhold_grpc_headers = true) { filter_ = std::make_unique("application/x-protobuf", withhold_grpc_headers); diff --git a/test/extensions/filters/http/grpc_json_transcoder/config_test.cc b/test/extensions/filters/http/grpc_json_transcoder/config_test.cc index 1a431615d6696..31f12b47d1cd1 100644 --- a/test/extensions/filters/http/grpc_json_transcoder/config_test.cc +++ b/test/extensions/filters/http/grpc_json_transcoder/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/http/grpc_json_transcoder/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc b/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc index b2477934ba2a0..64c63b6cbfdc8 100644 --- a/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc +++ b/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc @@ -6,10 +6,10 @@ #include "test/integration/http_integration.h" #include "test/mocks/http/mocks.h" #include "test/proto/bookstore.pb.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" -#include "gtest/gtest.h" using Envoy::Protobuf::Message; using Envoy::Protobuf::TextFormat; @@ -20,9 +20,8 @@ using Envoy::ProtobufWkt::Empty; namespace Envoy { -class GrpcJsonTranscoderIntegrationTest - : public HttpIntegrationTest, - public testing::TestWithParam { +class GrpcJsonTranscoderIntegrationTest : public HttpIntegrationTest, + public TestBaseWithParam { public: GrpcJsonTranscoderIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/grpc_json_transcoder/json_transcoder_filter_test.cc b/test/extensions/filters/http/grpc_json_transcoder/json_transcoder_filter_test.cc index 3fc56f08a66dd..f5ad48329deab 100644 --- a/test/extensions/filters/http/grpc_json_transcoder/json_transcoder_filter_test.cc +++ b/test/extensions/filters/http/grpc_json_transcoder/json_transcoder_filter_test.cc @@ -15,10 +15,10 @@ #include "test/proto/bookstore.pb.h" #include "test/test_common/environment.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -50,7 +50,7 @@ class GrpcJsonTranscoderFilterTestBase { Api::ApiPtr api_; }; -class GrpcJsonTranscoderConfigTest : public testing::Test, public GrpcJsonTranscoderFilterTestBase { +class GrpcJsonTranscoderConfigTest : public TestBase, public GrpcJsonTranscoderFilterTestBase { protected: const envoy::config::filter::http::transcoder::v2::GrpcJsonTranscoder getProtoConfig(const std::string& descriptor_path, const std::string& service_name, @@ -271,7 +271,7 @@ TEST_F(GrpcJsonTranscoderConfigTest, InvalidVariableBinding) { EXPECT_FALSE(transcoder); } -class GrpcJsonTranscoderFilterTest : public testing::Test, public GrpcJsonTranscoderFilterTestBase { +class GrpcJsonTranscoderFilterTest : public TestBase, public GrpcJsonTranscoderFilterTestBase { protected: GrpcJsonTranscoderFilterTest(const bool match_incoming_request_route = false) : config_(bookstoreProtoConfig(match_incoming_request_route), *api_), filter_(config_) { @@ -702,7 +702,7 @@ struct GrpcJsonTranscoderFilterPrintTestParam { }; class GrpcJsonTranscoderFilterPrintTest - : public testing::TestWithParam, + : public TestBaseWithParam, public GrpcJsonTranscoderFilterTestBase { protected: GrpcJsonTranscoderFilterPrintTest() { diff --git a/test/extensions/filters/http/grpc_json_transcoder/transcoder_input_stream_test.cc b/test/extensions/filters/http/grpc_json_transcoder/transcoder_input_stream_test.cc index e72c8beaa24ff..9d2d8aab8d80c 100644 --- a/test/extensions/filters/http/grpc_json_transcoder/transcoder_input_stream_test.cc +++ b/test/extensions/filters/http/grpc_json_transcoder/transcoder_input_stream_test.cc @@ -2,7 +2,7 @@ #include "extensions/filters/http/grpc_json_transcoder/transcoder_input_stream_impl.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { @@ -10,7 +10,7 @@ namespace HttpFilters { namespace GrpcJsonTranscoder { namespace { -class TranscoderInputStreamTest : public testing::Test { +class TranscoderInputStreamTest : public TestBase { public: TranscoderInputStreamTest() { Buffer::OwnedImpl buffer{"abcd"}; diff --git a/test/extensions/filters/http/grpc_web/config_test.cc b/test/extensions/filters/http/grpc_web/config_test.cc index 6035cd312dc54..8c1aa3729a560 100644 --- a/test/extensions/filters/http/grpc_web/config_test.cc +++ b/test/extensions/filters/http/grpc_web/config_test.cc @@ -1,9 +1,9 @@ #include "extensions/filters/http/grpc_web/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc b/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc index c9bad9b824a68..b9fcb90c96d50 100644 --- a/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc +++ b/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc @@ -12,10 +12,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Combine; @@ -45,7 +45,7 @@ const size_t TRAILERS_SIZE = sizeof(TRAILERS) - 1; } // namespace -class GrpcWebFilterTest : public testing::TestWithParam> { +class GrpcWebFilterTest : public TestBaseWithParam> { public: GrpcWebFilterTest() : filter_() { filter_.setDecoderFilterCallbacks(decoder_callbacks_); diff --git a/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc b/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc index 00e24d9bab558..aa56d03ee1e96 100644 --- a/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc +++ b/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc @@ -4,14 +4,13 @@ #include "test/integration/http_integration.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { class GzipIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: GzipIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), simTime()) {} diff --git a/test/extensions/filters/http/gzip/gzip_filter_test.cc b/test/extensions/filters/http/gzip/gzip_filter_test.cc index bfe1389dd7aaa..6161e095e5468 100644 --- a/test/extensions/filters/http/gzip/gzip_filter_test.cc +++ b/test/extensions/filters/http/gzip/gzip_filter_test.cc @@ -9,10 +9,9 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::Return; namespace Envoy { @@ -20,7 +19,7 @@ namespace Extensions { namespace HttpFilters { namespace Gzip { -class GzipFilterTest : public testing::Test { +class GzipFilterTest : public TestBase { protected: GzipFilterTest() { ON_CALL(runtime_.snapshot_, featureEnabled("gzip.filter_enabled", 100)) diff --git a/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc b/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc index f756d9c5f37b9..42f3973b4f54f 100644 --- a/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc +++ b/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc @@ -4,10 +4,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/stream_info/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -17,7 +17,7 @@ namespace Extensions { namespace HttpFilters { namespace HeaderToMetadataFilter { -class HeaderToMetadataTest : public testing::Test { +class HeaderToMetadataTest : public TestBase { public: HeaderToMetadataTest() {} diff --git a/test/extensions/filters/http/health_check/config_test.cc b/test/extensions/filters/http/health_check/config_test.cc index b2b7b33935608..fd7cb7bad3cd2 100644 --- a/test/extensions/filters/http/health_check/config_test.cc +++ b/test/extensions/filters/http/health_check/config_test.cc @@ -1,10 +1,10 @@ #include "extensions/filters/http/health_check/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/http/health_check/health_check_test.cc b/test/extensions/filters/http/health_check/health_check_test.cc index 8c13393197158..6aa280d235c6d 100644 --- a/test/extensions/filters/http/health_check/health_check_test.cc +++ b/test/extensions/filters/http/health_check/health_check_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/upstream/cluster_info.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -28,7 +28,7 @@ namespace Extensions { namespace HttpFilters { namespace HealthCheck { -class HealthCheckFilterTest : public testing::Test { +class HealthCheckFilterTest : public TestBase { public: HealthCheckFilterTest(bool pass_through, bool caching) : request_headers_{{":path", "/healthcheck"}}, request_headers_no_hc_{{":path", "/foo"}} { diff --git a/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc b/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc index b48b9a9f3ead5..69a47eb221e00 100644 --- a/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc +++ b/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc @@ -11,10 +11,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; @@ -25,7 +25,7 @@ namespace Extensions { namespace HttpFilters { namespace IpTagging { -class IpTaggingFilterTest : public testing::Test { +class IpTaggingFilterTest : public TestBase { public: IpTaggingFilterTest() { ON_CALL(runtime_.snapshot_, featureEnabled("ip_tagging.http_filter_enabled", 100)) diff --git a/test/extensions/filters/http/jwt_authn/all_verifier_test.cc b/test/extensions/filters/http/jwt_authn/all_verifier_test.cc index 59db8de2d8707..06f7f8ac9903f 100644 --- a/test/extensions/filters/http/jwt_authn/all_verifier_test.cc +++ b/test/extensions/filters/http/jwt_authn/all_verifier_test.cc @@ -17,7 +17,7 @@ namespace Extensions { namespace HttpFilters { namespace JwtAuthn { -class AllVerifierTest : public ::testing::Test { +class AllVerifierTest : public TestBase { public: void SetUp() { MessageUtil::loadFromYaml(ExampleConfig, proto_config_); } diff --git a/test/extensions/filters/http/jwt_authn/authenticator_test.cc b/test/extensions/filters/http/jwt_authn/authenticator_test.cc index e0d52927e2bc2..143120ff0c312 100644 --- a/test/extensions/filters/http/jwt_authn/authenticator_test.cc +++ b/test/extensions/filters/http/jwt_authn/authenticator_test.cc @@ -9,10 +9,9 @@ #include "test/extensions/filters/http/jwt_authn/mock.h" #include "test/extensions/filters/http/jwt_authn/test_common.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using ::envoy::config::filter::http::jwt_authn::v2alpha::JwtAuthentication; using Envoy::Extensions::HttpFilters::Common::JwksFetcher; using Envoy::Extensions::HttpFilters::Common::JwksFetcherPtr; @@ -28,7 +27,7 @@ namespace Extensions { namespace HttpFilters { namespace JwtAuthn { -class AuthenticatorTest : public ::testing::Test { +class AuthenticatorTest : public TestBase { public: void SetUp() { MessageUtil::loadFromYaml(ExampleConfig, proto_config_); diff --git a/test/extensions/filters/http/jwt_authn/extractor_test.cc b/test/extensions/filters/http/jwt_authn/extractor_test.cc index 49f9dfe3ea434..11aa484583fc7 100644 --- a/test/extensions/filters/http/jwt_authn/extractor_test.cc +++ b/test/extensions/filters/http/jwt_authn/extractor_test.cc @@ -48,7 +48,7 @@ const char ExampleConfig[] = R"( value_prefix: AAABBB )"; -class ExtractorTest : public ::testing::Test { +class ExtractorTest : public TestBase { public: void SetUp() { MessageUtil::loadFromYaml(ExampleConfig, config_); diff --git a/test/extensions/filters/http/jwt_authn/filter_factory_test.cc b/test/extensions/filters/http/jwt_authn/filter_factory_test.cc index dfb2c94ff5842..6f1b60f227683 100644 --- a/test/extensions/filters/http/jwt_authn/filter_factory_test.cc +++ b/test/extensions/filters/http/jwt_authn/filter_factory_test.cc @@ -4,9 +4,9 @@ #include "test/extensions/filters/http/jwt_authn/test_common.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using ::envoy::config::filter::http::jwt_authn::v2alpha::JwtAuthentication; using ::envoy::config::filter::http::jwt_authn::v2alpha::JwtProvider; diff --git a/test/extensions/filters/http/jwt_authn/filter_test.cc b/test/extensions/filters/http/jwt_authn/filter_test.cc index 71f7589698333..7c988a5ee91ac 100644 --- a/test/extensions/filters/http/jwt_authn/filter_test.cc +++ b/test/extensions/filters/http/jwt_authn/filter_test.cc @@ -3,10 +3,10 @@ #include "test/extensions/filters/http/jwt_authn/mock.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using ::envoy::config::filter::http::jwt_authn::v2alpha::JwtAuthentication; using ::google::jwt_verify::Status; @@ -33,7 +33,7 @@ class MockFilterConfig : public FilterConfig { MOCK_CONST_METHOD1(findVerifier, const Verifier*(const Http::HeaderMap& headers)); }; -class FilterTest : public ::testing::Test { +class FilterTest : public TestBase { public: void SetUp() { mock_config_ = ::std::make_shared(proto_config_, "", mock_context_); diff --git a/test/extensions/filters/http/jwt_authn/group_verifier_test.cc b/test/extensions/filters/http/jwt_authn/group_verifier_test.cc index 1f7b2ad14c4f5..66855054ef8ff 100644 --- a/test/extensions/filters/http/jwt_authn/group_verifier_test.cc +++ b/test/extensions/filters/http/jwt_authn/group_verifier_test.cc @@ -64,7 +64,7 @@ typedef std::unordered_map StatusMap; constexpr auto allowfailed = "_allow_failed_"; -class GroupVerifierTest : public ::testing::Test { +class GroupVerifierTest : public TestBase { public: void createVerifier() { ON_CALL(mock_factory_, create(_, _, _)) diff --git a/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc b/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc index 37871daea0862..b8daf0214ea6d 100644 --- a/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc +++ b/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc @@ -19,7 +19,7 @@ namespace HttpFilters { namespace JwtAuthn { namespace { -class JwksCacheTest : public ::testing::Test { +class JwksCacheTest : public TestBase { protected: JwksCacheTest() : api_(Api::createApiForTest(stats_)) {} void SetUp() { diff --git a/test/extensions/filters/http/jwt_authn/matcher_test.cc b/test/extensions/filters/http/jwt_authn/matcher_test.cc index 8adc79dbbc400..f0f916c78fd1d 100644 --- a/test/extensions/filters/http/jwt_authn/matcher_test.cc +++ b/test/extensions/filters/http/jwt_authn/matcher_test.cc @@ -23,7 +23,7 @@ namespace HttpFilters { namespace JwtAuthn { namespace { -class MatcherTest : public ::testing::Test { +class MatcherTest : public TestBase { public: }; diff --git a/test/extensions/filters/http/jwt_authn/provider_verifier_test.cc b/test/extensions/filters/http/jwt_authn/provider_verifier_test.cc index b0da46ef6b66b..33954a27453c4 100644 --- a/test/extensions/filters/http/jwt_authn/provider_verifier_test.cc +++ b/test/extensions/filters/http/jwt_authn/provider_verifier_test.cc @@ -27,7 +27,7 @@ ProtobufWkt::Struct getExpectedPayload(const std::string& name) { return struct_obj; } -class ProviderVerifierTest : public ::testing::Test { +class ProviderVerifierTest : public TestBase { public: void createVerifier() { filter_config_ = ::std::make_shared(proto_config_, "", mock_factory_ctx_); diff --git a/test/extensions/filters/http/lua/config_test.cc b/test/extensions/filters/http/lua/config_test.cc index f9c113fc1449e..e1de99b6f32c2 100644 --- a/test/extensions/filters/http/lua/config_test.cc +++ b/test/extensions/filters/http/lua/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/http/lua/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/http/lua/lua_filter_test.cc b/test/extensions/filters/http/lua/lua_filter_test.cc index 7e9d9486d3fda..4955cb1b4ffcf 100644 --- a/test/extensions/filters/http/lua/lua_filter_test.cc +++ b/test/extensions/filters/http/lua/lua_filter_test.cc @@ -37,7 +37,7 @@ class TestFilter : public Filter { MOCK_METHOD2(scriptLog, void(spdlog::level::level_enum level, const char* message)); }; -class LuaHttpFilterTest : public testing::Test { +class LuaHttpFilterTest : public TestBase { public: LuaHttpFilterTest() { // Avoid strict mock failures for the following calls. We want strict for other calls. diff --git a/test/extensions/filters/http/lua/lua_integration_test.cc b/test/extensions/filters/http/lua/lua_integration_test.cc index cc7d04ac871df..9af429f4aef6c 100644 --- a/test/extensions/filters/http/lua/lua_integration_test.cc +++ b/test/extensions/filters/http/lua/lua_integration_test.cc @@ -1,15 +1,14 @@ #include "extensions/filters/http/well_known_names.h" #include "test/integration/http_integration.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace { class LuaIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: LuaIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/ratelimit/config_test.cc b/test/extensions/filters/http/ratelimit/config_test.cc index 8ce784acf917e..7b6ae66567a40 100644 --- a/test/extensions/filters/http/ratelimit/config_test.cc +++ b/test/extensions/filters/http/ratelimit/config_test.cc @@ -6,9 +6,9 @@ #include "extensions/filters/http/ratelimit/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ReturnRef; diff --git a/test/extensions/filters/http/ratelimit/ratelimit_test.cc b/test/extensions/filters/http/ratelimit/ratelimit_test.cc index 5ee6c2881c49c..ca5583c2569b4 100644 --- a/test/extensions/filters/http/ratelimit/ratelimit_test.cc +++ b/test/extensions/filters/http/ratelimit/ratelimit_test.cc @@ -18,10 +18,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -37,7 +37,7 @@ namespace Extensions { namespace HttpFilters { namespace RateLimitFilter { -class HttpRateLimitFilterTest : public testing::Test { +class HttpRateLimitFilterTest : public TestBase { public: HttpRateLimitFilterTest() { ON_CALL(runtime_.snapshot_, featureEnabled("ratelimit.http_filter_enabled", 100)) diff --git a/test/extensions/filters/http/rbac/config_test.cc b/test/extensions/filters/http/rbac/config_test.cc index 6085958c10717..646b527f0fed7 100644 --- a/test/extensions/filters/http/rbac/config_test.cc +++ b/test/extensions/filters/http/rbac/config_test.cc @@ -2,9 +2,9 @@ #include "extensions/filters/http/rbac/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/filters/http/rbac/rbac_filter_test.cc b/test/extensions/filters/http/rbac/rbac_filter_test.cc index bdeb72975287d..0ff7ddc7bedea 100644 --- a/test/extensions/filters/http/rbac/rbac_filter_test.cc +++ b/test/extensions/filters/http/rbac/rbac_filter_test.cc @@ -21,7 +21,7 @@ namespace HttpFilters { namespace RBACFilter { namespace { -class RoleBasedAccessControlFilterTest : public testing::Test { +class RoleBasedAccessControlFilterTest : public TestBase { public: RoleBasedAccessControlFilterConfigSharedPtr setupConfig() { envoy::config::filter::http::rbac::v2::RBAC config; diff --git a/test/extensions/filters/http/router/config_test.cc b/test/extensions/filters/http/router/config_test.cc index 89732808e5784..5c444d16e0cef 100644 --- a/test/extensions/filters/http/router/config_test.cc +++ b/test/extensions/filters/http/router/config_test.cc @@ -4,9 +4,9 @@ #include "extensions/filters/http/router/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/http/squash/config_test.cc b/test/extensions/filters/http/squash/config_test.cc index 278cd0e50996a..71e0828690c71 100644 --- a/test/extensions/filters/http/squash/config_test.cc +++ b/test/extensions/filters/http/squash/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/http/squash/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/http/squash/squash_filter_integration_test.cc b/test/extensions/filters/http/squash/squash_filter_integration_test.cc index af6823c1f963b..1ad01eb2283dc 100644 --- a/test/extensions/filters/http/squash/squash_filter_integration_test.cc +++ b/test/extensions/filters/http/squash/squash_filter_integration_test.cc @@ -17,7 +17,7 @@ using Envoy::Protobuf::util::MessageDifferencer; namespace Envoy { class SquashFilterIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: SquashFilterIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/squash/squash_filter_test.cc b/test/extensions/filters/http/squash/squash_filter_test.cc index c7f2c7fcf4e86..f9289e3269bd9 100644 --- a/test/extensions/filters/http/squash/squash_filter_test.cc +++ b/test/extensions/filters/http/squash/squash_filter_test.cc @@ -11,11 +11,11 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "fmt/format.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -164,7 +164,7 @@ TEST(SoloFilterConfigTest, ParsesEnvironmentInComplexTemplate) { EXPECT_JSON_EQ(expected_json, config.attachmentJson()); } -class SquashFilterTest : public testing::Test { +class SquashFilterTest : public TestBase { public: SquashFilterTest() : request_(&cm_.async_client_) {} diff --git a/test/extensions/filters/http/tap/tap_filter_integration_test.cc b/test/extensions/filters/http/tap/tap_filter_integration_test.cc index dc258d3ef67ab..84c3623d640d1 100644 --- a/test/extensions/filters/http/tap/tap_filter_integration_test.cc +++ b/test/extensions/filters/http/tap/tap_filter_integration_test.cc @@ -1,15 +1,15 @@ #include "envoy/data/tap/v2alpha/wrapper.pb.h" #include "test/integration/http_integration.h" +#include "test/test_common/test_base.h" #include "absl/strings/match.h" -#include "gtest/gtest.h" namespace Envoy { namespace { class TapIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: TapIntegrationTest() // Note: This test must use HTTP/2 because of the lack of early close detection for diff --git a/test/extensions/filters/http/tap/tap_filter_test.cc b/test/extensions/filters/http/tap/tap_filter_test.cc index d605488ea68b8..2c982c71fddb7 100644 --- a/test/extensions/filters/http/tap/tap_filter_test.cc +++ b/test/extensions/filters/http/tap/tap_filter_test.cc @@ -2,10 +2,10 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/stream_info/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::InSequence; using testing::Return; @@ -46,7 +46,7 @@ class MockHttpPerRequestTapper : public HttpPerRequestTapper { const Http::HeaderMap* response_trailers)); }; -class TapFilterTest : public testing::Test { +class TapFilterTest : public TestBase { public: void setup(bool has_config) { if (has_config) { diff --git a/test/extensions/filters/listener/original_src/config_test.cc b/test/extensions/filters/listener/original_src/config_test.cc index 4efe2c2c0f673..59f0e483f857a 100644 --- a/test/extensions/filters/listener/original_src/config_test.cc +++ b/test/extensions/filters/listener/original_src/config_test.cc @@ -5,7 +5,7 @@ #include "extensions/filters/listener/original_src/config.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { @@ -15,7 +15,7 @@ namespace { // In keeping with the class under test, it would have made sense to call this ConfigTest. However, // when running coverage tests, that conflicts with tests elsewhere in the codebase. -class OriginalSrcConfigTest : public testing::Test { +class OriginalSrcConfigTest : public TestBase { public: Config makeConfigFromProto( const envoy::config::filter::listener::original_src::v2alpha1::OriginalSrc& proto_config) { diff --git a/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc b/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc index 5fe8755dce72e..4ef3c0735373b 100644 --- a/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc +++ b/test/extensions/filters/listener/original_src/original_src_config_factory_test.cc @@ -6,9 +6,9 @@ #include "extensions/filters/listener/original_src/original_src_config_factory.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::Invoke; diff --git a/test/extensions/filters/listener/original_src/original_src_socket_option_test.cc b/test/extensions/filters/listener/original_src/original_src_socket_option_test.cc index 98e0c8c71a973..fdf555e7f4041 100644 --- a/test/extensions/filters/listener/original_src/original_src_socket_option_test.cc +++ b/test/extensions/filters/listener/original_src/original_src_socket_option_test.cc @@ -7,9 +7,9 @@ #include "test/mocks/common.h" #include "test/mocks/network/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Eq; @@ -20,7 +20,7 @@ namespace ListenerFilters { namespace OriginalSrc { namespace { -class OriginalSrcSocketOptionTest : public testing::Test { +class OriginalSrcSocketOptionTest : public TestBase { public: std::unique_ptr makeOptionByAddress(const Network::Address::InstanceConstSharedPtr& address) { diff --git a/test/extensions/filters/listener/original_src/original_src_test.cc b/test/extensions/filters/listener/original_src/original_src_test.cc index 23b5f700248b4..c76dd4ee6a4fd 100644 --- a/test/extensions/filters/listener/original_src/original_src_test.cc +++ b/test/extensions/filters/listener/original_src/original_src_test.cc @@ -10,9 +10,9 @@ #include "test/mocks/common.h" #include "test/mocks/network/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Exactly; @@ -24,7 +24,7 @@ namespace ListenerFilters { namespace OriginalSrc { namespace { -class OriginalSrcTest : public testing::Test { +class OriginalSrcTest : public TestBase { public: std::unique_ptr makeDefaultFilter() { Config default_config; diff --git a/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc b/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc index 6420a10e21384..50fae0a437564 100644 --- a/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc +++ b/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc @@ -22,12 +22,12 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -44,7 +44,7 @@ namespace ProxyProtocol { // Build again on the basis of the connection_handler_test.cc -class ProxyProtocolTest : public testing::TestWithParam, +class ProxyProtocolTest : public TestBaseWithParam, public Network::ListenerConfig, public Network::FilterChainManager, protected Logger::Loggable { @@ -865,7 +865,7 @@ TEST_P(ProxyProtocolTest, ClosedEmpty) { dispatcher_.run(Event::Dispatcher::RunType::NonBlock); } -class WildcardProxyProtocolTest : public testing::TestWithParam, +class WildcardProxyProtocolTest : public TestBaseWithParam, public Network::ListenerConfig, public Network::FilterChainManager, protected Logger::Loggable { diff --git a/test/extensions/filters/listener/tls_inspector/tls_inspector_benchmark.cc b/test/extensions/filters/listener/tls_inspector/tls_inspector_benchmark.cc index f2bc9964595d2..880edc3066fd0 100644 --- a/test/extensions/filters/listener/tls_inspector/tls_inspector_benchmark.cc +++ b/test/extensions/filters/listener/tls_inspector/tls_inspector_benchmark.cc @@ -9,10 +9,10 @@ #include "test/mocks/api/mocks.h" #include "test/mocks/network/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "benchmark/benchmark.h" -#include "gtest/gtest.h" #include "openssl/ssl.h" using testing::_; diff --git a/test/extensions/filters/listener/tls_inspector/tls_inspector_test.cc b/test/extensions/filters/listener/tls_inspector/tls_inspector_test.cc index a5a8fe37a726c..d51d1d9fa4418 100644 --- a/test/extensions/filters/listener/tls_inspector/tls_inspector_test.cc +++ b/test/extensions/filters/listener/tls_inspector/tls_inspector_test.cc @@ -6,9 +6,9 @@ #include "test/mocks/api/mocks.h" #include "test/mocks/network/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" -#include "gtest/gtest.h" #include "openssl/ssl.h" using testing::_; @@ -28,7 +28,7 @@ namespace Extensions { namespace ListenerFilters { namespace TlsInspector { -class TlsInspectorTest : public testing::Test { +class TlsInspectorTest : public TestBase { public: TlsInspectorTest() : cfg_(std::make_shared(store_)), diff --git a/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc b/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc index dce254914ad3d..2c6a78b380ac8 100644 --- a/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc +++ b/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc @@ -15,10 +15,10 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -55,7 +55,7 @@ TEST(ClientSslAuthConfigTest, BadClientSslAuthConfig) { Json::Exception); } -class ClientSslAuthFilterTest : public testing::Test { +class ClientSslAuthFilterTest : public TestBase { protected: ClientSslAuthFilterTest() : request_(&cm_.async_client_), interval_timer_(new Event::MockTimer(&dispatcher_)), diff --git a/test/extensions/filters/network/client_ssl_auth/config_test.cc b/test/extensions/filters/network/client_ssl_auth/config_test.cc index f25758b1b3cbd..bca273c01dd59 100644 --- a/test/extensions/filters/network/client_ssl_auth/config_test.cc +++ b/test/extensions/filters/network/client_ssl_auth/config_test.cc @@ -6,9 +6,9 @@ #include "extensions/filters/network/well_known_names.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; @@ -17,7 +17,7 @@ namespace Extensions { namespace NetworkFilters { namespace ClientSslAuth { -class IpWhiteListConfigTest : public ::testing::TestWithParam {}; +class IpWhiteListConfigTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpList, IpWhiteListConfigTest, ::testing::Values(R"EOF(["192.168.3.0/24"])EOF", diff --git a/test/extensions/filters/network/dubbo_proxy/config_test.cc b/test/extensions/filters/network/dubbo_proxy/config_test.cc index 11e5e3f5ef018..fd21b7c409791 100644 --- a/test/extensions/filters/network/dubbo_proxy/config_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/network/dubbo_proxy/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/network/dubbo_proxy/dubbo_protocol_impl_test.cc b/test/extensions/filters/network/dubbo_proxy/dubbo_protocol_impl_test.cc index 44ba352e6e003..387b25bab2417 100644 --- a/test/extensions/filters/network/dubbo_proxy/dubbo_protocol_impl_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/dubbo_protocol_impl_test.cc @@ -4,10 +4,10 @@ #include "test/extensions/filters/network/dubbo_proxy/mocks.h" #include "test/extensions/filters/network/dubbo_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/network/dubbo_proxy/filter_test.cc b/test/extensions/filters/network/dubbo_proxy/filter_test.cc index 024224ce63358..32eda7490e800 100644 --- a/test/extensions/filters/network/dubbo_proxy/filter_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/filter_test.cc @@ -10,9 +10,9 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; @@ -25,7 +25,7 @@ using ConfigProtocolType = envoy::config::filter::network::dubbo_proxy::v2alpha1 using ConfigSerializationType = envoy::config::filter::network::dubbo_proxy::v2alpha1::SerializationType; -class DubboFilterTest : public testing::Test { +class DubboFilterTest : public TestBase { public: DubboFilterTest() {} diff --git a/test/extensions/filters/network/dubbo_proxy/hessian_deserializer_impl_test.cc b/test/extensions/filters/network/dubbo_proxy/hessian_deserializer_impl_test.cc index a2c5b22a08c86..370ab9c1c5880 100644 --- a/test/extensions/filters/network/dubbo_proxy/hessian_deserializer_impl_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/hessian_deserializer_impl_test.cc @@ -3,10 +3,10 @@ #include "test/extensions/filters/network/dubbo_proxy/mocks.h" #include "test/extensions/filters/network/dubbo_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NotNull; diff --git a/test/extensions/filters/network/dubbo_proxy/hessian_utils_test.cc b/test/extensions/filters/network/dubbo_proxy/hessian_utils_test.cc index dfb721f30f4be..080e61e8f5c8f 100644 --- a/test/extensions/filters/network/dubbo_proxy/hessian_utils_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/hessian_utils_test.cc @@ -3,10 +3,9 @@ #include "extensions/filters/network/dubbo_proxy/hessian_utils.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { diff --git a/test/extensions/filters/network/dubbo_proxy/metadata_test.cc b/test/extensions/filters/network/dubbo_proxy/metadata_test.cc index f89179cd637cb..8340941610369 100644 --- a/test/extensions/filters/network/dubbo_proxy/metadata_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/metadata_test.cc @@ -1,6 +1,6 @@ #include "extensions/filters/network/dubbo_proxy/metadata.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/network/dubbo_proxy/mocks.cc b/test/extensions/filters/network/dubbo_proxy/mocks.cc index 2075536058f46..2cc0a101e242a 100644 --- a/test/extensions/filters/network/dubbo_proxy/mocks.cc +++ b/test/extensions/filters/network/dubbo_proxy/mocks.cc @@ -4,7 +4,7 @@ #include "common/protobuf/utility.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc b/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc index ebf53c63914e9..b5e8df89812fa 100644 --- a/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/route_matcher_test.cc @@ -7,7 +7,7 @@ #include "extensions/filters/network/dubbo_proxy/router/route_matcher.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/network/ext_authz/config_test.cc b/test/extensions/filters/network/ext_authz/config_test.cc index 2d955119a1a77..8ae3c47dd39fd 100644 --- a/test/extensions/filters/network/ext_authz/config_test.cc +++ b/test/extensions/filters/network/ext_authz/config_test.cc @@ -4,9 +4,9 @@ #include "extensions/filters/network/ext_authz/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/network/ext_authz/ext_authz_test.cc b/test/extensions/filters/network/ext_authz/ext_authz_test.cc index e334b75a46499..06440f8d8a14b 100644 --- a/test/extensions/filters/network/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/network/ext_authz/ext_authz_test.cc @@ -18,9 +18,9 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -35,7 +35,7 @@ namespace Extensions { namespace NetworkFilters { namespace ExtAuthz { -class ExtAuthzFilterTest : public testing::Test { +class ExtAuthzFilterTest : public TestBase { public: ExtAuthzFilterTest() { std::string json = R"EOF( diff --git a/test/extensions/filters/network/http_connection_manager/config_test.cc b/test/extensions/filters/network/http_connection_manager/config_test.cc index 8f1cbb7b16d6e..4fe6b5d7cc92d 100644 --- a/test/extensions/filters/network/http_connection_manager/config_test.cc +++ b/test/extensions/filters/network/http_connection_manager/config_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ContainerEq; @@ -43,7 +43,7 @@ parseHttpConnectionManagerFromV2Yaml(const std::string& yaml) { return http_connection_manager; } -class HttpConnectionManagerConfigTest : public testing::Test { +class HttpConnectionManagerConfigTest : public TestBase { public: NiceMock context_; Http::SlowDateProviderImpl date_provider_{context_.dispatcher().timeSystem()}; diff --git a/test/extensions/filters/network/mongo_proxy/bson_impl_test.cc b/test/extensions/filters/network/mongo_proxy/bson_impl_test.cc index 9bbe1a1bbc660..df3afaf5ccbaa 100644 --- a/test/extensions/filters/network/mongo_proxy/bson_impl_test.cc +++ b/test/extensions/filters/network/mongo_proxy/bson_impl_test.cc @@ -5,8 +5,7 @@ #include "extensions/filters/network/mongo_proxy/bson_impl.h" #include "test/test_common/printers.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/network/mongo_proxy/codec_impl_test.cc b/test/extensions/filters/network/mongo_proxy/codec_impl_test.cc index 350af0c22f4a9..231ec814ef4e5 100644 --- a/test/extensions/filters/network/mongo_proxy/codec_impl_test.cc +++ b/test/extensions/filters/network/mongo_proxy/codec_impl_test.cc @@ -7,9 +7,9 @@ #include "extensions/filters/network/mongo_proxy/codec_impl.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::Eq; using testing::NiceMock; @@ -41,7 +41,7 @@ class TestDecoderCallbacks : public DecoderCallbacks { MOCK_METHOD1(decodeCommandReply_, void(CommandReplyMessagePtr& message)); }; -class MongoCodecImplTest : public testing::Test { +class MongoCodecImplTest : public TestBase { public: Buffer::OwnedImpl output_; EncoderImpl encoder_{output_}; diff --git a/test/extensions/filters/network/mongo_proxy/config_test.cc b/test/extensions/filters/network/mongo_proxy/config_test.cc index 2c2c20379b695..b830022b6c24a 100644 --- a/test/extensions/filters/network/mongo_proxy/config_test.cc +++ b/test/extensions/filters/network/mongo_proxy/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/network/mongo_proxy/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/network/mongo_proxy/proxy_test.cc b/test/extensions/filters/network/mongo_proxy/proxy_test.cc index 740bc4fc32c1f..63dddf1a4194e 100644 --- a/test/extensions/filters/network/mongo_proxy/proxy_test.cc +++ b/test/extensions/filters/network/mongo_proxy/proxy_test.cc @@ -18,9 +18,9 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/runtime/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -60,7 +60,7 @@ class TestProxyFilter : public ProxyFilter { DecoderCallbacks* callbacks_{}; }; -class MongoProxyFilterTest : public testing::Test { +class MongoProxyFilterTest : public TestBase { public: MongoProxyFilterTest() { setup(); } diff --git a/test/extensions/filters/network/mongo_proxy/utility_test.cc b/test/extensions/filters/network/mongo_proxy/utility_test.cc index d297f9394c8b4..f15524711c82e 100644 --- a/test/extensions/filters/network/mongo_proxy/utility_test.cc +++ b/test/extensions/filters/network/mongo_proxy/utility_test.cc @@ -4,7 +4,7 @@ #include "extensions/filters/network/mongo_proxy/codec_impl.h" #include "extensions/filters/network/mongo_proxy/utility.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc index 97a17d4b96a9f..e724eb6011990 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc @@ -5,8 +5,9 @@ #include "extensions/filters/network/mysql_proxy/mysql_codec_greeting.h" #include "extensions/filters/network/mysql_proxy/mysql_utils.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "mysql_test_utils.h" namespace Envoy { @@ -19,7 +20,7 @@ constexpr int MYSQL_UT_LAST_ID = 0; constexpr int MYSQL_UT_SERVER_OK = 0; constexpr int MYSQL_UT_SERVER_WARNINGS = 0x0001; -class MySQLCodecTest : public MySQLTestUtils, public testing::Test { +class MySQLCodecTest : public MySQLTestUtils, public TestBase { protected: uint64_t offset_{0}; }; diff --git a/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc index a0c6ca81d7f8a..ce6cc1795045f 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc @@ -5,8 +5,9 @@ #include "extensions/filters/network/mysql_proxy/mysql_codec_greeting.h" #include "extensions/filters/network/mysql_proxy/mysql_utils.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "include/sqlparser/SQLParser.h" #include "mysql_test_utils.h" @@ -15,7 +16,7 @@ namespace Extensions { namespace NetworkFilters { namespace MySQLProxy { -class MySQLCommandTest : public MySQLTestUtils, public testing::Test { +class MySQLCommandTest : public MySQLTestUtils, public TestBase { public: int encodeQuery(std::string query, hsql::SQLParserResult& result) { Command mysql_cmd_encode{}; diff --git a/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc index 11e6e1c335ae6..cd5e80a547f5e 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/network/mysql_proxy/mysql_utils.h" #include "test/mocks/network/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "mysql_test_utils.h" using testing::NiceMock; @@ -17,7 +17,7 @@ namespace MySQLProxy { constexpr int SESSIONS = 5; -class MySQLFilterTest : public MySQLTestUtils, public testing::Test { +class MySQLFilterTest : public MySQLTestUtils, public TestBase { public: MySQLFilterTest() { ENVOY_LOG_MISC(info, "test"); } diff --git a/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc index 02e72eb07cb06..0c5adcb1691c9 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc @@ -11,9 +11,9 @@ #include "test/integration/utility.h" #include "test/mocks/network/mocks.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "mysql_test_utils.h" #include "rapidjson/document.h" @@ -28,7 +28,7 @@ constexpr int SESSIONS = 5; class MySQLIntegrationTest : public MySQLTestUtils, public BaseIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { std::string mysqlConfig() { return TestEnvironment::readFileToStringForTest(TestEnvironment::runfilesPath( "test/extensions/filters/network/mysql_proxy/mysql_test_config.yaml")); diff --git a/test/extensions/filters/network/ratelimit/config_test.cc b/test/extensions/filters/network/ratelimit/config_test.cc index c15553fa49db2..1019092538dcb 100644 --- a/test/extensions/filters/network/ratelimit/config_test.cc +++ b/test/extensions/filters/network/ratelimit/config_test.cc @@ -6,9 +6,9 @@ #include "extensions/filters/network/ratelimit/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ReturnRef; diff --git a/test/extensions/filters/network/ratelimit/ratelimit_test.cc b/test/extensions/filters/network/ratelimit/ratelimit_test.cc index eb6b9ee4db80c..2d3babd20ddd7 100644 --- a/test/extensions/filters/network/ratelimit/ratelimit_test.cc +++ b/test/extensions/filters/network/ratelimit/ratelimit_test.cc @@ -16,9 +16,9 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -32,7 +32,7 @@ namespace Extensions { namespace NetworkFilters { namespace RateLimitFilter { -class RateLimitFilterTest : public testing::Test { +class RateLimitFilterTest : public TestBase { public: RateLimitFilterTest() {} diff --git a/test/extensions/filters/network/rbac/config_test.cc b/test/extensions/filters/network/rbac/config_test.cc index 3479f43d032a4..62e1bc9bde113 100644 --- a/test/extensions/filters/network/rbac/config_test.cc +++ b/test/extensions/filters/network/rbac/config_test.cc @@ -3,10 +3,10 @@ #include "extensions/filters/network/rbac/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "fmt/printf.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -23,7 +23,7 @@ const std::string header = R"EOF( } // namespace -class RoleBasedAccessControlNetworkFilterConfigFactoryTest : public testing::Test { +class RoleBasedAccessControlNetworkFilterConfigFactoryTest : public TestBase { public: void validateRule(const std::string& policy_json) { checkRule(fmt::sprintf(policy_json, header)); diff --git a/test/extensions/filters/network/rbac/filter_test.cc b/test/extensions/filters/network/rbac/filter_test.cc index feb084d5714c6..031db15b7aba3 100644 --- a/test/extensions/filters/network/rbac/filter_test.cc +++ b/test/extensions/filters/network/rbac/filter_test.cc @@ -17,7 +17,7 @@ namespace Extensions { namespace NetworkFilters { namespace RBACFilter { -class RoleBasedAccessControlNetworkFilterTest : public testing::Test { +class RoleBasedAccessControlNetworkFilterTest : public TestBase { public: RoleBasedAccessControlFilterConfigSharedPtr setupConfig(bool with_policy = true, bool continuous = false) { diff --git a/test/extensions/filters/network/rbac/integration_test.cc b/test/extensions/filters/network/rbac/integration_test.cc index 753eb2c7b6f22..2e1d83186b9b4 100644 --- a/test/extensions/filters/network/rbac/integration_test.cc +++ b/test/extensions/filters/network/rbac/integration_test.cc @@ -16,7 +16,7 @@ std::string rbac_config; class RoleBasedAccessControlNetworkFilterIntegrationTest : public BaseIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: RoleBasedAccessControlNetworkFilterIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), rbac_config) {} diff --git a/test/extensions/filters/network/redis_proxy/codec_impl_test.cc b/test/extensions/filters/network/redis_proxy/codec_impl_test.cc index 9ecf214707635..1a53711ac9df9 100644 --- a/test/extensions/filters/network/redis_proxy/codec_impl_test.cc +++ b/test/extensions/filters/network/redis_proxy/codec_impl_test.cc @@ -7,16 +7,15 @@ #include "test/extensions/filters/network/redis_proxy/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { namespace RedisProxy { -class RedisEncoderDecoderImplTest : public testing::Test, public DecoderCallbacks { +class RedisEncoderDecoderImplTest : public TestBase, public DecoderCallbacks { public: RedisEncoderDecoderImplTest() : decoder_(*this) {} diff --git a/test/extensions/filters/network/redis_proxy/command_splitter_impl_test.cc b/test/extensions/filters/network/redis_proxy/command_splitter_impl_test.cc index 2fc502a26ebfa..0e4b53d16eb2c 100644 --- a/test/extensions/filters/network/redis_proxy/command_splitter_impl_test.cc +++ b/test/extensions/filters/network/redis_proxy/command_splitter_impl_test.cc @@ -14,9 +14,9 @@ #include "test/mocks/stats/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ByRef; @@ -35,7 +35,7 @@ namespace NetworkFilters { namespace RedisProxy { namespace CommandSplitter { -class RedisCommandSplitterImplTest : public testing::Test { +class RedisCommandSplitterImplTest : public TestBase { public: void makeBulkStringArray(RespValue& value, const std::vector& strings) { std::vector values(strings.size()); diff --git a/test/extensions/filters/network/redis_proxy/config_test.cc b/test/extensions/filters/network/redis_proxy/config_test.cc index 074862e5718c8..ca5a7b5305cbd 100644 --- a/test/extensions/filters/network/redis_proxy/config_test.cc +++ b/test/extensions/filters/network/redis_proxy/config_test.cc @@ -5,9 +5,9 @@ #include "extensions/filters/network/redis_proxy/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; diff --git a/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc b/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc index eaa065ac28f9c..95f0d84dfa4de 100644 --- a/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc +++ b/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc @@ -11,9 +11,9 @@ #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::DoAll; @@ -39,7 +39,7 @@ createConnPoolSettings() { return setting; } -class RedisClientImplTest : public testing::Test, public DecoderFactory { +class RedisClientImplTest : public TestBase, public DecoderFactory { public: // RedisProxy::DecoderFactory DecoderPtr create(DecoderCallbacks& callbacks) override { @@ -380,7 +380,7 @@ TEST(RedisClientFactoryImplTest, Basic) { client->close(); } -class RedisConnPoolImplTest : public testing::Test, public ClientFactory { +class RedisConnPoolImplTest : public TestBase, public ClientFactory { public: void setup(bool cluster_exists = true) { EXPECT_CALL(cm_, addThreadLocalClusterUpdateCallbacks_(_)) diff --git a/test/extensions/filters/network/redis_proxy/mocks.cc b/test/extensions/filters/network/redis_proxy/mocks.cc index c3283870c80d1..b18f0efed0e10 100644 --- a/test/extensions/filters/network/redis_proxy/mocks.cc +++ b/test/extensions/filters/network/redis_proxy/mocks.cc @@ -4,8 +4,9 @@ #include "common/common/assert.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/network/redis_proxy/proxy_filter_test.cc b/test/extensions/filters/network/redis_proxy/proxy_filter_test.cc index 9861b10e88f0f..b1a097f4386c7 100644 --- a/test/extensions/filters/network/redis_proxy/proxy_filter_test.cc +++ b/test/extensions/filters/network/redis_proxy/proxy_filter_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ByRef; @@ -40,7 +40,7 @@ parseProtoFromJson(const std::string& json_string) { return config; } -class RedisProxyFilterConfigTest : public testing::Test { +class RedisProxyFilterConfigTest : public TestBase { public: Stats::IsolatedStoreImpl store_; Network::MockDrainDecision drain_decision_; @@ -73,7 +73,7 @@ TEST_F(RedisProxyFilterConfigTest, BadRedisProxyConfig) { EXPECT_THROW(parseProtoFromJson(json_string), Json::Exception); } -class RedisProxyFilterTest : public testing::Test, public DecoderFactory { +class RedisProxyFilterTest : public TestBase, public DecoderFactory { public: RedisProxyFilterTest() { std::string json_string = R"EOF( diff --git a/test/extensions/filters/network/sni_cluster/sni_cluster_test.cc b/test/extensions/filters/network/sni_cluster/sni_cluster_test.cc index 9cc39bd6d2e61..4ce86542422d7 100644 --- a/test/extensions/filters/network/sni_cluster/sni_cluster_test.cc +++ b/test/extensions/filters/network/sni_cluster/sni_cluster_test.cc @@ -6,9 +6,9 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/mocks/stream_info/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Matcher; diff --git a/test/extensions/filters/network/tcp_proxy/config_test.cc b/test/extensions/filters/network/tcp_proxy/config_test.cc index 542b4414044f0..5300b146f2df9 100644 --- a/test/extensions/filters/network/tcp_proxy/config_test.cc +++ b/test/extensions/filters/network/tcp_proxy/config_test.cc @@ -1,9 +1,9 @@ #include "extensions/filters/network/tcp_proxy/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; @@ -12,7 +12,7 @@ namespace Extensions { namespace NetworkFilters { namespace TcpProxy { -class RouteIpListConfigTest : public ::testing::TestWithParam {}; +class RouteIpListConfigTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpList, RouteIpListConfigTest, ::testing::Values(R"EOF("destination_ip_list": [ diff --git a/test/extensions/filters/network/thrift_proxy/app_exception_impl_test.cc b/test/extensions/filters/network/thrift_proxy/app_exception_impl_test.cc index 245ecd9423abb..c755f35a5a8e5 100644 --- a/test/extensions/filters/network/thrift_proxy/app_exception_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/app_exception_impl_test.cc @@ -3,9 +3,9 @@ #include "extensions/filters/network/thrift_proxy/app_exception_impl.h" #include "test/extensions/filters/network/thrift_proxy/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::InSequence; using testing::Ref; diff --git a/test/extensions/filters/network/thrift_proxy/auto_protocol_impl_test.cc b/test/extensions/filters/network/thrift_proxy/auto_protocol_impl_test.cc index ffb756103f0d3..93a61e1f4a186 100644 --- a/test/extensions/filters/network/thrift_proxy/auto_protocol_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/auto_protocol_impl_test.cc @@ -10,10 +10,10 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::Ref; @@ -25,7 +25,7 @@ namespace Extensions { namespace NetworkFilters { namespace ThriftProxy { -class AutoProtocolTest : public testing::Test { +class AutoProtocolTest : public TestBase { public: void resetMetadata() { metadata_.setMethodName("-"); diff --git a/test/extensions/filters/network/thrift_proxy/auto_transport_impl_test.cc b/test/extensions/filters/network/thrift_proxy/auto_transport_impl_test.cc index e451dbdd6f85f..ae5d12408aaa6 100644 --- a/test/extensions/filters/network/thrift_proxy/auto_transport_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/auto_transport_impl_test.cc @@ -7,10 +7,10 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::Ref; diff --git a/test/extensions/filters/network/thrift_proxy/binary_protocol_impl_test.cc b/test/extensions/filters/network/thrift_proxy/binary_protocol_impl_test.cc index a3ea1d80a0cbc..68052ae7abc21 100644 --- a/test/extensions/filters/network/thrift_proxy/binary_protocol_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/binary_protocol_impl_test.cc @@ -6,16 +6,15 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { namespace ThriftProxy { -class BinaryProtocolTest : public testing::Test { +class BinaryProtocolTest : public TestBase { public: void resetMetadata() { metadata_.setMethodName("-"); diff --git a/test/extensions/filters/network/thrift_proxy/buffer_helper_test.cc b/test/extensions/filters/network/thrift_proxy/buffer_helper_test.cc index 0f2a1b0cdb3ad..8cdcf8453b2d2 100644 --- a/test/extensions/filters/network/thrift_proxy/buffer_helper_test.cc +++ b/test/extensions/filters/network/thrift_proxy/buffer_helper_test.cc @@ -8,10 +8,9 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { diff --git a/test/extensions/filters/network/thrift_proxy/compact_protocol_impl_test.cc b/test/extensions/filters/network/thrift_proxy/compact_protocol_impl_test.cc index 4ceed3eec0281..70ba1cb05b9c9 100644 --- a/test/extensions/filters/network/thrift_proxy/compact_protocol_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/compact_protocol_impl_test.cc @@ -6,11 +6,9 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - -using testing::TestWithParam; using testing::Values; namespace Envoy { @@ -18,7 +16,7 @@ namespace Extensions { namespace NetworkFilters { namespace ThriftProxy { -class CompactProtocolTest : public testing::Test { +class CompactProtocolTest : public TestBase { public: void resetMetadata() { metadata_.setMethodName("-"); @@ -998,7 +996,7 @@ TEST_F(CompactProtocolTest, ReadBinary) { EXPECT_EQ(buffer.length(), 0); } -class CompactProtocolFieldTypeTest : public TestWithParam {}; +class CompactProtocolFieldTypeTest : public TestBaseWithParam {}; TEST_P(CompactProtocolFieldTypeTest, ConvertsToFieldType) { uint8_t compact_field_type = GetParam(); diff --git a/test/extensions/filters/network/thrift_proxy/config_test.cc b/test/extensions/filters/network/thrift_proxy/config_test.cc index 823c9ba56d057..df1765741e06b 100644 --- a/test/extensions/filters/network/thrift_proxy/config_test.cc +++ b/test/extensions/filters/network/thrift_proxy/config_test.cc @@ -6,9 +6,9 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; @@ -67,11 +67,11 @@ class ThriftFilterConfigTestBase { ThriftProxyFilterConfigFactory factory_; }; -class ThriftFilterConfigTest : public ThriftFilterConfigTestBase, public testing::Test {}; +class ThriftFilterConfigTest : public ThriftFilterConfigTestBase, public TestBase {}; class ThriftFilterTransportConfigTest : public ThriftFilterConfigTestBase, - public testing::TestWithParam< + public TestBaseWithParam< envoy::config::filter::network::thrift_proxy::v2alpha1::TransportType> {}; INSTANTIATE_TEST_SUITE_P(TransportTypes, ThriftFilterTransportConfigTest, @@ -79,7 +79,7 @@ INSTANTIATE_TEST_SUITE_P(TransportTypes, ThriftFilterTransportConfigTest, class ThriftFilterProtocolConfigTest : public ThriftFilterConfigTestBase, - public testing::TestWithParam< + public TestBaseWithParam< envoy::config::filter::network::thrift_proxy::v2alpha1::ProtocolType> {}; INSTANTIATE_TEST_SUITE_P(ProtocolTypes, ThriftFilterProtocolConfigTest, diff --git a/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc b/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc index fc5d156b3ccac..45dfc7e78b85e 100644 --- a/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc +++ b/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc @@ -17,9 +17,9 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -70,7 +70,7 @@ class TestConfigImpl : public ConfigImpl { MockProtocol* protocol_{}; }; -class ThriftConnectionManagerTest : public testing::Test { +class ThriftConnectionManagerTest : public TestBase { public: ThriftConnectionManagerTest() : stats_(ThriftFilterStats::generateStats("test.", store_)) {} ~ThriftConnectionManagerTest() { diff --git a/test/extensions/filters/network/thrift_proxy/conn_state_test.cc b/test/extensions/filters/network/thrift_proxy/conn_state_test.cc index 5a875e9cc9875..63d71848e9e35 100644 --- a/test/extensions/filters/network/thrift_proxy/conn_state_test.cc +++ b/test/extensions/filters/network/thrift_proxy/conn_state_test.cc @@ -1,6 +1,6 @@ #include "extensions/filters/network/thrift_proxy/conn_state.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/filters/network/thrift_proxy/decoder_test.cc b/test/extensions/filters/network/thrift_proxy/decoder_test.cc index ad2670c1af21c..8cfa92bc37433 100644 --- a/test/extensions/filters/network/thrift_proxy/decoder_test.cc +++ b/test/extensions/filters/network/thrift_proxy/decoder_test.cc @@ -6,11 +6,11 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/string_view.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AnyNumber; @@ -26,8 +26,7 @@ using testing::Return; using testing::ReturnRef; using testing::SetArgReferee; using testing::StrictMock; -using testing::TestParamInfo; -using testing::TestWithParam; +using ::testing::TestParamInfo; using testing::Values; namespace Envoy { @@ -190,7 +189,7 @@ class DecoderStateMachineTestBase { }; class DecoderStateMachineNonValueTest : public DecoderStateMachineTestBase, - public TestWithParam {}; + public TestBaseWithParam {}; static std::string protoStateParamToString(const TestParamInfo& params) { return ProtocolStateNameValues::name(params.param); @@ -205,10 +204,10 @@ INSTANTIATE_TEST_SUITE_P(NonValueProtocolStates, DecoderStateMachineNonValueTest ProtocolState::SetBegin, ProtocolState::SetEnd), protoStateParamToString); -class DecoderStateMachineTest : public DecoderStateMachineTestBase, public testing::Test {}; +class DecoderStateMachineTest : public DecoderStateMachineTestBase, public TestBase {}; class DecoderStateMachineValueTest : public DecoderStateMachineTestBase, - public TestWithParam {}; + public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(PrimitiveFieldTypes, DecoderStateMachineValueTest, Values(FieldType::Bool, FieldType::Byte, FieldType::Double, FieldType::I16, @@ -217,7 +216,7 @@ INSTANTIATE_TEST_SUITE_P(PrimitiveFieldTypes, DecoderStateMachineValueTest, class DecoderStateMachineNestingTest : public DecoderStateMachineTestBase, - public TestWithParam> {}; + public TestBaseWithParam> {}; static std::string nestedFieldTypesParamToString( const TestParamInfo>& params) { diff --git a/test/extensions/filters/network/thrift_proxy/filters/ratelimit/config_test.cc b/test/extensions/filters/network/thrift_proxy/filters/ratelimit/config_test.cc index 93ad98c5202dc..d3913a8c2f3e7 100644 --- a/test/extensions/filters/network/thrift_proxy/filters/ratelimit/config_test.cc +++ b/test/extensions/filters/network/thrift_proxy/filters/ratelimit/config_test.cc @@ -5,9 +5,9 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ReturnRef; diff --git a/test/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit_test.cc b/test/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit_test.cc index 76ec64e8ab1c6..06fbdd7c47763 100644 --- a/test/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit_test.cc +++ b/test/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit_test.cc @@ -18,10 +18,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -39,7 +39,7 @@ namespace RateLimitFilter { using namespace Envoy::Extensions::NetworkFilters; -class ThriftRateLimitFilterTest : public testing::Test { +class ThriftRateLimitFilterTest : public TestBase { public: ThriftRateLimitFilterTest() { ON_CALL(runtime_.snapshot_, featureEnabled("ratelimit.thrift_filter_enabled", 100)) diff --git a/test/extensions/filters/network/thrift_proxy/framed_transport_impl_test.cc b/test/extensions/filters/network/thrift_proxy/framed_transport_impl_test.cc index f3afa26d2f101..ff4401140cdca 100644 --- a/test/extensions/filters/network/thrift_proxy/framed_transport_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/framed_transport_impl_test.cc @@ -6,10 +6,9 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { diff --git a/test/extensions/filters/network/thrift_proxy/header_transport_impl_test.cc b/test/extensions/filters/network/thrift_proxy/header_transport_impl_test.cc index 3884eac7862db..83296dd6e9c0d 100644 --- a/test/extensions/filters/network/thrift_proxy/header_transport_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/header_transport_impl_test.cc @@ -8,10 +8,10 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/mocks/buffer/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::Return; diff --git a/test/extensions/filters/network/thrift_proxy/integration_test.cc b/test/extensions/filters/network/thrift_proxy/integration_test.cc index bfea576f2872b..afe0d34a869f6 100644 --- a/test/extensions/filters/network/thrift_proxy/integration_test.cc +++ b/test/extensions/filters/network/thrift_proxy/integration_test.cc @@ -3,12 +3,10 @@ #include "test/extensions/filters/network/thrift_proxy/integration.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::Combine; -using testing::TestParamInfo; -using testing::TestWithParam; +using ::testing::TestParamInfo; using testing::Values; namespace Envoy { @@ -18,7 +16,7 @@ namespace ThriftProxy { class ThriftConnManagerIntegrationTest : public BaseThriftIntegrationTest, - public TestWithParam> { + public TestBaseWithParam> { public: static void SetUpTestSuite() { thrift_config_ = ConfigHelper::BASE_CONFIG + R"EOF( diff --git a/test/extensions/filters/network/thrift_proxy/metadata_test.cc b/test/extensions/filters/network/thrift_proxy/metadata_test.cc index 17bd4a0aaeb8c..a4eb46415cc61 100644 --- a/test/extensions/filters/network/thrift_proxy/metadata_test.cc +++ b/test/extensions/filters/network/thrift_proxy/metadata_test.cc @@ -1,10 +1,9 @@ #include "extensions/filters/network/thrift_proxy/metadata.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { diff --git a/test/extensions/filters/network/thrift_proxy/mocks.cc b/test/extensions/filters/network/thrift_proxy/mocks.cc index e32c0a6547820..fa4b6c13301b1 100644 --- a/test/extensions/filters/network/thrift_proxy/mocks.cc +++ b/test/extensions/filters/network/thrift_proxy/mocks.cc @@ -2,7 +2,7 @@ #include "common/protobuf/protobuf.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::_; using testing::Invoke; diff --git a/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc b/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc index 274285884f04e..8025b5ecf1457 100644 --- a/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc +++ b/test/extensions/filters/network/thrift_proxy/route_matcher_test.cc @@ -5,10 +5,9 @@ #include "extensions/filters/network/thrift_proxy/router/router_impl.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::_; namespace Envoy { diff --git a/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc b/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc index 92b2a3be00ce8..9bd8bda646899 100644 --- a/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc +++ b/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc @@ -13,9 +13,9 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/mocks/ratelimit/mocks.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::ContainerEq; using testing::NiceMock; @@ -27,7 +27,7 @@ namespace ThriftProxy { namespace Router { namespace { -class ThriftRateLimitConfigurationTest : public testing::Test { +class ThriftRateLimitConfigurationTest : public TestBase { public: void initialize(const std::string& yaml) { envoy::config::filter::network::thrift_proxy::v2alpha1::ThriftProxy config; @@ -168,7 +168,7 @@ TEST_F(ThriftRateLimitConfigurationTest, Stages) { EXPECT_TRUE(rate_limits.empty()); } -class ThriftRateLimitPolicyEntryTest : public testing::Test { +class ThriftRateLimitPolicyEntryTest : public TestBase { public: void initialize(const std::string yaml) { envoy::api::v2::route::RateLimit rate_limit; diff --git a/test/extensions/filters/network/thrift_proxy/router_test.cc b/test/extensions/filters/network/thrift_proxy/router_test.cc index 8082baed3f713..082328dfad5d0 100644 --- a/test/extensions/filters/network/thrift_proxy/router_test.cc +++ b/test/extensions/filters/network/thrift_proxy/router_test.cc @@ -17,9 +17,9 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ContainsRegex; @@ -29,7 +29,6 @@ using testing::NiceMock; using testing::Ref; using testing::Return; using testing::ReturnRef; -using testing::TestWithParam; using testing::Values; namespace Envoy { @@ -329,11 +328,11 @@ class ThriftRouterTestBase { NiceMock upstream_connection_; }; -class ThriftRouterTest : public ThriftRouterTestBase, public testing::Test { +class ThriftRouterTest : public ThriftRouterTestBase, public TestBase { public: }; -class ThriftRouterFieldTypeTest : public ThriftRouterTestBase, public TestWithParam { +class ThriftRouterFieldTypeTest : public ThriftRouterTestBase, public TestBaseWithParam { public: }; @@ -342,7 +341,7 @@ INSTANTIATE_TEST_SUITE_P(PrimitiveFieldTypes, ThriftRouterFieldTypeTest, FieldType::I64, FieldType::Double, FieldType::String), fieldTypeParamToString); -class ThriftRouterContainerTest : public ThriftRouterTestBase, public TestWithParam { +class ThriftRouterContainerTest : public ThriftRouterTestBase, public TestBaseWithParam { public: }; diff --git a/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc b/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc index f0df6641e6bc4..6b209fcc54bd7 100644 --- a/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc @@ -5,10 +5,10 @@ #include "test/extensions/filters/network/thrift_proxy/mocks.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::AnyNumber; using testing::Expectation; @@ -18,7 +18,6 @@ using testing::NiceMock; using testing::Ref; using testing::Return; using testing::ReturnRef; -using testing::TestWithParam; using testing::Values; namespace Envoy { @@ -143,7 +142,7 @@ class ThriftObjectImplTestBase { Buffer::OwnedImpl buffer_; }; -class ThriftObjectImplTest : public ThriftObjectImplTestBase, public testing::Test {}; +class ThriftObjectImplTest : public ThriftObjectImplTestBase, public TestBase {}; // Test parsing an empty struct (just a stop field). TEST_F(ThriftObjectImplTest, ParseEmptyStruct) { @@ -163,7 +162,7 @@ TEST_F(ThriftObjectImplTest, ParseEmptyStruct) { } class ThriftObjectImplValueTest : public ThriftObjectImplTestBase, - public TestWithParam {}; + public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(PrimitiveFieldTypes, ThriftObjectImplValueTest, Values(FieldType::Bool, FieldType::Byte, FieldType::Double, FieldType::I16, diff --git a/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc b/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc index 6997d9345ce01..3db1c54e6ba71 100644 --- a/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc +++ b/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc @@ -5,12 +5,10 @@ #include "test/extensions/filters/network/thrift_proxy/integration.h" #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::Combine; -using testing::TestParamInfo; -using testing::TestWithParam; +using ::testing::TestParamInfo; using testing::Values; namespace Envoy { @@ -20,7 +18,8 @@ namespace ThriftProxy { class ThriftTranslationIntegrationTest : public BaseThriftIntegrationTest, - public TestWithParam> { + public TestBaseWithParam< + std::tuple> { public: static void SetUpTestSuite() { thrift_config_ = ConfigHelper::BASE_CONFIG + R"EOF( diff --git a/test/extensions/filters/network/thrift_proxy/twitter_protocol_impl_test.cc b/test/extensions/filters/network/thrift_proxy/twitter_protocol_impl_test.cc index 5b1b77b9ae78e..388ce5e5fa7f8 100644 --- a/test/extensions/filters/network/thrift_proxy/twitter_protocol_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/twitter_protocol_impl_test.cc @@ -7,10 +7,9 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { @@ -36,7 +35,7 @@ class TestTwitterProtocolImpl : public TwitterProtocolImpl { } }; -class TwitterProtocolTest : public testing::Test { +class TwitterProtocolTest : public TestBase { public: void clearMetadata() { metadata_.reset(new MessageMetadata()); } diff --git a/test/extensions/filters/network/thrift_proxy/unframed_transport_impl_test.cc b/test/extensions/filters/network/thrift_proxy/unframed_transport_impl_test.cc index 48097a6f1c2a6..564c3df40130e 100644 --- a/test/extensions/filters/network/thrift_proxy/unframed_transport_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/unframed_transport_impl_test.cc @@ -4,10 +4,9 @@ #include "test/extensions/filters/network/thrift_proxy/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace NetworkFilters { diff --git a/test/extensions/filters/network/thrift_proxy/utility.h b/test/extensions/filters/network/thrift_proxy/utility.h index d4fd19bb537e2..3843375925766 100644 --- a/test/extensions/filters/network/thrift_proxy/utility.h +++ b/test/extensions/filters/network/thrift_proxy/utility.h @@ -10,12 +10,12 @@ #include "extensions/filters/network/thrift_proxy/thrift.h" #include "test/common/buffer/utility.h" +#include "test/test_common/test_base.h" #include "absl/strings/ascii.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" -using testing::TestParamInfo; +using ::testing::TestParamInfo; namespace Envoy { namespace Extensions { diff --git a/test/extensions/health_checkers/redis/redis_test.cc b/test/extensions/health_checkers/redis/redis_test.cc index 1fa714c68d90a..31579144ae373 100644 --- a/test/extensions/health_checkers/redis/redis_test.cc +++ b/test/extensions/health_checkers/redis/redis_test.cc @@ -25,7 +25,7 @@ namespace HealthCheckers { namespace RedisHealthChecker { class RedisHealthCheckerTest - : public testing::Test, + : public TestBase, public Extensions::NetworkFilters::RedisProxy::ConnPool::ClientFactory { public: RedisHealthCheckerTest() diff --git a/test/extensions/quic_listeners/quiche/dummy_test.cc b/test/extensions/quic_listeners/quiche/dummy_test.cc index 1d454c41e6a91..1624fd52ff946 100644 --- a/test/extensions/quic_listeners/quiche/dummy_test.cc +++ b/test/extensions/quic_listeners/quiche/dummy_test.cc @@ -1,6 +1,7 @@ #include "extensions/quic_listeners/quiche/dummy.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" + #include "quiche/http2/platform/api/http2_string.h" namespace Envoy { diff --git a/test/extensions/quic_listeners/quiche/platform/http2_platform_test.cc b/test/extensions/quic_listeners/quiche/platform/http2_platform_test.cc index 788c0c53921ec..4f16a1a16442e 100644 --- a/test/extensions/quic_listeners/quiche/platform/http2_platform_test.cc +++ b/test/extensions/quic_listeners/quiche/platform/http2_platform_test.cc @@ -1,6 +1,7 @@ #include -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" + #include "quiche/http2/platform/api/http2_arraysize.h" #include "quiche/http2/platform/api/http2_containers.h" #include "quiche/http2/platform/api/http2_estimate_memory_usage.h" diff --git a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc index b13e141ea2221..ed5222930ebb0 100644 --- a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc +++ b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc @@ -1,4 +1,5 @@ -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" + #include "quiche/quic/platform/api/quic_aligned.h" #include "quiche/quic/platform/api/quic_arraysize.h" #include "quiche/quic/platform/api/quic_containers.h" diff --git a/test/extensions/quic_listeners/quiche/platform/spdy_platform_test.cc b/test/extensions/quic_listeners/quiche/platform/spdy_platform_test.cc index 7e6ff7a6494b1..c2322424f53ea 100644 --- a/test/extensions/quic_listeners/quiche/platform/spdy_platform_test.cc +++ b/test/extensions/quic_listeners/quiche/platform/spdy_platform_test.cc @@ -1,6 +1,7 @@ #include -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" + #include "quiche/spdy/platform/api/spdy_arraysize.h" #include "quiche/spdy/platform/api/spdy_containers.h" #include "quiche/spdy/platform/api/spdy_endianness_util.h" diff --git a/test/extensions/resource_monitors/fixed_heap/config_test.cc b/test/extensions/resource_monitors/fixed_heap/config_test.cc index fb73abee200f8..edc9e54d44f68 100644 --- a/test/extensions/resource_monitors/fixed_heap/config_test.cc +++ b/test/extensions/resource_monitors/fixed_heap/config_test.cc @@ -8,8 +8,7 @@ #include "extensions/resource_monitors/fixed_heap/config.h" #include "test/mocks/event/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/resource_monitors/fixed_heap/fixed_heap_monitor_test.cc b/test/extensions/resource_monitors/fixed_heap/fixed_heap_monitor_test.cc index 637d5fe2a9433..699d119bc75b7 100644 --- a/test/extensions/resource_monitors/fixed_heap/fixed_heap_monitor_test.cc +++ b/test/extensions/resource_monitors/fixed_heap/fixed_heap_monitor_test.cc @@ -1,8 +1,9 @@ #include "extensions/resource_monitors/fixed_heap/fixed_heap_monitor.h" +#include "test/test_common/test_base.h" + #include "absl/types/optional.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/resource_monitors/injected_resource/config_test.cc b/test/extensions/resource_monitors/injected_resource/config_test.cc index 371ad3b115149..59f9cbfb37138 100644 --- a/test/extensions/resource_monitors/injected_resource/config_test.cc +++ b/test/extensions/resource_monitors/injected_resource/config_test.cc @@ -9,11 +9,10 @@ #include "extensions/resource_monitors/injected_resource/config.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace ResourceMonitors { diff --git a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc index c0fa0dd7c8ae2..5b2c5d862d988 100644 --- a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc +++ b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc @@ -6,13 +6,13 @@ #include "extensions/resource_monitors/injected_resource/injected_resource_monitor.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { @@ -43,7 +43,7 @@ class MockedCallbacks : public Server::ResourceMonitor::Callbacks { MOCK_METHOD1(onFailure, void(const EnvoyException&)); }; -class InjectedResourceMonitorTest : public testing::Test { +class InjectedResourceMonitorTest : public TestBase { protected: InjectedResourceMonitorTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_), diff --git a/test/extensions/retry/host/previous_hosts/config_test.cc b/test/extensions/retry/host/previous_hosts/config_test.cc index aed15a272c441..02621aabba0e9 100644 --- a/test/extensions/retry/host/previous_hosts/config_test.cc +++ b/test/extensions/retry/host/previous_hosts/config_test.cc @@ -5,9 +5,9 @@ #include "extensions/retry/host/well_known_names.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using namespace testing; diff --git a/test/extensions/retry/priority/previous_priorities/config_test.cc b/test/extensions/retry/priority/previous_priorities/config_test.cc index 9d4f0bfe09041..76933ba71092a 100644 --- a/test/extensions/retry/priority/previous_priorities/config_test.cc +++ b/test/extensions/retry/priority/previous_priorities/config_test.cc @@ -6,9 +6,9 @@ #include "extensions/retry/priority/well_known_names.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using namespace testing; @@ -17,7 +17,7 @@ namespace Extensions { namespace Retry { namespace Priority { -class RetryPriorityTest : public ::testing::Test { +class RetryPriorityTest : public TestBase { public: void initialize(const Upstream::HealthyLoad& original_healthy_priority_load, const Upstream::DegradedLoad& original_degraded_priority_load) { diff --git a/test/extensions/stats_sinks/common/statsd/statsd_test.cc b/test/extensions/stats_sinks/common/statsd/statsd_test.cc index 28e8cf180893c..4aa7c7f597c00 100644 --- a/test/extensions/stats_sinks/common/statsd/statsd_test.cc +++ b/test/extensions/stats_sinks/common/statsd/statsd_test.cc @@ -13,9 +13,9 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -29,7 +29,7 @@ namespace StatSinks { namespace Common { namespace Statsd { -class TcpStatsdSinkTest : public testing::Test { +class TcpStatsdSinkTest : public TestBase { public: TcpStatsdSinkTest() { sink_ = std::make_unique( diff --git a/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc b/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc index 85454d3fd6615..dbf8bac660b2a 100644 --- a/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc +++ b/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc @@ -9,10 +9,10 @@ #include "test/mocks/thread_local/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "spdlog/spdlog.h" using testing::NiceMock; @@ -28,7 +28,7 @@ class MockWriter : public Writer { MOCK_METHOD1(write, void(const std::string& message)); }; -class UdpStatsdSinkTest : public testing::TestWithParam {}; +class UdpStatsdSinkTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, UdpStatsdSinkTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); @@ -72,7 +72,7 @@ TEST_P(UdpStatsdSinkTest, InitWithIpAddress) { tls_.shutdownThread(); } -class UdpStatsdSinkWithTagsTest : public testing::TestWithParam {}; +class UdpStatsdSinkWithTagsTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, UdpStatsdSinkWithTagsTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); diff --git a/test/extensions/stats_sinks/dog_statsd/config_test.cc b/test/extensions/stats_sinks/dog_statsd/config_test.cc index a7d00a70f4d30..f73630a470bdf 100644 --- a/test/extensions/stats_sinks/dog_statsd/config_test.cc +++ b/test/extensions/stats_sinks/dog_statsd/config_test.cc @@ -11,10 +11,10 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -26,7 +26,7 @@ namespace Extensions { namespace StatSinks { namespace DogStatsd { -class DogStatsdConfigLoopbackTest : public testing::TestWithParam {}; +class DogStatsdConfigLoopbackTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, DogStatsdConfigLoopbackTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); diff --git a/test/extensions/stats_sinks/hystrix/config_test.cc b/test/extensions/stats_sinks/hystrix/config_test.cc index abcdcca16910f..f1a0557f610d5 100644 --- a/test/extensions/stats_sinks/hystrix/config_test.cc +++ b/test/extensions/stats_sinks/hystrix/config_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/stats_sinks/hystrix/hystrix_test.cc b/test/extensions/stats_sinks/hystrix/hystrix_test.cc index baf24727a0b31..1e20bc4effb0b 100644 --- a/test/extensions/stats_sinks/hystrix/hystrix_test.cc +++ b/test/extensions/stats_sinks/hystrix/hystrix_test.cc @@ -8,12 +8,12 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "absl/strings/str_split.h" #include "circllhist.h" #include "fmt/printf.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::HasSubstr; @@ -116,7 +116,7 @@ class HistogramWrapper { histogram_t* histogram_; }; -class HystrixSinkTest : public testing::Test { +class HystrixSinkTest : public TestBase { public: HystrixSinkTest() { sink_ = std::make_unique(server_, window_size_); } diff --git a/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc b/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc index 932a5ee8adb38..6b9d66f195694 100644 --- a/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc +++ b/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc @@ -19,7 +19,7 @@ namespace Extensions { namespace StatSinks { namespace MetricsService { -class GrpcMetricsStreamerImplTest : public testing::Test { +class GrpcMetricsStreamerImplTest : public TestBase { public: typedef Grpc::MockAsyncStream MockMetricsStream; typedef Grpc::TypedAsyncStreamCallbacks @@ -95,7 +95,7 @@ class TestGrpcMetricsStreamer : public GrpcMetricsStreamer { } }; -class MetricsServiceSinkTest : public testing::Test {}; +class MetricsServiceSinkTest : public TestBase {}; TEST(MetricsServiceSinkTest, CheckSendCall) { NiceMock source; diff --git a/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc b/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc index 696bdceb3e970..476dce27a5d49 100644 --- a/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc +++ b/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc @@ -8,10 +8,9 @@ #include "test/common/grpc/grpc_client_integration.h" #include "test/integration/http_integration.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::AssertionResult; namespace Envoy { diff --git a/test/extensions/stats_sinks/statsd/config_test.cc b/test/extensions/stats_sinks/statsd/config_test.cc index 17bc912432c3e..66c249445c618 100644 --- a/test/extensions/stats_sinks/statsd/config_test.cc +++ b/test/extensions/stats_sinks/statsd/config_test.cc @@ -12,10 +12,10 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; @@ -46,7 +46,7 @@ TEST(StatsConfigTest, ValidTcpStatsd) { EXPECT_NE(dynamic_cast(sink.get()), nullptr); } -class StatsConfigParameterizedTest : public testing::TestWithParam {}; +class StatsConfigParameterizedTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, StatsConfigParameterizedTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), @@ -163,7 +163,7 @@ TEST(StatsConfigTest, TcpSinkCustomPrefix) { EXPECT_EQ(tcp_sink->getPrefix(), prefix); } -class StatsConfigLoopbackTest : public testing::TestWithParam {}; +class StatsConfigLoopbackTest : public TestBaseWithParam {}; INSTANTIATE_TEST_SUITE_P(IpVersions, StatsConfigLoopbackTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); diff --git a/test/extensions/tracers/common/ot/opentracing_driver_impl_test.cc b/test/extensions/tracers/common/ot/opentracing_driver_impl_test.cc index c826495f54bce..fb9aa7c1228aa 100644 --- a/test/extensions/tracers/common/ot/opentracing_driver_impl_test.cc +++ b/test/extensions/tracers/common/ot/opentracing_driver_impl_test.cc @@ -5,9 +5,9 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/mocks/tracing/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "opentracing/mocktracer/in_memory_recorder.h" #include "opentracing/mocktracer/tracer.h" @@ -44,7 +44,7 @@ class TestDriver : public OpenTracingDriver { std::shared_ptr tracer_; }; -class OpenTracingDriverTest : public testing::Test { +class OpenTracingDriverTest : public TestBase { public: void setupValidDriver(OpenTracingDriver::PropagationMode propagation_mode = diff --git a/test/extensions/tracers/datadog/config_test.cc b/test/extensions/tracers/datadog/config_test.cc index a4f9b1947000b..49659cda9c188 100644 --- a/test/extensions/tracers/datadog/config_test.cc +++ b/test/extensions/tracers/datadog/config_test.cc @@ -1,9 +1,9 @@ #include "extensions/tracers/datadog/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/tracers/datadog/datadog_tracer_impl_test.cc b/test/extensions/tracers/datadog/datadog_tracer_impl_test.cc index f9cd337dc5ffc..951b4ec673f9f 100644 --- a/test/extensions/tracers/datadog/datadog_tracer_impl_test.cc +++ b/test/extensions/tracers/datadog/datadog_tracer_impl_test.cc @@ -21,10 +21,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtLeast; @@ -38,7 +38,7 @@ namespace Extensions { namespace Tracers { namespace Datadog { -class DatadogDriverTest : public testing::Test { +class DatadogDriverTest : public TestBase { public: void setup(envoy::config::trace::v2::DatadogConfig& datadog_config, bool init_timer) { ON_CALL(cm_, httpAsyncClientForCluster("fake_cluster")) diff --git a/test/extensions/tracers/dynamic_ot/config_test.cc b/test/extensions/tracers/dynamic_ot/config_test.cc index abe86ef705795..074efca2258e1 100644 --- a/test/extensions/tracers/dynamic_ot/config_test.cc +++ b/test/extensions/tracers/dynamic_ot/config_test.cc @@ -2,10 +2,10 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "fmt/printf.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/tracers/dynamic_ot/dynamic_opentracing_driver_impl_test.cc b/test/extensions/tracers/dynamic_ot/dynamic_opentracing_driver_impl_test.cc index 3e75240289bc4..a4789b82b76fa 100644 --- a/test/extensions/tracers/dynamic_ot/dynamic_opentracing_driver_impl_test.cc +++ b/test/extensions/tracers/dynamic_ot/dynamic_opentracing_driver_impl_test.cc @@ -8,17 +8,17 @@ #include "test/mocks/stats/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "fmt/printf.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { namespace Tracers { namespace DynamicOt { -class DynamicOpenTracingDriverTest : public testing::Test { +class DynamicOpenTracingDriverTest : public TestBase { public: void setup(const std::string& library, const std::string& tracer_config) { driver_ = std::make_unique(stats_, library, tracer_config); diff --git a/test/extensions/tracers/lightstep/config_test.cc b/test/extensions/tracers/lightstep/config_test.cc index 173d3b1c1bc62..ec0f129d4efc2 100644 --- a/test/extensions/tracers/lightstep/config_test.cc +++ b/test/extensions/tracers/lightstep/config_test.cc @@ -1,9 +1,9 @@ #include "extensions/tracers/lightstep/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/extensions/tracers/lightstep/lightstep_tracer_impl_test.cc b/test/extensions/tracers/lightstep/lightstep_tracer_impl_test.cc index 5bbd6c6c2e02f..ac34b3bb8abd3 100644 --- a/test/extensions/tracers/lightstep/lightstep_tracer_impl_test.cc +++ b/test/extensions/tracers/lightstep/lightstep_tracer_impl_test.cc @@ -22,10 +22,10 @@ #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AtLeast; @@ -39,7 +39,7 @@ namespace Extensions { namespace Tracers { namespace Lightstep { -class LightStepDriverTest : public testing::Test { +class LightStepDriverTest : public TestBase { public: void setup(envoy::config::trace::v2::LightstepConfig& lightstep_config, bool init_timer, Common::Ot::OpenTracingDriver::PropagationMode propagation_mode = diff --git a/test/extensions/tracers/zipkin/config_test.cc b/test/extensions/tracers/zipkin/config_test.cc index 017c7344f6b9e..f9ced3f656112 100644 --- a/test/extensions/tracers/zipkin/config_test.cc +++ b/test/extensions/tracers/zipkin/config_test.cc @@ -3,9 +3,9 @@ #include "extensions/tracers/zipkin/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { diff --git a/test/extensions/tracers/zipkin/span_buffer_test.cc b/test/extensions/tracers/zipkin/span_buffer_test.cc index 987e059efdbb6..4e31f1574592d 100644 --- a/test/extensions/tracers/zipkin/span_buffer_test.cc +++ b/test/extensions/tracers/zipkin/span_buffer_test.cc @@ -1,9 +1,8 @@ #include "extensions/tracers/zipkin/span_buffer.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace Tracers { diff --git a/test/extensions/tracers/zipkin/span_context_extractor_test.cc b/test/extensions/tracers/zipkin/span_context_extractor_test.cc index a88815b173c51..19f47d6ad4cf7 100644 --- a/test/extensions/tracers/zipkin/span_context_extractor_test.cc +++ b/test/extensions/tracers/zipkin/span_context_extractor_test.cc @@ -3,10 +3,9 @@ #include "extensions/tracers/zipkin/span_context.h" #include "extensions/tracers/zipkin/span_context_extractor.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace Tracers { diff --git a/test/extensions/tracers/zipkin/tracer_test.cc b/test/extensions/tracers/zipkin/tracer_test.cc index d564ea71a3d80..5f8683f02b8b5 100644 --- a/test/extensions/tracers/zipkin/tracer_test.cc +++ b/test/extensions/tracers/zipkin/tracer_test.cc @@ -11,10 +11,10 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::Return; @@ -36,7 +36,7 @@ class TestReporterImpl : public Reporter { std::vector reported_spans_; }; -class ZipkinTracerTest : public testing::Test { +class ZipkinTracerTest : public TestBase { protected: Event::SimulatedTimeSystem time_system_; }; diff --git a/test/extensions/tracers/zipkin/util_test.cc b/test/extensions/tracers/zipkin/util_test.cc index 3383409837e3e..da23564fcdf15 100644 --- a/test/extensions/tracers/zipkin/util_test.cc +++ b/test/extensions/tracers/zipkin/util_test.cc @@ -1,9 +1,8 @@ #include "extensions/tracers/zipkin/util.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace Tracers { diff --git a/test/extensions/tracers/zipkin/zipkin_core_types_test.cc b/test/extensions/tracers/zipkin/zipkin_core_types_test.cc index a534e6b6e9c04..8ee41672f36e2 100644 --- a/test/extensions/tracers/zipkin/zipkin_core_types_test.cc +++ b/test/extensions/tracers/zipkin/zipkin_core_types_test.cc @@ -5,10 +5,9 @@ #include "extensions/tracers/zipkin/zipkin_core_constants.h" #include "extensions/tracers/zipkin/zipkin_core_types.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Extensions { namespace Tracers { diff --git a/test/extensions/tracers/zipkin/zipkin_tracer_impl_test.cc b/test/extensions/tracers/zipkin/zipkin_tracer_impl_test.cc index 28fb6d2087652..5b65d2650ff1c 100644 --- a/test/extensions/tracers/zipkin/zipkin_tracer_impl_test.cc +++ b/test/extensions/tracers/zipkin/zipkin_tracer_impl_test.cc @@ -21,10 +21,10 @@ #include "test/mocks/thread_local/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -37,7 +37,7 @@ namespace Extensions { namespace Tracers { namespace Zipkin { -class ZipkinDriverTest : public testing::Test { +class ZipkinDriverTest : public TestBase { public: ZipkinDriverTest() : time_source_(test_time_.timeSystem()) {} diff --git a/test/extensions/transport_sockets/alts/alts_integration_test.cc b/test/extensions/transport_sockets/alts/alts_integration_test.cc index 39a2884e6d736..c4edaaac6d92c 100644 --- a/test/extensions/transport_sockets/alts/alts_integration_test.cc +++ b/test/extensions/transport_sockets/alts/alts_integration_test.cc @@ -11,6 +11,7 @@ #include "test/integration/utility.h" #include "test/mocks/server/mocks.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" @@ -18,7 +19,6 @@ #include "gmock/gmock.h" #include "grpcpp/grpcpp.h" #include "grpcpp/impl/codegen/service_type.h" -#include "gtest/gtest.h" namespace Envoy { namespace Extensions { @@ -26,7 +26,7 @@ namespace TransportSockets { namespace Alts { class AltsIntegrationTestBase : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: AltsIntegrationTestBase(const std::string& server_peer_identity, const std::string& client_peer_identity, bool server_connect_handshaker, diff --git a/test/extensions/transport_sockets/alts/config_test.cc b/test/extensions/transport_sockets/alts/config_test.cc index ec73769e2547b..01b5a4bd4962b 100644 --- a/test/extensions/transport_sockets/alts/config_test.cc +++ b/test/extensions/transport_sockets/alts/config_test.cc @@ -5,9 +5,9 @@ #include "extensions/transport_sockets/alts/config.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using Envoy::Server::Configuration::MockTransportSocketFactoryContext; using testing::_; diff --git a/test/extensions/transport_sockets/alts/noop_transport_socket_callbacks_test.cc b/test/extensions/transport_sockets/alts/noop_transport_socket_callbacks_test.cc index e9a3b6bdfb3c5..7bcd43dee9104 100644 --- a/test/extensions/transport_sockets/alts/noop_transport_socket_callbacks_test.cc +++ b/test/extensions/transport_sockets/alts/noop_transport_socket_callbacks_test.cc @@ -5,8 +5,7 @@ #include "extensions/transport_sockets/alts/noop_transport_socket_callbacks.h" #include "test/mocks/network/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Extensions { @@ -37,7 +36,7 @@ class TestTransportSocketCallbacks : public Network::TransportSocketCallbacks { Network::Connection& connection_; }; -class NoOpTransportSocketCallbacksTest : public testing::Test { +class NoOpTransportSocketCallbacksTest : public TestBase { protected: NoOpTransportSocketCallbacksTest() : wrapper_callbacks_(connection_), wrapped_callbacks_(wrapper_callbacks_) {} diff --git a/test/extensions/transport_sockets/alts/tsi_frame_protector_test.cc b/test/extensions/transport_sockets/alts/tsi_frame_protector_test.cc index 724638b3d4a10..a82d33a11afd2 100644 --- a/test/extensions/transport_sockets/alts/tsi_frame_protector_test.cc +++ b/test/extensions/transport_sockets/alts/tsi_frame_protector_test.cc @@ -2,8 +2,9 @@ #include "extensions/transport_sockets/alts/tsi_frame_protector.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "src/core/tsi/fake_transport_security.h" namespace Envoy { @@ -22,7 +23,7 @@ using namespace std::string_literals; * Test with fake frame protector. The protected frame header is 4 byte length (little endian, * include header itself) and following the body. */ -class TsiFrameProtectorTest : public testing::Test { +class TsiFrameProtectorTest : public TestBase { public: TsiFrameProtectorTest() : raw_frame_protector_(tsi_create_fake_frame_protector(nullptr)), diff --git a/test/extensions/transport_sockets/alts/tsi_handshaker_test.cc b/test/extensions/transport_sockets/alts/tsi_handshaker_test.cc index 75ff19c0f32ed..a07ce881bed19 100644 --- a/test/extensions/transport_sockets/alts/tsi_handshaker_test.cc +++ b/test/extensions/transport_sockets/alts/tsi_handshaker_test.cc @@ -1,9 +1,9 @@ #include "extensions/transport_sockets/alts/tsi_handshaker.h" #include "test/mocks/event/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "src/core/tsi/fake_transport_security.h" namespace Envoy { @@ -32,7 +32,7 @@ class MockTsiHandshakerCallbacks : public TsiHandshakerCallbacks { } }; -class TsiHandshakerTest : public testing::Test { +class TsiHandshakerTest : public TestBase { public: TsiHandshakerTest() : server_handshaker_({tsi_create_fake_handshaker(0)}, dispatcher_), diff --git a/test/extensions/transport_sockets/alts/tsi_socket_test.cc b/test/extensions/transport_sockets/alts/tsi_socket_test.cc index f3e42b231f952..032207fd8a127 100644 --- a/test/extensions/transport_sockets/alts/tsi_socket_test.cc +++ b/test/extensions/transport_sockets/alts/tsi_socket_test.cc @@ -3,9 +3,9 @@ #include "extensions/transport_sockets/alts/tsi_socket.h" #include "test/mocks/network/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "src/core/tsi/fake_transport_security.h" namespace Envoy { @@ -18,7 +18,7 @@ using testing::Return; using testing::ReturnRef; using testing::StrictMock; -class TsiSocketTest : public testing::Test { +class TsiSocketTest : public TestBase { protected: TsiSocketTest() { server_.handshaker_factory_ = [](Event::Dispatcher& dispatcher, @@ -382,7 +382,7 @@ TEST_F(TsiSocketTest, HandshakeWithInternalError) { raw_handshaker->vtable = vtable; } -class TsiSocketFactoryTest : public testing::Test { +class TsiSocketFactoryTest : public TestBase { protected: void SetUp() override { auto handshaker_factory = [](Event::Dispatcher& dispatcher, diff --git a/test/extensions/transport_sockets/tls/context_impl_test.cc b/test/extensions/transport_sockets/tls/context_impl_test.cc index 274f4d0a9add1..bfa059bb2a290 100644 --- a/test/extensions/transport_sockets/tls/context_impl_test.cc +++ b/test/extensions/transport_sockets/tls/context_impl_test.cc @@ -19,9 +19,9 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" #include "openssl/x509v3.h" using Envoy::Protobuf::util::MessageDifferencer; diff --git a/test/extensions/transport_sockets/tls/ssl_certs_test.h b/test/extensions/transport_sockets/tls/ssl_certs_test.h index 94b6dc206c394..339716fe92237 100644 --- a/test/extensions/transport_sockets/tls/ssl_certs_test.h +++ b/test/extensions/transport_sockets/tls/ssl_certs_test.h @@ -2,13 +2,12 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::ReturnRef; namespace Envoy { -class SslCertsTest : public testing::Test { +class SslCertsTest : public TestBase { public: static void SetUpTestSuite() { TestEnvironment::exec({TestEnvironment::runfilesPath( diff --git a/test/extensions/transport_sockets/tls/ssl_socket_test.cc b/test/extensions/transport_sockets/tls/ssl_socket_test.cc index 0e1d6152df0d8..10d4d6e064d44 100644 --- a/test/extensions/transport_sockets/tls/ssl_socket_test.cc +++ b/test/extensions/transport_sockets/tls/ssl_socket_test.cc @@ -33,11 +33,11 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/str_replace.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "openssl/ssl.h" using testing::_; diff --git a/test/extensions/transport_sockets/tls/ssl_test_utility.h b/test/extensions/transport_sockets/tls/ssl_test_utility.h index 7fa071c800bf2..7d41cbbdcd690 100644 --- a/test/extensions/transport_sockets/tls/ssl_test_utility.h +++ b/test/extensions/transport_sockets/tls/ssl_test_utility.h @@ -4,8 +4,8 @@ #include #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" -#include "gtest/gtest.h" #include "openssl/ssl.h" #include "openssl/x509v3.h" diff --git a/test/extensions/transport_sockets/tls/utility_test.cc b/test/extensions/transport_sockets/tls/utility_test.cc index 494170a21ba00..385ad365f2b65 100644 --- a/test/extensions/transport_sockets/tls/utility_test.cc +++ b/test/extensions/transport_sockets/tls/utility_test.cc @@ -7,10 +7,10 @@ #include "test/extensions/transport_sockets/tls/test_data/san_dns_cert_info.h" #include "test/test_common/environment.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/time/time.h" -#include "gtest/gtest.h" #include "openssl/x509v3.h" namespace Envoy { diff --git a/test/fuzz/main.cc b/test/fuzz/main.cc index 61d53dd7b22e0..023a5078cc1ca 100644 --- a/test/fuzz/main.cc +++ b/test/fuzz/main.cc @@ -18,17 +18,16 @@ #include "test/fuzz/fuzz_runner.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace { // List of paths for files in the test corpus. std::vector test_corpus_; -class FuzzerCorpusTest : public ::testing::TestWithParam { +class FuzzerCorpusTest : public TestBaseWithParam { protected: FuzzerCorpusTest() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/integration/ads_integration_test.cc b/test/integration/ads_integration_test.cc index 9455793f8eb0d..e2f7294b9ee3a 100644 --- a/test/integration/ads_integration_test.cc +++ b/test/integration/ads_integration_test.cc @@ -20,10 +20,9 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/network_utility.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; diff --git a/test/integration/cds_integration_test.cc b/test/integration/cds_integration_test.cc index 455d58a46ddfa..9958c2d58c9c3 100644 --- a/test/integration/cds_integration_test.cc +++ b/test/integration/cds_integration_test.cc @@ -14,10 +14,10 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/network_utility.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/synchronization/notification.h" -#include "gtest/gtest.h" using testing::AssertionFailure; using testing::AssertionResult; diff --git a/test/integration/echo_integration_test.cc b/test/integration/echo_integration_test.cc index 55dae2942a08e..da64a31270779 100644 --- a/test/integration/echo_integration_test.cc +++ b/test/integration/echo_integration_test.cc @@ -8,7 +8,7 @@ namespace Envoy { std::string echo_config; class EchoIntegrationTest : public BaseIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: EchoIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), echo_config) {} diff --git a/test/integration/eds_integration_test.cc b/test/integration/eds_integration_test.cc index ebfacb27906d1..7412163d7661e 100644 --- a/test/integration/eds_integration_test.cc +++ b/test/integration/eds_integration_test.cc @@ -5,8 +5,7 @@ #include "test/config/utility.h" #include "test/integration/http_integration.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace { @@ -14,7 +13,7 @@ namespace { // Integration test for EDS features. EDS is consumed via filesystem // subscription. class EdsIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: EdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/integration/hds_integration_test.cc b/test/integration/hds_integration_test.cc index bd3d6de7607a9..8b0e9468c1ca9 100644 --- a/test/integration/hds_integration_test.cc +++ b/test/integration/hds_integration_test.cc @@ -16,15 +16,15 @@ #include "test/config/utility.h" #include "test/integration/http_integration.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace { class HdsIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: HdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/integration/header_integration_test.cc b/test/integration/header_integration_test.cc index bc665df7c72aa..40c0672504c8a 100644 --- a/test/integration/header_integration_test.cc +++ b/test/integration/header_integration_test.cc @@ -8,19 +8,18 @@ #include "test/integration/http_integration.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace { std::string ipSuppressEnvoyHeadersTestParamsToString( - const testing::TestParamInfo>& params) { + const ::testing::TestParamInfo>& params) { return fmt::format( "{}_{}", TestUtility::ipTestParamsToString( - testing::TestParamInfo(std::get<0>(params.param), 0)), + ::testing::TestParamInfo(std::get<0>(params.param), 0)), std::get<1>(params.param) ? "with_x_envoy_from_router" : "without_x_envoy_from_router"); } @@ -151,7 +150,7 @@ stat_prefix: header_test class HeaderIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam> { + public TestBaseWithParam> { public: HeaderIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, std::get<0>(GetParam()), realTime()) {} diff --git a/test/integration/http2_integration_test.cc b/test/integration/http2_integration_test.cc index 3665698d89da6..cdcd637b5550c 100644 --- a/test/integration/http2_integration_test.cc +++ b/test/integration/http2_integration_test.cc @@ -9,10 +9,9 @@ #include "test/mocks/http/mocks.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using ::testing::HasSubstr; using ::testing::MatchesRegex; diff --git a/test/integration/http2_integration_test.h b/test/integration/http2_integration_test.h index 9319cc27fd98c..c63d60ba0dfe9 100644 --- a/test/integration/http2_integration_test.h +++ b/test/integration/http2_integration_test.h @@ -1,12 +1,11 @@ #pragma once #include "test/integration/http_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { class Http2IntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: Http2IntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} diff --git a/test/integration/http2_upstream_integration_test.cc b/test/integration/http2_upstream_integration_test.cc index 0e0ba792cb485..155dd9f0386a2 100644 --- a/test/integration/http2_upstream_integration_test.cc +++ b/test/integration/http2_upstream_integration_test.cc @@ -6,10 +6,9 @@ #include "test/integration/autonomous_upstream.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { INSTANTIATE_TEST_SUITE_P(IpVersions, Http2UpstreamIntegrationTest, diff --git a/test/integration/http2_upstream_integration_test.h b/test/integration/http2_upstream_integration_test.h index 4a7779580bc26..0bcb228acbd79 100644 --- a/test/integration/http2_upstream_integration_test.h +++ b/test/integration/http2_upstream_integration_test.h @@ -1,12 +1,11 @@ #pragma once #include "test/integration/http_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { class Http2UpstreamIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: Http2UpstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} diff --git a/test/integration/http_integration.cc b/test/integration/http_integration.cc index 0cee15a594947..2815e2e59d212 100644 --- a/test/integration/http_integration.cc +++ b/test/integration/http_integration.cc @@ -30,8 +30,7 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/registry.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::_; using testing::AnyNumber; diff --git a/test/integration/http_protocol_integration.h b/test/integration/http_protocol_integration.h index 4f587c7e839b5..36d47b7a038e7 100644 --- a/test/integration/http_protocol_integration.h +++ b/test/integration/http_protocol_integration.h @@ -1,8 +1,7 @@ #pragma once #include "test/integration/http_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { @@ -27,7 +26,7 @@ struct HttpProtocolTestParams { // .... // } class HttpProtocolIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: // By default returns 8 combinations of // [HTTP upstream / HTTP downstream] x [Ipv4, IPv6] @@ -46,7 +45,7 @@ class HttpProtocolIntegrationTest : public HttpIntegrationTest, // Allows pretty printed test names of the form // FooTestCase.BarInstance/IPv4_Http2Downstream_HttpUpstream static std::string - protocolTestParamsToString(const testing::TestParamInfo& p); + protocolTestParamsToString(const ::testing::TestParamInfo& p); HttpProtocolIntegrationTest() : HttpIntegrationTest(GetParam().downstream_protocol, GetParam().version, realTime()) {} diff --git a/test/integration/integration.cc b/test/integration/integration.cc index 84859fd73a45e..ac57ca81079dc 100644 --- a/test/integration/integration.cc +++ b/test/integration/integration.cc @@ -30,8 +30,7 @@ #include "test/integration/utility.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::_; using testing::AnyNumber; diff --git a/test/integration/integration_admin_test.cc b/test/integration/integration_admin_test.cc index 3e940e82a7c68..0dcdf795a00c1 100644 --- a/test/integration/integration_admin_test.cc +++ b/test/integration/integration_admin_test.cc @@ -9,9 +9,9 @@ #include "common/stats/stats_matcher_impl.h" #include "test/integration/utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" #include "spdlog/spdlog.h" namespace Envoy { @@ -416,7 +416,7 @@ TEST_P(IntegrationAdminTest, AdminCpuProfilerStart) { EXPECT_STREQ("200", response->headers().Status()->value().c_str()); } -class IntegrationAdminIpv4Ipv6Test : public HttpIntegrationTest, public testing::Test { +class IntegrationAdminIpv4Ipv6Test : public HttpIntegrationTest, public TestBase { public: IntegrationAdminIpv4Ipv6Test() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, Network::Address::IpVersion::v4, @@ -451,7 +451,7 @@ TEST_F(IntegrationAdminIpv4Ipv6Test, Ipv4Ipv6Listen) { // restrictions on their names. class StatsMatcherIntegrationTest : public HttpIntegrationTest, - public testing::Test, + public TestBase, public testing::WithParamInterface { public: StatsMatcherIntegrationTest() diff --git a/test/integration/integration_admin_test.h b/test/integration/integration_admin_test.h index 0bc34fbe72d46..d8d21a9ce1299 100644 --- a/test/integration/integration_admin_test.h +++ b/test/integration/integration_admin_test.h @@ -3,8 +3,7 @@ #include "common/json/json_loader.h" #include "test/integration/http_protocol_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/integration/integration_test.cc b/test/integration/integration_test.cc index b1c2c984fc47a..6efef370306f1 100644 --- a/test/integration/integration_test.cc +++ b/test/integration/integration_test.cc @@ -12,10 +12,9 @@ #include "test/mocks/http/mocks.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using Envoy::Http::Headers; using Envoy::Http::HeaderValueOf; using Envoy::Http::HttpStatusIs; diff --git a/test/integration/integration_test.h b/test/integration/integration_test.h index 96f17288e1712..13352ca960e79 100644 --- a/test/integration/integration_test.h +++ b/test/integration/integration_test.h @@ -1,12 +1,11 @@ #pragma once #include "test/integration/http_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { class IntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: IntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} }; diff --git a/test/integration/load_stats_integration_test.cc b/test/integration/load_stats_integration_test.cc index fe0bcceeab9ef..aeef4cc7ee8a1 100644 --- a/test/integration/load_stats_integration_test.cc +++ b/test/integration/load_stats_integration_test.cc @@ -8,15 +8,14 @@ #include "test/config/utility.h" #include "test/integration/http_integration.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace { class LoadStatsIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: LoadStatsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) { diff --git a/test/integration/proxy_proto_integration_test.cc b/test/integration/proxy_proto_integration_test.cc index 691abd149b13b..d5fe3a79e6c7a 100644 --- a/test/integration/proxy_proto_integration_test.cc +++ b/test/integration/proxy_proto_integration_test.cc @@ -4,10 +4,10 @@ #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "fmt/format.h" -#include "gtest/gtest.h" namespace Envoy { diff --git a/test/integration/proxy_proto_integration_test.h b/test/integration/proxy_proto_integration_test.h index d12badf470ad2..5f663e6b9f51a 100644 --- a/test/integration/proxy_proto_integration_test.h +++ b/test/integration/proxy_proto_integration_test.h @@ -5,12 +5,11 @@ #include "test/integration/fake_upstream.h" #include "test/integration/http_integration.h" #include "test/integration/server.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { class ProxyProtoIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: ProxyProtoIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) { diff --git a/test/integration/ratelimit_integration_test.cc b/test/integration/ratelimit_integration_test.cc index ed855fe5a4021..ae0bc73b5fcac 100644 --- a/test/integration/ratelimit_integration_test.cc +++ b/test/integration/ratelimit_integration_test.cc @@ -8,8 +8,7 @@ #include "test/common/grpc/grpc_client_integration.h" #include "test/integration/http_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace { diff --git a/test/integration/sds_dynamic_integration_test.cc b/test/integration/sds_dynamic_integration_test.cc index 2c2ffe5135e40..e1d026a10defa 100644 --- a/test/integration/sds_dynamic_integration_test.cc +++ b/test/integration/sds_dynamic_integration_test.cc @@ -20,12 +20,12 @@ #include "test/mocks/secret/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time_system.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "integration.h" #include "utility.h" diff --git a/test/integration/sds_static_integration_test.cc b/test/integration/sds_static_integration_test.cc index 462094696737a..9fa494a7992ee 100644 --- a/test/integration/sds_static_integration_test.cc +++ b/test/integration/sds_static_integration_test.cc @@ -18,12 +18,12 @@ #include "test/mocks/secret/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time_system.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "integration.h" #include "utility.h" @@ -33,9 +33,8 @@ using testing::Return; namespace Envoy { namespace Ssl { -class SdsStaticDownstreamIntegrationTest - : public HttpIntegrationTest, - public testing::TestWithParam { +class SdsStaticDownstreamIntegrationTest : public HttpIntegrationTest, + public TestBaseWithParam { public: SdsStaticDownstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} @@ -106,9 +105,8 @@ TEST_P(SdsStaticDownstreamIntegrationTest, RouterRequestAndResponseWithGiantBody testRouterRequestAndResponseWithBody(16 * 1024 * 1024, 16 * 1024 * 1024, false, &creator); } -class SdsStaticUpstreamIntegrationTest - : public HttpIntegrationTest, - public testing::TestWithParam { +class SdsStaticUpstreamIntegrationTest : public HttpIntegrationTest, + public TestBaseWithParam { public: SdsStaticUpstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/integration/server.cc b/test/integration/server.cc index 251438fb242d0..4fa5551d9fa0d 100644 --- a/test/integration/server.cc +++ b/test/integration/server.cc @@ -19,9 +19,9 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "absl/strings/str_replace.h" -#include "gtest/gtest.h" namespace Envoy { namespace Server { diff --git a/test/integration/ssl_integration_test.cc b/test/integration/ssl_integration_test.cc index 97083b02b7dab..99d13f7b62a2c 100644 --- a/test/integration/ssl_integration_test.cc +++ b/test/integration/ssl_integration_test.cc @@ -14,11 +14,11 @@ #include "extensions/transport_sockets/tls/context_manager_impl.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "integration.h" #include "utility.h" @@ -176,8 +176,8 @@ TEST_P(SslIntegrationTest, AdminCertEndpoint) { // Validate certificate selection across different certificate types and client TLS versions. class SslCertficateIntegrationTest : public SslIntegrationTestBase, - public testing::TestWithParam> { + public TestBaseWithParam> { public: SslCertficateIntegrationTest() : SslIntegrationTestBase(std::get<0>(GetParam())) { server_tlsv1_3_ = true; @@ -210,7 +210,7 @@ class SslCertficateIntegrationTest } static std::string ipClientVersionTestParamsToString( - const testing::TestParamInfo< + const ::testing::TestParamInfo< std::tuple>& params) { return fmt::format("{}_TLSv1_{}", diff --git a/test/integration/ssl_integration_test.h b/test/integration/ssl_integration_test.h index 4acbb234f747a..f28a9343803b7 100644 --- a/test/integration/ssl_integration_test.h +++ b/test/integration/ssl_integration_test.h @@ -7,9 +7,9 @@ #include "test/integration/server.h" #include "test/integration/ssl_utility.h" #include "test/mocks/secret/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; @@ -44,7 +44,7 @@ class SslIntegrationTestBase : public HttpIntegrationTest { }; class SslIntegrationTest : public SslIntegrationTestBase, - public testing::TestWithParam { + public TestBaseWithParam { public: SslIntegrationTest() : SslIntegrationTestBase(GetParam()) {} void TearDown() override { SslIntegrationTestBase::TearDown(); }; diff --git a/test/integration/ssl_utility.cc b/test/integration/ssl_utility.cc index 59c036109ead2..4254a7c273144 100644 --- a/test/integration/ssl_utility.cc +++ b/test/integration/ssl_utility.cc @@ -12,8 +12,7 @@ #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::ReturnRef; diff --git a/test/integration/stats_integration_test.cc b/test/integration/stats_integration_test.cc index a90fa5115d724..4d36b4d8c5a7a 100644 --- a/test/integration/stats_integration_test.cc +++ b/test/integration/stats_integration_test.cc @@ -5,15 +5,14 @@ #include "test/integration/integration.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace { class StatsIntegrationTest : public BaseIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: StatsIntegrationTest() : BaseIntegrationTest(GetParam(), realTime()) {} diff --git a/test/integration/tcp_conn_pool_integration_test.cc b/test/integration/tcp_conn_pool_integration_test.cc index 1335ebc1d5d7b..5ca30b0e8ed7a 100644 --- a/test/integration/tcp_conn_pool_integration_test.cc +++ b/test/integration/tcp_conn_pool_integration_test.cc @@ -112,7 +112,7 @@ class TestFilterConfigFactory : public Server::Configuration::NamedNetworkFilter } // namespace class TcpConnPoolIntegrationTest : public BaseIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: TcpConnPoolIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), tcp_conn_pool_config), diff --git a/test/integration/tcp_proxy_integration_test.cc b/test/integration/tcp_proxy_integration_test.cc index 2d9862983762e..d2de9a7d12822 100644 --- a/test/integration/tcp_proxy_integration_test.cc +++ b/test/integration/tcp_proxy_integration_test.cc @@ -11,8 +11,7 @@ #include "test/integration/ssl_utility.h" #include "test/integration/utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::_; using testing::Invoke; diff --git a/test/integration/tcp_proxy_integration_test.h b/test/integration/tcp_proxy_integration_test.h index 5e7fb5c29b369..af0156821e87a 100644 --- a/test/integration/tcp_proxy_integration_test.h +++ b/test/integration/tcp_proxy_integration_test.h @@ -5,13 +5,12 @@ #include "test/integration/integration.h" #include "test/mocks/secret/mocks.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace { class TcpProxyIntegrationTest : public BaseIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: TcpProxyIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), ConfigHelper::TCP_PROXY_CONFIG) { diff --git a/test/integration/uds_integration_test.cc b/test/integration/uds_integration_test.cc index 8c93f738ea05a..f4d70a81e07b0 100644 --- a/test/integration/uds_integration_test.cc +++ b/test/integration/uds_integration_test.cc @@ -4,8 +4,7 @@ #include "common/network/utility.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/integration/uds_integration_test.h b/test/integration/uds_integration_test.h index 85891bd18d98d..7cb73485c2205 100644 --- a/test/integration/uds_integration_test.h +++ b/test/integration/uds_integration_test.h @@ -9,14 +9,13 @@ #include "test/integration/http_integration.h" #include "test/integration/server.h" #include "test/test_common/environment.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { class UdsUpstreamIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam> { + public TestBaseWithParam> { public: UdsUpstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, std::get<0>(GetParam()), realTime()), @@ -47,7 +46,7 @@ class UdsUpstreamIntegrationTest class UdsListenerIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam> { + public TestBaseWithParam> { public: UdsListenerIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, std::get<0>(GetParam()), realTime()), diff --git a/test/integration/websocket_integration_test.cc b/test/integration/websocket_integration_test.cc index 92d1f696403e3..0473e41a65734 100644 --- a/test/integration/websocket_integration_test.cc +++ b/test/integration/websocket_integration_test.cc @@ -10,10 +10,10 @@ #include "test/integration/utility.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/str_cat.h" -#include "gtest/gtest.h" using testing::MatchesRegex; diff --git a/test/integration/websocket_integration_test.h b/test/integration/websocket_integration_test.h index 69f88ccb1f1b2..398d478d9c2d4 100644 --- a/test/integration/websocket_integration_test.h +++ b/test/integration/websocket_integration_test.h @@ -1,8 +1,7 @@ #pragma once #include "test/integration/http_protocol_integration.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { diff --git a/test/integration/xds_integration_test.cc b/test/integration/xds_integration_test.cc index 68bde1631235a..ebe86cb9332c3 100644 --- a/test/integration/xds_integration_test.cc +++ b/test/integration/xds_integration_test.cc @@ -1,14 +1,13 @@ #include "test/integration/http_integration.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace { // This is a minimal litmus test for the v2 xDS APIs. class XdsIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: XdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) { diff --git a/test/integration/xfcc_integration_test.cc b/test/integration/xfcc_integration_test.cc index b31660b46e84a..2d98a774389b2 100644 --- a/test/integration/xfcc_integration_test.cc +++ b/test/integration/xfcc_integration_test.cc @@ -17,10 +17,10 @@ #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "integration.h" #include "ssl_integration_test.h" #include "utility.h" diff --git a/test/integration/xfcc_integration_test.h b/test/integration/xfcc_integration_test.h index 055b76132b07c..780e36f6ebbf7 100644 --- a/test/integration/xfcc_integration_test.h +++ b/test/integration/xfcc_integration_test.h @@ -7,11 +7,11 @@ #include "test/integration/http_integration.h" #include "test/integration/server.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "absl/strings/ascii.h" #include "absl/strings/str_replace.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; using testing::ReturnRef; @@ -20,7 +20,7 @@ namespace Envoy { namespace Xfcc { class XfccIntegrationTest : public HttpIntegrationTest, - public testing::TestWithParam { + public TestBaseWithParam { public: const std::string previous_xfcc_ = "By=spiffe://lyft.com/frontend;Hash=123456;URI=spiffe://lyft.com/testclient"; diff --git a/test/mocks/access_log/mocks.cc b/test/mocks/access_log/mocks.cc index 6f7edb0232aa2..d1e10758c3fb3 100644 --- a/test/mocks/access_log/mocks.cc +++ b/test/mocks/access_log/mocks.cc @@ -1,7 +1,8 @@ #include "test/mocks/access_log/mocks.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; diff --git a/test/mocks/api/mocks.cc b/test/mocks/api/mocks.cc index a805a623d7c32..4aab4c9c1759e 100644 --- a/test/mocks/api/mocks.cc +++ b/test/mocks/api/mocks.cc @@ -3,8 +3,9 @@ #include "common/common/assert.h" #include "common/common/lock_guard.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; diff --git a/test/mocks/common.h b/test/mocks/common.h index 5908a0f9a804c..41bf7fe903cdc 100644 --- a/test/mocks/common.h +++ b/test/mocks/common.h @@ -8,6 +8,7 @@ #include "common/common/logger.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "absl/strings/string_view.h" diff --git a/test/mocks/event/mocks.cc b/test/mocks/event/mocks.cc index 59d724f85e4da..13c929af64d55 100644 --- a/test/mocks/event/mocks.cc +++ b/test/mocks/event/mocks.cc @@ -1,7 +1,8 @@ #include "mocks.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/http/mocks.cc b/test/mocks/http/mocks.cc index 2e071d5a11c03..77c29ff6ffe36 100644 --- a/test/mocks/http/mocks.cc +++ b/test/mocks/http/mocks.cc @@ -3,8 +3,9 @@ #include "envoy/buffer/buffer.h" #include "envoy/event/dispatcher.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/init/mocks.cc b/test/mocks/init/mocks.cc index ce0cb291ebcad..6eeac3f5e2c7b 100644 --- a/test/mocks/init/mocks.cc +++ b/test/mocks/init/mocks.cc @@ -2,8 +2,9 @@ #include +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/local_info/mocks.cc b/test/mocks/local_info/mocks.cc index c5addcc3912ca..26329ccf1dad8 100644 --- a/test/mocks/local_info/mocks.cc +++ b/test/mocks/local_info/mocks.cc @@ -2,8 +2,9 @@ #include "common/network/address_impl.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::Invoke; using testing::Return; diff --git a/test/mocks/network/mocks.cc b/test/mocks/network/mocks.cc index 538c5c36cd312..268053547040b 100644 --- a/test/mocks/network/mocks.cc +++ b/test/mocks/network/mocks.cc @@ -10,9 +10,9 @@ #include "common/network/utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/router/mocks.cc b/test/mocks/router/mocks.cc index 17b94a4b97f2e..278a4084a4335 100644 --- a/test/mocks/router/mocks.cc +++ b/test/mocks/router/mocks.cc @@ -2,8 +2,9 @@ #include +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::NiceMock; diff --git a/test/mocks/runtime/mocks.cc b/test/mocks/runtime/mocks.cc index acc39e811d862..c9e9793dcbb4b 100644 --- a/test/mocks/runtime/mocks.cc +++ b/test/mocks/runtime/mocks.cc @@ -1,7 +1,8 @@ #include "mocks.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Return; diff --git a/test/mocks/secret/mocks.h b/test/mocks/secret/mocks.h index 428f1ec28faad..b69fa6897a526 100644 --- a/test/mocks/secret/mocks.h +++ b/test/mocks/secret/mocks.h @@ -5,8 +5,9 @@ #include "envoy/server/transport_socket_config.h" #include "envoy/ssl/tls_certificate_config.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { namespace Secret { diff --git a/test/mocks/server/mocks.cc b/test/mocks/server/mocks.cc index b0523c36fa538..c0ab9e59f422e 100644 --- a/test/mocks/server/mocks.cc +++ b/test/mocks/server/mocks.cc @@ -4,8 +4,9 @@ #include "common/singleton/manager_impl.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/server/mocks.h b/test/mocks/server/mocks.h index 0e8dfde93f5c3..74d48128444ed 100644 --- a/test/mocks/server/mocks.h +++ b/test/mocks/server/mocks.h @@ -39,11 +39,11 @@ #include "test/mocks/thread_local/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/mocks/upstream/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time_system.h" #include "absl/strings/string_view.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "spdlog/spdlog.h" namespace Envoy { diff --git a/test/mocks/stats/mocks.cc b/test/mocks/stats/mocks.cc index 5b1dbf98df98c..860ccee04e0b6 100644 --- a/test/mocks/stats/mocks.cc +++ b/test/mocks/stats/mocks.cc @@ -1,7 +1,8 @@ #include "mocks.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index 7a17c006bd2ab..ac27d97443a97 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -2,8 +2,9 @@ #include "common/network/address_impl.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Const; diff --git a/test/mocks/thread_local/mocks.cc b/test/mocks/thread_local/mocks.cc index cfabd7a7f52f0..713855d3ce301 100644 --- a/test/mocks/thread_local/mocks.cc +++ b/test/mocks/thread_local/mocks.cc @@ -1,7 +1,8 @@ #include "mocks.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/tracing/mocks.cc b/test/mocks/tracing/mocks.cc index f35c98b383569..ee157fc212bdd 100644 --- a/test/mocks/tracing/mocks.cc +++ b/test/mocks/tracing/mocks.cc @@ -1,7 +1,8 @@ #include "mocks.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::Return; using testing::ReturnRef; diff --git a/test/mocks/upstream/cluster_info.h b/test/mocks/upstream/cluster_info.h index 0aa4f3627e712..df09688a5bc7c 100644 --- a/test/mocks/upstream/cluster_info.h +++ b/test/mocks/upstream/cluster_info.h @@ -14,9 +14,9 @@ #include "test/mocks/runtime/mocks.h" #include "test/mocks/stats/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; diff --git a/test/mocks/upstream/mocks.cc b/test/mocks/upstream/mocks.cc index 0e32283276a02..cf84f12047da3 100644 --- a/test/mocks/upstream/mocks.cc +++ b/test/mocks/upstream/mocks.cc @@ -5,8 +5,9 @@ #include "envoy/upstream/load_balancer.h" +#include "test/test_common/test_base.h" + #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; diff --git a/test/mocks/upstream/mocks.h b/test/mocks/upstream/mocks.h index 0800d58f56294..ed0546f1b4820 100644 --- a/test/mocks/upstream/mocks.h +++ b/test/mocks/upstream/mocks.h @@ -25,9 +25,9 @@ #include "test/mocks/tcp/mocks.h" #include "test/mocks/upstream/cluster_info.h" #include "test/mocks/upstream/load_balancer_context.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::NiceMock; diff --git a/test/server/backtrace_test.cc b/test/server/backtrace_test.cc index cfcc2cc2c81e7..894ec568bfc12 100644 --- a/test/server/backtrace_test.cc +++ b/test/server/backtrace_test.cc @@ -1,6 +1,6 @@ #include "server/backtrace.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { TEST(Backward, Basic) { diff --git a/test/server/config_validation/dispatcher_test.cc b/test/server/config_validation/dispatcher_test.cc index d30db3ad8ba3e..7f7342380e721 100644 --- a/test/server/config_validation/dispatcher_test.cc +++ b/test/server/config_validation/dispatcher_test.cc @@ -19,7 +19,7 @@ namespace Envoy { // Define fixture which allocates ValidationDispatcher. -class ConfigValidation : public ::testing::TestWithParam { +class ConfigValidation : public TestBaseWithParam { public: ConfigValidation() { Event::Libevent::Global::initialize(); diff --git a/test/server/config_validation/server_test.cc b/test/server/config_validation/server_test.cc index 2099653510239..0479b9d2cc103 100644 --- a/test/server/config_validation/server_test.cc +++ b/test/server/config_validation/server_test.cc @@ -11,7 +11,7 @@ namespace Envoy { namespace Server { // Test param is the path to the config file to validate. -class ValidationServerTest : public testing::TestWithParam { +class ValidationServerTest : public TestBaseWithParam { public: static void SetupTestDirectory() { TestEnvironment::exec( diff --git a/test/server/configuration_impl_test.cc b/test/server/configuration_impl_test.cc index 032fe30c47096..2b6b6217bee9b 100644 --- a/test/server/configuration_impl_test.cc +++ b/test/server/configuration_impl_test.cc @@ -16,11 +16,11 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "fmt/printf.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::InSequence; using testing::Return; @@ -50,7 +50,7 @@ TEST(FilterChainUtility, buildFilterChainFailWithBadFilters) { EXPECT_EQ(FilterChainUtility::buildFilterChain(connection, factories), false); } -class ConfigurationImplTest : public testing::Test { +class ConfigurationImplTest : public TestBase { protected: ConfigurationImplTest() : api_(Api::createApiForTest(stats_store_)), diff --git a/test/server/connection_handler_test.cc b/test/server/connection_handler_test.cc index c22078eee68b8..4ebe8816cb438 100644 --- a/test/server/connection_handler_test.cc +++ b/test/server/connection_handler_test.cc @@ -10,9 +10,9 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/network_utility.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::ByRef; @@ -25,7 +25,7 @@ using testing::ReturnRef; namespace Envoy { namespace Server { -class ConnectionHandlerTest : public testing::Test, protected Logger::Loggable { +class ConnectionHandlerTest : public TestBase, protected Logger::Loggable { public: ConnectionHandlerTest() : handler_(new ConnectionHandlerImpl(ENVOY_LOGGER(), dispatcher_)), diff --git a/test/server/drain_manager_impl_test.cc b/test/server/drain_manager_impl_test.cc index 29ba7fd659915..b74f26bda3431 100644 --- a/test/server/drain_manager_impl_test.cc +++ b/test/server/drain_manager_impl_test.cc @@ -3,9 +3,9 @@ #include "server/drain_manager_impl.h" #include "test/mocks/server/mocks.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -15,7 +15,7 @@ using testing::SaveArg; namespace Envoy { namespace Server { -class DrainManagerImplTest : public testing::Test { +class DrainManagerImplTest : public TestBase { public: DrainManagerImplTest() { ON_CALL(server_.options_, drainTime()).WillByDefault(Return(std::chrono::seconds(600))); diff --git a/test/server/guarddog_impl_test.cc b/test/server/guarddog_impl_test.cc index 4b27653cc780a..b2bd21eef329b 100644 --- a/test/server/guarddog_impl_test.cc +++ b/test/server/guarddog_impl_test.cc @@ -13,10 +13,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::InSequence; using testing::NiceMock; @@ -24,7 +24,7 @@ using testing::NiceMock; namespace Envoy { namespace Server { -class GuardDogTestBase : public testing::Test { +class GuardDogTestBase : public TestBase { protected: GuardDogTestBase() : api_(Api::createApiForTest(stats_store_)) {} diff --git a/test/server/hot_restart_impl_test.cc b/test/server/hot_restart_impl_test.cc index a22392b56ad56..7bb5ed4e7f4ac 100644 --- a/test/server/hot_restart_impl_test.cc +++ b/test/server/hot_restart_impl_test.cc @@ -8,11 +8,11 @@ #include "test/mocks/api/mocks.h" #include "test/mocks/server/mocks.h" #include "test/test_common/logging.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "absl/strings/match.h" #include "absl/strings/string_view.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -24,7 +24,7 @@ using testing::WithArg; namespace Envoy { namespace Server { -class HotRestartImplTest : public testing::Test { +class HotRestartImplTest : public TestBase { public: void setup() { EXPECT_CALL(os_sys_calls_, shmUnlink(_)); diff --git a/test/server/http/admin_test.cc b/test/server/http/admin_test.cc index a13a93629c4a8..1ac6f062b462d 100644 --- a/test/server/http/admin_test.cc +++ b/test/server/http/admin_test.cc @@ -26,11 +26,11 @@ #include "test/test_common/logging.h" #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AllOf; @@ -48,7 +48,7 @@ using testing::ReturnRef; namespace Envoy { namespace Server { -class AdminStatsTest : public testing::TestWithParam { +class AdminStatsTest : public TestBaseWithParam { public: AdminStatsTest() : alloc_(options_) { store_ = std::make_unique(options_, alloc_); @@ -71,7 +71,7 @@ class AdminStatsTest : public testing::TestWithParam store_; }; -class AdminFilterTest : public testing::TestWithParam { +class AdminFilterTest : public TestBaseWithParam { public: AdminFilterTest() : admin_(TestEnvironment::temporaryPath("envoy.prof"), server_), @@ -588,7 +588,7 @@ TEST_P(AdminFilterTest, Trailers) { EXPECT_EQ(Http::FilterTrailersStatus::StopIteration, filter_.decodeTrailers(request_headers_)); } -class AdminInstanceTest : public testing::TestWithParam { +class AdminInstanceTest : public TestBaseWithParam { public: AdminInstanceTest() : address_out_path_(TestEnvironment::temporaryPath("admin.address")), @@ -1219,7 +1219,7 @@ class HistogramWrapper { histogram_t* histogram_; }; -class PrometheusStatsFormatterTest : public testing::Test { +class PrometheusStatsFormatterTest : public TestBase { protected: PrometheusStatsFormatterTest() /*: alloc_(stats_options_)*/ {} void addCounter(const std::string& name, std::vector cluster_tags) { diff --git a/test/server/http/config_tracker_impl_test.cc b/test/server/http/config_tracker_impl_test.cc index d085e2c962af9..c89c9ba4f43ac 100644 --- a/test/server/http/config_tracker_impl_test.cc +++ b/test/server/http/config_tracker_impl_test.cc @@ -9,7 +9,7 @@ using testing::_; namespace Envoy { namespace Server { -class ConfigTrackerImplTest : public testing::Test { +class ConfigTrackerImplTest : public TestBase { public: ConfigTrackerImplTest() : cbs_map(tracker.getCallbacksMap()) { EXPECT_TRUE(cbs_map.empty()); diff --git a/test/server/init_manager_impl_test.cc b/test/server/init_manager_impl_test.cc index afaa2e44a0176..1bbeac062ac0e 100644 --- a/test/server/init_manager_impl_test.cc +++ b/test/server/init_manager_impl_test.cc @@ -12,7 +12,7 @@ using testing::Invoke; namespace Envoy { namespace Server { -class InitManagerImplTest : public testing::Test { +class InitManagerImplTest : public TestBase { public: InitManagerImpl manager_; ReadyWatcher initialized_; diff --git a/test/server/lds_api_test.cc b/test/server/lds_api_test.cc index 597716e6c8c28..73a092984c555 100644 --- a/test/server/lds_api_test.cc +++ b/test/server/lds_api_test.cc @@ -22,7 +22,7 @@ using testing::Throw; namespace Envoy { namespace Server { -class LdsApiTest : public testing::Test { +class LdsApiTest : public TestBase { public: LdsApiTest() : request_(&cluster_manager_.async_client_), api_(Api::createApiForTest(store_)) {} diff --git a/test/server/listener_manager_impl_test.cc b/test/server/listener_manager_impl_test.cc index be4c516e742e9..2da9582823033 100644 --- a/test/server/listener_manager_impl_test.cc +++ b/test/server/listener_manager_impl_test.cc @@ -25,12 +25,12 @@ #include "test/test_common/environment.h" #include "test/test_common/registry.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" -#include "gtest/gtest.h" using testing::_; using testing::InSequence; @@ -55,7 +55,7 @@ class ListenerHandle { Configuration::FactoryContext* context_{}; }; -class ListenerManagerImplTest : public testing::Test { +class ListenerManagerImplTest : public TestBase { protected: ListenerManagerImplTest() : api_(Api::createApiForTest(stats_)) { ON_CALL(server_, api()).WillByDefault(ReturnRef(*api_)); diff --git a/test/server/options_impl_test.cc b/test/server/options_impl_test.cc index 08bb03ee116ec..dd4b6aaeec84a 100644 --- a/test/server/options_impl_test.cc +++ b/test/server/options_impl_test.cc @@ -9,17 +9,17 @@ #include "server/options_impl.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" #include "spdlog/spdlog.h" using testing::HasSubstr; namespace Envoy { -class OptionsImplTest : public testing::Test { +class OptionsImplTest : public TestBase { public: // Do the ugly work of turning a std::string into a char** and create an OptionsImpl. Args are diff --git a/test/server/overload_manager_impl_test.cc b/test/server/overload_manager_impl_test.cc index 439103650548f..f79598a43ec24 100644 --- a/test/server/overload_manager_impl_test.cc +++ b/test/server/overload_manager_impl_test.cc @@ -10,10 +10,10 @@ #include "test/mocks/event/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/test_common/registry.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::Invoke; @@ -69,7 +69,7 @@ class FakeResourceMonitorFactory FakeResourceMonitor* monitor_; // not owned }; -class OverloadManagerImplTest : public testing::Test { +class OverloadManagerImplTest : public TestBase { protected: OverloadManagerImplTest() : factory1_("envoy.resource_monitors.fake_resource1"), diff --git a/test/server/server_test.cc b/test/server/server_test.cc index aebaf8b1e653f..a0d036d5d5435 100644 --- a/test/server/server_test.cc +++ b/test/server/server_test.cc @@ -11,11 +11,10 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/test_common/environment.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::_; using testing::Assign; using testing::HasSubstr; @@ -54,7 +53,7 @@ TEST(ServerInstanceUtil, flushHelper) { InstanceUtil::flushMetricsToSinks(sinks, source); } -class RunHelperTest : public testing::Test { +class RunHelperTest : public TestBase { public: RunHelperTest() : shutdown_(false) { InSequence s; @@ -113,7 +112,7 @@ TEST_F(RunHelperTest, ShutdownBeforeInitManagerInit) { } // Class creates minimally viable server instance for testing. -class ServerInstanceImplTest : public testing::TestWithParam { +class ServerInstanceImplTest : public TestBaseWithParam { protected: ServerInstanceImplTest() : version_(GetParam()) {} diff --git a/test/server/worker_impl_test.cc b/test/server/worker_impl_test.cc index 398e59e2e5719..0be4f48732037 100644 --- a/test/server/worker_impl_test.cc +++ b/test/server/worker_impl_test.cc @@ -6,11 +6,10 @@ #include "test/mocks/network/mocks.h" #include "test/mocks/server/mocks.h" #include "test/mocks/thread_local/mocks.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using testing::_; using testing::InSequence; using testing::Invoke; @@ -22,7 +21,7 @@ using testing::Throw; namespace Envoy { namespace Server { -class WorkerImplTest : public testing::Test { +class WorkerImplTest : public TestBase { public: WorkerImplTest() : api_(Api::createApiForTest(stats_store_)) { // In the real worker the watchdog has timers that prevent exit. Here we need to prevent event diff --git a/test/test_common/BUILD b/test/test_common/BUILD index 4b164f56c4b55..0aa8c4956b797 100644 --- a/test/test_common/BUILD +++ b/test/test_common/BUILD @@ -137,7 +137,7 @@ envoy_cc_library( ], ) -envoy_cc_test_library( +envoy_cc_library( name = "global_lib", srcs = ["global.cc"], hdrs = ["global.h"], @@ -155,6 +155,16 @@ envoy_cc_test( ], ) +envoy_cc_library( + name = "test_base", + srcs = ["test_base.cc"], + hdrs = ["test_base.h"], + deps = [ + "//external:googletest", + "//test/test_common:global_lib", + ], +) + envoy_cc_test_library( name = "test_time_lib", srcs = ["test_time.cc"], diff --git a/test/test_common/environment.cc b/test/test_common/environment.cc index 87cdadacb427c..5097558f1ff95 100644 --- a/test/test_common/environment.cc +++ b/test/test_common/environment.cc @@ -27,7 +27,7 @@ #include "test/test_common/network_utility.h" #include "absl/strings/match.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" #include "spdlog/spdlog.h" namespace Envoy { diff --git a/test/test_common/global_test.cc b/test/test_common/global_test.cc index bd6bb56746600..901da205f9249 100644 --- a/test/test_common/global_test.cc +++ b/test/test_common/global_test.cc @@ -2,13 +2,12 @@ #include #include "test/test_common/global.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Test { -class GlobalTest : public testing::Test { +class GlobalTest : public TestBase { protected: }; diff --git a/test/test_common/network_utility_test.cc b/test/test_common/network_utility_test.cc index 9d58e523abdef..97fd38fb24f5c 100644 --- a/test/test_common/network_utility_test.cc +++ b/test/test_common/network_utility_test.cc @@ -2,14 +2,13 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Network { namespace Test { -class NetworkUtilityTest : public testing::TestWithParam { +class NetworkUtilityTest : public TestBaseWithParam { protected: NetworkUtilityTest() : version_(GetParam()) {} const Address::IpVersion version_; diff --git a/test/test_common/registry.h b/test/test_common/registry.h index 0cdcd8f5afd74..c1b04c8ba6f19 100644 --- a/test/test_common/registry.h +++ b/test/test_common/registry.h @@ -2,7 +2,7 @@ #include "envoy/registry/registry.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" namespace Envoy { namespace Registry { diff --git a/test/test_common/simulated_time_system_test.cc b/test/test_common/simulated_time_system_test.cc index 3dcd5a6278681..ddc7db5dcae57 100644 --- a/test/test_common/simulated_time_system_test.cc +++ b/test/test_common/simulated_time_system_test.cc @@ -2,16 +2,16 @@ #include "common/event/libevent.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "event2/event.h" -#include "gtest/gtest.h" namespace Envoy { namespace Event { namespace Test { -class SimulatedTimeSystemTest : public testing::Test { +class SimulatedTimeSystemTest : public TestBase { protected: SimulatedTimeSystemTest() : event_system_(event_base_new()), scheduler_(time_system_.createScheduler(event_system_)), diff --git a/test/test_common/test_base.cc b/test/test_common/test_base.cc new file mode 100644 index 0000000000000..2e5b9d72bb301 --- /dev/null +++ b/test/test_common/test_base.cc @@ -0,0 +1,19 @@ +#include "test/test_common/test_base.h" + +#include "test/test_common/global.h" + +namespace Envoy { + +bool TestBase::checkSingletonQuiescensce() { + // Check that all singletons have been destroyed. + std::string active_singletons = Envoy::Test::Globals::describeActiveSingletons(); + if (!active_singletons.empty()) { + std::cerr << "\n\nFAIL: Active singletons exist:\n" << active_singletons << std::endl; + return false; + } + return true; +} + +TestBase::~TestBase() { checkSingletonQuiescensce(); } + +} // namespace Envoy diff --git a/test/test_common/test_base.h b/test/test_common/test_base.h new file mode 100644 index 0000000000000..c4044fe6b745d --- /dev/null +++ b/test/test_common/test_base.h @@ -0,0 +1,21 @@ +#pragma once + +#include "gtest/gtest.h" + +namespace Envoy { + +// Provides a common test-base class for all tests in Envoy to use. This offers +// a place to put hooks we'd like to run on every tests. +class TestBase : public ::testing::Test { +public: + static bool checkSingletonQuiescensce(); + ~TestBase() override; +}; + +// Templatized version of TestBase. +template class TestBaseWithParam : public ::testing::TestWithParam { +public: + ~TestBaseWithParam() { TestBase::checkSingletonQuiescensce(); } +}; + +} // namespace Envoy diff --git a/test/test_common/test_time_system_test.cc b/test/test_common/test_time_system_test.cc index 30268d3fe6bfa..27fc24cab94ca 100644 --- a/test/test_common/test_time_system_test.cc +++ b/test/test_common/test_time_system_test.cc @@ -1,15 +1,14 @@ #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_base.h" #include "test/test_common/test_time.h" #include "test/test_common/test_time_system.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - namespace Envoy { namespace Event { namespace Test { -class TestTimeSystemTest : public testing::Test { +class TestTimeSystemTest : public TestBase { protected: }; diff --git a/test/test_common/utility.cc b/test/test_common/utility.cc index 2040262085c75..4b10d5208c446 100644 --- a/test/test_common/utility.cc +++ b/test/test_common/utility.cc @@ -41,7 +41,7 @@ #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" using testing::GTEST_FLAG(random_seed); diff --git a/test/test_common/utility.h b/test/test_common/utility.h index 4b36e2082d2c4..02726229002c2 100644 --- a/test/test_common/utility.h +++ b/test/test_common/utility.h @@ -24,10 +24,10 @@ #include "common/stats/raw_stat_data.h" #include "test/test_common/printers.h" +#include "test/test_common/test_base.h" #include "absl/time/time.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" using testing::_; using testing::AssertionFailure; @@ -285,7 +285,7 @@ class TestUtility { // Tests using this will be of the form IpVersions/SslSocketTest.HalfClose/IPv4 // instead of IpVersions/SslSocketTest.HalfClose/1 static std::string - ipTestParamsToString(const testing::TestParamInfo& params) { + ipTestParamsToString(const ::testing::TestParamInfo& params) { return params.param == Network::Address::IpVersion::v4 ? "IPv4" : "IPv6"; } diff --git a/test/test_common/utility_test.cc b/test/test_common/utility_test.cc index 40083fe339469..347440eea7478 100644 --- a/test/test_common/utility_test.cc +++ b/test/test_common/utility_test.cc @@ -1,7 +1,6 @@ +#include "test/test_common/test_base.h" #include "test/test_common/utility.h" -#include "gtest/gtest.h" - using Envoy::Http::HeaderMap; namespace Envoy { diff --git a/test/test_runner.h b/test/test_runner.h index 7893ddf597abe..34754d376de16 100644 --- a/test/test_runner.h +++ b/test/test_runner.h @@ -7,10 +7,9 @@ #include "test/mocks/access_log/mocks.h" #include "test/test_common/environment.h" -#include "test/test_common/global.h" +#include "test/test_common/test_base.h" #include "gmock/gmock.h" -#include "gtest/gtest.h" namespace Envoy { class TestRunner { @@ -27,8 +26,8 @@ class TestRunner { // (https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md#logging-additional-information), // they are available in the test XML. // TODO(htuch): Log these as well? - ::testing::Test::RecordProperty("TemporaryDirectory", TestEnvironment::temporaryDirectory()); - ::testing::Test::RecordProperty("RunfilesDirectory", TestEnvironment::runfilesDirectory()); + TestBase::RecordProperty("TemporaryDirectory", TestEnvironment::temporaryDirectory()); + TestBase::RecordProperty("RunfilesDirectory", TestEnvironment::runfilesDirectory()); TestEnvironment::setEnvVar("TEST_UDSDIR", TestEnvironment::unixDomainSocketDirectory(), 1); @@ -49,9 +48,7 @@ class TestRunner { int exit_status = RUN_ALL_TESTS(); // Check that all singletons have been destroyed. - std::string active_singletons = Test::Globals::describeActiveSingletons(); - if (!active_singletons.empty()) { - std::cerr << "\n\nFAIL: Active singletons exist:\n" << active_singletons << std::endl; + if (!TestBase::checkSingletonQuiescensce()) { exit_status = EXIT_FAILURE; } diff --git a/test/tools/config_load_check/config_load_check.cc b/test/tools/config_load_check/config_load_check.cc index a36e531c53b16..dbbacdb499977 100644 --- a/test/tools/config_load_check/config_load_check.cc +++ b/test/tools/config_load_check/config_load_check.cc @@ -9,8 +9,7 @@ #include "common/event/libevent.h" #include "test/config_test/config_test.h" - -#include "gtest/gtest.h" +#include "test/test_common/test_base.h" int main(int argc, char* argv[]) { if (argc != 2) { diff --git a/tools/check_format.py b/tools/check_format.py index f03defe713ee5..c14ce69819a1a 100755 --- a/tools/check_format.py +++ b/tools/check_format.py @@ -380,6 +380,11 @@ def checkSourceLine(line, file_path, reportError): reportError("Don't use the '?:' operator, it is a non-standard GCC extension") if line.startswith('using testing::Test;'): reportError("Don't use 'using testing::Test;, elaborate the type instead") + if line.startswith('using testing::TestWithParams;'): + reportError("Don't use 'using testing::Test;, elaborate the type instead") + if file_path != './test/test_common/test_base.h' and (' testing::Test ' in line or + ' testing::TestWithParam' in line): + reportError("Derive test classes from TestBase in test/test_common/test_base.h") def checkBuildLine(line, file_path, reportError): From 0db550d178c50dcba814d08368e2841c29171246 Mon Sep 17 00:00:00 2001 From: alyssawilk Date: Mon, 4 Feb 2019 09:49:27 -0500 Subject: [PATCH 09/51] test: pulling protocol specific test code into protocol-specific test files (#5775) (sort of) part of #5638 This and the follow-up should remove a bunch of code from all the integration tests which link http_integration.cc Risk Level: low (test only) Testing: integration tests pass Docs Changes: n/a Release Notes: n/a Signed-off-by: Alyssa Wilk --- test/integration/http2_integration_test.cc | 347 ++++++++++- test/integration/http_integration.cc | 664 --------------------- test/integration/http_integration.h | 27 +- test/integration/integration_test.cc | 311 +++++++++- test/integration/integration_test.h | 1 + 5 files changed, 637 insertions(+), 713 deletions(-) diff --git a/test/integration/http2_integration_test.cc b/test/integration/http2_integration_test.cc index cdcd637b5550c..4287216c1392c 100644 --- a/test/integration/http2_integration_test.cc +++ b/test/integration/http2_integration_test.cc @@ -94,18 +94,355 @@ TEST_P(Http2IntegrationTest, RetryAttemptCount) { testRetryAttemptCountHeader(); TEST_P(Http2IntegrationTest, EnvoyHandling100Continue) { testEnvoyHandling100Continue(); } +static std::string response_metadata_filter = R"EOF( +name: response-metadata-filter +config: {} +)EOF"; + +// Verifies metadata can be sent at different locations of the responses. TEST_P(Http2MetadataIntegrationTest, ProxyMetadataInResponse) { - testEnvoyProxyMetadataInResponse(); + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + // Sends the first request. + auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends metadata before response header. + const std::string key = "key"; + std::string value = std::string(80 * 1024, '1'); + Http::MetadataMap metadata_map = {{key, value}}; + Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); + Http::MetadataMapVector metadata_map_vector; + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(12, true); + + // Verifies metadata is received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + EXPECT_EQ(response->metadata_map().find(key)->second, value); + + // Sends the second request. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends metadata after response header followed by an empty data frame with end_stream true. + value = std::string(10, '2'); + upstream_request_->encodeHeaders(default_response_headers_, false); + metadata_map = {{key, value}}; + metadata_map_ptr = std::make_unique(metadata_map); + metadata_map_vector.erase(metadata_map_vector.begin()); + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeData(0, true); + + // Verifies metadata is received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + EXPECT_EQ(response->metadata_map().find(key)->second, value); + + // Sends the third request. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends metadata after response header and before data. + value = std::string(10, '3'); + upstream_request_->encodeHeaders(default_response_headers_, false); + metadata_map = {{key, value}}; + metadata_map_ptr = std::make_unique(metadata_map); + metadata_map_vector.erase(metadata_map_vector.begin()); + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeData(10, true); + + // Verifies metadata is received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + EXPECT_EQ(response->metadata_map().find(key)->second, value); + + // Sends the fourth request. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends metadata between data frames. + value = std::string(10, '4'); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(10, false); + metadata_map = {{key, value}}; + metadata_map_ptr = std::make_unique(metadata_map); + metadata_map_vector.erase(metadata_map_vector.begin()); + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeData(10, true); + + // Verifies metadata is received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + EXPECT_EQ(response->metadata_map().find(key)->second, value); + + // Sends the fifth request. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends metadata after the last non-empty data frames. + value = std::string(10, '5'); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(10, false); + metadata_map = {{key, value}}; + metadata_map_ptr = std::make_unique(metadata_map); + metadata_map_vector.erase(metadata_map_vector.begin()); + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeData(0, true); + + // Verifies metadata is received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + EXPECT_EQ(response->metadata_map().find(key)->second, value); + + // Sends the sixth request. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends metadata before reset. + value = std::string(10, '6'); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(10, false); + metadata_map = {{key, value}}; + metadata_map_ptr = std::make_unique(metadata_map); + metadata_map_vector.erase(metadata_map_vector.begin()); + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeResetStream(); + + // Verifies stream is reset. + response->waitForReset(); + ASSERT_FALSE(response->complete()); } -TEST_P(Http2MetadataIntegrationTest, ProxyMultipleMetadata) { testEnvoyProxyMultipleMetadata(); } +TEST_P(Http2MetadataIntegrationTest, ProxyMultipleMetadata) { + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + // Sends a request. + auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + const int size = 4; + std::vector multiple_vecs(size); + for (int i = 0; i < size; i++) { + Runtime::RandomGeneratorImpl random; + int value_size = random.random() % Http::METADATA_MAX_PAYLOAD_SIZE + 1; + Http::MetadataMap metadata_map = {{std::string(i, 'a'), std::string(value_size, 'b')}}; + Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); + multiple_vecs[i].push_back(std::move(metadata_map_ptr)); + } + upstream_request_->encodeMetadata(multiple_vecs[0]); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeMetadata(multiple_vecs[1]); + upstream_request_->encodeData(12, false); + upstream_request_->encodeMetadata(multiple_vecs[2]); + upstream_request_->encodeData(12, false); + upstream_request_->encodeMetadata(multiple_vecs[3]); + upstream_request_->encodeData(12, true); + + // Verifies multiple metadata are received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + for (int i = 0; i < size; i++) { + for (const auto& metadata : *multiple_vecs[i][0]) { + EXPECT_EQ(response->metadata_map().find(metadata.first)->second, metadata.second); + } + } + EXPECT_EQ(response->metadata_map().size(), multiple_vecs.size()); +} -TEST_P(Http2MetadataIntegrationTest, ProxyInvalidMetadata) { testEnvoyProxyInvalidMetadata(); } +TEST_P(Http2MetadataIntegrationTest, ProxyInvalidMetadata) { + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); -TEST_P(Http2MetadataIntegrationTest, TestResponseMetadata) { testResponseMetadata(); } + // Sends a request. + auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends over-sized metadata before response header. + const std::string key = "key"; + std::string value = std::string(1024 * 1024, 'a'); + Http::MetadataMap metadata_map = {{key, value}}; + Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); + Http::MetadataMapVector metadata_map_vector; + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeData(12, false); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeData(12, true); + + // Verifies metadata is not received by the client. + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + EXPECT_EQ(response->metadata_map().size(), 0); +} + +void verifyExpectedMetadata(Http::MetadataMap metadata_map, std::set keys) { + for (const auto key : keys) { + // keys are the same as their corresponding values. + EXPECT_EQ(metadata_map.find(key)->second, key); + } + EXPECT_EQ(metadata_map.size(), keys.size()); +} + +TEST_P(Http2MetadataIntegrationTest, TestResponseMetadata) { + + addFilters({response_metadata_filter}); + config_helper_.addConfigModifier( + [&](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) + -> void { hcm.set_proxy_100_continue(true); }); + + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + // Upstream responds with headers. + auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + upstream_request_->encodeHeaders(default_response_headers_, true); + + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + // Verify metadata added in encodeHeaders(): "headers", "duplicate" and "keep". + std::set expected_metadata_keys = {"headers", "duplicate", "keep"}; + verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); + + // Upstream responds with headers and data. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(100, true); + + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + // Verify metadata added in encodeHeaders(): "headers" and "duplicate" and metadata added in + // encodeData(): "data" and "duplicate" are received by the client. Note that "remove" is + // consumed. + expected_metadata_keys.insert("data"); + verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); + EXPECT_EQ(response->keyCount("duplicate"), 2); + EXPECT_EQ(response->keyCount("keep"), 2); + + // Upstream responds with headers, data and trailers. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(10, false); + Http::TestHeaderMapImpl response_trailers{{"response", "trailer"}}; + upstream_request_->encodeTrailers(response_trailers); + + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + // Verify metadata added in encodeHeaders(): "headers" and "duplicate", and metadata added in + // encodeData(): "data" and "duplicate", and metadata added in encodeTrailer(): "trailers" and + // "duplicate" are received by the client. Note that "remove" is consumed. + expected_metadata_keys.insert("trailers"); + verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); + EXPECT_EQ(response->keyCount("duplicate"), 3); + EXPECT_EQ(response->keyCount("keep"), 4); + + // Upstream responds with headers, 100-continue and data. + response = codec_client_->makeRequestWithBody(Http::TestHeaderMapImpl{{":method", "GET"}, + {":path", "/dynamo/url"}, + {":scheme", "http"}, + {":authority", "host"}, + {"expect", "100-continue"}}, + 10); + + waitForNextUpstreamRequest(); + upstream_request_->encode100ContinueHeaders(Http::TestHeaderMapImpl{{":status", "100"}}); + response->waitForContinueHeaders(); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(100, true); + + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + // Verify metadata added in encodeHeaders: "headers" and "duplicate", and metadata added in + // encodeData(): "data" and "duplicate", and metadata added in encode100Continue(): "100-continue" + // and "duplicate" are received by the client. Note that "remove" is consumed. + expected_metadata_keys.erase("trailers"); + expected_metadata_keys.insert("100-continue"); + verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); + EXPECT_EQ(response->keyCount("duplicate"), 4); + EXPECT_EQ(response->keyCount("keep"), 4); + + // Upstream responds with headers and metadata that will not be consumed. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + Http::MetadataMap metadata_map = {{"aaa", "aaa"}}; + Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); + Http::MetadataMapVector metadata_map_vector; + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeHeaders(default_response_headers_, true); + + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + // Verify metadata added in encodeHeaders(): "headers" and "duplicate", and metadata added in + // encodeMetadata(): "aaa", "keep" and "duplicate" are received by the client. Note that "remove" + // is consumed. + expected_metadata_keys.erase("data"); + expected_metadata_keys.erase("100-continue"); + expected_metadata_keys.insert("aaa"); + verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); + EXPECT_EQ(response->keyCount("keep"), 2); + + // Upstream responds with headers, data and metadata that will be consumed. + response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + metadata_map = {{"consume", "consume"}, {"remove", "remove"}}; + metadata_map_ptr = std::make_unique(metadata_map); + metadata_map_vector.clear(); + metadata_map_vector.push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(metadata_map_vector); + upstream_request_->encodeHeaders(default_response_headers_, false); + upstream_request_->encodeData(100, true); + + response->waitForEndStream(); + ASSERT_TRUE(response->complete()); + // Verify metadata added in encodeHeaders(): "headers" and "duplicate", and metadata added in + // encodeData(): "data", "duplicate", and metadata added in encodeMetadata(): "keep", "duplicate", + // "replace" are received by the client. Note that key "remove" and "consume" are consumed. + expected_metadata_keys.erase("aaa"); + expected_metadata_keys.insert("data"); + expected_metadata_keys.insert("replace"); + verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); + EXPECT_EQ(response->keyCount("duplicate"), 2); + EXPECT_EQ(response->keyCount("keep"), 3); +} TEST_P(Http2MetadataIntegrationTest, ProxyMultipleMetadataReachSizeLimit) { - testEnvoyMultipleMetadataReachSizeLimit(); + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + // Sends a request. + auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); + waitForNextUpstreamRequest(); + + // Sends multiple metadata after response header until max size limit is reached. + upstream_request_->encodeHeaders(default_response_headers_, false); + const int size = 200; + std::vector multiple_vecs(size); + for (int i = 0; i < size; i++) { + Http::MetadataMap metadata_map = {{"key", std::string(10000, 'a')}}; + Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); + multiple_vecs[i].push_back(std::move(metadata_map_ptr)); + upstream_request_->encodeMetadata(multiple_vecs[i]); + } + upstream_request_->encodeData(12, true); + + // Verifies reset is received. + response->waitForReset(); + ASSERT_FALSE(response->complete()); } TEST_P(Http2IntegrationTest, EnvoyHandlingDuplicate100Continue) { diff --git a/test/integration/http_integration.cc b/test/integration/http_integration.cc index 2815e2e59d212..3b5eba31906a2 100644 --- a/test/integration/http_integration.cc +++ b/test/integration/http_integration.cc @@ -41,23 +41,6 @@ using testing::Not; namespace Envoy { namespace { -std::string normalizeDate(const std::string& s) { - const std::regex date_regex("date:[^\r]+"); - return std::regex_replace(s, date_regex, "date: Mon, 01 Jan 2017 00:00:00 GMT"); -} - -void setAllowAbsoluteUrl( - envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) { - envoy::api::v2::core::Http1ProtocolOptions options; - options.mutable_allow_absolute_url()->set_value(true); - hcm.mutable_http_protocol_options()->CopyFrom(options); -}; - -void setAllowHttp10WithDefaultHost( - envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) { - hcm.mutable_http_protocol_options()->set_accept_http_10(true); - hcm.mutable_http_protocol_options()->set_default_host_for_http_10("default.com"); -} envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager::CodecType typeToCodecType(Http::CodecClient::Type type) { @@ -441,47 +424,6 @@ void HttpIntegrationTest::testRouterRedirect() { response->headers().get(Http::Headers::get().Location)->value().c_str()); } -void HttpIntegrationTest::testRouterDirectResponse() { - const std::string body = "Response body"; - const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", body); - static const std::string domain("direct.example.com"); - static const std::string prefix("/"); - static const Http::Code status(Http::Code::OK); - config_helper_.addConfigModifier( - [&](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) - -> void { - auto* route_config = hcm.mutable_route_config(); - auto* header_value_option = route_config->mutable_response_headers_to_add()->Add(); - header_value_option->mutable_header()->set_key("x-additional-header"); - header_value_option->mutable_header()->set_value("example-value"); - header_value_option->mutable_append()->set_value(false); - header_value_option = route_config->mutable_response_headers_to_add()->Add(); - header_value_option->mutable_header()->set_key("content-type"); - header_value_option->mutable_header()->set_value("text/html"); - header_value_option->mutable_append()->set_value(false); - auto* virtual_host = route_config->add_virtual_hosts(); - virtual_host->set_name(domain); - virtual_host->add_domains(domain); - virtual_host->add_routes()->mutable_match()->set_prefix(prefix); - virtual_host->mutable_routes(0)->mutable_direct_response()->set_status( - static_cast(status)); - virtual_host->mutable_routes(0)->mutable_direct_response()->mutable_body()->set_filename( - file_path); - }); - initialize(); - - BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest( - lookupPort("http"), "GET", "/", "", downstream_protocol_, version_, "direct.example.com"); - ASSERT_TRUE(response->complete()); - EXPECT_STREQ("200", response->headers().Status()->value().c_str()); - EXPECT_STREQ("example-value", response->headers() - .get(Envoy::Http::LowerCaseString("x-additional-header")) - ->value() - .c_str()); - EXPECT_STREQ("text/html", response->headers().ContentType()->value().c_str()); - EXPECT_EQ(body, response->body()); -} - // Add a health check filter and verify correct computation of health based on upstream status. void HttpIntegrationTest::testComputedHealthCheck() { config_helper_.addFilter(R"EOF( @@ -1059,219 +1001,6 @@ void HttpIntegrationTest::testHittingEncoderFilterLimit() { EXPECT_STREQ("500", response->headers().Status()->value().c_str()); } -// Verifies metadata can be sent at different locations of the responses. -void HttpIntegrationTest::testEnvoyProxyMetadataInResponse() { - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - // Sends the first request. - auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends metadata before response header. - const std::string key = "key"; - std::string value = std::string(80 * 1024, '1'); - Http::MetadataMap metadata_map = {{key, value}}; - Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); - Http::MetadataMapVector metadata_map_vector; - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(12, true); - - // Verifies metadata is received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - EXPECT_EQ(response->metadata_map().find(key)->second, value); - - // Sends the second request. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends metadata after response header followed by an empty data frame with end_stream true. - value = std::string(10, '2'); - upstream_request_->encodeHeaders(default_response_headers_, false); - metadata_map = {{key, value}}; - metadata_map_ptr = std::make_unique(metadata_map); - metadata_map_vector.erase(metadata_map_vector.begin()); - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeData(0, true); - - // Verifies metadata is received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - EXPECT_EQ(response->metadata_map().find(key)->second, value); - - // Sends the third request. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends metadata after response header and before data. - value = std::string(10, '3'); - upstream_request_->encodeHeaders(default_response_headers_, false); - metadata_map = {{key, value}}; - metadata_map_ptr = std::make_unique(metadata_map); - metadata_map_vector.erase(metadata_map_vector.begin()); - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeData(10, true); - - // Verifies metadata is received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - EXPECT_EQ(response->metadata_map().find(key)->second, value); - - // Sends the fourth request. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends metadata between data frames. - value = std::string(10, '4'); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(10, false); - metadata_map = {{key, value}}; - metadata_map_ptr = std::make_unique(metadata_map); - metadata_map_vector.erase(metadata_map_vector.begin()); - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeData(10, true); - - // Verifies metadata is received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - EXPECT_EQ(response->metadata_map().find(key)->second, value); - - // Sends the fifth request. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends metadata after the last non-empty data frames. - value = std::string(10, '5'); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(10, false); - metadata_map = {{key, value}}; - metadata_map_ptr = std::make_unique(metadata_map); - metadata_map_vector.erase(metadata_map_vector.begin()); - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeData(0, true); - - // Verifies metadata is received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - EXPECT_EQ(response->metadata_map().find(key)->second, value); - - // Sends the sixth request. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends metadata before reset. - value = std::string(10, '6'); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(10, false); - metadata_map = {{key, value}}; - metadata_map_ptr = std::make_unique(metadata_map); - metadata_map_vector.erase(metadata_map_vector.begin()); - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeResetStream(); - - // Verifies stream is reset. - response->waitForReset(); - ASSERT_FALSE(response->complete()); -} - -void HttpIntegrationTest::testEnvoyProxyMultipleMetadata() { - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - // Sends a request. - auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - const int size = 4; - std::vector multiple_vecs(size); - for (int i = 0; i < size; i++) { - Runtime::RandomGeneratorImpl random; - int value_size = random.random() % Http::METADATA_MAX_PAYLOAD_SIZE + 1; - Http::MetadataMap metadata_map = {{std::string(i, 'a'), std::string(value_size, 'b')}}; - Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); - multiple_vecs[i].push_back(std::move(metadata_map_ptr)); - } - upstream_request_->encodeMetadata(multiple_vecs[0]); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeMetadata(multiple_vecs[1]); - upstream_request_->encodeData(12, false); - upstream_request_->encodeMetadata(multiple_vecs[2]); - upstream_request_->encodeData(12, false); - upstream_request_->encodeMetadata(multiple_vecs[3]); - upstream_request_->encodeData(12, true); - - // Verifies multiple metadata are received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - for (int i = 0; i < size; i++) { - for (const auto& metadata : *multiple_vecs[i][0]) { - EXPECT_EQ(response->metadata_map().find(metadata.first)->second, metadata.second); - } - } - EXPECT_EQ(response->metadata_map().size(), multiple_vecs.size()); -} - -void HttpIntegrationTest::testEnvoyProxyInvalidMetadata() { - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - // Sends a request. - auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends over-sized metadata before response header. - const std::string key = "key"; - std::string value = std::string(1024 * 1024, 'a'); - Http::MetadataMap metadata_map = {{key, value}}; - Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); - Http::MetadataMapVector metadata_map_vector; - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeData(12, false); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeData(12, true); - - // Verifies metadata is not received by the client. - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - EXPECT_EQ(response->metadata_map().size(), 0); -} - -void HttpIntegrationTest::testEnvoyMultipleMetadataReachSizeLimit() { - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - // Sends a request. - auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - - // Sends multiple metadata after response header until max size limit is reached. - upstream_request_->encodeHeaders(default_response_headers_, false); - const int size = 200; - std::vector multiple_vecs(size); - for (int i = 0; i < size; i++) { - Http::MetadataMap metadata_map = {{"key", std::string(10000, 'a')}}; - Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); - multiple_vecs[i].push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(multiple_vecs[i]); - } - upstream_request_->encodeData(12, true); - - // Verifies reset is received. - response->waitForReset(); - ASSERT_FALSE(response->complete()); -} - void HttpIntegrationTest::testEnvoyHandling100Continue(bool additional_continue_from_upstream, const std::string& via) { initialize(); @@ -1562,240 +1291,6 @@ void HttpIntegrationTest::testTwoRequests(bool network_backup) { EXPECT_EQ(1024U, response->body().size()); } -void HttpIntegrationTest::testBadFirstline() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "hello", &response); - EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); -} - -void HttpIntegrationTest::testMissingDelimiter() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), - "GET / HTTP/1.1\r\nHost: host\r\nfoo bar\r\n\r\n", &response); - EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); -} - -void HttpIntegrationTest::testInvalidCharacterInFirstline() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "GE(T / HTTP/1.1\r\nHost: host\r\n\r\n", - &response); - EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); -} - -void HttpIntegrationTest::testInvalidVersion() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.01\r\nHost: host\r\n\r\n", - &response); - EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); -} - -void HttpIntegrationTest::testHttp10DisabledWithUpgrade() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\nUpgrade: h2c\r\n\r\n", - &response, true); - EXPECT_TRUE(response.find("HTTP/1.1 426 Upgrade Required\r\n") == 0); -} - -void HttpIntegrationTest::testHttp10Disabled() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\n\r\n", &response, true); - EXPECT_TRUE(response.find("HTTP/1.1 426 Upgrade Required\r\n") == 0); -} - -// Turn HTTP/1.0 support on and verify the request is proxied and the default host is sent upstream. -void HttpIntegrationTest::testHttp10Enabled() { - autonomous_upstream_ = true; - config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\n\r\n", &response, false); - EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); - EXPECT_THAT(response, HasSubstr("connection: close")); - EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); - - std::unique_ptr upstream_headers = - reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); - ASSERT_TRUE(upstream_headers != nullptr); - EXPECT_EQ(upstream_headers->Host()->value(), "default.com"); - - sendRawHttpAndWaitForResponse(lookupPort("http"), "HEAD / HTTP/1.0\r\n\r\n", &response, false); - EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); - EXPECT_THAT(response, HasSubstr("connection: close")); - EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); -} - -// Verify for HTTP/1.0 a keep-alive header results in no connection: close. -// Also verify existing host headers are passed through for the HTTP/1.0 case. -void HttpIntegrationTest::testHttp10WithHostAndKeepAlive() { - autonomous_upstream_ = true; - config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), - "GET / HTTP/1.0\r\nHost: foo.com\r\nConnection:Keep-alive\r\n\r\n", - &response, true); - EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); - EXPECT_THAT(response, Not(HasSubstr("connection: close"))); - EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); - - std::unique_ptr upstream_headers = - reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); - ASSERT_TRUE(upstream_headers != nullptr); - EXPECT_EQ(upstream_headers->Host()->value(), "foo.com"); -} - -// Turn HTTP/1.0 support on and verify 09 style requests work. -void HttpIntegrationTest::testHttp09Enabled() { - autonomous_upstream_ = true; - config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), "GET /\r\n\r\n", &response, false); - EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); - EXPECT_THAT(response, HasSubstr("connection: close")); - EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); - - std::unique_ptr upstream_headers = - reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); - ASSERT_TRUE(upstream_headers != nullptr); - EXPECT_EQ(upstream_headers->Host()->value(), "default.com"); -} - -void HttpIntegrationTest::testAbsolutePath() { - // Configure www.redirect.com to send a redirect, and ensure the redirect is - // encountered via absolute URL. - config_helper_.addRoute("www.redirect.com", "/", "cluster_0", true, - envoy::api::v2::route::RouteAction::SERVICE_UNAVAILABLE, - envoy::api::v2::route::VirtualHost::ALL); - config_helper_.addConfigModifier(&setAllowAbsoluteUrl); - - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), - "GET http://www.redirect.com HTTP/1.1\r\nHost: host\r\n\r\n", - &response, true); - EXPECT_FALSE(response.find("HTTP/1.1 404 Not Found\r\n") == 0); -} - -void HttpIntegrationTest::testAbsolutePathWithPort() { - // Configure www.namewithport.com:1234 to send a redirect, and ensure the redirect is - // encountered via absolute URL with a port. - config_helper_.addRoute("www.namewithport.com:1234", "/", "cluster_0", true, - envoy::api::v2::route::RouteAction::SERVICE_UNAVAILABLE, - envoy::api::v2::route::VirtualHost::ALL); - config_helper_.addConfigModifier(&setAllowAbsoluteUrl); - initialize(); - std::string response; - sendRawHttpAndWaitForResponse( - lookupPort("http"), "GET http://www.namewithport.com:1234 HTTP/1.1\r\nHost: host\r\n\r\n", - &response, true); - EXPECT_FALSE(response.find("HTTP/1.1 404 Not Found\r\n") == 0); -} - -void HttpIntegrationTest::testAbsolutePathWithoutPort() { - // Add a restrictive default match, to avoid the request hitting the * / catchall. - config_helper_.setDefaultHostAndRoute("foo.com", "/found"); - // Set a matcher for www.namewithport.com:1234 and verify http://www.namewithport.com does not - // match - config_helper_.addRoute("www.namewithport.com:1234", "/", "cluster_0", true, - envoy::api::v2::route::RouteAction::SERVICE_UNAVAILABLE, - envoy::api::v2::route::VirtualHost::ALL); - config_helper_.addConfigModifier(&setAllowAbsoluteUrl); - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), - "GET http://www.namewithport.com HTTP/1.1\r\nHost: host\r\n\r\n", - &response, true); - EXPECT_TRUE(response.find("HTTP/1.1 404 Not Found\r\n") == 0) << response; -} - -void HttpIntegrationTest::testAllowAbsoluteSameRelative() { - // TODO(mattwoodyard) run this test. - // Ensure that relative urls behave the same with allow_absolute_url enabled and without - testEquivalent("GET /foo/bar HTTP/1.1\r\nHost: host\r\n\r\n"); -} - -void HttpIntegrationTest::testConnect() { - // Ensure that connect behaves the same with allow_absolute_url enabled and without - testEquivalent("CONNECT www.somewhere.com:80 HTTP/1.1\r\nHost: host\r\n\r\n"); -} - -void HttpIntegrationTest::testInlineHeaders() { - autonomous_upstream_ = true; - config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), - "GET / HTTP/1.1\r\n" - "Host: foo.com\r\n" - "Foo: bar\r\n" - "Cache-control: public\r\n" - "Cache-control: 123\r\n" - "Eep: baz\r\n\r\n", - &response, true); - EXPECT_THAT(response, HasSubstr("HTTP/1.1 200 OK\r\n")); - - std::unique_ptr upstream_headers = - reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); - ASSERT_TRUE(upstream_headers != nullptr); - EXPECT_EQ(upstream_headers->Host()->value(), "foo.com"); - EXPECT_EQ(upstream_headers->CacheControl()->value(), "public,123"); - ASSERT_TRUE(upstream_headers->get(Envoy::Http::LowerCaseString("foo")) != nullptr); - EXPECT_STREQ("bar", upstream_headers->get(Envoy::Http::LowerCaseString("foo"))->value().c_str()); - ASSERT_TRUE(upstream_headers->get(Envoy::Http::LowerCaseString("eep")) != nullptr); - EXPECT_STREQ("baz", upstream_headers->get(Envoy::Http::LowerCaseString("eep"))->value().c_str()); -} - -void HttpIntegrationTest::testEquivalent(const std::string& request) { - config_helper_.addConfigModifier([&](envoy::config::bootstrap::v2::Bootstrap& bootstrap) -> void { - // Clone the whole listener. - auto static_resources = bootstrap.mutable_static_resources(); - auto* old_listener = static_resources->mutable_listeners(0); - auto* cloned_listener = static_resources->add_listeners(); - cloned_listener->CopyFrom(*old_listener); - old_listener->set_name("http_forward"); - }); - // Set the first listener to allow absolute URLs. - config_helper_.addConfigModifier(&setAllowAbsoluteUrl); - initialize(); - - std::string response1; - sendRawHttpAndWaitForResponse(lookupPort("http"), request.c_str(), &response1, true); - - std::string response2; - sendRawHttpAndWaitForResponse(lookupPort("http_forward"), request.c_str(), &response2, true); - - EXPECT_EQ(normalizeDate(response1), normalizeDate(response2)); -} - -void HttpIntegrationTest::testBadPath() { - initialize(); - std::string response; - sendRawHttpAndWaitForResponse(lookupPort("http"), - "GET http://api.lyft.com HTTP/1.1\r\nHost: host\r\n\r\n", &response, - true); - EXPECT_TRUE(response.find("HTTP/1.1 404 Not Found\r\n") == 0); -} - -void HttpIntegrationTest::testNoHost() { - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - Http::TestHeaderMapImpl request_headers{ - {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}}; - auto response = codec_client_->makeHeaderOnlyRequest(request_headers); - response->waitForEndStream(); - - ASSERT_TRUE(response->complete()); - EXPECT_STREQ("400", response->headers().Status()->value().c_str()); -} - void HttpIntegrationTest::testValidZeroLengthContent() { initialize(); @@ -1902,28 +1397,6 @@ void HttpIntegrationTest::testLargeRequestHeaders(uint32_t size, uint32_t max_si } } -void HttpIntegrationTest::testUpstreamProtocolError() { - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - auto encoder_decoder = codec_client_->startRequest(Http::TestHeaderMapImpl{ - {":method", "GET"}, {":path", "/test/long/url"}, {":authority", "host"}}); - auto response = std::move(encoder_decoder.second); - - FakeRawConnectionPtr fake_upstream_connection; - ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); - // TODO(mattklein123): Waiting for exact amount of data is a hack. This needs to - // be fixed. - std::string data; - ASSERT_TRUE(fake_upstream_connection->waitForData(187, &data)); - ASSERT_TRUE(fake_upstream_connection->write("bad protocol data!")); - ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); - codec_client_->waitForDisconnect(); - - EXPECT_TRUE(response->complete()); - EXPECT_STREQ("503", response->headers().Status()->value().c_str()); -} - void HttpIntegrationTest::testHeadersOnlyFilterEncoding() { config_helper_.addFilter(R"EOF( name: encode-headers-only @@ -2155,143 +1628,6 @@ void HttpIntegrationTest::testTrailers(uint64_t request_size, uint64_t response_ } } -static std::string response_metadata_filter = R"EOF( -name: response-metadata-filter -config: {} -)EOF"; - -void verifyExpectedMetadata(Http::MetadataMap metadata_map, std::set keys) { - for (const auto key : keys) { - // keys are the same as their corresponding values. - EXPECT_EQ(metadata_map.find(key)->second, key); - } - EXPECT_EQ(metadata_map.size(), keys.size()); -} - -void HttpIntegrationTest::testResponseMetadata() { - addFilters({response_metadata_filter}); - config_helper_.addConfigModifier( - [&](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) - -> void { hcm.set_proxy_100_continue(true); }); - - initialize(); - codec_client_ = makeHttpConnection(lookupPort("http")); - - // Upstream responds with headers. - auto response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - upstream_request_->encodeHeaders(default_response_headers_, true); - - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - // Verify metadata added in encodeHeaders(): "headers", "duplicate" and "keep". - std::set expected_metadata_keys = {"headers", "duplicate", "keep"}; - verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); - - // Upstream responds with headers and data. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(100, true); - - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - // Verify metadata added in encodeHeaders(): "headers" and "duplicate" and metadata added in - // encodeData(): "data" and "duplicate" are received by the client. Note that "remove" is - // consumed. - expected_metadata_keys.insert("data"); - verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); - EXPECT_EQ(response->keyCount("duplicate"), 2); - EXPECT_EQ(response->keyCount("keep"), 2); - - // Upstream responds with headers, data and trailers. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(10, false); - Http::TestHeaderMapImpl response_trailers{{"response", "trailer"}}; - upstream_request_->encodeTrailers(response_trailers); - - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - // Verify metadata added in encodeHeaders(): "headers" and "duplicate", and metadata added in - // encodeData(): "data" and "duplicate", and metadata added in encodeTrailer(): "trailers" and - // "duplicate" are received by the client. Note that "remove" is consumed. - expected_metadata_keys.insert("trailers"); - verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); - EXPECT_EQ(response->keyCount("duplicate"), 3); - EXPECT_EQ(response->keyCount("keep"), 4); - - // Upstream responds with headers, 100-continue and data. - response = codec_client_->makeRequestWithBody(Http::TestHeaderMapImpl{{":method", "GET"}, - {":path", "/dynamo/url"}, - {":scheme", "http"}, - {":authority", "host"}, - {"expect", "100-continue"}}, - 10); - - waitForNextUpstreamRequest(); - upstream_request_->encode100ContinueHeaders(Http::TestHeaderMapImpl{{":status", "100"}}); - response->waitForContinueHeaders(); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(100, true); - - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - // Verify metadata added in encodeHeaders: "headers" and "duplicate", and metadata added in - // encodeData(): "data" and "duplicate", and metadata added in encode100Continue(): "100-continue" - // and "duplicate" are received by the client. Note that "remove" is consumed. - expected_metadata_keys.erase("trailers"); - expected_metadata_keys.insert("100-continue"); - verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); - EXPECT_EQ(response->keyCount("duplicate"), 4); - EXPECT_EQ(response->keyCount("keep"), 4); - - // Upstream responds with headers and metadata that will not be consumed. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - Http::MetadataMap metadata_map = {{"aaa", "aaa"}}; - Http::MetadataMapPtr metadata_map_ptr = std::make_unique(metadata_map); - Http::MetadataMapVector metadata_map_vector; - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeHeaders(default_response_headers_, true); - - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - // Verify metadata added in encodeHeaders(): "headers" and "duplicate", and metadata added in - // encodeMetadata(): "aaa", "keep" and "duplicate" are received by the client. Note that "remove" - // is consumed. - expected_metadata_keys.erase("data"); - expected_metadata_keys.erase("100-continue"); - expected_metadata_keys.insert("aaa"); - verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); - EXPECT_EQ(response->keyCount("keep"), 2); - - // Upstream responds with headers, data and metadata that will be consumed. - response = codec_client_->makeRequestWithBody(default_request_headers_, 10); - waitForNextUpstreamRequest(); - metadata_map = {{"consume", "consume"}, {"remove", "remove"}}; - metadata_map_ptr = std::make_unique(metadata_map); - metadata_map_vector.clear(); - metadata_map_vector.push_back(std::move(metadata_map_ptr)); - upstream_request_->encodeMetadata(metadata_map_vector); - upstream_request_->encodeHeaders(default_response_headers_, false); - upstream_request_->encodeData(100, true); - - response->waitForEndStream(); - ASSERT_TRUE(response->complete()); - // Verify metadata added in encodeHeaders(): "headers" and "duplicate", and metadata added in - // encodeData(): "data", "duplicate", and metadata added in encodeMetadata(): "keep", "duplicate", - // "replace" are received by the client. Note that key "remove" and "consume" are consumed. - expected_metadata_keys.erase("aaa"); - expected_metadata_keys.insert("data"); - expected_metadata_keys.insert("replace"); - verifyExpectedMetadata(response->metadata_map(), expected_metadata_keys); - EXPECT_EQ(response->keyCount("duplicate"), 2); - EXPECT_EQ(response->keyCount("keep"), 3); -} - std::string HttpIntegrationTest::listenerStatPrefix(const std::string& stat_name) { if (version_ == Network::Address::IpVersion::v4) { return "listener.127.0.0.1_0." + stat_name; diff --git a/test/integration/http_integration.h b/test/integration/http_integration.h index fa7ddfbdd7119..a0d2b0d2bc8a9 100644 --- a/test/integration/http_integration.h +++ b/test/integration/http_integration.h @@ -130,7 +130,6 @@ class HttpIntegrationTest : public BaseIntegrationTest { int upstream_index); void testRouterRedirect(); - void testRouterDirectResponse(); void testRouterNotFound(); void testRouterNotFoundWithBody(); void testRouterClusterNotFound404(); @@ -160,28 +159,9 @@ class HttpIntegrationTest : public BaseIntegrationTest { void testHeadersOnlyFilterEncodingIntermediateFilters(); void testHeadersOnlyFilterDecodingIntermediateFilters(); void testHeadersOnlyFilterInterleaved(); - // HTTP/1 tests - void testBadFirstline(); - void testMissingDelimiter(); - void testInvalidCharacterInFirstline(); - void testInvalidVersion(); - void testHttp10Disabled(); - void testHttp10DisabledWithUpgrade(); - void testHttp09Enabled(); - void testHttp10Enabled(); - void testHttp10WithHostAndKeepAlive(); - void testUpstreamProtocolError(); - void testBadPath(); - void testAbsolutePath(); - void testAbsolutePathWithPort(); - void testAbsolutePathWithoutPort(); - void testConnect(); - void testInlineHeaders(); - void testAllowAbsoluteSameRelative(); + // Test that a request returns the same content with both allow_absolute_urls enabled and // allow_absolute_urls disabled - void testEquivalent(const std::string& request); - void testNoHost(); void testDefaultHost(); void testValidZeroLengthContent(); void testInvalidContentLength(); @@ -198,11 +178,6 @@ class HttpIntegrationTest : public BaseIntegrationTest { void testRetryHostPredicateFilter(); void testHittingDecoderFilterLimit(); void testHittingEncoderFilterLimit(); - void testEnvoyProxyMetadataInResponse(); - void testEnvoyProxyMultipleMetadata(); - void testEnvoyProxyInvalidMetadata(); - void testResponseMetadata(); - void testEnvoyMultipleMetadataReachSizeLimit(); void testEnvoyHandling100Continue(bool additional_continue_from_upstream = false, const std::string& via = ""); void testEnvoyProxying100Continue(bool continue_before_upstream_complete = false, diff --git a/test/integration/integration_test.cc b/test/integration/integration_test.cc index 6efef370306f1..a2eac922b4a2b 100644 --- a/test/integration/integration_test.cc +++ b/test/integration/integration_test.cc @@ -8,6 +8,7 @@ #include "common/http/headers.h" #include "common/protobuf/utility.h" +#include "test/integration/autonomous_upstream.h" #include "test/integration/utility.h" #include "test/mocks/http/mocks.h" #include "test/test_common/network_utility.h" @@ -25,6 +26,28 @@ using testing::Not; namespace Envoy { +namespace { + +std::string normalizeDate(const std::string& s) { + const std::regex date_regex("date:[^\r]+"); + return std::regex_replace(s, date_regex, "date: Mon, 01 Jan 2017 00:00:00 GMT"); +} + +void setAllowAbsoluteUrl( + envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) { + envoy::api::v2::core::Http1ProtocolOptions options; + options.mutable_allow_absolute_url()->set_value(true); + hcm.mutable_http_protocol_options()->CopyFrom(options); +}; + +void setAllowHttp10WithDefaultHost( + envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) { + hcm.mutable_http_protocol_options()->set_accept_http_10(true); + hcm.mutable_http_protocol_options()->set_default_host_for_http_10("default.com"); +} + +} // namespace + INSTANTIATE_TEST_SUITE_P(IpVersions, IntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); @@ -39,7 +62,46 @@ TEST_P(IntegrationTest, RouterClusterNotFound503) { testRouterClusterNotFound503 TEST_P(IntegrationTest, RouterRedirect) { testRouterRedirect(); } -TEST_P(IntegrationTest, RouterDirectResponse) { testRouterDirectResponse(); } +TEST_P(IntegrationTest, RouterDirectResponse) { + const std::string body = "Response body"; + const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", body); + static const std::string domain("direct.example.com"); + static const std::string prefix("/"); + static const Http::Code status(Http::Code::OK); + config_helper_.addConfigModifier( + [&](envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager& hcm) + -> void { + auto* route_config = hcm.mutable_route_config(); + auto* header_value_option = route_config->mutable_response_headers_to_add()->Add(); + header_value_option->mutable_header()->set_key("x-additional-header"); + header_value_option->mutable_header()->set_value("example-value"); + header_value_option->mutable_append()->set_value(false); + header_value_option = route_config->mutable_response_headers_to_add()->Add(); + header_value_option->mutable_header()->set_key("content-type"); + header_value_option->mutable_header()->set_value("text/html"); + header_value_option->mutable_append()->set_value(false); + auto* virtual_host = route_config->add_virtual_hosts(); + virtual_host->set_name(domain); + virtual_host->add_domains(domain); + virtual_host->add_routes()->mutable_match()->set_prefix(prefix); + virtual_host->mutable_routes(0)->mutable_direct_response()->set_status( + static_cast(status)); + virtual_host->mutable_routes(0)->mutable_direct_response()->mutable_body()->set_filename( + file_path); + }); + initialize(); + + BufferingStreamDecoderPtr response = IntegrationUtil::makeSingleRequest( + lookupPort("http"), "GET", "/", "", downstream_protocol_, version_, "direct.example.com"); + ASSERT_TRUE(response->complete()); + EXPECT_STREQ("200", response->headers().Status()->value().c_str()); + EXPECT_STREQ("example-value", response->headers() + .get(Envoy::Http::LowerCaseString("x-additional-header")) + ->value() + .c_str()); + EXPECT_STREQ("text/html", response->headers().ContentType()->value().c_str()); + EXPECT_EQ(body, response->body()); +} TEST_P(IntegrationTest, ComputedHealthCheck) { testComputedHealthCheck(); } @@ -197,37 +259,230 @@ TEST_P(IntegrationTest, HittingGrpcFilterLimitBufferingHeaders) { TEST_P(IntegrationTest, HittingEncoderFilterLimit) { testHittingEncoderFilterLimit(); } -TEST_P(IntegrationTest, BadFirstline) { testBadFirstline(); } +TEST_P(IntegrationTest, BadFirstline) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "hello", &response); + EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); +} + +TEST_P(IntegrationTest, MissingDelimiter) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), + "GET / HTTP/1.1\r\nHost: host\r\nfoo bar\r\n\r\n", &response); + EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); +} + +TEST_P(IntegrationTest, InvalidCharacterInFirstline) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "GE(T / HTTP/1.1\r\nHost: host\r\n\r\n", + &response); + EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); +} + +TEST_P(IntegrationTest, InvalidVersion) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.01\r\nHost: host\r\n\r\n", + &response); + EXPECT_EQ("HTTP/1.1 400 Bad Request\r\ncontent-length: 0\r\nconnection: close\r\n\r\n", response); +} + +TEST_P(IntegrationTest, Http10Disabled) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\n\r\n", &response, true); + EXPECT_TRUE(response.find("HTTP/1.1 426 Upgrade Required\r\n") == 0); +} + +TEST_P(IntegrationTest, Http10DisabledWithUpgrade) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\nUpgrade: h2c\r\n\r\n", + &response, true); + EXPECT_TRUE(response.find("HTTP/1.1 426 Upgrade Required\r\n") == 0); +} + +// Turn HTTP/1.0 support on and verify 09 style requests work. +TEST_P(IntegrationTest, Http09Enabled) { + autonomous_upstream_ = true; + config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "GET /\r\n\r\n", &response, false); + EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); + EXPECT_THAT(response, HasSubstr("connection: close")); + EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); + + std::unique_ptr upstream_headers = + reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); + ASSERT_TRUE(upstream_headers != nullptr); + EXPECT_EQ(upstream_headers->Host()->value(), "default.com"); +} + +// Turn HTTP/1.0 support on and verify the request is proxied and the default host is sent upstream. +TEST_P(IntegrationTest, Http10Enabled) { + autonomous_upstream_ = true; + config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), "GET / HTTP/1.0\r\n\r\n", &response, false); + EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); + EXPECT_THAT(response, HasSubstr("connection: close")); + EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); + + std::unique_ptr upstream_headers = + reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); + ASSERT_TRUE(upstream_headers != nullptr); + EXPECT_EQ(upstream_headers->Host()->value(), "default.com"); + + sendRawHttpAndWaitForResponse(lookupPort("http"), "HEAD / HTTP/1.0\r\n\r\n", &response, false); + EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); + EXPECT_THAT(response, HasSubstr("connection: close")); + EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); +} -TEST_P(IntegrationTest, MissingDelimiter) { testMissingDelimiter(); } +TEST_P(IntegrationTest, TestInlineHeaders) { + autonomous_upstream_ = true; + config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), + "GET / HTTP/1.1\r\n" + "Host: foo.com\r\n" + "Foo: bar\r\n" + "Cache-control: public\r\n" + "Cache-control: 123\r\n" + "Eep: baz\r\n\r\n", + &response, true); + EXPECT_THAT(response, HasSubstr("HTTP/1.1 200 OK\r\n")); -TEST_P(IntegrationTest, InvalidCharacterInFirstline) { testInvalidCharacterInFirstline(); } + std::unique_ptr upstream_headers = + reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); + ASSERT_TRUE(upstream_headers != nullptr); + EXPECT_EQ(upstream_headers->Host()->value(), "foo.com"); + EXPECT_EQ(upstream_headers->CacheControl()->value(), "public,123"); + ASSERT_TRUE(upstream_headers->get(Envoy::Http::LowerCaseString("foo")) != nullptr); + EXPECT_STREQ("bar", upstream_headers->get(Envoy::Http::LowerCaseString("foo"))->value().c_str()); + ASSERT_TRUE(upstream_headers->get(Envoy::Http::LowerCaseString("eep")) != nullptr); + EXPECT_STREQ("baz", upstream_headers->get(Envoy::Http::LowerCaseString("eep"))->value().c_str()); +} -TEST_P(IntegrationTest, InvalidVersion) { testInvalidVersion(); } +// Verify for HTTP/1.0 a keep-alive header results in no connection: close. +// Also verify existing host headers are passed through for the HTTP/1.0 case. +TEST_P(IntegrationTest, Http10WithHostandKeepAlive) { + autonomous_upstream_ = true; + config_helper_.addConfigModifier(&setAllowHttp10WithDefaultHost); + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), + "GET / HTTP/1.0\r\nHost: foo.com\r\nConnection:Keep-alive\r\n\r\n", + &response, true); + EXPECT_THAT(response, HasSubstr("HTTP/1.0 200 OK\r\n")); + EXPECT_THAT(response, Not(HasSubstr("connection: close"))); + EXPECT_THAT(response, Not(HasSubstr("transfer-encoding: chunked\r\n"))); + + std::unique_ptr upstream_headers = + reinterpret_cast(fake_upstreams_.front().get())->lastRequestHeaders(); + ASSERT_TRUE(upstream_headers != nullptr); + EXPECT_EQ(upstream_headers->Host()->value(), "foo.com"); +} -TEST_P(IntegrationTest, Http10Disabled) { testHttp10Disabled(); } +TEST_P(IntegrationTest, NoHost) { + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); -TEST_P(IntegrationTest, Http10DisabledWithUpgrade) { testHttp10DisabledWithUpgrade(); } + Http::TestHeaderMapImpl request_headers{ + {":method", "GET"}, {":path", "/test/long/url"}, {":scheme", "http"}}; + auto response = codec_client_->makeHeaderOnlyRequest(request_headers); + response->waitForEndStream(); -TEST_P(IntegrationTest, Http09Enabled) { testHttp09Enabled(); } + ASSERT_TRUE(response->complete()); + EXPECT_STREQ("400", response->headers().Status()->value().c_str()); +} -TEST_P(IntegrationTest, Http10Enabled) { testHttp10Enabled(); } +TEST_P(IntegrationTest, BadPath) { + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), + "GET http://api.lyft.com HTTP/1.1\r\nHost: host\r\n\r\n", &response, + true); + EXPECT_TRUE(response.find("HTTP/1.1 404 Not Found\r\n") == 0); +} -TEST_P(IntegrationTest, TestInlineHeaders) { testInlineHeaders(); } +TEST_P(IntegrationTest, AbsolutePath) { + // Configure www.redirect.com to send a redirect, and ensure the redirect is + // encountered via absolute URL. + config_helper_.addRoute("www.redirect.com", "/", "cluster_0", true, + envoy::api::v2::route::RouteAction::SERVICE_UNAVAILABLE, + envoy::api::v2::route::VirtualHost::ALL); + config_helper_.addConfigModifier(&setAllowAbsoluteUrl); -TEST_P(IntegrationTest, Http10WithHostandKeepAlive) { testHttp10WithHostAndKeepAlive(); } + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), + "GET http://www.redirect.com HTTP/1.1\r\nHost: host\r\n\r\n", + &response, true); + EXPECT_FALSE(response.find("HTTP/1.1 404 Not Found\r\n") == 0); +} -TEST_P(IntegrationTest, NoHost) { testNoHost(); } +TEST_P(IntegrationTest, AbsolutePathWithPort) { + // Configure www.namewithport.com:1234 to send a redirect, and ensure the redirect is + // encountered via absolute URL with a port. + config_helper_.addRoute("www.namewithport.com:1234", "/", "cluster_0", true, + envoy::api::v2::route::RouteAction::SERVICE_UNAVAILABLE, + envoy::api::v2::route::VirtualHost::ALL); + config_helper_.addConfigModifier(&setAllowAbsoluteUrl); + initialize(); + std::string response; + sendRawHttpAndWaitForResponse( + lookupPort("http"), "GET http://www.namewithport.com:1234 HTTP/1.1\r\nHost: host\r\n\r\n", + &response, true); + EXPECT_FALSE(response.find("HTTP/1.1 404 Not Found\r\n") == 0); +} -TEST_P(IntegrationTest, BadPath) { testBadPath(); } +TEST_P(IntegrationTest, AbsolutePathWithoutPort) { + // Add a restrictive default match, to avoid the request hitting the * / catchall. + config_helper_.setDefaultHostAndRoute("foo.com", "/found"); + // Set a matcher for www.namewithport.com:1234 and verify http://www.namewithport.com does not + // match + config_helper_.addRoute("www.namewithport.com:1234", "/", "cluster_0", true, + envoy::api::v2::route::RouteAction::SERVICE_UNAVAILABLE, + envoy::api::v2::route::VirtualHost::ALL); + config_helper_.addConfigModifier(&setAllowAbsoluteUrl); + initialize(); + std::string response; + sendRawHttpAndWaitForResponse(lookupPort("http"), + "GET http://www.namewithport.com HTTP/1.1\r\nHost: host\r\n\r\n", + &response, true); + EXPECT_TRUE(response.find("HTTP/1.1 404 Not Found\r\n") == 0) << response; +} -TEST_P(IntegrationTest, AbsolutePath) { testAbsolutePath(); } +// Ensure that connect behaves the same with allow_absolute_url enabled and without +TEST_P(IntegrationTest, Connect) { + const std::string& request = "CONNECT www.somewhere.com:80 HTTP/1.1\r\nHost: host\r\n\r\n"; + config_helper_.addConfigModifier([&](envoy::config::bootstrap::v2::Bootstrap& bootstrap) -> void { + // Clone the whole listener. + auto static_resources = bootstrap.mutable_static_resources(); + auto* old_listener = static_resources->mutable_listeners(0); + auto* cloned_listener = static_resources->add_listeners(); + cloned_listener->CopyFrom(*old_listener); + old_listener->set_name("http_forward"); + }); + // Set the first listener to allow absolute URLs. + config_helper_.addConfigModifier(&setAllowAbsoluteUrl); + initialize(); -TEST_P(IntegrationTest, AbsolutePathWithPort) { testAbsolutePathWithPort(); } + std::string response1; + sendRawHttpAndWaitForResponse(lookupPort("http"), request.c_str(), &response1, true); -TEST_P(IntegrationTest, AbsolutePathWithoutPort) { testAbsolutePathWithoutPort(); } + std::string response2; + sendRawHttpAndWaitForResponse(lookupPort("http_forward"), request.c_str(), &response2, true); -TEST_P(IntegrationTest, Connect) { testConnect(); } + EXPECT_EQ(normalizeDate(response1), normalizeDate(response2)); +} TEST_P(IntegrationTest, ValidZeroLengthContent) { testValidZeroLengthContent(); } @@ -239,7 +494,27 @@ TEST_P(IntegrationTest, LargeHeadersRejected) { testLargeRequestHeaders(62, 60); TEST_P(IntegrationTest, LargeHeadersAccepted) { testLargeRequestHeaders(62, 63); } -TEST_P(IntegrationTest, UpstreamProtocolError) { testUpstreamProtocolError(); } +TEST_P(IntegrationTest, UpstreamProtocolError) { + initialize(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + auto encoder_decoder = codec_client_->startRequest(Http::TestHeaderMapImpl{ + {":method", "GET"}, {":path", "/test/long/url"}, {":authority", "host"}}); + auto response = std::move(encoder_decoder.second); + + FakeRawConnectionPtr fake_upstream_connection; + ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); + // TODO(mattklein123): Waiting for exact amount of data is a hack. This needs to + // be fixed. + std::string data; + ASSERT_TRUE(fake_upstream_connection->waitForData(187, &data)); + ASSERT_TRUE(fake_upstream_connection->write("bad protocol data!")); + ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); + codec_client_->waitForDisconnect(); + + EXPECT_TRUE(response->complete()); + EXPECT_STREQ("503", response->headers().Status()->value().c_str()); +} TEST_P(IntegrationTest, TestHead) { initialize(); diff --git a/test/integration/integration_test.h b/test/integration/integration_test.h index 13352ca960e79..7d4e8c61c7f54 100644 --- a/test/integration/integration_test.h +++ b/test/integration/integration_test.h @@ -3,6 +3,7 @@ #include "test/integration/http_integration.h" #include "test/test_common/test_base.h" +// A test class for testing HTTP/1.1 upstream and downstreams namespace Envoy { class IntegrationTest : public HttpIntegrationTest, public TestBaseWithParam { From 87daa8119ed954e213a10c2b7bd2acb838fc2a1e Mon Sep 17 00:00:00 2001 From: Kim Saabye Pedersen Date: Mon, 4 Feb 2019 16:25:13 +0100 Subject: [PATCH 10/51] added example for delay fault injection (#5816) Signed-off-by: Kim Saabye Pedersen --- examples/fault-injection/Dockerfile-envoy | 2 +- examples/fault-injection/README.md | 32 +++++++++++++++---- ...on.sh => disable_abort_fault_injection.sh} | 0 .../disable_delay_fault_injection.sh | 9 ++++++ ...ion.sh => enable_abort_fault_injection.sh} | 0 .../enable_delay_fault_injection.sh | 10 ++++++ 6 files changed, 46 insertions(+), 7 deletions(-) rename examples/fault-injection/{disable_fault_injection.sh => disable_abort_fault_injection.sh} (100%) create mode 100755 examples/fault-injection/disable_delay_fault_injection.sh rename examples/fault-injection/{enable_fault_injection.sh => enable_abort_fault_injection.sh} (100%) create mode 100755 examples/fault-injection/enable_delay_fault_injection.sh diff --git a/examples/fault-injection/Dockerfile-envoy b/examples/fault-injection/Dockerfile-envoy index bba3b6e9316c4..421547df5a887 100644 --- a/examples/fault-injection/Dockerfile-envoy +++ b/examples/fault-injection/Dockerfile-envoy @@ -1,4 +1,4 @@ FROM envoyproxy/envoy:latest RUN apt-get update && apt-get install -y curl tree -COPY enable_fault_injection.sh disable_fault_injection.sh send_request.sh / +COPY enable_delay_fault_injection.sh disable_delay_fault_injection.sh enable_abort_fault_injection.sh disable_abort_fault_injection.sh send_request.sh / diff --git a/examples/fault-injection/README.md b/examples/fault-injection/README.md index f7e2ea1442947..a39a5aab153e9 100644 --- a/examples/fault-injection/README.md +++ b/examples/fault-injection/README.md @@ -5,7 +5,6 @@ This simple example demonstrates [Envoy's fault injection capability](https://www.envoyproxy.io/docs/envoy/latest/configuration/http_filters/fault_filter) using [Envoy's runtime support](https://www.envoyproxy.io/docs/envoy/latest/configuration/runtime) to control the feature. - ## Usage ``` # in terminal 1, launch Envoy and backend service containers. @@ -20,25 +19,46 @@ The script above (`send_request.sh`) sends a continuous stream of HTTP requests requests to the backend container. Fault injection is configured in Envoy but turned off (i.e. affects 0% of requests). Consequently, you should see a continuous sequence of HTTP 200 response code. -Tun on fault injection via the runtime using the commands below. + +### Abort fault injection +Turn on _abort_ fault injection via the runtime using the commands below. ``` # in terminal 3 docker-compose exec envoy bash -bash enable_fault_injection.sh +bash enable_abort_fault_injection.sh ``` The script above enables HTTP aborts for 100% of requests. So, you should now see a continuous sequence of HTTP 503 responses for all requests. -To disable the fault injection: +To disable the abort injection: + +``` +# in terminal 3 in the "envoy" container +bash disable_abort_fault_injection.sh +``` + +### Delay fault injection +Turn on _delay_ fault injection via the runtime using the commands below. + +``` +# in terminal 3 +docker-compose exec envoy bash +bash enable_delay_fault_injection.sh +``` + +The script above will add a 3-second delay to 50% of HTTP requests. You should now see a continuous sequence of HTTP 200 responses for all requests, but half of the requests will take 3 seconds to complete. + +To disable the delay injection: ``` # in terminal 3 in the "envoy" container -bash disable_fault_injection.sh +bash disable_delay_fault_injection.sh ``` -To see current runtime filesystem overview: +### The current runtime +To see the current runtime filesystem overview: ``` # in terminal 3 in the "envoy" container diff --git a/examples/fault-injection/disable_fault_injection.sh b/examples/fault-injection/disable_abort_fault_injection.sh similarity index 100% rename from examples/fault-injection/disable_fault_injection.sh rename to examples/fault-injection/disable_abort_fault_injection.sh diff --git a/examples/fault-injection/disable_delay_fault_injection.sh b/examples/fault-injection/disable_delay_fault_injection.sh new file mode 100755 index 0000000000000..72c84f90b71b6 --- /dev/null +++ b/examples/fault-injection/disable_delay_fault_injection.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -ex + +rm /srv/runtime/v1/envoy/fault/http/delay/fixed_delay_percent +rm /srv/runtime/v1/envoy/fault/http/delay/fixed_duration_ms + +pushd /srv/runtime +ln -s /srv/runtime/v1 new && mv -Tf new current +popd diff --git a/examples/fault-injection/enable_fault_injection.sh b/examples/fault-injection/enable_abort_fault_injection.sh similarity index 100% rename from examples/fault-injection/enable_fault_injection.sh rename to examples/fault-injection/enable_abort_fault_injection.sh diff --git a/examples/fault-injection/enable_delay_fault_injection.sh b/examples/fault-injection/enable_delay_fault_injection.sh new file mode 100755 index 0000000000000..09740d17fcb04 --- /dev/null +++ b/examples/fault-injection/enable_delay_fault_injection.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +set -ex + +mkdir -p /srv/runtime/v1/envoy/fault/http/delay +echo '50' > /srv/runtime/v1/envoy/fault/http/delay/fixed_delay_percent +echo '3000' > /srv/runtime/v1/envoy/fault/http/delay/fixed_duration_ms + +pushd /srv/runtime +ln -s /srv/runtime/v1 new && mv -Tf new current +popd From bb9735abcf7a306dd33c2639d7ec59c6b9e60d24 Mon Sep 17 00:00:00 2001 From: alyssawilk Date: Mon, 4 Feb 2019 14:54:37 -0500 Subject: [PATCH 11/51] config: logging a warning on use of deprecated proto fields (#5760) Risk Level: Low (logging only) Testing: new unit tests Docs Changes: n/a Release Notes: not included Part of #5559 Signed-off-by: Alyssa Wilk --- docs/root/intro/version_history.rst | 1 + source/common/protobuf/utility.cc | 40 ++++++++++++++++ source/common/protobuf/utility.h | 12 +++++ test/common/protobuf/BUILD | 2 + test/common/protobuf/utility_test.cc | 68 ++++++++++++++++++++++++++++ test/proto/BUILD | 5 ++ test/proto/deprecated.proto | 16 +++++++ 7 files changed, 144 insertions(+) create mode 100644 test/proto/deprecated.proto diff --git a/docs/root/intro/version_history.rst b/docs/root/intro/version_history.rst index cc3cb90f95107..e07bd5b2abe46 100644 --- a/docs/root/intro/version_history.rst +++ b/docs/root/intro/version_history.rst @@ -7,6 +7,7 @@ Version history * admin: the admin server can now be accessed via HTTP/2 (prior knowledge). * buffer: fix vulnerabilities when allocation fails. * config: added support of using google.protobuf.Any in opaque configs for extensions. +* config: logging warnings when deprecated fields are in use. * config: removed deprecated --v2-config-only from command line config. * config: removed deprecated_v1 sds_config from :ref:`Bootstrap config `. * config: removed REST_LEGACY as a valid :ref:`ApiType `. diff --git a/source/common/protobuf/utility.cc b/source/common/protobuf/utility.cc index 6c372fc915041..404abb2e572c2 100644 --- a/source/common/protobuf/utility.cc +++ b/source/common/protobuf/utility.cc @@ -106,6 +106,46 @@ void MessageUtil::loadFromFile(const std::string& path, Protobuf::Message& messa } } +void MessageUtil::checkForDeprecation(const Protobuf::Message& message, bool warn_only) { + const Protobuf::Descriptor* descriptor = message.GetDescriptor(); + const Protobuf::Reflection* reflection = message.GetReflection(); + for (int i = 0; i < descriptor->field_count(); ++i) { + const auto* field = descriptor->field(i); + + // If this field is not in use, continue. + if ((field->is_repeated() && reflection->FieldSize(message, field) == 0) || + (!field->is_repeated() && !reflection->HasField(message, field))) { + continue; + } + + // If this field is deprecated, warn or throw an error. + if (field->options().deprecated()) { + std::string err = fmt::format( + "Using deprecated option '{}'. This configuration will be removed from Envoy soon. " + "Please see https://github.com/envoyproxy/envoy/blob/master/DEPRECATED.md for " + "details.", + field->full_name()); + if (warn_only) { + ENVOY_LOG_MISC(warn, "{}", err); + } else { + throw ProtoValidationException(err, message); + } + } + + // If this is a message, recurse to check for deprecated fields in the sub-message. + if (field->cpp_type() == Protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { + if (field->is_repeated()) { + const int size = reflection->FieldSize(message, field); + for (int j = 0; j < size; ++j) { + checkForDeprecation(reflection->GetRepeatedMessage(message, field, j), warn_only); + } + } else { + checkForDeprecation(reflection->GetMessage(message, field), warn_only); + } + } + } +} + std::string MessageUtil::getJsonStringFromMessage(const Protobuf::Message& message, const bool pretty_print, const bool always_print_primitive_fields) { diff --git a/source/common/protobuf/utility.h b/source/common/protobuf/utility.h index b7b804f45c5f8..7496f4aa69edd 100644 --- a/source/common/protobuf/utility.h +++ b/source/common/protobuf/utility.h @@ -178,6 +178,15 @@ class MessageUtil { static void loadFromYaml(const std::string& yaml, Protobuf::Message& message); static void loadFromFile(const std::string& path, Protobuf::Message& message, Api::Api& api); + /** + * Checks for use of deprecated fields in message and all sub-messages. + * @param message message to validate. + * @param warn_only if true, logs a warning rather than throwing an exception if deprecated fields + * are in use. + * @throw ProtoValidationException if deprecated fields are used and warn_only is false. + */ + static void checkForDeprecation(const Protobuf::Message& message, bool warn_only); + /** * Validate protoc-gen-validate constraints on a given protobuf. * Note the corresponding `.pb.validate.h` for the message has to be included in the source file @@ -186,6 +195,9 @@ class MessageUtil { * @throw ProtoValidationException if the message does not satisfy its type constraints. */ template static void validate(const MessageType& message) { + // Log warnings if deprecated fields are in use. + checkForDeprecation(message, true); + std::string err; if (!Validate(message, &err)) { throw ProtoValidationException(err, message); diff --git a/test/common/protobuf/BUILD b/test/common/protobuf/BUILD index 9a82a8b547896..54e44139d97c7 100644 --- a/test/common/protobuf/BUILD +++ b/test/common/protobuf/BUILD @@ -15,7 +15,9 @@ envoy_cc_test( deps = [ "//source/common/protobuf:utility_lib", "//source/common/stats:isolated_store_lib", + "//test/proto:deprecated_proto_cc", "//test/test_common:environment_lib", + "//test/test_common:logging_lib", "//test/test_common:utility_lib", "@envoy_api//envoy/config/bootstrap/v2:bootstrap_cc", ], diff --git a/test/common/protobuf/utility_test.cc b/test/common/protobuf/utility_test.cc index 58d4c00d2d12c..1352ecd17910b 100644 --- a/test/common/protobuf/utility_test.cc +++ b/test/common/protobuf/utility_test.cc @@ -7,7 +7,9 @@ #include "common/protobuf/utility.h" #include "common/stats/isolated_store_impl.h" +#include "test/proto/deprecated.pb.h" #include "test/test_common/environment.h" +#include "test/test_common/logging.h" #include "test/test_common/test_base.h" #include "test/test_common/utility.h" @@ -337,6 +339,72 @@ TEST(DurationUtilTest, OutOfRange) { } } +TEST(DeprecatedFields, NoErrorWhenDeprecatedFieldsUnused) { + envoy::test::deprecation_test::Base base; + base.set_not_deprecated("foo"); + // Fatal checks for a non-deprecated field should cause no problem. + MessageUtil::checkForDeprecation(base, true); +} + +TEST(DeprecatedFields, IndividualFieldDeprecated) { + envoy::test::deprecation_test::Base base; + base.set_is_deprecated("foo"); + // Non-fatal checks for a deprecated field should log rather than throw an exception. + EXPECT_LOG_CONTAINS("warning", + "Using deprecated option 'envoy.test.deprecation_test.Base.is_deprecated'.", + MessageUtil::checkForDeprecation(base, true)); + // Fatal checks for a deprecated field should result in an exception. + EXPECT_THROW_WITH_REGEX( + MessageUtil::checkForDeprecation(base, false), ProtoValidationException, + "Using deprecated option 'envoy.test.deprecation_test.Base.is_deprecated'."); +} + +TEST(DeprecatedFields, MessageDeprecated) { + envoy::test::deprecation_test::Base base; + base.mutable_deprecated_message(); + // Fatal checks for a present (unused) deprecated message should result in an exception. + EXPECT_THROW_WITH_REGEX( + MessageUtil::checkForDeprecation(base, false), ProtoValidationException, + "Using deprecated option 'envoy.test.deprecation_test.Base.deprecated_message'."); +} + +TEST(DeprecatedFields, InnerMessageDeprecated) { + envoy::test::deprecation_test::Base base; + base.mutable_not_deprecated_message()->set_inner_not_deprecated("foo"); + // Non-fatal checks for a deprecated field shouldn't throw an exception. + MessageUtil::checkForDeprecation(base, true); + + base.mutable_not_deprecated_message()->set_inner_deprecated("bar"); + // Fatal checks for a deprecated sub-message should result in an exception. + EXPECT_THROW_WITH_REGEX(MessageUtil::checkForDeprecation(base, false), ProtoValidationException, + "Using deprecated option " + "'envoy.test.deprecation_test.Base.InnerMessage.inner_deprecated'."); +} + +// Check that repeated sub-messages get validated. +TEST(DeprecatedFields, SubMessageDeprecated) { + envoy::test::deprecation_test::Base base; + base.add_repeated_message(); + base.add_repeated_message()->set_inner_deprecated("foo"); + base.add_repeated_message(); + + // Fatal checks for a repeated deprecated sub-message should result in an exception. + EXPECT_THROW_WITH_REGEX(MessageUtil::checkForDeprecation(base, false), ProtoValidationException, + "Using deprecated option " + "'envoy.test.deprecation_test.Base.InnerMessage.inner_deprecated'."); +} + +// Check that deprecated repeated messages trigger +TEST(DeprecatedFields, RepeatedMessageDeprecated) { + envoy::test::deprecation_test::Base base; + base.add_deprecated_repeated_message(); + + // Fatal checks for a repeated deprecated sub-message should result in an exception. + EXPECT_THROW_WITH_REGEX( + MessageUtil::checkForDeprecation(base, false), ProtoValidationException, + "Using deprecated option 'envoy.test.deprecation_test.Base.deprecated_repeated_message'."); +} + class TimestampUtilTest : public TestBase, public ::testing::WithParamInterface {}; TEST_P(TimestampUtilTest, SystemClockToTimestampTest) { diff --git a/test/proto/BUILD b/test/proto/BUILD index 3e339d903b55f..08c8384dee44c 100644 --- a/test/proto/BUILD +++ b/test/proto/BUILD @@ -11,6 +11,11 @@ envoy_package() exports_files(["bookstore.proto"]) +envoy_proto_library( + name = "deprecated_proto", + srcs = [":deprecated.proto"], +) + envoy_proto_library( name = "helloworld_proto", srcs = [":helloworld.proto"], diff --git a/test/proto/deprecated.proto b/test/proto/deprecated.proto new file mode 100644 index 0000000000000..f6d965ae971c7 --- /dev/null +++ b/test/proto/deprecated.proto @@ -0,0 +1,16 @@ +syntax = "proto3"; + +package envoy.test.deprecation_test; + +message Base { + string not_deprecated = 1; + string is_deprecated = 2 [deprecated = true]; + message InnerMessage { + string inner_not_deprecated = 1; + string inner_deprecated = 2 [deprecated = true]; + } + InnerMessage deprecated_message = 3 [deprecated = true]; + InnerMessage not_deprecated_message = 4; + repeated InnerMessage repeated_message = 5; + repeated InnerMessage deprecated_repeated_message = 6 [deprecated = true]; +} From 5b9912def9b4dddbec06c1ba6b74a0058e05cb31 Mon Sep 17 00:00:00 2001 From: htuch Date: Mon, 4 Feb 2019 15:40:42 -0500 Subject: [PATCH 12/51] ci: fix OS X CI issues. (#5827) E.g. from https://circleci.com/gh/envoyproxy/envoy/159452?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link we're seeing: Error: No available formula with the name "bazelbuild/tap/bazel" Please tap it and then try again: brew tap bazelbuild/tap Looks like some additional steps are needed for the brew tap based on https://docs.bazel.build/versions/master/install-os-x.html. Risk Level: Low Testing: CI Fixes #5830 Signed-off-by: Harvey Tuch --- ci/mac_ci_setup.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ci/mac_ci_setup.sh b/ci/mac_ci_setup.sh index d98c1297b6a48..8e97d63b06a95 100755 --- a/ci/mac_ci_setup.sh +++ b/ci/mac_ci_setup.sh @@ -3,6 +3,10 @@ # Installs the dependencies required for a macOS build via homebrew. # Tools are not upgraded to new versions. +# Setup bazelbuild tap +brew tap bazelbuild/tap +brew tap-pin bazelbuild/tap + function is_installed { brew ls --versions "$1" >/dev/null } From d95f56811afedfc39e4f51dd9f4af36b900295e7 Mon Sep 17 00:00:00 2001 From: Joshua Marantz Date: Mon, 4 Feb 2019 17:00:07 -0500 Subject: [PATCH 13/51] test: fix several clang-tidy warnings from #5811 (#5826) * test: fix several clang-tidy warnings from #5811 Signed-off-by: Joshua Marantz --- test/common/buffer/owned_impl_test.cc | 2 - test/common/grpc/grpc_client_integration.h | 2 +- test/common/network/address_impl_test.cc | 12 +++--- test/common/router/config_impl_test.cc | 3 +- test/common/router/router_ratelimit_test.cc | 42 +++++++++---------- .../common/router/router_upstream_log_test.cc | 2 - test/common/stats/thread_local_store_test.cc | 2 +- .../upstream/health_checker_impl_test.cc | 2 - .../http_grpc/grpc_access_log_impl_test.cc | 6 +-- .../ext_authz/ext_authz_http_impl_test.cc | 3 +- .../filters/http/common/jwks_fetcher_test.cc | 2 +- .../filters/http/ext_authz/ext_authz_test.cc | 4 +- .../http1_bridge_filter_test.cc | 2 +- .../http/grpc_web/grpc_web_filter_test.cc | 2 +- .../header_to_metadata_filter_test.cc | 2 - .../http/jwt_authn/all_verifier_test.cc | 2 +- .../http/jwt_authn/authenticator_test.cc | 2 +- .../filters/http/jwt_authn/extractor_test.cc | 2 +- .../filters/http/jwt_authn/filter_test.cc | 2 +- .../filters/http/jwt_authn/jwks_cache_test.cc | 2 +- .../network/dubbo_proxy/filter_test.cc | 2 - .../network/ratelimit/ratelimit_test.cc | 2 - .../network/thrift_proxy/conn_manager_test.cc | 2 +- .../thrift_proxy/router_ratelimit_test.cc | 2 +- .../grpc_metrics_service_impl_test.cc | 6 +-- test/integration/tcp_proxy_integration_test.h | 2 +- test/server/http/admin_test.cc | 1 - test/server/server_test.cc | 2 +- 28 files changed, 51 insertions(+), 66 deletions(-) diff --git a/test/common/buffer/owned_impl_test.cc b/test/common/buffer/owned_impl_test.cc index aad9ada564907..66aa39dd39bc6 100644 --- a/test/common/buffer/owned_impl_test.cc +++ b/test/common/buffer/owned_impl_test.cc @@ -17,8 +17,6 @@ namespace { class OwnedImplTest : public TestBase { public: - OwnedImplTest() {} - bool release_callback_called_ = false; }; diff --git a/test/common/grpc/grpc_client_integration.h b/test/common/grpc/grpc_client_integration.h index ee664f4f2f599..782e1579aed7e 100644 --- a/test/common/grpc/grpc_client_integration.h +++ b/test/common/grpc/grpc_client_integration.h @@ -40,7 +40,7 @@ class GrpcClientIntegrationParamTest : public BaseGrpcClientIntegrationParamTest, public TestBaseWithParam> { public: - ~GrpcClientIntegrationParamTest() {} + ~GrpcClientIntegrationParamTest() override = default; static std::string protocolTestParamsToString( const ::testing::TestParamInfo>& p) { return absl::StrCat( diff --git a/test/common/network/address_impl_test.cc b/test/common/network/address_impl_test.cc index 8cae44fe9589a..afd68212cc471 100644 --- a/test/common/network/address_impl_test.cc +++ b/test/common/network/address_impl_test.cc @@ -416,18 +416,18 @@ TEST(AddressFromSockAddrDeathTest, Pipe) { struct TestCase { enum InstanceType { Ipv4, Ipv6, Pipe }; - TestCase() : type_(Ipv4), port_(0) {} - TestCase(enum InstanceType type, std::string address, uint32_t port) - : type_(type), address_(address), port_(port) {} - TestCase(const TestCase& rhs) : type_(rhs.type_), address_(rhs.address_), port_(rhs.port_) {} + TestCase() = default; + TestCase(enum InstanceType type, const std::string& address, uint32_t port) + : address_(address), type_(type), port_(port) {} + TestCase(const TestCase& rhs) : address_(rhs.address_), type_(rhs.type_), port_(rhs.port_) {} bool operator==(const TestCase& rhs) { return (type_ == rhs.type_ && address_ == rhs.address_ && port_ == rhs.port_); } - enum InstanceType type_; std::string address_; - uint32_t port_; // Ignored for Pipe + enum InstanceType type_ { Ipv4 }; + uint32_t port_ = 0; // Ignored for Pipe }; class MixedAddressTest : public TestBaseWithParam<::testing::tuple> { diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index 40a2a9636a417..37926cb9518ad 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -5250,8 +5250,7 @@ name: RetriableStatusCodes class PerFilterConfigsTest : public TestBase, public ConfigImplTestBase { public: PerFilterConfigsTest() - : factory_(), registered_factory_(factory_), default_factory_(), - registered_default_factory_(default_factory_) {} + : registered_factory_(factory_), registered_default_factory_(default_factory_) {} struct DerivedFilterConfig : public RouteSpecificFilterConfig { ProtobufWkt::Timestamp config_; diff --git a/test/common/router/router_ratelimit_test.cc b/test/common/router/router_ratelimit_test.cc index 9ec8c79c1903f..8b020dacd6d07 100644 --- a/test/common/router/router_ratelimit_test.cc +++ b/test/common/router/router_ratelimit_test.cc @@ -99,7 +99,7 @@ static Http::TestHeaderMapImpl genHeaders(const std::string& host, const std::st class RateLimitConfiguration : public TestBase { public: - void SetUpTest(const std::string json) { + void setupTest(const std::string& json) { envoy::api::v2::RouteConfiguration route_config; auto json_object_ptr = Json::Factory::loadFromString(json); Envoy::Config::RdsJson::translateRouteConfiguration(*json_object_ptr, route_config, @@ -146,7 +146,7 @@ TEST_F(RateLimitConfiguration, NoApplicableRateLimit) { } )EOF"; - SetUpTest(json); + setupTest(json); EXPECT_EQ(0U, config_->route(genHeaders("www.lyft.com", "/bar", "GET"), 0) ->routeEntry() @@ -173,7 +173,7 @@ TEST_F(RateLimitConfiguration, NoRateLimitPolicy) { } )EOF"; - SetUpTest(json); + setupTest(json); route_ = config_->route(genHeaders("www.lyft.com", "/bar", "GET"), 0)->routeEntry(); EXPECT_EQ(0U, route_->rateLimitPolicy().getApplicableRateLimit(0).size()); @@ -207,7 +207,7 @@ TEST_F(RateLimitConfiguration, TestGetApplicationRateLimit) { } )EOF"; - SetUpTest(json); + setupTest(json); route_ = config_->route(genHeaders("www.lyft.com", "/foo", "GET"), 0)->routeEntry(); EXPECT_FALSE(route_->rateLimitPolicy().empty()); @@ -250,7 +250,7 @@ TEST_F(RateLimitConfiguration, TestVirtualHost) { } )EOF"; - SetUpTest(json); + setupTest(json); route_ = config_->route(genHeaders("www.lyft.com", "/bar", "GET"), 0)->routeEntry(); std::vector> rate_limits = @@ -311,7 +311,7 @@ TEST_F(RateLimitConfiguration, Stages) { } )EOF"; - SetUpTest(json); + setupTest(json); route_ = config_->route(genHeaders("www.lyft.com", "/foo", "GET"), 0)->routeEntry(); std::vector> rate_limits = @@ -345,7 +345,7 @@ TEST_F(RateLimitConfiguration, Stages) { class RateLimitPolicyEntryTest : public TestBase { public: - void SetUpTest(const std::string json) { + void setupTest(const std::string& json) { rate_limit_entry_ = std::make_unique(parseRateLimitFromJson(json)); descriptors_.clear(); } @@ -370,7 +370,7 @@ TEST_F(RateLimitPolicyEntryTest, RateLimitPolicyEntryMembers) { } )EOF"; - SetUpTest(json); + setupTest(json); EXPECT_EQ(2UL, rate_limit_entry_->stage()); EXPECT_EQ("no_ratelimit", rate_limit_entry_->disableKey()); @@ -387,7 +387,7 @@ TEST_F(RateLimitPolicyEntryTest, RemoteAddress) { } )EOF"; - SetUpTest(json); + setupTest(json); rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header_, default_remote_address_); @@ -407,7 +407,7 @@ TEST_F(RateLimitPolicyEntryTest, PipeAddress) { } )EOF"; - SetUpTest(json); + setupTest(json); Network::Address::PipeInstance pipe_address("/hello"); rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header_, pipe_address); @@ -425,7 +425,7 @@ TEST_F(RateLimitPolicyEntryTest, SourceService) { } )EOF"; - SetUpTest(json); + setupTest(json); rate_limit_entry_->populateDescriptors(route_, descriptors_, "service_cluster", header_, default_remote_address_); @@ -445,7 +445,7 @@ TEST_F(RateLimitPolicyEntryTest, DestinationService) { } )EOF"; - SetUpTest(json); + setupTest(json); rate_limit_entry_->populateDescriptors(route_, descriptors_, "service_cluster", header_, default_remote_address_); @@ -467,7 +467,7 @@ TEST_F(RateLimitPolicyEntryTest, RequestHeaders) { } )EOF"; - SetUpTest(json); + setupTest(json); Http::TestHeaderMapImpl header{{"x-header-name", "test_value"}}; rate_limit_entry_->populateDescriptors(route_, descriptors_, "service_cluster", header, @@ -489,7 +489,7 @@ TEST_F(RateLimitPolicyEntryTest, RequestHeadersNoMatch) { } )EOF"; - SetUpTest(json); + setupTest(json); Http::TestHeaderMapImpl header{{"x-header-name", "test_value"}}; rate_limit_entry_->populateDescriptors(route_, descriptors_, "service_cluster", header, @@ -509,7 +509,7 @@ TEST_F(RateLimitPolicyEntryTest, RateLimitKey) { } )EOF"; - SetUpTest(json); + setupTest(json); rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header_, default_remote_address_); @@ -536,7 +536,7 @@ TEST_F(RateLimitPolicyEntryTest, HeaderValueMatch) { } )EOF"; - SetUpTest(json); + setupTest(json); Http::TestHeaderMapImpl header{{"x-header-name", "test_value"}}; rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header, default_remote_address_); @@ -563,7 +563,7 @@ TEST_F(RateLimitPolicyEntryTest, HeaderValueMatchNoMatch) { } )EOF"; - SetUpTest(json); + setupTest(json); Http::TestHeaderMapImpl header{{"x-header-name", "not_same_value"}}; rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header, default_remote_address_); @@ -590,7 +590,7 @@ TEST_F(RateLimitPolicyEntryTest, HeaderValueMatchHeadersNotPresent) { } )EOF"; - SetUpTest(json); + setupTest(json); Http::TestHeaderMapImpl header{{"x-header-name", "not_same_value"}}; rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header, default_remote_address_); @@ -618,7 +618,7 @@ TEST_F(RateLimitPolicyEntryTest, HeaderValueMatchHeadersPresent) { } )EOF"; - SetUpTest(json); + setupTest(json); Http::TestHeaderMapImpl header{{"x-header-name", "test_value"}}; rate_limit_entry_->populateDescriptors(route_, descriptors_, "", header, default_remote_address_); @@ -639,7 +639,7 @@ TEST_F(RateLimitPolicyEntryTest, CompoundActions) { } )EOF"; - SetUpTest(json); + setupTest(json); rate_limit_entry_->populateDescriptors(route_, descriptors_, "service_cluster", header_, default_remote_address_); @@ -671,7 +671,7 @@ TEST_F(RateLimitPolicyEntryTest, CompoundActionsNoDescriptor) { } )EOF"; - SetUpTest(json); + setupTest(json); rate_limit_entry_->populateDescriptors(route_, descriptors_, "service_cluster", header_, default_remote_address_); diff --git a/test/common/router/router_upstream_log_test.cc b/test/common/router/router_upstream_log_test.cc index 8bf7069a6e14b..c0d52c474697d 100644 --- a/test/common/router/router_upstream_log_test.cc +++ b/test/common/router/router_upstream_log_test.cc @@ -74,8 +74,6 @@ class TestFilter : public Filter { class RouterUpstreamLogTest : public TestBase { public: - RouterUpstreamLogTest() {} - void init(absl::optional upstream_log) { envoy::config::filter::http::router::v2::Router router_proto; diff --git a/test/common/stats/thread_local_store_test.cc b/test/common/stats/thread_local_store_test.cc index f13ed96ca61ce..0249781de59a4 100644 --- a/test/common/stats/thread_local_store_test.cc +++ b/test/common/stats/thread_local_store_test.cc @@ -73,7 +73,7 @@ class HistogramWrapper { class HistogramTest : public TestBase { public: - typedef std::map NameHistogramMap; + using NameHistogramMap = std::map; HistogramTest() : alloc_(options_) {} diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index bf7e3b2c65751..77cf92c352370 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -104,8 +104,6 @@ class TestHttpHealthCheckerImpl : public HttpHealthCheckerImpl { class HttpHealthCheckerImplTest : public TestBase { public: struct TestSession { - TestSession() {} - Event::MockTimer* interval_timer_{}; Event::MockTimer* timeout_timer_{}; Http::MockClientConnection* codec_{}; diff --git a/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc b/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc index ebc8fe6482600..5cc038d714e96 100644 --- a/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc +++ b/test/extensions/access_loggers/http_grpc/grpc_access_log_impl_test.cc @@ -24,9 +24,9 @@ namespace HttpGrpc { class GrpcAccessLogStreamerImplTest : public TestBase { public: - typedef Grpc::MockAsyncStream MockAccessLogStream; - typedef Grpc::TypedAsyncStreamCallbacks - AccessLogCallbacks; + using MockAccessLogStream = Grpc::MockAsyncStream; + using AccessLogCallbacks = + Grpc::TypedAsyncStreamCallbacks; GrpcAccessLogStreamerImplTest() { EXPECT_CALL(*factory_, create()).WillOnce(Invoke([this] { diff --git a/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc b/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc index 4a529ccce0a06..ee8c490a75cb1 100644 --- a/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc +++ b/test/extensions/filters/common/ext_authz/ext_authz_http_impl_test.cc @@ -33,8 +33,7 @@ namespace ExtAuthz { class ExtAuthzHttpClientTest : public TestBase { public: ExtAuthzHttpClientTest() - : cm_{}, async_client_{}, - async_request_{&async_client_}, config_{createConfig()}, client_{cm_, config_} { + : async_request_{&async_client_}, config_{createConfig()}, client_{cm_, config_} { ON_CALL(cm_, httpAsyncClientForCluster(config_->cluster())) .WillByDefault(ReturnRef(async_client_)); } diff --git a/test/extensions/filters/http/common/jwks_fetcher_test.cc b/test/extensions/filters/http/common/jwks_fetcher_test.cc index a1bc4a2d74edf..292db6bf2f9e3 100644 --- a/test/extensions/filters/http/common/jwks_fetcher_test.cc +++ b/test/extensions/filters/http/common/jwks_fetcher_test.cc @@ -51,7 +51,7 @@ cluster: pubkey_cluster class JwksFetcherTest : public TestBase { public: - void SetUp() { MessageUtil::loadFromYaml(JwksUri, uri_); } + void SetUp() override { MessageUtil::loadFromYaml(JwksUri, uri_); } HttpUri uri_; testing::NiceMock mock_factory_ctx_; }; diff --git a/test/extensions/filters/http/ext_authz/ext_authz_test.cc b/test/extensions/filters/http/ext_authz/ext_authz_test.cc index b064f78ade3d1..77e401ddea472 100644 --- a/test/extensions/filters/http/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/http/ext_authz/ext_authz_test.cc @@ -83,11 +83,11 @@ template class HttpFilterTestBase : public T { class HttpFilterTest : public HttpFilterTestBase {}; -typedef envoy::config::filter::http::ext_authz::v2::ExtAuthz CreateFilterConfigFunc(); +using CreateFilterConfigFunc = envoy::config::filter::http::ext_authz::v2::ExtAuthz(); class HttpFilterTestParam : public HttpFilterTestBase> { public: - virtual void SetUp() override { initialize(""); } + void SetUp() override { initialize(""); } }; template diff --git a/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc b/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc index ac3bc03983821..c347c3f49b66d 100644 --- a/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc +++ b/test/extensions/filters/http/grpc_http1_bridge/http1_bridge_filter_test.cc @@ -24,7 +24,7 @@ namespace GrpcHttp1Bridge { class GrpcHttp1BridgeFilterTest : public TestBase { public: - GrpcHttp1BridgeFilterTest() : filter_() { + GrpcHttp1BridgeFilterTest() { filter_.setDecoderFilterCallbacks(decoder_callbacks_); filter_.setEncoderFilterCallbacks(encoder_callbacks_); ON_CALL(decoder_callbacks_.stream_info_, protocol()).WillByDefault(ReturnPointee(&protocol_)); diff --git a/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc b/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc index b9fcb90c96d50..a04da574508f0 100644 --- a/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc +++ b/test/extensions/filters/http/grpc_web/grpc_web_filter_test.cc @@ -47,7 +47,7 @@ const size_t TRAILERS_SIZE = sizeof(TRAILERS) - 1; class GrpcWebFilterTest : public TestBaseWithParam> { public: - GrpcWebFilterTest() : filter_() { + GrpcWebFilterTest() { filter_.setDecoderFilterCallbacks(decoder_callbacks_); filter_.setEncoderFilterCallbacks(encoder_callbacks_); } diff --git a/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc b/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc index 42f3973b4f54f..88c1751585245 100644 --- a/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc +++ b/test/extensions/filters/http/header_to_metadata/header_to_metadata_filter_test.cc @@ -19,8 +19,6 @@ namespace HeaderToMetadataFilter { class HeaderToMetadataTest : public TestBase { public: - HeaderToMetadataTest() {} - const std::string request_config_yaml = R"EOF( request_rules: - header: x-version diff --git a/test/extensions/filters/http/jwt_authn/all_verifier_test.cc b/test/extensions/filters/http/jwt_authn/all_verifier_test.cc index 06f7f8ac9903f..a5ee9ff253801 100644 --- a/test/extensions/filters/http/jwt_authn/all_verifier_test.cc +++ b/test/extensions/filters/http/jwt_authn/all_verifier_test.cc @@ -19,7 +19,7 @@ namespace JwtAuthn { class AllVerifierTest : public TestBase { public: - void SetUp() { MessageUtil::loadFromYaml(ExampleConfig, proto_config_); } + void SetUp() override { MessageUtil::loadFromYaml(ExampleConfig, proto_config_); } void createVerifier() { filter_config_ = ::std::make_shared(proto_config_, "", mock_factory_ctx_); diff --git a/test/extensions/filters/http/jwt_authn/authenticator_test.cc b/test/extensions/filters/http/jwt_authn/authenticator_test.cc index 143120ff0c312..026592ffdc5ba 100644 --- a/test/extensions/filters/http/jwt_authn/authenticator_test.cc +++ b/test/extensions/filters/http/jwt_authn/authenticator_test.cc @@ -29,7 +29,7 @@ namespace JwtAuthn { class AuthenticatorTest : public TestBase { public: - void SetUp() { + void SetUp() override { MessageUtil::loadFromYaml(ExampleConfig, proto_config_); CreateAuthenticator(); } diff --git a/test/extensions/filters/http/jwt_authn/extractor_test.cc b/test/extensions/filters/http/jwt_authn/extractor_test.cc index 11aa484583fc7..d1473cc1e44c5 100644 --- a/test/extensions/filters/http/jwt_authn/extractor_test.cc +++ b/test/extensions/filters/http/jwt_authn/extractor_test.cc @@ -50,7 +50,7 @@ const char ExampleConfig[] = R"( class ExtractorTest : public TestBase { public: - void SetUp() { + void SetUp() override { MessageUtil::loadFromYaml(ExampleConfig, config_); extractor_ = Extractor::create(config_); } diff --git a/test/extensions/filters/http/jwt_authn/filter_test.cc b/test/extensions/filters/http/jwt_authn/filter_test.cc index 7c988a5ee91ac..5ffd9c47d9e69 100644 --- a/test/extensions/filters/http/jwt_authn/filter_test.cc +++ b/test/extensions/filters/http/jwt_authn/filter_test.cc @@ -35,7 +35,7 @@ class MockFilterConfig : public FilterConfig { class FilterTest : public TestBase { public: - void SetUp() { + void SetUp() override { mock_config_ = ::std::make_shared(proto_config_, "", mock_context_); mock_verifier_ = std::make_unique(); diff --git a/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc b/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc index b8daf0214ea6d..29ce11ed0cd6e 100644 --- a/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc +++ b/test/extensions/filters/http/jwt_authn/jwks_cache_test.cc @@ -22,7 +22,7 @@ namespace { class JwksCacheTest : public TestBase { protected: JwksCacheTest() : api_(Api::createApiForTest(stats_)) {} - void SetUp() { + void SetUp() override { MessageUtil::loadFromYaml(ExampleConfig, config_); cache_ = JwksCache::create(config_, time_system_, *api_); jwks_ = google::jwt_verify::Jwks::createFrom(PublicKey, google::jwt_verify::Jwks::JWKS); diff --git a/test/extensions/filters/network/dubbo_proxy/filter_test.cc b/test/extensions/filters/network/dubbo_proxy/filter_test.cc index 32eda7490e800..9d4102d75bba6 100644 --- a/test/extensions/filters/network/dubbo_proxy/filter_test.cc +++ b/test/extensions/filters/network/dubbo_proxy/filter_test.cc @@ -27,8 +27,6 @@ using ConfigSerializationType = class DubboFilterTest : public TestBase { public: - DubboFilterTest() {} - TimeSource& timeSystem() { return factory_context_.dispatcher().timeSystem(); } void initializeFilter() { diff --git a/test/extensions/filters/network/ratelimit/ratelimit_test.cc b/test/extensions/filters/network/ratelimit/ratelimit_test.cc index 2d3babd20ddd7..ab6c6cd2ca3da 100644 --- a/test/extensions/filters/network/ratelimit/ratelimit_test.cc +++ b/test/extensions/filters/network/ratelimit/ratelimit_test.cc @@ -34,8 +34,6 @@ namespace RateLimitFilter { class RateLimitFilterTest : public TestBase { public: - RateLimitFilterTest() {} - void SetUpTest(const std::string& yaml) { ON_CALL(runtime_.snapshot_, featureEnabled("ratelimit.tcp_filter_enabled", 100)) .WillByDefault(Return(true)); diff --git a/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc b/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc index 45dfc7e78b85e..4c53c5419caa2 100644 --- a/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc +++ b/test/extensions/filters/network/thrift_proxy/conn_manager_test.cc @@ -73,7 +73,7 @@ class TestConfigImpl : public ConfigImpl { class ThriftConnectionManagerTest : public TestBase { public: ThriftConnectionManagerTest() : stats_(ThriftFilterStats::generateStats("test.", store_)) {} - ~ThriftConnectionManagerTest() { + ~ThriftConnectionManagerTest() override { filter_callbacks_.connection_.dispatcher_.clearDeferredDeleteList(); } diff --git a/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc b/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc index 9bd8bda646899..7d4da715c6682 100644 --- a/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc +++ b/test/extensions/filters/network/thrift_proxy/router_ratelimit_test.cc @@ -170,7 +170,7 @@ TEST_F(ThriftRateLimitConfigurationTest, Stages) { class ThriftRateLimitPolicyEntryTest : public TestBase { public: - void initialize(const std::string yaml) { + void initialize(const std::string& yaml) { envoy::api::v2::route::RateLimit rate_limit; MessageUtil::loadFromYaml(yaml, rate_limit); diff --git a/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc b/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc index 6b9d66f195694..b41b51a42aaa8 100644 --- a/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc +++ b/test/extensions/stats_sinks/metrics_service/grpc_metrics_service_impl_test.cc @@ -21,9 +21,9 @@ namespace MetricsService { class GrpcMetricsStreamerImplTest : public TestBase { public: - typedef Grpc::MockAsyncStream MockMetricsStream; - typedef Grpc::TypedAsyncStreamCallbacks - MetricsServiceCallbacks; + using MockMetricsStream = Grpc::MockAsyncStream; + using MetricsServiceCallbacks = + Grpc::TypedAsyncStreamCallbacks; GrpcMetricsStreamerImplTest() { EXPECT_CALL(*factory_, create()).WillOnce(Invoke([this] { diff --git a/test/integration/tcp_proxy_integration_test.h b/test/integration/tcp_proxy_integration_test.h index af0156821e87a..317846879781a 100644 --- a/test/integration/tcp_proxy_integration_test.h +++ b/test/integration/tcp_proxy_integration_test.h @@ -17,7 +17,7 @@ class TcpProxyIntegrationTest : public BaseIntegrationTest, enable_half_close_ = true; } - ~TcpProxyIntegrationTest() { + ~TcpProxyIntegrationTest() override { test_server_.reset(); fake_upstreams_.clear(); } diff --git a/test/server/http/admin_test.cc b/test/server/http/admin_test.cc index 1ac6f062b462d..3dcdf4e56a172 100644 --- a/test/server/http/admin_test.cc +++ b/test/server/http/admin_test.cc @@ -1221,7 +1221,6 @@ class HistogramWrapper { class PrometheusStatsFormatterTest : public TestBase { protected: - PrometheusStatsFormatterTest() /*: alloc_(stats_options_)*/ {} void addCounter(const std::string& name, std::vector cluster_tags) { std::string tname = std::string(name); counters_.push_back(alloc_.makeCounter(name, std::move(tname), std::move(cluster_tags))); diff --git a/test/server/server_test.cc b/test/server/server_test.cc index a0d036d5d5435..40e20d897d5a6 100644 --- a/test/server/server_test.cc +++ b/test/server/server_test.cc @@ -55,7 +55,7 @@ TEST(ServerInstanceUtil, flushHelper) { class RunHelperTest : public TestBase { public: - RunHelperTest() : shutdown_(false) { + RunHelperTest() { InSequence s; sigterm_ = new Event::MockSignalEvent(&dispatcher_); From f6049429f1845efbe500e424d64bacc3a6e73432 Mon Sep 17 00:00:00 2001 From: Joshua Marantz Date: Mon, 4 Feb 2019 22:11:42 -0500 Subject: [PATCH 14/51] Add a note explaining in more detail the current and potential benefits of a common TestBase class. (#5837) Signed-off-by: Joshua Marantz --- test/test_common/test_base.h | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/test/test_common/test_base.h b/test/test_common/test_base.h index c4044fe6b745d..fc0396fcc2c90 100644 --- a/test/test_common/test_base.h +++ b/test/test_common/test_base.h @@ -5,14 +5,27 @@ namespace Envoy { // Provides a common test-base class for all tests in Envoy to use. This offers -// a place to put hooks we'd like to run on every tests. +// a place to put hooks we'd like to run on every test. There's currently a +// check that all test-scoped singletons have been destroyed. A test-scoped +// singleton might remain at the end of a test if it's transitively referenced +// by a leaked structure or a static. +// +// In the future, we can also add: +// - a test-specific ThreadFactory that enables us to verify there are no +// outstanding threads at the end of each thread. +// - a check that no more bytes of memory are allocated at the end of a test +// than there were at the start of it. This is likely to fail in a few +// places when introduced, but we could add known test overrides for this. +// +// Note: nothing compute-intensive should be put in this test-class, as it will +// be a tax paid by every test method in the codebase. class TestBase : public ::testing::Test { public: static bool checkSingletonQuiescensce(); ~TestBase() override; }; -// Templatized version of TestBase. +// Templatized version of TestBase. See above notes. template class TestBaseWithParam : public ::testing::TestWithParam { public: ~TestBaseWithParam() { TestBase::checkSingletonQuiescensce(); } From cbf03b90e8aa1c3476b493d8629abe7fc82b22c9 Mon Sep 17 00:00:00 2001 From: Auni Ahsan Date: Tue, 5 Feb 2019 00:04:23 -0500 Subject: [PATCH 15/51] (codec) Increase max_request_headers_kb limit to 64 and add http2 codec checks (#5773) Signed-off-by: Auni Ahsan --- .../v2/http_connection_manager.proto | 4 +- .../configuration/http_conn_man/stats.rst | 2 +- include/envoy/http/codec.h | 2 +- source/common/http/codec_client.cc | 3 +- source/common/http/conn_manager_config.h | 2 +- source/common/http/conn_manager_impl.cc | 5 +- source/common/http/conn_manager_utility.cc | 14 ++-- source/common/http/conn_manager_utility.h | 3 +- source/common/http/http2/codec_impl.cc | 14 ++-- source/common/http/http2/codec_impl.h | 16 ++-- .../network/http_connection_manager/config.cc | 11 +-- .../network/http_connection_manager/config.h | 4 +- source/server/http/admin.cc | 3 +- source/server/http/admin.h | 4 +- .../http/conn_manager_impl_fuzz_test.cc | 4 +- test/common/http/conn_manager_impl_test.cc | 6 +- test/common/http/conn_manager_utility_test.cc | 2 +- test/common/http/http2/BUILD | 11 +++ .../common/http/http2/codec_impl_fuzz_test.cc | 26 ++---- test/common/http/http2/codec_impl_test.cc | 80 ++++++++++++------- test/common/http/http2/codec_impl_test_util.h | 33 ++++++++ .../http_connection_manager/config_test.cc | 4 +- test/integration/fake_upstream.cc | 5 +- test/integration/http2_integration_test.cc | 4 +- test/integration/integration_test.cc | 4 +- 25 files changed, 161 insertions(+), 105 deletions(-) create mode 100644 test/common/http/http2/codec_impl_test_util.h diff --git a/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto b/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto index 60e7728a86e0c..be519e7da07f0 100644 --- a/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto +++ b/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto @@ -133,11 +133,11 @@ message HttpConnectionManager { // The maximum request headers size for incoming connections. The default max // is 60K, based on default settings for http codecs. For HTTP1, the current // limit set by http_parser is 80K. for HTTP2, the default allowed header - // block in nghttp2 is 64K. The max configurable setting is 63K in order to + // block in nghttp2 is 64K. The max configurable setting is 64K in order to // stay under both codec limits. // Requests that exceed this size will receive a 431 response. google.protobuf.UInt32Value max_request_headers_kb = 29 - [(validate.rules).uint32.gt = 0, (validate.rules).uint32.lte = 63]; + [(validate.rules).uint32.gt = 0, (validate.rules).uint32.lte = 64]; // The idle timeout for connections managed by the connection manager. The // idle timeout is defined as the period in which there are no active diff --git a/docs/root/configuration/http_conn_man/stats.rst b/docs/root/configuration/http_conn_man/stats.rst index 188b79d1873cb..174fa99bdb105 100644 --- a/docs/root/configuration/http_conn_man/stats.rst +++ b/docs/root/configuration/http_conn_man/stats.rst @@ -109,7 +109,7 @@ All http2 statistics are rooted at *http2.* :header: Name, Type, Description :widths: 1, 1, 2 - header_overflow, Counter, Total number of connections reset due to the headers being larger than `Envoy::Http::Http2::ConnectionImpl::StreamImpl::MAX_HEADER_SIZE` (63k) + header_overflow, Counter, Total number of connections reset due to the headers being larger than the :ref:`configured value `. headers_cb_no_stream, Counter, Total number of errors where a header callback is called without an associated stream. This tracks an unexpected occurrence due to an as yet undiagnosed bug rx_messaging_error, Counter, Total number of invalid received frames that violated `section 8 `_ of the HTTP/2 spec. This will result in a *tx_reset* rx_reset, Counter, Total number of reset stream frames received by Envoy diff --git a/include/envoy/http/codec.h b/include/envoy/http/codec.h index 7f4701a63ea21..568a735339e7f 100644 --- a/include/envoy/http/codec.h +++ b/include/envoy/http/codec.h @@ -14,7 +14,7 @@ namespace Envoy { namespace Http { // Legacy default value of 60K is safely under both codec default limits. -static const uint32_t DEFAULT_MAX_REQUEST_HEADERS_SIZE_KB = 60; +static const uint32_t DEFAULT_MAX_REQUEST_HEADERS_KB = 60; class Stream; diff --git a/source/common/http/codec_client.cc b/source/common/http/codec_client.cc index 43ae66e859d8a..3f8defb71ee6d 100644 --- a/source/common/http/codec_client.cc +++ b/source/common/http/codec_client.cc @@ -145,7 +145,8 @@ CodecClientProd::CodecClientProd(Type type, Network::ClientConnectionPtr&& conne } case Type::HTTP2: { codec_ = std::make_unique( - *connection_, *this, host->cluster().statsScope(), host->cluster().http2Settings()); + *connection_, *this, host->cluster().statsScope(), host->cluster().http2Settings(), + Http::DEFAULT_MAX_REQUEST_HEADERS_KB); break; } } diff --git a/source/common/http/conn_manager_config.h b/source/common/http/conn_manager_config.h index ee7b486aaf973..32d7d8b7d2f69 100644 --- a/source/common/http/conn_manager_config.h +++ b/source/common/http/conn_manager_config.h @@ -231,7 +231,7 @@ class ConnectionManagerConfig { /** * @return maximum request headers size the connection manager will accept. */ - virtual uint32_t maxRequestHeadersSizeKb() const PURE; + virtual uint32_t maxRequestHeadersKb() const PURE; /** * @return per-stream idle timeout for incoming connection manager connections. Zero indicates a diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index c941694efb99d..8805eacffe33e 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -617,9 +617,8 @@ void ConnectionManagerImpl::ActiveStream::decodeHeaders(HeaderMapPtr&& headers, } } - ASSERT(connection_manager_.config_.maxRequestHeadersSizeKb() > 0); - if (request_headers_->byteSize() > - (connection_manager_.config_.maxRequestHeadersSizeKb() * 1024)) { + ASSERT(connection_manager_.config_.maxRequestHeadersKb() > 0); + if (request_headers_->byteSize() > (connection_manager_.config_.maxRequestHeadersKb() * 1024)) { sendLocalReply(Grpc::Common::hasGrpcContentType(*request_headers_), Code::RequestHeaderFieldsTooLarge, "", nullptr, is_head_request_, absl::nullopt); return; diff --git a/source/common/http/conn_manager_utility.cc b/source/common/http/conn_manager_utility.cc index 7e28efd675f7f..2ebfe881d4d79 100644 --- a/source/common/http/conn_manager_utility.cc +++ b/source/common/http/conn_manager_utility.cc @@ -36,15 +36,13 @@ std::string ConnectionManagerUtility::determineNextProtocol(Network::Connection& return ""; } -ServerConnectionPtr ConnectionManagerUtility::autoCreateCodec(Network::Connection& connection, - const Buffer::Instance& data, - ServerConnectionCallbacks& callbacks, - Stats::Scope& scope, - const Http1Settings& http1_settings, - const Http2Settings& http2_settings) { +ServerConnectionPtr ConnectionManagerUtility::autoCreateCodec( + Network::Connection& connection, const Buffer::Instance& data, + ServerConnectionCallbacks& callbacks, Stats::Scope& scope, const Http1Settings& http1_settings, + const Http2Settings& http2_settings, const uint32_t max_request_headers_kb) { if (determineNextProtocol(connection, data) == Http2::ALPN_STRING) { - return ServerConnectionPtr{ - new Http2::ServerConnectionImpl(connection, callbacks, scope, http2_settings)}; + return ServerConnectionPtr{new Http2::ServerConnectionImpl( + connection, callbacks, scope, http2_settings, max_request_headers_kb)}; } else { return ServerConnectionPtr{ new Http1::ServerConnectionImpl(connection, callbacks, http1_settings)}; diff --git a/source/common/http/conn_manager_utility.h b/source/common/http/conn_manager_utility.h index 7ba81d8eeb52e..0d313f185e649 100644 --- a/source/common/http/conn_manager_utility.h +++ b/source/common/http/conn_manager_utility.h @@ -36,7 +36,8 @@ class ConnectionManagerUtility { static ServerConnectionPtr autoCreateCodec(Network::Connection& connection, const Buffer::Instance& data, ServerConnectionCallbacks& callbacks, Stats::Scope& scope, - const Http1Settings& http1_settings, const Http2Settings& http2_settings); + const Http1Settings& http1_settings, const Http2Settings& http2_settings, + const uint32_t max_request_headers_kb); /** * Mutates request headers in various ways. This functionality is broken out because of its diff --git a/source/common/http/http2/codec_impl.cc b/source/common/http/http2/codec_impl.cc index a3ad27a815120..c7dd029d8ce0c 100644 --- a/source/common/http/http2/codec_impl.cc +++ b/source/common/http/http2/codec_impl.cc @@ -641,7 +641,7 @@ int ConnectionImpl::saveHeader(const nghttp2_frame* frame, HeaderString&& name, } stream->saveHeader(std::move(name), std::move(value)); - if (stream->headers_->byteSize() > StreamImpl::MAX_HEADER_SIZE) { + if (stream->headers_->byteSize() > max_request_headers_kb_ * 1024) { // This will cause the library to reset/close the stream. stats_.header_overflow_.inc(); return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; @@ -877,8 +877,10 @@ ConnectionImpl::ClientHttp2Options::ClientHttp2Options(const Http2Settings& http ClientConnectionImpl::ClientConnectionImpl(Network::Connection& connection, Http::ConnectionCallbacks& callbacks, - Stats::Scope& stats, const Http2Settings& http2_settings) - : ConnectionImpl(connection, stats, http2_settings), callbacks_(callbacks) { + Stats::Scope& stats, const Http2Settings& http2_settings, + const uint32_t max_request_headers_kb) + : ConnectionImpl(connection, stats, http2_settings, max_request_headers_kb), + callbacks_(callbacks) { ClientHttp2Options client_http2_options(http2_settings); nghttp2_session_client_new2(&session_, http2_callbacks_.callbacks(), base(), client_http2_options.options()); @@ -924,8 +926,10 @@ int ClientConnectionImpl::onHeader(const nghttp2_frame* frame, HeaderString&& na ServerConnectionImpl::ServerConnectionImpl(Network::Connection& connection, Http::ServerConnectionCallbacks& callbacks, - Stats::Scope& scope, const Http2Settings& http2_settings) - : ConnectionImpl(connection, scope, http2_settings), callbacks_(callbacks) { + Stats::Scope& scope, const Http2Settings& http2_settings, + const uint32_t max_request_headers_kb) + : ConnectionImpl(connection, scope, http2_settings, max_request_headers_kb), + callbacks_(callbacks) { Http2Options http2_options(http2_settings); nghttp2_session_server_new2(&session_, http2_callbacks_.callbacks(), base(), http2_options.options()); diff --git a/source/common/http/http2/codec_impl.h b/source/common/http/http2/codec_impl.h index 143b306d6ce87..713abb886aefc 100644 --- a/source/common/http/http2/codec_impl.h +++ b/source/common/http/http2/codec_impl.h @@ -74,9 +74,9 @@ class Utility { class ConnectionImpl : public virtual Connection, protected Logger::Loggable { public: ConnectionImpl(Network::Connection& connection, Stats::Scope& stats, - const Http2Settings& http2_settings) + const Http2Settings& http2_settings, const uint32_t max_request_headers_kb) : stats_{ALL_HTTP2_CODEC_STATS(POOL_COUNTER_PREFIX(stats, "http2."))}, - connection_(connection), + connection_(connection), max_request_headers_kb_(max_request_headers_kb), per_stream_buffer_limit_(http2_settings.initial_stream_window_size_), dispatching_(false), raised_goaway_(false), pending_deferred_reset_(false) {} @@ -185,11 +185,6 @@ class ConnectionImpl : public virtual Connection, protected Logger::Loggable, FilterChainFactory& filterFactory() override { return *this; } bool reverseEncodeOrder() override { return reverse_encode_order_; } bool generateRequestId() override { return generate_request_id_; } - uint32_t maxRequestHeadersSizeKb() const override { return max_request_headers_size_kb_; } + uint32_t maxRequestHeadersKb() const override { return max_request_headers_kb_; } absl::optional idleTimeout() const override { return idle_timeout_; } std::chrono::milliseconds streamIdleTimeout() const override { return stream_idle_timeout_; } std::chrono::milliseconds requestTimeout() const override { return request_timeout_; } @@ -158,7 +158,7 @@ class HttpConnectionManagerConfig : Logger::Loggable, std::string server_name_; Http::TracingConnectionManagerConfigPtr tracing_config_; absl::optional user_agent_; - uint32_t max_request_headers_size_kb_; + const uint32_t max_request_headers_kb_; absl::optional idle_timeout_; std::chrono::milliseconds stream_idle_timeout_; std::chrono::milliseconds request_timeout_; diff --git a/source/server/http/admin.cc b/source/server/http/admin.cc index c16b7ae5396ba..ade0137129bfc 100644 --- a/source/server/http/admin.cc +++ b/source/server/http/admin.cc @@ -1106,7 +1106,8 @@ Http::ServerConnectionPtr AdminImpl::createCodec(Network::Connection& connection const Buffer::Instance& data, Http::ServerConnectionCallbacks& callbacks) { return Http::ConnectionManagerUtility::autoCreateCodec( - connection, data, callbacks, server_.stats(), Http::Http1Settings(), Http::Http2Settings()); + connection, data, callbacks, server_.stats(), Http::Http1Settings(), Http::Http2Settings(), + maxRequestHeadersKb()); } bool AdminImpl::createNetworkFilterChain(Network::Connection& connection, diff --git a/source/server/http/admin.h b/source/server/http/admin.h index 05b3c1fa840c5..8587c9ec52df9 100644 --- a/source/server/http/admin.h +++ b/source/server/http/admin.h @@ -100,7 +100,7 @@ class AdminImpl : public Admin, bool reverseEncodeOrder() override { return false; } bool generateRequestId() override { return false; } absl::optional idleTimeout() const override { return idle_timeout_; } - uint32_t maxRequestHeadersSizeKb() const override { return max_request_headers_size_kb_; } + uint32_t maxRequestHeadersKb() const override { return max_request_headers_kb_; } std::chrono::milliseconds streamIdleTimeout() const override { return {}; } std::chrono::milliseconds requestTimeout() const override { return {}; } std::chrono::milliseconds delayedCloseTimeout() const override { return {}; } @@ -305,7 +305,7 @@ class AdminImpl : public Admin, Http::ConnectionManagerTracingStats tracing_stats_; NullRouteConfigProvider route_config_provider_; std::list handlers_; - uint32_t max_request_headers_size_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_SIZE_KB}; + const uint32_t max_request_headers_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_KB}; absl::optional idle_timeout_; absl::optional user_agent_; Http::SlowDateProviderImpl date_provider_; diff --git a/test/common/http/conn_manager_impl_fuzz_test.cc b/test/common/http/conn_manager_impl_fuzz_test.cc index d2c53be04898b..40e85bfc23cbf 100644 --- a/test/common/http/conn_manager_impl_fuzz_test.cc +++ b/test/common/http/conn_manager_impl_fuzz_test.cc @@ -91,7 +91,7 @@ class FuzzConfig : public ConnectionManagerConfig { FilterChainFactory& filterFactory() override { return filter_factory_; } bool reverseEncodeOrder() override { return true; } bool generateRequestId() override { return true; } - uint32_t maxRequestHeadersSizeKb() const override { return max_request_headers_size_kb_; } + uint32_t maxRequestHeadersKb() const override { return max_request_headers_kb_; } absl::optional idleTimeout() const override { return idle_timeout_; } std::chrono::milliseconds streamIdleTimeout() const override { return stream_idle_timeout_; } std::chrono::milliseconds requestTimeout() const override { return request_timeout_; } @@ -132,7 +132,7 @@ class FuzzConfig : public ConnectionManagerConfig { ConnectionManagerStats stats_; ConnectionManagerTracingStats tracing_stats_; ConnectionManagerListenerStats listener_stats_; - uint32_t max_request_headers_size_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_SIZE_KB}; + uint32_t max_request_headers_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_KB}; absl::optional idle_timeout_; std::chrono::milliseconds stream_idle_timeout_{}; std::chrono::milliseconds request_timeout_{}; diff --git a/test/common/http/conn_manager_impl_test.cc b/test/common/http/conn_manager_impl_test.cc index 527bb7b86578f..39885de7c4e0c 100644 --- a/test/common/http/conn_manager_impl_test.cc +++ b/test/common/http/conn_manager_impl_test.cc @@ -230,7 +230,7 @@ class HttpConnectionManagerImplTest : public TestBase, public ConnectionManagerC FilterChainFactory& filterFactory() override { return filter_factory_; } bool reverseEncodeOrder() override { return reverse_encode_order_; } bool generateRequestId() override { return true; } - uint32_t maxRequestHeadersSizeKb() const override { return max_request_headers_size_kb_; } + uint32_t maxRequestHeadersKb() const override { return max_request_headers_kb_; } absl::optional idleTimeout() const override { return idle_timeout_; } std::chrono::milliseconds streamIdleTimeout() const override { return stream_idle_timeout_; } std::chrono::milliseconds requestTimeout() const override { return request_timeout_; } @@ -281,7 +281,7 @@ class HttpConnectionManagerImplTest : public TestBase, public ConnectionManagerC Http::ForwardClientCertType forward_client_cert_{Http::ForwardClientCertType::Sanitize}; std::vector set_current_client_cert_details_; absl::optional user_agent_; - uint32_t max_request_headers_size_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_SIZE_KB}; + uint32_t max_request_headers_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_KB}; absl::optional idle_timeout_; std::chrono::milliseconds stream_idle_timeout_{}; std::chrono::milliseconds request_timeout_{}; @@ -3624,7 +3624,7 @@ TEST_F(HttpConnectionManagerImplTest, OverlyLongHeadersRejected) { } TEST_F(HttpConnectionManagerImplTest, OverlyLongHeadersAcceptedIfConfigured) { - max_request_headers_size_kb_ = 62; + max_request_headers_kb_ = 62; setup(false, ""); EXPECT_CALL(*codec_, dispatch(_)).Times(1).WillOnce(Invoke([&](Buffer::Instance&) -> void { diff --git a/test/common/http/conn_manager_utility_test.cc b/test/common/http/conn_manager_utility_test.cc index 6ede90b769f41..6fa6608d219da 100644 --- a/test/common/http/conn_manager_utility_test.cc +++ b/test/common/http/conn_manager_utility_test.cc @@ -51,7 +51,7 @@ class MockConnectionManagerConfig : public ConnectionManagerConfig { MOCK_METHOD0(filterFactory, FilterChainFactory&()); MOCK_METHOD0(reverseEncodeOrder, bool()); MOCK_METHOD0(generateRequestId, bool()); - MOCK_CONST_METHOD0(maxRequestHeadersSizeKb, uint32_t()); + MOCK_CONST_METHOD0(maxRequestHeadersKb, uint32_t()); MOCK_CONST_METHOD0(idleTimeout, absl::optional()); MOCK_CONST_METHOD0(streamIdleTimeout, std::chrono::milliseconds()); MOCK_CONST_METHOD0(requestTimeout, std::chrono::milliseconds()); diff --git a/test/common/http/http2/BUILD b/test/common/http/http2/BUILD index 27677cfd9b454..436b29f83860d 100644 --- a/test/common/http/http2/BUILD +++ b/test/common/http/http2/BUILD @@ -4,6 +4,7 @@ load( "//bazel:envoy_build_system.bzl", "envoy_cc_fuzz_test", "envoy_cc_test", + "envoy_cc_test_library", "envoy_package", "envoy_proto_library", ) @@ -22,6 +23,7 @@ envoy_cc_fuzz_test( corpus = "codec_impl_corpus", deps = [ ":codec_impl_fuzz_proto_cc", + ":codec_impl_test_util", "//source/common/http:header_map_lib", "//source/common/http/http2:codec_lib", "//test/fuzz:utility_lib", @@ -35,6 +37,7 @@ envoy_cc_test( srcs = ["codec_impl_test.cc"], shard_count = 5, deps = [ + ":codec_impl_test_util", "//source/common/event:dispatcher_lib", "//source/common/http:exception_lib", "//source/common/http:header_map_lib", @@ -48,6 +51,14 @@ envoy_cc_test( ], ) +envoy_cc_test_library( + name = "codec_impl_test_util", + hdrs = ["codec_impl_test_util.h"], + deps = [ + "//source/common/http/http2:codec_lib", + ], +) + envoy_cc_test( name = "conn_pool_test", srcs = ["conn_pool_test.cc"], diff --git a/test/common/http/http2/codec_impl_fuzz_test.cc b/test/common/http/http2/codec_impl_fuzz_test.cc index c023d11207420..32f5af6e981c3 100644 --- a/test/common/http/http2/codec_impl_fuzz_test.cc +++ b/test/common/http/http2/codec_impl_fuzz_test.cc @@ -9,6 +9,8 @@ #include +#include "codec_impl_test_util.h" + #include "common/common/assert.h" #include "common/common/logger.h" #include "common/http/header_map_impl.h" @@ -30,24 +32,6 @@ namespace Envoy { namespace Http { namespace Http2 { -class TestServerConnectionImpl : public ServerConnectionImpl { -public: - TestServerConnectionImpl(Network::Connection& connection, ServerConnectionCallbacks& callbacks, - Stats::Scope& scope, const Http2Settings& http2_settings) - : ServerConnectionImpl(connection, callbacks, scope, http2_settings) {} - nghttp2_session* session() { return session_; } - using ServerConnectionImpl::getStream; -}; - -class TestClientConnectionImpl : public ClientConnectionImpl { -public: - TestClientConnectionImpl(Network::Connection& connection, Http::ConnectionCallbacks& callbacks, - Stats::Scope& scope, const Http2Settings& http2_settings) - : ClientConnectionImpl(connection, callbacks, scope, http2_settings) {} - nghttp2_session* session() { return session_; } - using ClientConnectionImpl::getStream; -}; - // Convert from test proto Http2Settings to Http2Settings. Http2Settings fromHttp2Settings(const test::common::http::http2::Http2Settings& settings) { Http2Settings h2_settings; @@ -260,14 +244,16 @@ DEFINE_PROTO_FUZZER(const test::common::http::http2::CodecImplFuzzTestCase& inpu NiceMock client_connection; const Http2Settings client_http2settings{fromHttp2Settings(input.client_settings())}; NiceMock client_callbacks; + uint32_t max_request_headers_kb = Http::DEFAULT_MAX_REQUEST_HEADERS_KB; + TestClientConnectionImpl client(client_connection, client_callbacks, stats_store, - client_http2settings); + client_http2settings, max_request_headers_kb); NiceMock server_connection; const Http2Settings server_http2settings{fromHttp2Settings(input.server_settings())}; NiceMock server_callbacks; TestServerConnectionImpl server(server_connection, server_callbacks, stats_store, - server_http2settings); + server_http2settings, max_request_headers_kb); ReorderBuffer client_write_buf{server}; ReorderBuffer server_write_buf{client}; diff --git a/test/common/http/http2/codec_impl_test.cc b/test/common/http/http2/codec_impl_test.cc index a20bfda08d15f..2399511a129e3 100644 --- a/test/common/http/http2/codec_impl_test.cc +++ b/test/common/http/http2/codec_impl_test.cc @@ -15,6 +15,7 @@ #include "test/test_common/test_base.h" #include "test/test_common/utility.h" +#include "codec_impl_test_util.h" #include "gmock/gmock.h" using testing::_; @@ -33,24 +34,6 @@ namespace Http2 { using Http2SettingsTuple = ::testing::tuple; using Http2SettingsTestParam = ::testing::tuple; -class TestServerConnectionImpl : public ServerConnectionImpl { -public: - TestServerConnectionImpl(Network::Connection& connection, ServerConnectionCallbacks& callbacks, - Stats::Scope& scope, const Http2Settings& http2_settings) - : ServerConnectionImpl(connection, callbacks, scope, http2_settings) {} - nghttp2_session* session() { return session_; } - using ServerConnectionImpl::getStream; -}; - -class TestClientConnectionImpl : public ClientConnectionImpl { -public: - TestClientConnectionImpl(Network::Connection& connection, Http::ConnectionCallbacks& callbacks, - Stats::Scope& scope, const Http2Settings& http2_settings) - : ClientConnectionImpl(connection, callbacks, scope, http2_settings) {} - nghttp2_session* session() { return session_; } - using ClientConnectionImpl::getStream; -}; - class Http2CodecImplTest : public TestBaseWithParam { public: struct ConnectionWrapper { @@ -73,9 +56,11 @@ class Http2CodecImplTest : public TestBaseWithParam { Http2SettingsFromTuple(client_http2settings_, ::testing::get<0>(GetParam())); Http2SettingsFromTuple(server_http2settings_, ::testing::get<1>(GetParam())); client_ = std::make_unique(client_connection_, client_callbacks_, - stats_store_, client_http2settings_); + stats_store_, client_http2settings_, + max_request_headers_kb_); server_ = std::make_unique(server_connection_, server_callbacks_, - stats_store_, server_http2settings_); + stats_store_, server_http2settings_, + max_request_headers_kb_); request_encoder_ = &client_->newStream(response_decoder_); setupDefaultConnectionMocks(); @@ -144,6 +129,7 @@ class Http2CodecImplTest : public TestBaseWithParam { StreamEncoder* response_encoder_{}; MockStreamCallbacks server_stream_callbacks_; bool corrupt_data_ = false; + uint32_t max_request_headers_kb_ = Http::DEFAULT_MAX_REQUEST_HEADERS_KB; }; TEST_P(Http2CodecImplTest, ShutdownNotice) { @@ -775,9 +761,11 @@ TEST_P(Http2CodecImplStreamLimitTest, MaxClientStreams) { Http2SettingsFromTuple(client_http2settings_, ::testing::get<0>(GetParam())); Http2SettingsFromTuple(server_http2settings_, ::testing::get<1>(GetParam())); client_ = std::make_unique(client_connection_, client_callbacks_, - stats_store_, client_http2settings_); + stats_store_, client_http2settings_, + max_request_headers_kb_); server_ = std::make_unique(server_connection_, server_callbacks_, - stats_store_, server_http2settings_); + stats_store_, server_http2settings_, + max_request_headers_kb_); for (int i = 0; i < 101; ++i) { request_encoder_ = &client_->newStream(response_decoder_); @@ -877,20 +865,54 @@ TEST(Http2CodecUtility, reconstituteCrumbledCookies) { } } -// For issue #1421 regression test that Envoy's H2 codec applies header limits early. -TEST_P(Http2CodecImplTest, TestCodecHeaderLimits) { +TEST_P(Http2CodecImplTest, TestLargeHeadersInvokeResetStream) { initialize(); TestHeaderMapImpl request_headers; HttpTestUtility::addDefaultHeaders(request_headers); - std::string long_string = std::string(1024, 'q'); - for (int i = 0; i < 63; ++i) { - request_headers.addCopy(fmt::format("{}", i), long_string); - } - EXPECT_CALL(server_stream_callbacks_, onResetStream(_)); + std::string long_string = std::string(63 * 1024, 'q'); + request_headers.addCopy("big", long_string); + EXPECT_CALL(server_stream_callbacks_, onResetStream(_)).Times(1); + request_encoder_->encodeHeaders(request_headers, false); +} + +TEST_P(Http2CodecImplTest, TestLargeHeadersAcceptedIfConfigured) { + max_request_headers_kb_ = 64; + initialize(); + + TestHeaderMapImpl request_headers; + HttpTestUtility::addDefaultHeaders(request_headers); + std::string long_string = std::string(63 * 1024, 'q'); + request_headers.addCopy("big", long_string); + + EXPECT_CALL(request_decoder_, decodeHeaders_(_, _)); + EXPECT_CALL(server_stream_callbacks_, onResetStream(_)).Times(0); request_encoder_->encodeHeaders(request_headers, false); } +TEST_P(Http2CodecImplTest, TestLargeHeadersAtLimitAccepted) { + uint32_t codec_limit_kb = 64; + max_request_headers_kb_ = codec_limit_kb; + initialize(); + + TestHeaderMapImpl request_headers; + HttpTestUtility::addDefaultHeaders(request_headers); + std::string key = "big"; + uint32_t head_room = 77; + uint32_t long_string_length = + codec_limit_kb * 1024 - request_headers.byteSize() - key.length() - head_room; + std::string long_string = std::string(long_string_length, 'q'); + request_headers.addCopy(key, long_string); + + // The amount of data sent to the codec is not equivalent to the size of the + // request headers that Envoy computes, as the codec limits based on the + // entire http2 frame. The exact head room needed (76) was found through iteration. + ASSERT_EQ(request_headers.byteSize() + head_room, codec_limit_kb * 1024); + + EXPECT_CALL(request_decoder_, decodeHeaders_(_, _)); + request_encoder_->encodeHeaders(request_headers, true); +} + TEST_P(Http2CodecImplTest, TestCodecHeaderCompression) { initialize(); diff --git a/test/common/http/http2/codec_impl_test_util.h b/test/common/http/http2/codec_impl_test_util.h new file mode 100644 index 0000000000000..b642701265c44 --- /dev/null +++ b/test/common/http/http2/codec_impl_test_util.h @@ -0,0 +1,33 @@ +#include "envoy/http/codec.h" + +#include "common/http/http2/codec_impl.h" + +namespace Envoy { +namespace Http { +namespace Http2 { + +class TestServerConnectionImpl : public ServerConnectionImpl { +public: + TestServerConnectionImpl(Network::Connection& connection, ServerConnectionCallbacks& callbacks, + Stats::Scope& scope, const Http2Settings& http2_settings, + uint32_t max_request_headers_kb) + : ServerConnectionImpl(connection, callbacks, scope, http2_settings, max_request_headers_kb) { + } + nghttp2_session* session() { return session_; } + using ServerConnectionImpl::getStream; +}; + +class TestClientConnectionImpl : public ClientConnectionImpl { +public: + TestClientConnectionImpl(Network::Connection& connection, Http::ConnectionCallbacks& callbacks, + Stats::Scope& scope, const Http2Settings& http2_settings, + uint32_t max_request_headers_kb) + : ClientConnectionImpl(connection, callbacks, scope, http2_settings, max_request_headers_kb) { + } + nghttp2_session* session() { return session_; } + using ClientConnectionImpl::getStream; +}; + +} // namespace Http2 +} // namespace Http +} // namespace Envoy diff --git a/test/extensions/filters/network/http_connection_manager/config_test.cc b/test/extensions/filters/network/http_connection_manager/config_test.cc index 4fe6b5d7cc92d..2e42f07f03dcb 100644 --- a/test/extensions/filters/network/http_connection_manager/config_test.cc +++ b/test/extensions/filters/network/http_connection_manager/config_test.cc @@ -163,7 +163,7 @@ TEST_F(HttpConnectionManagerConfigTest, MaxRequestHeadersSizeDefault) { HttpConnectionManagerConfig config(parseHttpConnectionManagerFromV2Yaml(yaml_string), context_, date_provider_, route_config_provider_manager_); - EXPECT_EQ(60, config.maxRequestHeadersSizeKb()); + EXPECT_EQ(60, config.maxRequestHeadersKb()); } TEST_F(HttpConnectionManagerConfigTest, MaxRequestHeadersSizeConfigured) { @@ -178,7 +178,7 @@ TEST_F(HttpConnectionManagerConfigTest, MaxRequestHeadersSizeConfigured) { HttpConnectionManagerConfig config(parseHttpConnectionManagerFromV2Yaml(yaml_string), context_, date_provider_, route_config_provider_manager_); - EXPECT_EQ(16, config.maxRequestHeadersSizeKb()); + EXPECT_EQ(16, config.maxRequestHeadersKb()); } // Validated that an explicit zero stream idle timeout disables. diff --git a/test/integration/fake_upstream.cc b/test/integration/fake_upstream.cc index d97f56258b3fb..0a48b7e0c526f 100644 --- a/test/integration/fake_upstream.cc +++ b/test/integration/fake_upstream.cc @@ -217,8 +217,9 @@ FakeHttpConnection::FakeHttpConnection(SharedConnectionWrapper& shared_connectio auto settings = Http::Http2Settings(); settings.allow_connect_ = true; settings.allow_metadata_ = true; - codec_ = std::make_unique(shared_connection_.connection(), - *this, store, settings); + codec_ = std::make_unique( + shared_connection_.connection(), *this, store, settings, + Http::DEFAULT_MAX_REQUEST_HEADERS_KB); ASSERT(type == Type::HTTP2); } diff --git a/test/integration/http2_integration_test.cc b/test/integration/http2_integration_test.cc index 4287216c1392c..666abf707efc7 100644 --- a/test/integration/http2_integration_test.cc +++ b/test/integration/http2_integration_test.cc @@ -467,9 +467,9 @@ TEST_P(Http2IntegrationTest, RetryPriority) { testRetryPriority(); } TEST_P(Http2IntegrationTest, GrpcRetry) { testGrpcRetry(); } -TEST_P(Http2IntegrationTest, LargeHeadersInvokeResetStream) { testLargeRequestHeaders(62, 60); } +TEST_P(Http2IntegrationTest, LargeHeadersInvokeResetStream) { testLargeRequestHeaders(63, 60); } -TEST_P(Http2IntegrationTest, LargeHeadersAcceptedIfConfigured) { testLargeRequestHeaders(62, 63); } +TEST_P(Http2IntegrationTest, LargeHeadersAcceptedIfConfigured) { testLargeRequestHeaders(63, 64); } TEST_P(Http2IntegrationTest, EncodingHeaderOnlyResponse) { testHeadersOnlyFilterEncoding(); } diff --git a/test/integration/integration_test.cc b/test/integration/integration_test.cc index a2eac922b4a2b..8b2be331f9f68 100644 --- a/test/integration/integration_test.cc +++ b/test/integration/integration_test.cc @@ -490,9 +490,9 @@ TEST_P(IntegrationTest, InvalidContentLength) { testInvalidContentLength(); } TEST_P(IntegrationTest, MultipleContentLengths) { testMultipleContentLengths(); } -TEST_P(IntegrationTest, LargeHeadersRejected) { testLargeRequestHeaders(62, 60); } +TEST_P(IntegrationTest, LargeHeadersRejected) { testLargeRequestHeaders(63, 60); } -TEST_P(IntegrationTest, LargeHeadersAccepted) { testLargeRequestHeaders(62, 63); } +TEST_P(IntegrationTest, LargeHeadersAcceptedIfConfigured) { testLargeRequestHeaders(63, 64); } TEST_P(IntegrationTest, UpstreamProtocolError) { initialize(); From 4519a370c592db6a8df29a1e92479169c531023e Mon Sep 17 00:00:00 2001 From: Maxime Bedard Date: Tue, 5 Feb 2019 00:05:54 -0500 Subject: [PATCH 16/51] redis: Add hashtagging to redis-proxy filter (#5623) Signed-off-by: Maxime Bedard --- .../network/redis_proxy/v2/redis_proxy.proto | 12 +++++++ docs/root/intro/version_history.rst | 3 +- .../filters/network/redis_proxy/conn_pool.h | 6 ++++ .../network/redis_proxy/conn_pool_impl.cc | 31 ++++++++++++++--- .../network/redis_proxy/conn_pool_impl.h | 11 +++++-- .../extensions/health_checkers/redis/redis.h | 1 + .../redis_proxy/conn_pool_impl_test.cc | 33 +++++++++++++++++++ 7 files changed, 88 insertions(+), 9 deletions(-) diff --git a/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto b/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto index a7847be18dd4e..29648bda3f607 100644 --- a/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto +++ b/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto @@ -31,6 +31,18 @@ message RedisProxy { // is ready. google.protobuf.Duration op_timeout = 1 [(validate.rules).duration.required = true, (gogoproto.stdduration) = true]; + + // Use hash tagging on every redis key to guarantee that keys with the same hash tag will be + // forwarded to the same upstream. The hash key used for determining the upstream in a + // consistent hash ring configuration will be computed from the hash tagged key instead of the + // whole key. The algorithm used to compute the hash tag is identical to the `redis-cluster + // implementation `_. + // + // Examples: + // + // * '{user1000}.following' and '{user1000}.followers' **will** be sent to the same upstream + // * '{user1000}.following' and '{user1001}.following' **might** be sent to the same upstream + bool enable_hashtagging = 2; } // Network settings for the connection pool to the upstream cluster. diff --git a/docs/root/intro/version_history.rst b/docs/root/intro/version_history.rst index e07bd5b2abe46..08ed0c9fa4d00 100644 --- a/docs/root/intro/version_history.rst +++ b/docs/root/intro/version_history.rst @@ -25,8 +25,9 @@ Version history * outlier_detection: added support for :ref:`outlier detection event protobuf-based logging `. * mysql: added a MySQL proxy filter that is capable of parsing SQL queries over MySQL wire protocol. Refer to ::ref:`MySQL proxy` for more details. * http: added :ref:`max request headers size `. The default behaviour is unchanged. -* redis: added :ref:`success and error stats ` for commands. +* redis: added :ref:`hashtagging ` to guarantee a given key's upstream. * redis: added :ref:`latency stats ` for commands. +* redis: added :ref:`success and error stats ` for commands. * redis: migrate hash function for host selection to `MurmurHash2 `_ from std::hash. MurmurHash2 is compatible with std::hash in GNU libstdc++ 3.4.20 or above. This is typically the case when compiled on Linux and not macOS. * router: added ability to configure a :ref:`retry policy ` at the virtual host level. diff --git a/source/extensions/filters/network/redis_proxy/conn_pool.h b/source/extensions/filters/network/redis_proxy/conn_pool.h index 341a0732be39e..c37a46dc185c6 100644 --- a/source/extensions/filters/network/redis_proxy/conn_pool.h +++ b/source/extensions/filters/network/redis_proxy/conn_pool.h @@ -94,6 +94,12 @@ class Config { * passive healthcheck operations. */ virtual bool disableOutlierEvents() const PURE; + + /** + * @return when enabled, a hash tagging function will be used to guarantee that keys with the + * same hash tag will be forwarded to the same upstream. + */ + virtual bool enableHashtagging() const PURE; }; /** diff --git a/source/extensions/filters/network/redis_proxy/conn_pool_impl.cc b/source/extensions/filters/network/redis_proxy/conn_pool_impl.cc index d34449e968f20..596233af4f55c 100644 --- a/source/extensions/filters/network/redis_proxy/conn_pool_impl.cc +++ b/source/extensions/filters/network/redis_proxy/conn_pool_impl.cc @@ -15,7 +15,8 @@ namespace ConnPool { ConfigImpl::ConfigImpl( const envoy::config::filter::network::redis_proxy::v2::RedisProxy::ConnPoolSettings& config) - : op_timeout_(PROTOBUF_GET_MS_REQUIRED(config, op_timeout)) {} + : op_timeout_(PROTOBUF_GET_MS_REQUIRED(config, op_timeout)), + enable_hashtagging_(config.enable_hashtagging()) {} ClientPtr ClientImpl::create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher, EncoderPtr&& encoder, DecoderFactory& decoder_factory, @@ -199,9 +200,9 @@ InstanceImpl::InstanceImpl( }); } -PoolRequest* InstanceImpl::makeRequest(const std::string& hash_key, const RespValue& value, +PoolRequest* InstanceImpl::makeRequest(const std::string& key, const RespValue& value, PoolCallbacks& callbacks) { - return tls_->getTyped().makeRequest(hash_key, value, callbacks); + return tls_->getTyped().makeRequest(key, value, callbacks); } InstanceImpl::ThreadLocalPool::ThreadLocalPool(InstanceImpl& parent, Event::Dispatcher& dispatcher, @@ -272,7 +273,7 @@ void InstanceImpl::ThreadLocalPool::onHostsRemoved( } } -PoolRequest* InstanceImpl::ThreadLocalPool::makeRequest(const std::string& hash_key, +PoolRequest* InstanceImpl::ThreadLocalPool::makeRequest(const std::string& key, const RespValue& request, PoolCallbacks& callbacks) { if (cluster_ == nullptr) { @@ -281,7 +282,7 @@ PoolRequest* InstanceImpl::ThreadLocalPool::makeRequest(const std::string& hash_ return nullptr; } - LbContextImpl lb_context(hash_key); + LbContextImpl lb_context(key, parent_.config_.enableHashtagging()); Upstream::HostConstSharedPtr host = cluster_->loadBalancer().chooseHost(&lb_context); if (!host) { return nullptr; @@ -308,6 +309,26 @@ void InstanceImpl::ThreadLocalActiveClient::onEvent(Network::ConnectionEvent eve } } +// Inspired by the redis-cluster hashtagging algorithm +// https://redis.io/topics/cluster-spec#keys-hash-tags +absl::string_view InstanceImpl::LbContextImpl::hashtag(absl::string_view v, bool enabled) { + if (!enabled) { + return v; + } + + auto start = v.find('{'); + if (start == std::string::npos) { + return v; + } + + auto end = v.find('}', start); + if (end == std::string::npos || end == start + 1) { + return v; + } + + return v.substr(start + 1, end - start - 1); +} + } // namespace ConnPool } // namespace RedisProxy } // namespace NetworkFilters diff --git a/source/extensions/filters/network/redis_proxy/conn_pool_impl.h b/source/extensions/filters/network/redis_proxy/conn_pool_impl.h index b985c271c1605..ba89f3098a8d1 100644 --- a/source/extensions/filters/network/redis_proxy/conn_pool_impl.h +++ b/source/extensions/filters/network/redis_proxy/conn_pool_impl.h @@ -37,9 +37,11 @@ class ConfigImpl : public Config { bool disableOutlierEvents() const override { return false; } std::chrono::milliseconds opTimeout() const override { return op_timeout_; } + bool enableHashtagging() const override { return enable_hashtagging_; } private: const std::chrono::milliseconds op_timeout_; + const bool enable_hashtagging_; }; class ClientImpl : public Client, public DecoderCallbacks, public Network::ConnectionCallbacks { @@ -127,7 +129,7 @@ class InstanceImpl : public Instance { const envoy::config::filter::network::redis_proxy::v2::RedisProxy::ConnPoolSettings& config); // RedisProxy::ConnPool::Instance - PoolRequest* makeRequest(const std::string& hash_key, const RespValue& request, + PoolRequest* makeRequest(const std::string& key, const RespValue& request, PoolCallbacks& callbacks) override; private: @@ -152,7 +154,7 @@ class InstanceImpl : public Instance { public Upstream::ClusterUpdateCallbacks { ThreadLocalPool(InstanceImpl& parent, Event::Dispatcher& dispatcher, std::string cluster_name); ~ThreadLocalPool(); - PoolRequest* makeRequest(const std::string& hash_key, const RespValue& request, + PoolRequest* makeRequest(const std::string& key, const RespValue& request, PoolCallbacks& callbacks); void onClusterAddOrUpdateNonVirtual(Upstream::ThreadLocalCluster& cluster); void onHostsRemoved(const std::vector& hosts_removed); @@ -173,10 +175,13 @@ class InstanceImpl : public Instance { }; struct LbContextImpl : public Upstream::LoadBalancerContextBase { - LbContextImpl(const std::string& hash_key) : hash_key_(MurmurHash::murmurHash2_64(hash_key)) {} + LbContextImpl(const std::string& key, bool enabled_hashtagging) + : hash_key_(MurmurHash::murmurHash2_64(hashtag(key, enabled_hashtagging))) {} absl::optional computeHashKey() override { return hash_key_; } + absl::string_view hashtag(absl::string_view v, bool enabled); + const absl::optional hash_key_; }; diff --git a/source/extensions/health_checkers/redis/redis.h b/source/extensions/health_checkers/redis/redis.h index 7de0ddb682519..5aa702e5665d5 100644 --- a/source/extensions/health_checkers/redis/redis.h +++ b/source/extensions/health_checkers/redis/redis.h @@ -57,6 +57,7 @@ class RedisHealthChecker : public Upstream::HealthCheckerImplBase { // Allow the main Health Check infra to control timeout. return parent_.timeout_ * 2; } + bool enableHashtagging() const override { return false; } // Extensions::NetworkFilters::RedisProxy::ConnPool::PoolCallbacks void onResponse(Extensions::NetworkFilters::RedisProxy::RespValuePtr&& value) override; diff --git a/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc b/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc index 95f0d84dfa4de..7104eb615265b 100644 --- a/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc +++ b/test/extensions/filters/network/redis_proxy/conn_pool_impl_test.cc @@ -36,6 +36,7 @@ envoy::config::filter::network::redis_proxy::v2::RedisProxy::ConnPoolSettings createConnPoolSettings() { envoy::config::filter::network::redis_proxy::v2::RedisProxy::ConnPoolSettings setting{}; setting.mutable_op_timeout()->CopyFrom(Protobuf::util::TimeUtil::MillisecondsToDuration(20)); + setting.set_enable_hashtagging(true); return setting; } @@ -302,6 +303,7 @@ TEST_F(RedisClientImplTest, ConnectFail) { class ConfigOutlierDisabled : public Config { bool disableOutlierEvents() const override { return true; } std::chrono::milliseconds opTimeout() const override { return std::chrono::milliseconds(25); } + bool enableHashtagging() const override { return false; } }; TEST_F(RedisClientImplTest, OutlierDisabled) { @@ -449,6 +451,37 @@ TEST_F(RedisConnPoolImplTest, Basic) { tls_.shutdownThread(); }; +TEST_F(RedisConnPoolImplTest, Hashtagging) { + InSequence s; + + setup(); + + RespValue value; + MockPoolCallbacks callbacks; + + auto expectHashKey = [](const std::string& s) { + return [s](Upstream::LoadBalancerContext* context) -> Upstream::HostConstSharedPtr { + EXPECT_EQ(context->computeHashKey().value(), MurmurHash::murmurHash2_64(s)); + return nullptr; + }; + }; + + EXPECT_CALL(cm_.thread_local_cluster_.lb_, chooseHost(_)).WillOnce(Invoke(expectHashKey("foo"))); + conn_pool_->makeRequest("{foo}.bar", value, callbacks); + + EXPECT_CALL(cm_.thread_local_cluster_.lb_, chooseHost(_)) + .WillOnce(Invoke(expectHashKey("foo{}{bar}"))); + conn_pool_->makeRequest("foo{}{bar}", value, callbacks); + + EXPECT_CALL(cm_.thread_local_cluster_.lb_, chooseHost(_)).WillOnce(Invoke(expectHashKey("{bar"))); + conn_pool_->makeRequest("foo{{bar}}zap", value, callbacks); + + EXPECT_CALL(cm_.thread_local_cluster_.lb_, chooseHost(_)).WillOnce(Invoke(expectHashKey("bar"))); + conn_pool_->makeRequest("foo{bar}{zap}", value, callbacks); + + tls_.shutdownThread(); +}; + // Conn pool created when no cluster exists at creation time. Dynamic cluster creation and removal // work correctly. TEST_F(RedisConnPoolImplTest, NoClusterAtConstruction) { From 4a5f85809cef13be47873483789a5a7bb64ded7c Mon Sep 17 00:00:00 2001 From: ZHANG Dapeng Date: Mon, 4 Feb 2019 21:15:43 -0800 Subject: [PATCH 17/51] api: add java proto options to avoid risk of future breakage (#5764) As discussed with @snowp in [envoyproxy/java-control-plane#87 (comment)](https://github.com/envoyproxy/java-control-plane/issues/87#issuecomment-456537248) and [envoyproxy/java-control-plane#87 (comment)](https://github.com/envoyproxy/java-control-plane/issues/87#issuecomment-457649859), adding these options will avoid the risk of having API breaking changes on the generated java code as the proto files evolve. Risk Level_: Medium Note that e.g. [envoyproxy/java-control-plane](https://github.com/envoyproxy/java-control-plane) will have to do a refactoring when they sync the proto files next time. Signed-off-by: Penn (Dapeng) Zhang --- api/envoy/admin/v2alpha/certs.proto | 3 + api/envoy/admin/v2alpha/clusters.proto | 3 + api/envoy/admin/v2alpha/config_dump.proto | 3 + api/envoy/admin/v2alpha/memory.proto | 3 + api/envoy/admin/v2alpha/metrics.proto | 3 + api/envoy/admin/v2alpha/mutex_stats.proto | 3 + api/envoy/admin/v2alpha/server_info.proto | 3 + api/envoy/admin/v2alpha/tap.proto | 3 + api/envoy/api/v2/auth/cert.proto | 3 + api/envoy/api/v2/cds.proto | 3 + .../api/v2/cluster/circuit_breaker.proto | 3 + .../api/v2/cluster/outlier_detection.proto | 3 + api/envoy/api/v2/core/address.proto | 3 + api/envoy/api/v2/core/base.proto | 3 + api/envoy/api/v2/core/config_source.proto | 3 + api/envoy/api/v2/core/grpc_service.proto | 3 + api/envoy/api/v2/core/health_check.proto | 3 + api/envoy/api/v2/core/http_uri.proto | 3 + api/envoy/api/v2/core/protocol.proto | 3 + api/envoy/api/v2/discovery.proto | 3 + api/envoy/api/v2/eds.proto | 3 + api/envoy/api/v2/endpoint/endpoint.proto | 3 + api/envoy/api/v2/endpoint/load_report.proto | 3 + api/envoy/api/v2/lds.proto | 3 + api/envoy/api/v2/listener/listener.proto | 3 + api/envoy/api/v2/ratelimit/ratelimit.proto | 3 + api/envoy/api/v2/rds.proto | 3 + api/envoy/api/v2/route/route.proto | 3 + api/envoy/config/accesslog/v2/als.proto | 3 + api/envoy/config/accesslog/v2/file.proto | 3 + api/envoy/config/bootstrap/v2/bootstrap.proto | 3 + .../config/common/tap/v2alpha/common.proto | 3 + .../filter/accesslog/v2/accesslog.proto | 3 + api/envoy/config/filter/fault/v2/fault.proto | 3 + .../config/filter/http/buffer/v2/buffer.proto | 3 + .../filter/http/ext_authz/v2/ext_authz.proto | 2 + .../config/filter/http/fault/v2/fault.proto | 3 + .../v2alpha1/config.proto | 3 + .../config/filter/http/gzip/v2/gzip.proto | 3 + .../v2/header_to_metadata.proto | 3 + .../http/health_check/v2/health_check.proto | 3 + .../http/ip_tagging/v2/ip_tagging.proto | 3 + .../http/jwt_authn/v2alpha/config.proto | 3 + api/envoy/config/filter/http/lua/v2/lua.proto | 3 + .../http/rate_limit/v2/rate_limit.proto | 3 + .../config/filter/http/rbac/v2/rbac.proto | 3 + .../config/filter/http/router/v2/router.proto | 3 + .../config/filter/http/squash/v2/squash.proto | 3 + .../config/filter/http/tap/v2alpha/tap.proto | 3 + .../http/transcoder/v2/transcoder.proto | 3 + .../original_src/v2alpha1/original_src.proto | 3 + .../client_ssl_auth/v2/client_ssl_auth.proto | 3 + .../dubbo_proxy/v2alpha1/dubbo_proxy.proto | 3 + .../network/dubbo_proxy/v2alpha1/route.proto | 3 + .../network/ext_authz/v2/ext_authz.proto | 3 + .../v2/http_connection_manager.proto | 3 + .../network/mongo_proxy/v2/mongo_proxy.proto | 3 + .../mysql_proxy/v1alpha1/mysql_proxy.proto | 3 + .../network/rate_limit/v2/rate_limit.proto | 3 + .../config/filter/network/rbac/v2/rbac.proto | 3 + .../network/redis_proxy/v2/redis_proxy.proto | 3 + .../network/tcp_proxy/v2/tcp_proxy.proto | 3 + .../network/thrift_proxy/v2alpha1/route.proto | 3 + .../thrift_proxy/v2alpha1/thrift_proxy.proto | 3 + .../rate_limit/v2alpha1/rate_limit.proto | 3 + .../thrift/router/v2alpha1/router.proto | 3 + .../v2alpha/file_based_metadata.proto | 3 + .../health_checker/redis/v2/redis.proto | 3 + .../config/metrics/v2/metrics_service.proto | 3 + api/envoy/config/metrics/v2/stats.proto | 3 + .../config/overload/v2alpha/overload.proto | 3 + api/envoy/config/ratelimit/v2/rls.proto | 3 + api/envoy/config/rbac/v2alpha/rbac.proto | 3 + .../fixed_heap/v2alpha/fixed_heap.proto | 3 + .../v2alpha/injected_resource.proto | 3 + .../previous_priorities_config.proto | 3 + api/envoy/config/trace/v2/trace.proto | 3 + .../transport_socket/alts/v2alpha/alts.proto | 3 + .../transport_socket/tap/v2alpha/tap.proto | 3 + api/envoy/data/accesslog/v2/accesslog.proto | 3 + .../v2alpha/outlier_detection_event.proto | 3 + .../core/v2alpha/health_check_event.proto | 3 + api/envoy/data/tap/v2alpha/http.proto | 3 + api/envoy/data/tap/v2alpha/transport.proto | 3 + api/envoy/data/tap/v2alpha/wrapper.proto | 3 + api/envoy/service/accesslog/v2/als.proto | 3 + .../service/auth/v2/attribute_context.proto | 3 + api/envoy/service/auth/v2/external_auth.proto | 3 + api/envoy/service/discovery/v2/ads.proto | 3 + api/envoy/service/discovery/v2/hds.proto | 3 + api/envoy/service/discovery/v2/sds.proto | 3 + api/envoy/service/load_stats/v2/lrs.proto | 3 + .../service/metrics/v2/metrics_service.proto | 3 + api/envoy/service/ratelimit/v2/rls.proto | 3 + api/envoy/service/tap/v2alpha/common.proto | 3 + .../service/trace/v2/trace_service.proto | 3 + api/envoy/type/http_status.proto | 3 + api/envoy/type/matcher/metadata.proto | 3 + api/envoy/type/matcher/number.proto | 3 + api/envoy/type/matcher/string.proto | 3 + api/envoy/type/matcher/value.proto | 3 + api/envoy/type/percent.proto | 3 + api/envoy/type/range.proto | 3 + tools/check_format.py | 94 ++++++++++++++----- .../check_format/api/java_options.proto.gold | 3 + 105 files changed, 380 insertions(+), 25 deletions(-) diff --git a/api/envoy/admin/v2alpha/certs.proto b/api/envoy/admin/v2alpha/certs.proto index bb8d173b97d43..c6d5e4154aed8 100644 --- a/api/envoy/admin/v2alpha/certs.proto +++ b/api/envoy/admin/v2alpha/certs.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "CertsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; import "google/protobuf/timestamp.proto"; diff --git a/api/envoy/admin/v2alpha/clusters.proto b/api/envoy/admin/v2alpha/clusters.proto index 68e3cb363df05..be7011be03036 100644 --- a/api/envoy/admin/v2alpha/clusters.proto +++ b/api/envoy/admin/v2alpha/clusters.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "ClustersProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; import "envoy/admin/v2alpha/metrics.proto"; diff --git a/api/envoy/admin/v2alpha/config_dump.proto b/api/envoy/admin/v2alpha/config_dump.proto index 0cb1ad21e11ca..cfc1cdd54d8f5 100644 --- a/api/envoy/admin/v2alpha/config_dump.proto +++ b/api/envoy/admin/v2alpha/config_dump.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "ConfigDumpProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; import "envoy/api/v2/cds.proto"; diff --git a/api/envoy/admin/v2alpha/memory.proto b/api/envoy/admin/v2alpha/memory.proto index 3e83811a75c4c..f4158f4bb37a2 100644 --- a/api/envoy/admin/v2alpha/memory.proto +++ b/api/envoy/admin/v2alpha/memory.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "MemoryProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; // [#protodoc-title: Memory] diff --git a/api/envoy/admin/v2alpha/metrics.proto b/api/envoy/admin/v2alpha/metrics.proto index f2a90b0bca0be..9a91c7477be5b 100644 --- a/api/envoy/admin/v2alpha/metrics.proto +++ b/api/envoy/admin/v2alpha/metrics.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "MetricsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; // [#protodoc-title: Metrics] diff --git a/api/envoy/admin/v2alpha/mutex_stats.proto b/api/envoy/admin/v2alpha/mutex_stats.proto index 65f121cce398c..272d7224b0e98 100644 --- a/api/envoy/admin/v2alpha/mutex_stats.proto +++ b/api/envoy/admin/v2alpha/mutex_stats.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "MutexStatsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; // [#protodoc-title: MutexStats] diff --git a/api/envoy/admin/v2alpha/server_info.proto b/api/envoy/admin/v2alpha/server_info.proto index 3feb5952b83a5..18dcc70b805cc 100644 --- a/api/envoy/admin/v2alpha/server_info.proto +++ b/api/envoy/admin/v2alpha/server_info.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.admin.v2alpha; + +option java_outer_classname = "ServerInfoProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; import "google/protobuf/duration.proto"; diff --git a/api/envoy/admin/v2alpha/tap.proto b/api/envoy/admin/v2alpha/tap.proto index e35ef3cc5aec6..789be14b01c37 100644 --- a/api/envoy/admin/v2alpha/tap.proto +++ b/api/envoy/admin/v2alpha/tap.proto @@ -4,6 +4,9 @@ import "envoy/service/tap/v2alpha/common.proto"; import "validate/validate.proto"; package envoy.admin.v2alpha; + +option java_outer_classname = "TapProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.admin.v2alpha"; // The /tap admin request body that is used to configure an active tap session. diff --git a/api/envoy/api/v2/auth/cert.proto b/api/envoy/api/v2/auth/cert.proto index 778c8c17ba0d0..8bc2ee37b849d 100644 --- a/api/envoy/api/v2/auth/cert.proto +++ b/api/envoy/api/v2/auth/cert.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.auth; + +option java_outer_classname = "CertProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.auth"; option go_package = "auth"; diff --git a/api/envoy/api/v2/cds.proto b/api/envoy/api/v2/cds.proto index bd200eae261bb..cca6de9e0d670 100644 --- a/api/envoy/api/v2/cds.proto +++ b/api/envoy/api/v2/cds.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2; + +option java_outer_classname = "CdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2"; option java_generic_services = true; diff --git a/api/envoy/api/v2/cluster/circuit_breaker.proto b/api/envoy/api/v2/cluster/circuit_breaker.proto index a1193cc6b61f5..50b20c08e5e7e 100644 --- a/api/envoy/api/v2/cluster/circuit_breaker.proto +++ b/api/envoy/api/v2/cluster/circuit_breaker.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.cluster; + +option java_outer_classname = "CircuitBreakerProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.cluster"; option go_package = "cluster"; option csharp_namespace = "Envoy.Api.V2.ClusterNS"; diff --git a/api/envoy/api/v2/cluster/outlier_detection.proto b/api/envoy/api/v2/cluster/outlier_detection.proto index dd373c2e29471..cd33cde1eccd9 100644 --- a/api/envoy/api/v2/cluster/outlier_detection.proto +++ b/api/envoy/api/v2/cluster/outlier_detection.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.cluster; + +option java_outer_classname = "OutlierDetectionProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.cluster"; option csharp_namespace = "Envoy.Api.V2.ClusterNS"; diff --git a/api/envoy/api/v2/core/address.proto b/api/envoy/api/v2/core/address.proto index dbf6acc7a1ec3..6e76f5b721901 100644 --- a/api/envoy/api/v2/core/address.proto +++ b/api/envoy/api/v2/core/address.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "AddressProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; import "envoy/api/v2/core/base.proto"; diff --git a/api/envoy/api/v2/core/base.proto b/api/envoy/api/v2/core/base.proto index 23f525096c9b8..3d03b3eb467ae 100644 --- a/api/envoy/api/v2/core/base.proto +++ b/api/envoy/api/v2/core/base.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "BaseProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; option go_package = "core"; diff --git a/api/envoy/api/v2/core/config_source.proto b/api/envoy/api/v2/core/config_source.proto index eb314fc4a0157..3be59c1886b5f 100644 --- a/api/envoy/api/v2/core/config_source.proto +++ b/api/envoy/api/v2/core/config_source.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "ConfigSourceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; import "envoy/api/v2/core/grpc_service.proto"; diff --git a/api/envoy/api/v2/core/grpc_service.proto b/api/envoy/api/v2/core/grpc_service.proto index 08672849ce69c..0ee84e3b1077d 100644 --- a/api/envoy/api/v2/core/grpc_service.proto +++ b/api/envoy/api/v2/core/grpc_service.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "GrpcServiceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; import "envoy/api/v2/core/base.proto"; diff --git a/api/envoy/api/v2/core/health_check.proto b/api/envoy/api/v2/core/health_check.proto index b158b6c80ea8c..65102d613dc81 100644 --- a/api/envoy/api/v2/core/health_check.proto +++ b/api/envoy/api/v2/core/health_check.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "HealthCheckProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; import "envoy/api/v2/core/base.proto"; diff --git a/api/envoy/api/v2/core/http_uri.proto b/api/envoy/api/v2/core/http_uri.proto index c0a007e10ee7e..21c66c7fa63c0 100644 --- a/api/envoy/api/v2/core/http_uri.proto +++ b/api/envoy/api/v2/core/http_uri.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "HttpUriProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; import "google/protobuf/duration.proto"; diff --git a/api/envoy/api/v2/core/protocol.proto b/api/envoy/api/v2/core/protocol.proto index 69bddec072a5d..1f5027e7e8b8b 100644 --- a/api/envoy/api/v2/core/protocol.proto +++ b/api/envoy/api/v2/core/protocol.proto @@ -3,6 +3,9 @@ syntax = "proto3"; package envoy.api.v2.core; + +option java_outer_classname = "ProtocolProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.core"; import "google/protobuf/duration.proto"; diff --git a/api/envoy/api/v2/discovery.proto b/api/envoy/api/v2/discovery.proto index 75fcc02a8d7b5..17e5cfdcc38d6 100644 --- a/api/envoy/api/v2/discovery.proto +++ b/api/envoy/api/v2/discovery.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2; + +option java_outer_classname = "DiscoveryProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2"; option go_package = "v2"; diff --git a/api/envoy/api/v2/eds.proto b/api/envoy/api/v2/eds.proto index afb932190d35b..fcef8c5f95fc9 100644 --- a/api/envoy/api/v2/eds.proto +++ b/api/envoy/api/v2/eds.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2; + +option java_outer_classname = "EdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2"; option java_generic_services = true; diff --git a/api/envoy/api/v2/endpoint/endpoint.proto b/api/envoy/api/v2/endpoint/endpoint.proto index 2efe7d1ff5f7e..c458884c3a2bf 100644 --- a/api/envoy/api/v2/endpoint/endpoint.proto +++ b/api/envoy/api/v2/endpoint/endpoint.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.endpoint; + +option java_outer_classname = "EndpointProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.endpoint"; option go_package = "endpoint"; diff --git a/api/envoy/api/v2/endpoint/load_report.proto b/api/envoy/api/v2/endpoint/load_report.proto index cbb01d3271897..58580d4203913 100644 --- a/api/envoy/api/v2/endpoint/load_report.proto +++ b/api/envoy/api/v2/endpoint/load_report.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.endpoint; + +option java_outer_classname = "LoadReportProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.endpoint"; import "envoy/api/v2/core/address.proto"; diff --git a/api/envoy/api/v2/lds.proto b/api/envoy/api/v2/lds.proto index 56980a11f9cea..5b2f8bbc1b976 100644 --- a/api/envoy/api/v2/lds.proto +++ b/api/envoy/api/v2/lds.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2; + +option java_outer_classname = "LdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2"; option java_generic_services = true; diff --git a/api/envoy/api/v2/listener/listener.proto b/api/envoy/api/v2/listener/listener.proto index c919531c0f83e..96b7668af2560 100644 --- a/api/envoy/api/v2/listener/listener.proto +++ b/api/envoy/api/v2/listener/listener.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.listener; + +option java_outer_classname = "ListenerProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.listener"; option go_package = "listener"; option csharp_namespace = "Envoy.Api.V2.ListenerNS"; diff --git a/api/envoy/api/v2/ratelimit/ratelimit.proto b/api/envoy/api/v2/ratelimit/ratelimit.proto index 78bdc9c86463b..8ebec7182257e 100644 --- a/api/envoy/api/v2/ratelimit/ratelimit.proto +++ b/api/envoy/api/v2/ratelimit/ratelimit.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.ratelimit; + +option java_outer_classname = "RatelimitProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.ratelimit"; option go_package = "ratelimit"; diff --git a/api/envoy/api/v2/rds.proto b/api/envoy/api/v2/rds.proto index 9699accf95ce2..8d41b384ba9bd 100644 --- a/api/envoy/api/v2/rds.proto +++ b/api/envoy/api/v2/rds.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2; + +option java_outer_classname = "RdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2"; option java_generic_services = true; diff --git a/api/envoy/api/v2/route/route.proto b/api/envoy/api/v2/route/route.proto index 7e7b41de30251..f752ad14e26e1 100644 --- a/api/envoy/api/v2/route/route.proto +++ b/api/envoy/api/v2/route/route.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.api.v2.route; + +option java_outer_classname = "RouteProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.api.v2.route"; option go_package = "route"; option java_generic_services = true; diff --git a/api/envoy/config/accesslog/v2/als.proto b/api/envoy/config/accesslog/v2/als.proto index fdc5fa12c8f50..c71fe70a8c855 100644 --- a/api/envoy/config/accesslog/v2/als.proto +++ b/api/envoy/config/accesslog/v2/als.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.accesslog.v2; + +option java_outer_classname = "AlsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.accesslog.v2"; option go_package = "v2"; diff --git a/api/envoy/config/accesslog/v2/file.proto b/api/envoy/config/accesslog/v2/file.proto index fb5bddcebdae6..48a1841a9614a 100644 --- a/api/envoy/config/accesslog/v2/file.proto +++ b/api/envoy/config/accesslog/v2/file.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.accesslog.v2; + +option java_outer_classname = "FileProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.accesslog.v2"; option go_package = "v2"; diff --git a/api/envoy/config/bootstrap/v2/bootstrap.proto b/api/envoy/config/bootstrap/v2/bootstrap.proto index f6f883b822521..5bf09febcddd0 100644 --- a/api/envoy/config/bootstrap/v2/bootstrap.proto +++ b/api/envoy/config/bootstrap/v2/bootstrap.proto @@ -6,6 +6,9 @@ syntax = "proto3"; package envoy.config.bootstrap.v2; + +option java_outer_classname = "BootstrapProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.bootstrap.v2"; option go_package = "v2"; diff --git a/api/envoy/config/common/tap/v2alpha/common.proto b/api/envoy/config/common/tap/v2alpha/common.proto index 9fb3832868efb..a7b587e3ba38c 100644 --- a/api/envoy/config/common/tap/v2alpha/common.proto +++ b/api/envoy/config/common/tap/v2alpha/common.proto @@ -5,6 +5,9 @@ import "envoy/service/tap/v2alpha/common.proto"; import "validate/validate.proto"; package envoy.config.common.tap.v2alpha; + +option java_outer_classname = "CommonProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.tap.v2alpha"; // [#protodoc-title: Common tap extension configuration] diff --git a/api/envoy/config/filter/accesslog/v2/accesslog.proto b/api/envoy/config/filter/accesslog/v2/accesslog.proto index c85f06efa3e1b..da699432ee177 100644 --- a/api/envoy/config/filter/accesslog/v2/accesslog.proto +++ b/api/envoy/config/filter/accesslog/v2/accesslog.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.accesslog.v2; + +option java_outer_classname = "AccesslogProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.accesslog.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/fault/v2/fault.proto b/api/envoy/config/filter/fault/v2/fault.proto index 8462a2f95c5d7..7c6e405ba9704 100644 --- a/api/envoy/config/filter/fault/v2/fault.proto +++ b/api/envoy/config/filter/fault/v2/fault.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.fault.v2; + +option java_outer_classname = "FaultProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.fault.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/buffer/v2/buffer.proto b/api/envoy/config/filter/http/buffer/v2/buffer.proto index fce389c68b0c2..6da5cbb94746a 100644 --- a/api/envoy/config/filter/http/buffer/v2/buffer.proto +++ b/api/envoy/config/filter/http/buffer/v2/buffer.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.buffer.v2; + +option java_outer_classname = "BufferProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.buffer.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/ext_authz/v2/ext_authz.proto b/api/envoy/config/filter/http/ext_authz/v2/ext_authz.proto index ddcdf6ab51c16..2f5423afd4a83 100644 --- a/api/envoy/config/filter/http/ext_authz/v2/ext_authz.proto +++ b/api/envoy/config/filter/http/ext_authz/v2/ext_authz.proto @@ -1,6 +1,8 @@ syntax = "proto3"; package envoy.config.filter.http.ext_authz.v2; + +option java_outer_classname = "ExtAuthzProto"; option java_package = "io.envoyproxy.envoy.config.filter.http.ext_authz.v2"; option java_multiple_files = true; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/fault/v2/fault.proto b/api/envoy/config/filter/http/fault/v2/fault.proto index 134a5424cee14..aaffbc1f316ab 100644 --- a/api/envoy/config/filter/http/fault/v2/fault.proto +++ b/api/envoy/config/filter/http/fault/v2/fault.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.fault.v2; + +option java_outer_classname = "FaultProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.fault.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/grpc_http1_reverse_bridge/v2alpha1/config.proto b/api/envoy/config/filter/http/grpc_http1_reverse_bridge/v2alpha1/config.proto index 5b236fff4f30f..eb1dfd68fe2d9 100644 --- a/api/envoy/config/filter/http/grpc_http1_reverse_bridge/v2alpha1/config.proto +++ b/api/envoy/config/filter/http/grpc_http1_reverse_bridge/v2alpha1/config.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.extensions.filter.http.grpc_http1_reverse_bridge.v2alpha1; + +option java_outer_classname = "ConfigProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.extensions.filter.http.grpc_http1_reverse_bridge.v2alpha1"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/gzip/v2/gzip.proto b/api/envoy/config/filter/http/gzip/v2/gzip.proto index e6609f171f34d..fb6b8878e6528 100644 --- a/api/envoy/config/filter/http/gzip/v2/gzip.proto +++ b/api/envoy/config/filter/http/gzip/v2/gzip.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.gzip.v2; + +option java_outer_classname = "GzipProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.gzip.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/header_to_metadata/v2/header_to_metadata.proto b/api/envoy/config/filter/http/header_to_metadata/v2/header_to_metadata.proto index af9a4d0cf0c3b..2c8c606d3f863 100644 --- a/api/envoy/config/filter/http/header_to_metadata/v2/header_to_metadata.proto +++ b/api/envoy/config/filter/http/header_to_metadata/v2/header_to_metadata.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.header_to_metadata.v2; + +option java_outer_classname = "HeaderToMetadataProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.header_to_metadata.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/health_check/v2/health_check.proto b/api/envoy/config/filter/http/health_check/v2/health_check.proto index 5cb6a9d37265b..c951f08c1314b 100644 --- a/api/envoy/config/filter/http/health_check/v2/health_check.proto +++ b/api/envoy/config/filter/http/health_check/v2/health_check.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.health_check.v2; + +option java_outer_classname = "HealthCheckProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.health_check.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/ip_tagging/v2/ip_tagging.proto b/api/envoy/config/filter/http/ip_tagging/v2/ip_tagging.proto index aba17986ab739..4d0b4fe64de7e 100644 --- a/api/envoy/config/filter/http/ip_tagging/v2/ip_tagging.proto +++ b/api/envoy/config/filter/http/ip_tagging/v2/ip_tagging.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.ip_tagging.v2; + +option java_outer_classname = "IpTaggingProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.ip_tagging.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/jwt_authn/v2alpha/config.proto b/api/envoy/config/filter/http/jwt_authn/v2alpha/config.proto index b585cb6dbde0b..b60d74a652b87 100644 --- a/api/envoy/config/filter/http/jwt_authn/v2alpha/config.proto +++ b/api/envoy/config/filter/http/jwt_authn/v2alpha/config.proto @@ -2,6 +2,9 @@ syntax = "proto3"; package envoy.config.filter.http.jwt_authn.v2alpha; + +option java_outer_classname = "ConfigProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.jwt_authn.v2alpha"; import "envoy/api/v2/core/base.proto"; diff --git a/api/envoy/config/filter/http/lua/v2/lua.proto b/api/envoy/config/filter/http/lua/v2/lua.proto index a2bbb3fc7c951..f29bcdbe89ef0 100644 --- a/api/envoy/config/filter/http/lua/v2/lua.proto +++ b/api/envoy/config/filter/http/lua/v2/lua.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.lua.v2; + +option java_outer_classname = "LuaProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.lua.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/rate_limit/v2/rate_limit.proto b/api/envoy/config/filter/http/rate_limit/v2/rate_limit.proto index f153e59bfc143..e9ea6fbb12753 100644 --- a/api/envoy/config/filter/http/rate_limit/v2/rate_limit.proto +++ b/api/envoy/config/filter/http/rate_limit/v2/rate_limit.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.rate_limit.v2; + +option java_outer_classname = "RateLimitProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.rate_limit.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/rbac/v2/rbac.proto b/api/envoy/config/filter/http/rbac/v2/rbac.proto index 82f92f6ef221e..936d39807c9fc 100644 --- a/api/envoy/config/filter/http/rbac/v2/rbac.proto +++ b/api/envoy/config/filter/http/rbac/v2/rbac.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.rbac.v2; + +option java_outer_classname = "RbacProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.rbac.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/router/v2/router.proto b/api/envoy/config/filter/http/router/v2/router.proto index b23624271dc28..02115cb81f734 100644 --- a/api/envoy/config/filter/http/router/v2/router.proto +++ b/api/envoy/config/filter/http/router/v2/router.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.router.v2; + +option java_outer_classname = "RouterProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.router.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/squash/v2/squash.proto b/api/envoy/config/filter/http/squash/v2/squash.proto index f3bdd9d2e0679..006af4380d41f 100644 --- a/api/envoy/config/filter/http/squash/v2/squash.proto +++ b/api/envoy/config/filter/http/squash/v2/squash.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.squash.v2; + +option java_outer_classname = "SquashProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.squash.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/http/tap/v2alpha/tap.proto b/api/envoy/config/filter/http/tap/v2alpha/tap.proto index 9d93d2943a5b5..10d7bdd1e0d81 100644 --- a/api/envoy/config/filter/http/tap/v2alpha/tap.proto +++ b/api/envoy/config/filter/http/tap/v2alpha/tap.proto @@ -5,6 +5,9 @@ import "envoy/config/common/tap/v2alpha/common.proto"; import "validate/validate.proto"; package envoy.config.filter.http.tap.v2alpha; + +option java_outer_classname = "TapProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.tap.v2alpha"; // [#protodoc-title: Tap] diff --git a/api/envoy/config/filter/http/transcoder/v2/transcoder.proto b/api/envoy/config/filter/http/transcoder/v2/transcoder.proto index ccb455ac2168c..fecd55d694b66 100644 --- a/api/envoy/config/filter/http/transcoder/v2/transcoder.proto +++ b/api/envoy/config/filter/http/transcoder/v2/transcoder.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.http.transcoder.v2; + +option java_outer_classname = "TranscoderProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.http.transcoder.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/listener/original_src/v2alpha1/original_src.proto b/api/envoy/config/filter/listener/original_src/v2alpha1/original_src.proto index 0f3ab8fe20c9f..aa38e1d3df0a5 100644 --- a/api/envoy/config/filter/listener/original_src/v2alpha1/original_src.proto +++ b/api/envoy/config/filter/listener/original_src/v2alpha1/original_src.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.listener.original_src.v2alpha1; + +option java_outer_classname = "OriginalSrcProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.listener.original_src.v2alpha1"; option go_package = "v2alpha1"; diff --git a/api/envoy/config/filter/network/client_ssl_auth/v2/client_ssl_auth.proto b/api/envoy/config/filter/network/client_ssl_auth/v2/client_ssl_auth.proto index 30bf9910fed64..fe0a6a3800b88 100644 --- a/api/envoy/config/filter/network/client_ssl_auth/v2/client_ssl_auth.proto +++ b/api/envoy/config/filter/network/client_ssl_auth/v2/client_ssl_auth.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.client_ssl_auth.v2; + +option java_outer_classname = "ClientSslAuthProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.client_ssl_auth.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/dubbo_proxy.proto b/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/dubbo_proxy.proto index e38e50a50a3ec..e639830794741 100644 --- a/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/dubbo_proxy.proto +++ b/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/dubbo_proxy.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.dubbo_proxy.v2alpha1; + +option java_outer_classname = "DubboProxyProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.dubbo_proxy.v2alpha1"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/route.proto b/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/route.proto index 8ac386c32874d..2c3d80ae3608c 100644 --- a/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/route.proto +++ b/api/envoy/config/filter/network/dubbo_proxy/v2alpha1/route.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.dubbo_proxy.v2alpha1; + +option java_outer_classname = "RouteProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.dubbo_proxy.v2alpha1"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/ext_authz/v2/ext_authz.proto b/api/envoy/config/filter/network/ext_authz/v2/ext_authz.proto index c8d59c1b5d9f1..f9a2f351f79e8 100644 --- a/api/envoy/config/filter/network/ext_authz/v2/ext_authz.proto +++ b/api/envoy/config/filter/network/ext_authz/v2/ext_authz.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.ext_authz.v2; + +option java_outer_classname = "ExtAuthzProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.ext_authz.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto b/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto index be519e7da07f0..5fb51dd823187 100644 --- a/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto +++ b/api/envoy/config/filter/network/http_connection_manager/v2/http_connection_manager.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.http_connection_manager.v2; + +option java_outer_classname = "HttpConnectionManagerProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.http_connection_manager.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/mongo_proxy/v2/mongo_proxy.proto b/api/envoy/config/filter/network/mongo_proxy/v2/mongo_proxy.proto index 1149a53ba0115..0d3d67bf66545 100644 --- a/api/envoy/config/filter/network/mongo_proxy/v2/mongo_proxy.proto +++ b/api/envoy/config/filter/network/mongo_proxy/v2/mongo_proxy.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.mongo_proxy.v2; + +option java_outer_classname = "MongoProxyProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.mongo_proxy.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/mysql_proxy/v1alpha1/mysql_proxy.proto b/api/envoy/config/filter/network/mysql_proxy/v1alpha1/mysql_proxy.proto index 3f107057dc02f..e4246c9314aa2 100644 --- a/api/envoy/config/filter/network/mysql_proxy/v1alpha1/mysql_proxy.proto +++ b/api/envoy/config/filter/network/mysql_proxy/v1alpha1/mysql_proxy.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.mysql_proxy.v1alpha1; + +option java_outer_classname = "MysqlProxyProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.mysql_proxy.v1alpha1"; option go_package = "v1alpha1"; diff --git a/api/envoy/config/filter/network/rate_limit/v2/rate_limit.proto b/api/envoy/config/filter/network/rate_limit/v2/rate_limit.proto index 9a89081bf98eb..0ceab0ebd6d54 100644 --- a/api/envoy/config/filter/network/rate_limit/v2/rate_limit.proto +++ b/api/envoy/config/filter/network/rate_limit/v2/rate_limit.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.rate_limit.v2; + +option java_outer_classname = "RateLimitProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.rate_limit.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/rbac/v2/rbac.proto b/api/envoy/config/filter/network/rbac/v2/rbac.proto index 4441d5e4ebadc..ccab4779ca6c2 100644 --- a/api/envoy/config/filter/network/rbac/v2/rbac.proto +++ b/api/envoy/config/filter/network/rbac/v2/rbac.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.rbac.v2; + +option java_outer_classname = "RbacProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.rbac.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto b/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto index 29648bda3f607..250b034d0712d 100644 --- a/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto +++ b/api/envoy/config/filter/network/redis_proxy/v2/redis_proxy.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.redis_proxy.v2; + +option java_outer_classname = "RedisProxyProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.redis_proxy.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/tcp_proxy/v2/tcp_proxy.proto b/api/envoy/config/filter/network/tcp_proxy/v2/tcp_proxy.proto index ef9407d8c5a23..12ce0d2757896 100644 --- a/api/envoy/config/filter/network/tcp_proxy/v2/tcp_proxy.proto +++ b/api/envoy/config/filter/network/tcp_proxy/v2/tcp_proxy.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.tcp_proxy.v2; + +option java_outer_classname = "TcpProxyProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.tcp_proxy.v2"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/thrift_proxy/v2alpha1/route.proto b/api/envoy/config/filter/network/thrift_proxy/v2alpha1/route.proto index f8d38fdbb61ef..c516f516fab1d 100644 --- a/api/envoy/config/filter/network/thrift_proxy/v2alpha1/route.proto +++ b/api/envoy/config/filter/network/thrift_proxy/v2alpha1/route.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.thrift_proxy.v2alpha1; + +option java_outer_classname = "RouteProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.thrift_proxy.v2alpha1"; option go_package = "v2"; diff --git a/api/envoy/config/filter/network/thrift_proxy/v2alpha1/thrift_proxy.proto b/api/envoy/config/filter/network/thrift_proxy/v2alpha1/thrift_proxy.proto index 8ca4e64df1219..951a51e871621 100644 --- a/api/envoy/config/filter/network/thrift_proxy/v2alpha1/thrift_proxy.proto +++ b/api/envoy/config/filter/network/thrift_proxy/v2alpha1/thrift_proxy.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.network.thrift_proxy.v2alpha1; + +option java_outer_classname = "ThriftProxyProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.network.thrift_proxy.v2alpha1"; option go_package = "v2"; diff --git a/api/envoy/config/filter/thrift/rate_limit/v2alpha1/rate_limit.proto b/api/envoy/config/filter/thrift/rate_limit/v2alpha1/rate_limit.proto index e3ced525ad1e5..7b4db2ae3d49d 100644 --- a/api/envoy/config/filter/thrift/rate_limit/v2alpha1/rate_limit.proto +++ b/api/envoy/config/filter/thrift/rate_limit/v2alpha1/rate_limit.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.thrift.rate_limit.v2alpha1; + +option java_outer_classname = "RateLimitProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.thrift.rate_limit.v2alpha1"; option go_package = "v2alpha1"; diff --git a/api/envoy/config/filter/thrift/router/v2alpha1/router.proto b/api/envoy/config/filter/thrift/router/v2alpha1/router.proto index d7ac3b02e1ef9..c515752c2a001 100644 --- a/api/envoy/config/filter/thrift/router/v2alpha1/router.proto +++ b/api/envoy/config/filter/thrift/router/v2alpha1/router.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.filter.thrift.router.v2alpha1; + +option java_outer_classname = "RouterProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.filter.thrift.router.v2alpha1"; option go_package = "v2alpha1"; diff --git a/api/envoy/config/grpc_credential/v2alpha/file_based_metadata.proto b/api/envoy/config/grpc_credential/v2alpha/file_based_metadata.proto index f210da30acf13..c91c50e39a55d 100644 --- a/api/envoy/config/grpc_credential/v2alpha/file_based_metadata.proto +++ b/api/envoy/config/grpc_credential/v2alpha/file_based_metadata.proto @@ -4,6 +4,9 @@ syntax = "proto3"; // Configuration for File Based Metadata Grpc Credentials Plugin package envoy.config.grpc_credential.v2alpha; + +option java_outer_classname = "FileBasedMetadataProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.grpc_credential.v2alpha"; option go_package = "v2alpha"; diff --git a/api/envoy/config/health_checker/redis/v2/redis.proto b/api/envoy/config/health_checker/redis/v2/redis.proto index 2aa32364773c1..130454b5d4069 100644 --- a/api/envoy/config/health_checker/redis/v2/redis.proto +++ b/api/envoy/config/health_checker/redis/v2/redis.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.health_checker.redis.v2; + +option java_outer_classname = "RedisProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.health_checker.redis.v2"; option go_package = "v2"; diff --git a/api/envoy/config/metrics/v2/metrics_service.proto b/api/envoy/config/metrics/v2/metrics_service.proto index ae78e8403e03a..208a5c2076edf 100644 --- a/api/envoy/config/metrics/v2/metrics_service.proto +++ b/api/envoy/config/metrics/v2/metrics_service.proto @@ -3,6 +3,9 @@ syntax = "proto3"; // [#protodoc-title: Metrics service] package envoy.config.metrics.v2; + +option java_outer_classname = "MetricsServiceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.metrics.v2"; import "envoy/api/v2/core/grpc_service.proto"; diff --git a/api/envoy/config/metrics/v2/stats.proto b/api/envoy/config/metrics/v2/stats.proto index 63470a5e7e197..8b85198f60cef 100644 --- a/api/envoy/config/metrics/v2/stats.proto +++ b/api/envoy/config/metrics/v2/stats.proto @@ -4,6 +4,9 @@ syntax = "proto3"; package envoy.config.metrics.v2; + +option java_outer_classname = "StatsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.metrics.v2"; option go_package = "v2"; diff --git a/api/envoy/config/overload/v2alpha/overload.proto b/api/envoy/config/overload/v2alpha/overload.proto index 925bd9ddb6106..cf50275201a58 100644 --- a/api/envoy/config/overload/v2alpha/overload.proto +++ b/api/envoy/config/overload/v2alpha/overload.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.overload.v2alpha; + +option java_outer_classname = "OverloadProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.overload.v2alpha"; option go_package = "v2alpha"; diff --git a/api/envoy/config/ratelimit/v2/rls.proto b/api/envoy/config/ratelimit/v2/rls.proto index c0d615abcf5df..8f039b44efeb3 100644 --- a/api/envoy/config/ratelimit/v2/rls.proto +++ b/api/envoy/config/ratelimit/v2/rls.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.ratelimit.v2; + +option java_outer_classname = "RlsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.ratelimit.v2"; option go_package = "v2"; diff --git a/api/envoy/config/rbac/v2alpha/rbac.proto b/api/envoy/config/rbac/v2alpha/rbac.proto index 2856dd0370bfe..19b61473496a8 100644 --- a/api/envoy/config/rbac/v2alpha/rbac.proto +++ b/api/envoy/config/rbac/v2alpha/rbac.proto @@ -7,6 +7,9 @@ import "envoy/type/matcher/metadata.proto"; import "envoy/type/matcher/string.proto"; package envoy.config.rbac.v2alpha; + +option java_outer_classname = "RbacProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.rbac.v2alpha"; option go_package = "v2alpha"; diff --git a/api/envoy/config/resource_monitor/fixed_heap/v2alpha/fixed_heap.proto b/api/envoy/config/resource_monitor/fixed_heap/v2alpha/fixed_heap.proto index 96d439c2afe30..f945a31495944 100644 --- a/api/envoy/config/resource_monitor/fixed_heap/v2alpha/fixed_heap.proto +++ b/api/envoy/config/resource_monitor/fixed_heap/v2alpha/fixed_heap.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.resource_monitor.fixed_heap.v2alpha; + +option java_outer_classname = "FixedHeapProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.resource_monitor.fixed_heap.v2alpha"; option go_package = "v2alpha"; diff --git a/api/envoy/config/resource_monitor/injected_resource/v2alpha/injected_resource.proto b/api/envoy/config/resource_monitor/injected_resource/v2alpha/injected_resource.proto index bd364ebbf333b..cab704a4b64ae 100644 --- a/api/envoy/config/resource_monitor/injected_resource/v2alpha/injected_resource.proto +++ b/api/envoy/config/resource_monitor/injected_resource/v2alpha/injected_resource.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.resource_monitor.injected_resource.v2alpha; + +option java_outer_classname = "InjectedResourceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.resource_monitor.injected_resource.v2alpha"; option go_package = "v2alpha"; diff --git a/api/envoy/config/retry/previous_priorities/previous_priorities_config.proto b/api/envoy/config/retry/previous_priorities/previous_priorities_config.proto index 0d84b929f2e56..9ee2ed5526871 100644 --- a/api/envoy/config/retry/previous_priorities/previous_priorities_config.proto +++ b/api/envoy/config/retry/previous_priorities/previous_priorities_config.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.retry.previous_priorities; + +option java_outer_classname = "PreviousPrioritiesConfigProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.retry.previous_priorities"; // A retry host selector that attempts to spread retries between priorities, even if certain diff --git a/api/envoy/config/trace/v2/trace.proto b/api/envoy/config/trace/v2/trace.proto index 4f25ec69bc4be..10c25df5a97f8 100644 --- a/api/envoy/config/trace/v2/trace.proto +++ b/api/envoy/config/trace/v2/trace.proto @@ -4,6 +4,9 @@ syntax = "proto3"; package envoy.config.trace.v2; + +option java_outer_classname = "TraceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.trace.v2"; option go_package = "v2"; diff --git a/api/envoy/config/transport_socket/alts/v2alpha/alts.proto b/api/envoy/config/transport_socket/alts/v2alpha/alts.proto index d9cf9b6fc96c7..f5a9db64c0e45 100644 --- a/api/envoy/config/transport_socket/alts/v2alpha/alts.proto +++ b/api/envoy/config/transport_socket/alts/v2alpha/alts.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.transport_socket.alts.v2alpha; + +option java_outer_classname = "AltsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.transport_socket.alts.v2alpha"; option go_package = "v2"; diff --git a/api/envoy/config/transport_socket/tap/v2alpha/tap.proto b/api/envoy/config/transport_socket/tap/v2alpha/tap.proto index 52338f7c6f9e4..84918699ef97d 100644 --- a/api/envoy/config/transport_socket/tap/v2alpha/tap.proto +++ b/api/envoy/config/transport_socket/tap/v2alpha/tap.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.config.transport_socket.tap.v2alpha; + +option java_outer_classname = "TapProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.config.transport_socket.tap.v2alpha"; option go_package = "v2"; diff --git a/api/envoy/data/accesslog/v2/accesslog.proto b/api/envoy/data/accesslog/v2/accesslog.proto index 95763781b83f2..3f52910573129 100644 --- a/api/envoy/data/accesslog/v2/accesslog.proto +++ b/api/envoy/data/accesslog/v2/accesslog.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.data.accesslog.v2; + +option java_outer_classname = "AccesslogProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.data.accesslog.v2"; import "envoy/api/v2/core/address.proto"; diff --git a/api/envoy/data/cluster/v2alpha/outlier_detection_event.proto b/api/envoy/data/cluster/v2alpha/outlier_detection_event.proto index ed2b763099db0..ba3f0289942f0 100644 --- a/api/envoy/data/cluster/v2alpha/outlier_detection_event.proto +++ b/api/envoy/data/cluster/v2alpha/outlier_detection_event.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.data.cluster.v2alpha; + +option java_outer_classname = "OutlierDetectionEventProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.data.cluster.v2alpha"; import "google/protobuf/timestamp.proto"; diff --git a/api/envoy/data/core/v2alpha/health_check_event.proto b/api/envoy/data/core/v2alpha/health_check_event.proto index 54dc8f38a1698..adfb6c67e5c72 100644 --- a/api/envoy/data/core/v2alpha/health_check_event.proto +++ b/api/envoy/data/core/v2alpha/health_check_event.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.data.core.v2alpha; + +option java_outer_classname = "HealthCheckEventProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.data.core.v2alpha"; import "envoy/api/v2/core/address.proto"; diff --git a/api/envoy/data/tap/v2alpha/http.proto b/api/envoy/data/tap/v2alpha/http.proto index 92b731c2ec977..253f1ad9e04e6 100644 --- a/api/envoy/data/tap/v2alpha/http.proto +++ b/api/envoy/data/tap/v2alpha/http.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.data.tap.v2alpha; + +option java_outer_classname = "HttpProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.data.tap.v2alpha"; import "envoy/api/v2/core/base.proto"; diff --git a/api/envoy/data/tap/v2alpha/transport.proto b/api/envoy/data/tap/v2alpha/transport.proto index 216cf9db6d1fb..87e4b8d26018c 100644 --- a/api/envoy/data/tap/v2alpha/transport.proto +++ b/api/envoy/data/tap/v2alpha/transport.proto @@ -5,6 +5,9 @@ syntax = "proto3"; // sequences on a socket. package envoy.data.tap.v2alpha; + +option java_outer_classname = "TransportProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.data.tap.v2alpha"; option go_package = "v2"; diff --git a/api/envoy/data/tap/v2alpha/wrapper.proto b/api/envoy/data/tap/v2alpha/wrapper.proto index 48a6f863fabb8..f3c3c9a169964 100644 --- a/api/envoy/data/tap/v2alpha/wrapper.proto +++ b/api/envoy/data/tap/v2alpha/wrapper.proto @@ -6,6 +6,9 @@ import "envoy/data/tap/v2alpha/transport.proto"; import "validate/validate.proto"; package envoy.data.tap.v2alpha; + +option java_outer_classname = "WrapperProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.data.tap.v2alpha"; // [#protodoc-title: Tap data wrappers] diff --git a/api/envoy/service/accesslog/v2/als.proto b/api/envoy/service/accesslog/v2/als.proto index ebb7013ae2f8e..1ee6ccd0094c3 100644 --- a/api/envoy/service/accesslog/v2/als.proto +++ b/api/envoy/service/accesslog/v2/als.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.accesslog.v2; + +option java_outer_classname = "AlsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.accesslog.v2"; option go_package = "v2"; option java_generic_services = true; diff --git a/api/envoy/service/auth/v2/attribute_context.proto b/api/envoy/service/auth/v2/attribute_context.proto index ca3fde9cfec96..ed0dd33b7c749 100644 --- a/api/envoy/service/auth/v2/attribute_context.proto +++ b/api/envoy/service/auth/v2/attribute_context.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.auth.v2; + +option java_outer_classname = "AttributeContextProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.auth.v2"; import "envoy/api/v2/core/address.proto"; diff --git a/api/envoy/service/auth/v2/external_auth.proto b/api/envoy/service/auth/v2/external_auth.proto index c071d528e385d..c08046f532815 100644 --- a/api/envoy/service/auth/v2/external_auth.proto +++ b/api/envoy/service/auth/v2/external_auth.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.auth.v2; + +option java_outer_classname = "ExternalAuthProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.auth.v2"; option go_package = "v2"; option java_generic_services = true; diff --git a/api/envoy/service/discovery/v2/ads.proto b/api/envoy/service/discovery/v2/ads.proto index e8774dd291725..73f272191bd01 100644 --- a/api/envoy/service/discovery/v2/ads.proto +++ b/api/envoy/service/discovery/v2/ads.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.discovery.v2; + +option java_outer_classname = "AdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.discovery.v2"; option go_package = "v2"; option java_generic_services = true; diff --git a/api/envoy/service/discovery/v2/hds.proto b/api/envoy/service/discovery/v2/hds.proto index 7dd3e8a9631fd..354dae9447ccd 100644 --- a/api/envoy/service/discovery/v2/hds.proto +++ b/api/envoy/service/discovery/v2/hds.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.discovery.v2; + +option java_outer_classname = "HdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.discovery.v2"; option java_generic_services = true; diff --git a/api/envoy/service/discovery/v2/sds.proto b/api/envoy/service/discovery/v2/sds.proto index 60d5d22812d55..055df682d9aff 100644 --- a/api/envoy/service/discovery/v2/sds.proto +++ b/api/envoy/service/discovery/v2/sds.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.discovery.v2; + +option java_outer_classname = "SdsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.discovery.v2"; import "envoy/api/v2/discovery.proto"; diff --git a/api/envoy/service/load_stats/v2/lrs.proto b/api/envoy/service/load_stats/v2/lrs.proto index aa3638b63e6ef..2fe95f3b6a904 100644 --- a/api/envoy/service/load_stats/v2/lrs.proto +++ b/api/envoy/service/load_stats/v2/lrs.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.load_stats.v2; + +option java_outer_classname = "LrsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.load_stats.v2"; option go_package = "v2"; option java_generic_services = true; diff --git a/api/envoy/service/metrics/v2/metrics_service.proto b/api/envoy/service/metrics/v2/metrics_service.proto index 6b88148ecc2b7..b70be3bdd9a18 100644 --- a/api/envoy/service/metrics/v2/metrics_service.proto +++ b/api/envoy/service/metrics/v2/metrics_service.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.metrics.v2; + +option java_outer_classname = "MetricsServiceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.metrics.v2"; option go_package = "v2"; option java_generic_services = true; diff --git a/api/envoy/service/ratelimit/v2/rls.proto b/api/envoy/service/ratelimit/v2/rls.proto index 07478d1983527..18b6b678e9082 100644 --- a/api/envoy/service/ratelimit/v2/rls.proto +++ b/api/envoy/service/ratelimit/v2/rls.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.service.ratelimit.v2; + +option java_outer_classname = "RlsProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.ratelimit.v2"; option go_package = "v2"; diff --git a/api/envoy/service/tap/v2alpha/common.proto b/api/envoy/service/tap/v2alpha/common.proto index 47f9b53f7e261..b330b6c96ea31 100644 --- a/api/envoy/service/tap/v2alpha/common.proto +++ b/api/envoy/service/tap/v2alpha/common.proto @@ -5,6 +5,9 @@ import "envoy/api/v2/route/route.proto"; import "validate/validate.proto"; package envoy.service.tap.v2alpha; + +option java_outer_classname = "CommonProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.tap.v2alpha"; // [#protodoc-title: Common tap configuration] diff --git a/api/envoy/service/trace/v2/trace_service.proto b/api/envoy/service/trace/v2/trace_service.proto index 9ab4579a0cceb..a6385bb1f7430 100644 --- a/api/envoy/service/trace/v2/trace_service.proto +++ b/api/envoy/service/trace/v2/trace_service.proto @@ -3,6 +3,9 @@ syntax = "proto3"; // [#proto-status: draft] package envoy.service.trace.v2; + +option java_outer_classname = "TraceServiceProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.service.trace.v2"; option go_package = "v2"; option java_generic_services = true; diff --git a/api/envoy/type/http_status.proto b/api/envoy/type/http_status.proto index 626805b8d9cd6..9d9a6230c29bb 100644 --- a/api/envoy/type/http_status.proto +++ b/api/envoy/type/http_status.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type; + +option java_outer_classname = "HttpStatusProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type"; import "validate/validate.proto"; diff --git a/api/envoy/type/matcher/metadata.proto b/api/envoy/type/matcher/metadata.proto index 60df44d7c6dcc..1739a00ba47c3 100644 --- a/api/envoy/type/matcher/metadata.proto +++ b/api/envoy/type/matcher/metadata.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type.matcher; + +option java_outer_classname = "MetadataProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type.matcher"; option go_package = "matcher"; diff --git a/api/envoy/type/matcher/number.proto b/api/envoy/type/matcher/number.proto index c6e6a26c29e06..f6c49b3fcdf60 100644 --- a/api/envoy/type/matcher/number.proto +++ b/api/envoy/type/matcher/number.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type.matcher; + +option java_outer_classname = "NumberProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type.matcher"; option go_package = "matcher"; diff --git a/api/envoy/type/matcher/string.proto b/api/envoy/type/matcher/string.proto index 44d4a53f51a1f..02077522d8255 100644 --- a/api/envoy/type/matcher/string.proto +++ b/api/envoy/type/matcher/string.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type.matcher; + +option java_outer_classname = "StringProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type.matcher"; option go_package = "matcher"; diff --git a/api/envoy/type/matcher/value.proto b/api/envoy/type/matcher/value.proto index def4e49d53c2a..52f5e5b100b15 100644 --- a/api/envoy/type/matcher/value.proto +++ b/api/envoy/type/matcher/value.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type.matcher; + +option java_outer_classname = "ValueProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type.matcher"; option go_package = "matcher"; diff --git a/api/envoy/type/percent.proto b/api/envoy/type/percent.proto index 543c0a0535c12..551e93bfdd1ec 100644 --- a/api/envoy/type/percent.proto +++ b/api/envoy/type/percent.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type; + +option java_outer_classname = "PercentProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type"; import "validate/validate.proto"; diff --git a/api/envoy/type/range.proto b/api/envoy/type/range.proto index 3ce3e32b7a372..e64b71e440f39 100644 --- a/api/envoy/type/range.proto +++ b/api/envoy/type/range.proto @@ -1,6 +1,9 @@ syntax = "proto3"; package envoy.type; + +option java_outer_classname = "RangeProto"; +option java_multiple_files = true; option java_package = "io.envoyproxy.envoy.type"; option go_package = "envoy_type"; diff --git a/tools/check_format.py b/tools/check_format.py index c14ce69819a1a..bfd9c9061aaeb 100755 --- a/tools/check_format.py +++ b/tools/check_format.py @@ -50,7 +50,10 @@ SUBDIR_SET = set(common.includeDirOrder()) INCLUDE_ANGLE = "#include <" INCLUDE_ANGLE_LEN = len(INCLUDE_ANGLE) -PROTO_PACKAGE_REGEX = re.compile("package (.*);") +PROTO_PACKAGE_REGEX = re.compile(r"^package (\S+);\n*", re.MULTILINE) +PROTO_OPTION_JAVA_PACKAGE = "option java_package = \"" +PROTO_OPTION_JAVA_OUTER_CLASSNAME = "option java_outer_classname = \"" +PROTO_OPTION_JAVA_MULTIPLE_FILES = "option java_multiple_files = " # yapf: disable PROTOBUF_TYPE_ERRORS = { @@ -147,37 +150,58 @@ def checkNamespace(file_path): return [] -def fixJavaProtoOptions(file_path): - package_name = None - for line in fileinput.FileInput(file_path): - if line.startswith("package "): - result = PROTO_PACKAGE_REGEX.search(line) - if result is None or len(result.groups()) != 1: - continue +# If the substring is not found in the file, then insert to_add +def insertProtoOptionIfNotFound(substring, file_path, to_add): + text = None + with open(file_path) as f: + text = f.read() - package_name = result.group(1) - if "option java_package = \"io.envoyproxy.envoy" in line: - return [] + if not substring in text: + + def repl(m): + return m.group(0).rstrip() + "\n\n" + to_add + "\n" - if package_name is None: - return ["Unable to find package name for proto file: %s" % file_path] + with open(file_path, "w") as f: + f.write(re.sub(PROTO_PACKAGE_REGEX, repl, text)) - to_add = "option java_package = \"io.envoyproxy.{}\";\n".format(package_name) - for line in fileinput.FileInput(file_path, inplace=True): - if line.startswith("package "): - line = line.replace(line, line + to_add) - sys.stdout.write(line) +def packageNameForProto(file_path): + package_name = None + error_message = [] + with open(file_path) as f: + result = PROTO_PACKAGE_REGEX.search(f.read()) + if result is not None and len(result.groups()) == 1: + package_name = result.group(1) + if package_name is None: + error_message = ["Unable to find package name for proto file: %s" % file_path] + + return [package_name, error_message] + +def fixJavaPackageProtoOption(file_path): + package_name = packageNameForProto(file_path)[0] + to_add = PROTO_OPTION_JAVA_PACKAGE + "io.envoyproxy.{}\";".format(package_name) + insertProtoOptionIfNotFound("\n" + PROTO_OPTION_JAVA_PACKAGE, file_path, to_add) return [] -def checkJavaProtoOptions(file_path): - for line in fileinput.FileInput(file_path): - if "option java_package = \"io.envoyproxy.envoy" in line: - return [] +# Add "option java_outer_classname = FooBarProto;" for foo_bar.proto +def fixJavaOuterClassnameProtoOption(file_path): + file_name = os.path.basename(file_path)[:-len(".proto")] + if "-" in file_name or "." in file_name or not file_name.islower(): + return ["Unable to decide java_outer_classname for proto file: %s" % file_path] + + to_add = PROTO_OPTION_JAVA_OUTER_CLASSNAME \ + + "".join(x.title() for x in file_name.split("_")) \ + + "Proto\";" + insertProtoOptionIfNotFound("\n" + PROTO_OPTION_JAVA_OUTER_CLASSNAME, file_path, to_add) + return [] + - return ["Java proto option 'java_package' not set correctly for file: %s" % file_path] +def fixJavaMultipleFilesProtoOption(file_path): + to_add = PROTO_OPTION_JAVA_MULTIPLE_FILES + "true;" + insertProtoOptionIfNotFound("\n" + PROTO_OPTION_JAVA_MULTIPLE_FILES, file_path, to_add) + return [] # To avoid breaking the Lyft import, we just check for path inclusion here. @@ -211,6 +235,11 @@ def findSubstringAndReturnError(pattern, file_path, error_message): return [] +def errorIfNoSubstringFound(pattern, file_path, error_message): + with open(file_path) as f: + return [] if pattern in f.read() else [file_path + ": " + error_message] + + def isApiFile(file_path): return file_path.startswith(args.api_prefix) @@ -440,7 +469,13 @@ def fixSourcePath(file_path): error_messages += fixHeaderOrder(file_path) error_messages += clangFormat(file_path) if file_path.endswith(PROTO_SUFFIX) and isApiFile(file_path): - error_messages += fixJavaProtoOptions(file_path) + package_name, error_message = packageNameForProto(file_path) + if package_name is None: + error_messages += error_message + else: + error_messages += fixJavaMultipleFilesProtoOption(file_path) + error_messages += fixJavaOuterClassnameProtoOption(file_path) + error_messages += fixJavaPackageProtoOption(file_path) return error_messages @@ -456,7 +491,16 @@ def checkSourcePath(file_path): error_messages += executeCommand(command, "clang-format check failed", file_path) if file_path.endswith(PROTO_SUFFIX) and isApiFile(file_path): - error_messages += checkJavaProtoOptions(file_path) + package_name, error_message = packageNameForProto(file_path) + if package_name is None: + error_messages += error_message + else: + error_messages += errorIfNoSubstringFound("\n" + PROTO_OPTION_JAVA_PACKAGE, file_path, + "Java proto option 'java_package' not set") + error_messages += errorIfNoSubstringFound("\n" + PROTO_OPTION_JAVA_OUTER_CLASSNAME, file_path, + "Java proto option 'java_outer_classname' not set") + error_messages += errorIfNoSubstringFound("\n" + PROTO_OPTION_JAVA_MULTIPLE_FILES, file_path, + "Java proto option 'java_multiple_files' not set") return error_messages diff --git a/tools/testdata/check_format/api/java_options.proto.gold b/tools/testdata/check_format/api/java_options.proto.gold index ab524690ed71d..54513d2a81fe0 100644 --- a/tools/testdata/check_format/api/java_options.proto.gold +++ b/tools/testdata/check_format/api/java_options.proto.gold @@ -1,2 +1,5 @@ package envoy.foo; + option java_package = "io.envoyproxy.envoy.foo"; +option java_outer_classname = "JavaOptionsProto"; +option java_multiple_files = true; From 5361b775605a9ddc5ed5810992699e8a1e9ece4d Mon Sep 17 00:00:00 2001 From: Bin Wu <46450037+wu-bin@users.noreply.github.com> Date: Tue, 5 Feb 2019 08:55:28 -0500 Subject: [PATCH 18/51] Add quic_client_stats_impl.h to QUICHE platform implementation (#5832) Add quic_client_stats_impl.h to QUICHE platform implementation, with everything being no-op. _Risk Level_: minimal: code not used yet _Testing_: bazel test test/extensions/quic_listeners/quiche/platform:quic_platform_test --test_output=all _Docs Changes_: none _Release Notes_: none Signed-off-by: Bin Wu --- bazel/external/quiche.BUILD | 2 +- .../quic_listeners/quiche/platform/BUILD | 1 + .../quiche/platform/quic_client_stats_impl.h | 32 +++++++++++++++++++ .../quiche/platform/quic_platform_test.cc | 14 ++++++++ 4 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 source/extensions/quic_listeners/quiche/platform/quic_client_stats_impl.h diff --git a/bazel/external/quiche.BUILD b/bazel/external/quiche.BUILD index b287afa1dc695..788441bf40533 100644 --- a/bazel/external/quiche.BUILD +++ b/bazel/external/quiche.BUILD @@ -114,6 +114,7 @@ cc_library( hdrs = [ "quiche/quic/platform/api/quic_aligned.h", "quiche/quic/platform/api/quic_arraysize.h", + "quiche/quic/platform/api/quic_client_stats.h", "quiche/quic/platform/api/quic_containers.h", "quiche/quic/platform/api/quic_endian.h", "quiche/quic/platform/api/quic_estimate_memory_usage.h", @@ -130,7 +131,6 @@ cc_library( "quiche/quic/platform/api/quic_uint128.h", # TODO: uncomment the following files as implementations are added. # "quiche/quic/platform/api/quic_bug_tracker.h", - # "quiche/quic/platform/api/quic_client_stats.h", # "quiche/quic/platform/api/quic_clock.h", # "quiche/quic/platform/api/quic_expect_bug.h", # "quiche/quic/platform/api/quic_exported_stats.h", diff --git a/source/extensions/quic_listeners/quiche/platform/BUILD b/source/extensions/quic_listeners/quiche/platform/BUILD index 8687dd1cb0b6f..fb8ffa1ccfeac 100644 --- a/source/extensions/quic_listeners/quiche/platform/BUILD +++ b/source/extensions/quic_listeners/quiche/platform/BUILD @@ -42,6 +42,7 @@ envoy_cc_library( hdrs = [ "quic_aligned_impl.h", "quic_arraysize_impl.h", + "quic_client_stats_impl.h", "quic_containers_impl.h", "quic_endian_impl.h", "quic_estimate_memory_usage_impl.h", diff --git a/source/extensions/quic_listeners/quiche/platform/quic_client_stats_impl.h b/source/extensions/quic_listeners/quiche/platform/quic_client_stats_impl.h new file mode 100644 index 0000000000000..7108de135e2b8 --- /dev/null +++ b/source/extensions/quic_listeners/quiche/platform/quic_client_stats_impl.h @@ -0,0 +1,32 @@ +#pragma once + +// NOLINT(namespace-envoy) +// +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +#include + +// NOTE(wub): These macros are currently NOOP because they are supposed to be +// used by client-side stats. They should be implemented when QUIC client code +// is used by Envoy to connect to backends. + +#define QUIC_CLIENT_HISTOGRAM_ENUM_IMPL(name, sample, enum_size, docstring) \ + do { \ + } while (0) +#define QUIC_CLIENT_HISTOGRAM_BOOL_IMPL(name, sample, docstring) \ + do { \ + } while (0) +#define QUIC_CLIENT_HISTOGRAM_TIMES_IMPL(name, sample, min, max, num_buckets, docstring) \ + do { \ + } while (0) +#define QUIC_CLIENT_HISTOGRAM_COUNTS_IMPL(name, sample, min, max, num_buckets, docstring) \ + do { \ + } while (0) + +namespace quic { + +inline void QuicClientSparseHistogramImpl(const std::string& /*name*/, int /*sample*/) {} + +} // namespace quic diff --git a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc index ed5222930ebb0..44b343af8efd7 100644 --- a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc +++ b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc @@ -2,6 +2,7 @@ #include "quiche/quic/platform/api/quic_aligned.h" #include "quiche/quic/platform/api/quic_arraysize.h" +#include "quiche/quic/platform/api/quic_client_stats.h" #include "quiche/quic/platform/api/quic_containers.h" #include "quiche/quic/platform/api/quic_endian.h" #include "quiche/quic/platform/api/quic_estimate_memory_usage.h" @@ -29,6 +30,19 @@ TEST(QuicPlatformTest, QuicArraysize) { EXPECT_EQ(5, QUIC_ARRAYSIZE(array)); } +enum class TestEnum { ZERO = 0, ONE, TWO, COUNT }; + +TEST(QuicPlatformTest, QuicClientStats) { + // Just make sure they compile. + QUIC_CLIENT_HISTOGRAM_ENUM("my.enum.histogram", TestEnum::ONE, TestEnum::COUNT, "doc"); + QUIC_CLIENT_HISTOGRAM_BOOL("my.bool.histogram", false, "doc"); + QUIC_CLIENT_HISTOGRAM_TIMES("my.timing.histogram", quic::QuicTime::Delta::FromSeconds(5), + quic::QuicTime::Delta::FromSeconds(1), + quic::QuicTime::Delta::FromSecond(3600), 100, "doc"); + QUIC_CLIENT_HISTOGRAM_COUNTS("my.count.histogram", 123, 0, 1000, 100, "doc"); + quic::QuicClientSparseHistogram("my.sparse.histogram", 345); +} + TEST(QuicPlatformTest, QuicUnorderedMap) { quic::QuicUnorderedMap umap; umap.insert({"foo", 2}); From e2bf272b05c4e88c29fe1db50c8e194d15a418d2 Mon Sep 17 00:00:00 2001 From: Bin Wu <46450037+wu-bin@users.noreply.github.com> Date: Tue, 5 Feb 2019 11:10:10 -0500 Subject: [PATCH 19/51] Disable quic_platform_test by default. Take 2. (#5838) Disable quic_platform_test by default. Enable it only when "--define quiche=enabled" is specified in the bazel command line. This is needed to workaround a issue with --experimental_remap_main_repo + ci asan build, see here for details. Risk Level: minimal: build only Testing: I introduced a failure in quic_platform_test, then confirmed quic_platform_test still passes by default(since it does nothing), and failed when "--define enable_quiche=enabled" is specified. Signed-off-by: Bin Wu --- bazel/BUILD | 5 +++++ bazel/envoy_build_system.bzl | 6 ++++++ test/extensions/quic_listeners/quiche/platform/BUILD | 3 ++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/bazel/BUILD b/bazel/BUILD index 6a82a1bc87d18..34315c825bab8 100644 --- a/bazel/BUILD +++ b/bazel/BUILD @@ -149,6 +149,11 @@ config_setting( values = {"define": "boringssl=fips"}, ) +config_setting( + name = "enable_quiche", + values = {"define": "quiche=enabled"}, +) + # Alias pointing to the selected version of BoringSSL: # - BoringSSL FIPS from @boringssl_fips//:ssl, # - non-FIPS BoringSSL from @boringssl//:ssl. diff --git a/bazel/envoy_build_system.bzl b/bazel/envoy_build_system.bzl index a244d8be7a94d..a8b314a8677d9 100644 --- a/bazel/envoy_build_system.bzl +++ b/bazel/envoy_build_system.bzl @@ -592,3 +592,9 @@ def envoy_select_boringssl(if_fips, default = None): "@envoy//bazel:boringssl_fips": if_fips, "//conditions:default": default or [], }) + +def envoy_select_quiche(xs, repository = ""): + return select({ + repository + "//bazel:enable_quiche": xs, + "//conditions:default": [], + }) diff --git a/test/extensions/quic_listeners/quiche/platform/BUILD b/test/extensions/quic_listeners/quiche/platform/BUILD index 0c456774f7359..59fcc209a9ab6 100644 --- a/test/extensions/quic_listeners/quiche/platform/BUILD +++ b/test/extensions/quic_listeners/quiche/platform/BUILD @@ -8,6 +8,7 @@ load( "envoy_cc_test_library", "envoy_package", "envoy_proto_library", + "envoy_select_quiche", ) envoy_package() @@ -23,7 +24,7 @@ envoy_cc_test( envoy_cc_test( name = "quic_platform_test", - srcs = ["quic_platform_test.cc"], + srcs = envoy_select_quiche(["quic_platform_test.cc"]), external_deps = ["quiche_quic_platform"], deps = [ "//test/test_common:utility_lib", From ed051633f13f374d7024ff21d5ada8766459d9a8 Mon Sep 17 00:00:00 2001 From: Joshua Marantz Date: Tue, 5 Feb 2019 12:26:57 -0500 Subject: [PATCH 20/51] api: Put Event::TimeSystem& into API and plumb that instead of TimeSystem in various places. (#5660) * Put Event::TimeSystem& into API and plumb that instead of TimeSystem in various places. Signed-off-by: Joshua Marantz --- include/envoy/api/api.h | 11 +++++--- include/envoy/server/BUILD | 1 + source/common/api/api_impl.cc | 14 +++++----- source/common/api/api_impl.h | 10 ++++--- source/common/event/dispatched_thread.h | 3 +-- source/common/event/dispatcher_impl.cc | 12 ++++----- source/common/event/dispatcher_impl.h | 7 +++-- source/common/router/router.h | 2 +- source/server/config_validation/api.cc | 9 ++++--- source/server/config_validation/api.h | 5 ++-- .../server/config_validation/async_client.cc | 3 +-- .../server/config_validation/async_client.h | 2 +- .../config_validation/cluster_manager.cc | 2 +- source/server/config_validation/dispatcher.h | 2 +- source/server/config_validation/server.cc | 17 ++++++------ source/server/config_validation/server.h | 3 +-- source/server/guarddog_impl.cc | 4 +-- source/server/guarddog_impl.h | 3 +-- source/server/listener_manager_impl.cc | 5 ++-- source/server/listener_manager_impl.h | 5 ++-- source/server/server.cc | 12 ++++----- source/server/worker_impl.cc | 2 +- source/server/worker_impl.h | 6 ++--- .../filesystem_subscription_test_harness.h | 4 +-- test/common/event/BUILD | 2 -- .../event/dispatched_thread_impl_test.cc | 10 +++---- test/common/event/dispatcher_impl_test.cc | 9 ++----- test/common/event/file_event_impl_test.cc | 8 ++---- test/common/filesystem/BUILD | 1 - test/common/filesystem/watcher_impl_test.cc | 5 +--- .../grpc/google_async_client_impl_test.cc | 2 +- .../grpc_client_integration_test_harness.h | 2 +- test/common/http/BUILD | 1 - test/common/http/codec_client_test.cc | 5 +--- test/common/http/http1/BUILD | 1 - test/common/http/http1/conn_pool_test.cc | 5 +--- test/common/http/http2/BUILD | 1 - test/common/http/http2/conn_pool_test.cc | 5 +--- test/common/network/BUILD | 3 +-- test/common/network/connection_impl_test.cc | 26 +++++++++---------- test/common/network/dns_impl_test.cc | 9 ++----- test/common/network/listener_impl_test.cc | 7 ++--- test/common/network/udp_listener_impl_test.cc | 18 ++++++------- test/common/stats/BUILD | 1 + .../stats/thread_local_store_speed_test.cc | 8 +++--- test/common/thread_local/BUILD | 1 - .../thread_local/thread_local_impl_test.cc | 6 ++--- test/common/upstream/hds_test.cc | 9 ++++--- test/config_test/BUILD | 1 + test/config_test/config_test.cc | 3 +-- .../http/gzip/gzip_filter_integration_test.cc | 6 ++--- .../proxy_protocol/proxy_protocol_test.cc | 7 ++--- .../resource_monitors/injected_resource/BUILD | 2 -- .../injected_resource/config_test.cc | 4 +-- .../injected_resource_monitor_test.cc | 4 +-- .../transport_sockets/tls/ssl_socket_test.cc | 20 +++++++------- test/integration/echo_integration_test.cc | 2 +- test/integration/fake_upstream.cc | 2 +- test/integration/http_integration.cc | 5 ++-- test/integration/http_integration.h | 6 ++++- test/integration/http_protocol_integration.h | 2 +- test/integration/integration.cc | 19 +++++++------- test/integration/integration.h | 19 +++++--------- test/integration/integration_admin_test.cc | 6 ++--- test/integration/utility.cc | 7 ++--- test/mocks/api/BUILD | 2 +- test/mocks/api/mocks.cc | 4 +++ test/mocks/api/mocks.h | 8 +++--- test/mocks/server/mocks.cc | 1 + test/server/BUILD | 2 +- test/server/config_validation/BUILD | 1 - .../config_validation/async_client_test.cc | 4 +-- .../config_validation/cluster_manager_test.cc | 4 +-- .../config_validation/dispatcher_test.cc | 7 ++--- test/server/guarddog_impl_test.cc | 22 ++++++++-------- test/server/listener_manager_impl_test.cc | 3 +-- test/server/worker_impl_test.cc | 4 +-- test/test_common/BUILD | 1 + test/test_common/environment.cc | 2 +- test/test_common/utility.cc | 21 +++++++++++++-- test/test_common/utility.h | 1 + tools/bootstrap2pb.cc | 6 +++-- tools/v1_to_bootstrap.cc | 6 +++-- 83 files changed, 236 insertions(+), 267 deletions(-) diff --git a/include/envoy/api/api.h b/include/envoy/api/api.h index 33373c4023268..26724bc11e742 100644 --- a/include/envoy/api/api.h +++ b/include/envoy/api/api.h @@ -22,10 +22,9 @@ class Api { /** * Allocate a dispatcher. - * @param time_source the time source. * @return Event::DispatcherPtr which is owned by the caller. */ - virtual Event::DispatcherPtr allocateDispatcher(Event::TimeSystem& time_system) PURE; + virtual Event::DispatcherPtr allocateDispatcher() PURE; /** * @return a reference to the ThreadFactory @@ -36,9 +35,15 @@ class Api { * @return a reference to the Filesystem::Instance */ virtual Filesystem::Instance& fileSystem() PURE; + + /** + * @return a reference to the TimeSystem + * TODO(jmarantz): change this to return a TimeSource. + */ + virtual Event::TimeSystem& timeSystem() PURE; }; typedef std::unique_ptr ApiPtr; } // namespace Api -} // namespace Envoy \ No newline at end of file +} // namespace Envoy diff --git a/include/envoy/server/BUILD b/include/envoy/server/BUILD index 934b216b33773..aefef1c978545 100644 --- a/include/envoy/server/BUILD +++ b/include/envoy/server/BUILD @@ -145,6 +145,7 @@ envoy_cc_library( deps = [ ":admin_interface", "//include/envoy/access_log:access_log_interface", + "//include/envoy/api:api_interface", "//include/envoy/http:codes_interface", "//include/envoy/http:context_interface", "//include/envoy/http:filter_interface", diff --git a/source/common/api/api_impl.cc b/source/common/api/api_impl.cc index 4f93d2b0417aa..ab6e1479b56c6 100644 --- a/source/common/api/api_impl.cc +++ b/source/common/api/api_impl.cc @@ -10,17 +10,15 @@ namespace Envoy { namespace Api { Impl::Impl(std::chrono::milliseconds file_flush_interval_msec, - Thread::ThreadFactory& thread_factory, Stats::Store& stats_store) + Thread::ThreadFactory& thread_factory, Stats::Store& stats_store, + Event::TimeSystem& time_system) : thread_factory_(thread_factory), - file_system_(file_flush_interval_msec, thread_factory, stats_store) {} + file_system_(file_flush_interval_msec, thread_factory, stats_store), + time_system_(time_system) {} -Event::DispatcherPtr Impl::allocateDispatcher(Event::TimeSystem& time_system) { - return std::make_unique(time_system, *this); +Event::DispatcherPtr Impl::allocateDispatcher() { + return std::make_unique(*this); } -Thread::ThreadFactory& Impl::threadFactory() { return thread_factory_; } - -Filesystem::Instance& Impl::fileSystem() { return file_system_; } - } // namespace Api } // namespace Envoy diff --git a/source/common/api/api_impl.h b/source/common/api/api_impl.h index 8223e7d90443c..050b18cfca12c 100644 --- a/source/common/api/api_impl.h +++ b/source/common/api/api_impl.h @@ -19,16 +19,18 @@ namespace Api { class Impl : public Api { public: Impl(std::chrono::milliseconds file_flush_interval_msec, Thread::ThreadFactory& thread_factory, - Stats::Store& stats_store); + Stats::Store& stats_store, Event::TimeSystem& time_system); // Api::Api - Event::DispatcherPtr allocateDispatcher(Event::TimeSystem& time_system) override; - Thread::ThreadFactory& threadFactory() override; - Filesystem::Instance& fileSystem() override; + Event::DispatcherPtr allocateDispatcher() override; + Thread::ThreadFactory& threadFactory() override { return thread_factory_; } + Filesystem::Instance& fileSystem() override { return file_system_; } + Event::TimeSystem& timeSystem() override { return time_system_; } private: Thread::ThreadFactory& thread_factory_; Filesystem::InstanceImpl file_system_; + Event::TimeSystem& time_system_; }; } // namespace Api diff --git a/source/common/event/dispatched_thread.h b/source/common/event/dispatched_thread.h index 1f3aaf86c41dc..8ea8d3beeb9b3 100644 --- a/source/common/event/dispatched_thread.h +++ b/source/common/event/dispatched_thread.h @@ -39,8 +39,7 @@ namespace Event { */ class DispatchedThreadImpl : Logger::Loggable { public: - DispatchedThreadImpl(Api::Api& api, TimeSystem& time_system) - : api_(api), dispatcher_(new DispatcherImpl(time_system, api_)) {} + explicit DispatchedThreadImpl(Api::Api& api) : api_(api), dispatcher_(new DispatcherImpl(api_)) {} /** * Start the thread. diff --git a/source/common/event/dispatcher_impl.cc b/source/common/event/dispatcher_impl.cc index ced376e638dc5..9c146ea2f518b 100644 --- a/source/common/event/dispatcher_impl.cc +++ b/source/common/event/dispatcher_impl.cc @@ -26,17 +26,15 @@ namespace Envoy { namespace Event { -DispatcherImpl::DispatcherImpl(TimeSystem& time_system, Api::Api& api) - : DispatcherImpl(time_system, Buffer::WatermarkFactoryPtr{new Buffer::WatermarkBufferFactory}, - api) { +DispatcherImpl::DispatcherImpl(Api::Api& api) + : DispatcherImpl(Buffer::WatermarkFactoryPtr{new Buffer::WatermarkBufferFactory}, api) { // The dispatcher won't work as expected if libevent hasn't been configured to use threads. RELEASE_ASSERT(Libevent::Global::initialized(), ""); } -DispatcherImpl::DispatcherImpl(TimeSystem& time_system, Buffer::WatermarkFactoryPtr&& factory, - Api::Api& api) - : api_(api), time_system_(time_system), buffer_factory_(std::move(factory)), - base_(event_base_new()), scheduler_(time_system_.createScheduler(base_)), +DispatcherImpl::DispatcherImpl(Buffer::WatermarkFactoryPtr&& factory, Api::Api& api) + : api_(api), buffer_factory_(std::move(factory)), base_(event_base_new()), + scheduler_(api.timeSystem().createScheduler(base_)), deferred_delete_timer_(createTimer([this]() -> void { clearDeferredDeleteList(); })), post_timer_(createTimer([this]() -> void { runPostCallbacks(); })), current_to_delete_(&to_delete_1_) { diff --git a/source/common/event/dispatcher_impl.h b/source/common/event/dispatcher_impl.h index c13108809df8d..99306ced0502b 100644 --- a/source/common/event/dispatcher_impl.h +++ b/source/common/event/dispatcher_impl.h @@ -23,8 +23,8 @@ namespace Event { */ class DispatcherImpl : Logger::Loggable, public Dispatcher { public: - explicit DispatcherImpl(TimeSystem& time_system, Api::Api& api); - DispatcherImpl(TimeSystem& time_system, Buffer::WatermarkFactoryPtr&& factory, Api::Api& api); + explicit DispatcherImpl(Api::Api& api); + DispatcherImpl(Buffer::WatermarkFactoryPtr&& factory, Api::Api& api); ~DispatcherImpl(); /** @@ -33,7 +33,7 @@ class DispatcherImpl : Logger::Loggable, public Dispatcher { event_base& base() { return *base_; } // Event::Dispatcher - TimeSystem& timeSystem() override { return time_system_; } + TimeSystem& timeSystem() override { return api_.timeSystem(); } void clearDeferredDeleteList() override; Network::ConnectionPtr createServerConnection(Network::ConnectionSocketPtr&& socket, @@ -70,7 +70,6 @@ class DispatcherImpl : Logger::Loggable, public Dispatcher { bool isThreadSafe() const { return run_tid_ == nullptr || run_tid_->isCurrentThreadId(); } Api::Api& api_; - TimeSystem& time_system_; Thread::ThreadIdPtr run_tid_; Buffer::WatermarkFactoryPtr buffer_factory_; Libevent::BasePtr base_; diff --git a/source/common/router/router.h b/source/common/router/router.h index 291354b0c1978..9fcafdad5b424 100644 --- a/source/common/router/router.h +++ b/source/common/router/router.h @@ -112,7 +112,7 @@ class FilterConfig { context.runtime(), context.random(), std::move(shadow_writer), PROTOBUF_GET_WRAPPED_OR_DEFAULT(config, dynamic_stats, true), config.start_child_span(), config.suppress_envoy_headers(), - context.timeSource(), context.httpContext()) { + context.api().timeSystem(), context.httpContext()) { for (const auto& upstream_log : config.upstream_log()) { upstream_logs_.push_back(AccessLog::AccessLogFactory::fromProto(upstream_log, context)); } diff --git a/source/server/config_validation/api.cc b/source/server/config_validation/api.cc index 14b52e6e8e653..4763d043b4480 100644 --- a/source/server/config_validation/api.cc +++ b/source/server/config_validation/api.cc @@ -6,11 +6,12 @@ namespace Envoy { namespace Api { ValidationImpl::ValidationImpl(std::chrono::milliseconds file_flush_interval_msec, - Thread::ThreadFactory& thread_factory, Stats::Store& stats_store) - : Impl(file_flush_interval_msec, thread_factory, stats_store) {} + Thread::ThreadFactory& thread_factory, Stats::Store& stats_store, + Event::TimeSystem& time_system) + : Impl(file_flush_interval_msec, thread_factory, stats_store, time_system) {} -Event::DispatcherPtr ValidationImpl::allocateDispatcher(Event::TimeSystem& time_system) { - return Event::DispatcherPtr{new Event::ValidationDispatcher(time_system, *this)}; +Event::DispatcherPtr ValidationImpl::allocateDispatcher() { + return Event::DispatcherPtr{new Event::ValidationDispatcher(*this)}; } } // namespace Api diff --git a/source/server/config_validation/api.h b/source/server/config_validation/api.h index b00cd2c81e1c5..ef05bfdc70319 100644 --- a/source/server/config_validation/api.h +++ b/source/server/config_validation/api.h @@ -16,9 +16,10 @@ namespace Api { class ValidationImpl : public Impl { public: ValidationImpl(std::chrono::milliseconds file_flush_interval_msec, - Thread::ThreadFactory& thread_factory, Stats::Store& stats_store); + Thread::ThreadFactory& thread_factory, Stats::Store& stats_store, + Event::TimeSystem& time_system); - Event::DispatcherPtr allocateDispatcher(Event::TimeSystem&) override; + Event::DispatcherPtr allocateDispatcher() override; }; } // namespace Api diff --git a/source/server/config_validation/async_client.cc b/source/server/config_validation/async_client.cc index 9d04323d5fe3a..be388769f8383 100644 --- a/source/server/config_validation/async_client.cc +++ b/source/server/config_validation/async_client.cc @@ -3,8 +3,7 @@ namespace Envoy { namespace Http { -ValidationAsyncClient::ValidationAsyncClient(Event::TimeSystem& time_system, Api::Api& api) - : dispatcher_(time_system, api) {} +ValidationAsyncClient::ValidationAsyncClient(Api::Api& api) : dispatcher_(api) {} AsyncClient::Request* ValidationAsyncClient::send(MessagePtr&&, Callbacks&, const RequestOptions&) { return nullptr; diff --git a/source/server/config_validation/async_client.h b/source/server/config_validation/async_client.h index 29b533c013d3f..026fd01882767 100644 --- a/source/server/config_validation/async_client.h +++ b/source/server/config_validation/async_client.h @@ -19,7 +19,7 @@ namespace Http { */ class ValidationAsyncClient : public AsyncClient { public: - ValidationAsyncClient(Event::TimeSystem& time_system, Api::Api& api); + ValidationAsyncClient(Api::Api& api); // Http::AsyncClient AsyncClient::Request* send(MessagePtr&& request, Callbacks& callbacks, diff --git a/source/server/config_validation/cluster_manager.cc b/source/server/config_validation/cluster_manager.cc index 2978e13d150c2..328921df74804 100644 --- a/source/server/config_validation/cluster_manager.cc +++ b/source/server/config_validation/cluster_manager.cc @@ -29,7 +29,7 @@ ValidationClusterManager::ValidationClusterManager( Server::Admin& admin, Api::Api& api, Http::Context& http_context) : ClusterManagerImpl(bootstrap, factory, stats, tls, runtime, random, local_info, log_manager, main_thread_dispatcher, admin, api, http_context), - async_client_(main_thread_dispatcher.timeSystem(), api) {} + async_client_(api) {} Http::ConnectionPool::Instance* ValidationClusterManager::httpConnPoolForCluster(const std::string&, ResourcePriority, diff --git a/source/server/config_validation/dispatcher.h b/source/server/config_validation/dispatcher.h index a30addebe8a51..8024c9e2591f4 100644 --- a/source/server/config_validation/dispatcher.h +++ b/source/server/config_validation/dispatcher.h @@ -16,7 +16,7 @@ namespace Event { */ class ValidationDispatcher : public DispatcherImpl { public: - ValidationDispatcher(TimeSystem& time_system, Api::Api& api) : DispatcherImpl(time_system, api) {} + ValidationDispatcher(Api::Api& api) : DispatcherImpl(api) {} Network::ClientConnectionPtr createClientConnection(Network::Address::InstanceConstSharedPtr, diff --git a/source/server/config_validation/server.cc b/source/server/config_validation/server.cc index adb4c785db111..b2220e00acb5d 100644 --- a/source/server/config_validation/server.cc +++ b/source/server/config_validation/server.cc @@ -40,9 +40,10 @@ ValidationInstance::ValidationInstance(Options& options, Event::TimeSystem& time Thread::BasicLockable& access_log_lock, ComponentFactory& component_factory, Thread::ThreadFactory& thread_factory) - : options_(options), time_system_(time_system), stats_store_(store), - api_(new Api::ValidationImpl(options.fileFlushIntervalMsec(), thread_factory, store)), - dispatcher_(api_->allocateDispatcher(time_system)), + : options_(options), stats_store_(store), + api_(new Api::ValidationImpl(options.fileFlushIntervalMsec(), thread_factory, store, + time_system)), + dispatcher_(api_->allocateDispatcher()), singleton_manager_(new Singleton::ManagerImpl(api_->threadFactory().currentThreadId())), access_log_manager_(*api_, *dispatcher_, access_log_lock), mutex_tracer_(nullptr) { try { @@ -69,7 +70,7 @@ void ValidationInstance::initialize(Options& options, // be ready to serve, then the config has passed validation. // Handle configuration that needs to take place prior to the main configuration load. envoy::config::bootstrap::v2::Bootstrap bootstrap; - InstanceUtil::loadBootstrapConfig(bootstrap, options, api()); + InstanceUtil::loadBootstrapConfig(bootstrap, options, *api_); Config::Utility::createTagProducer(bootstrap); @@ -81,16 +82,16 @@ void ValidationInstance::initialize(Options& options, Configuration::InitialImpl initial_config(bootstrap); overload_manager_ = std::make_unique(dispatcher(), stats(), threadLocal(), - bootstrap.overload_manager(), api()); - listener_manager_ = std::make_unique(*this, *this, *this, time_system_); + bootstrap.overload_manager(), *api_); + listener_manager_ = std::make_unique(*this, *this, *this); thread_local_.registerThread(*dispatcher_, true); runtime_loader_ = component_factory.createRuntime(*this, initial_config); secret_manager_ = std::make_unique(); ssl_context_manager_ = - std::make_unique(time_system_); + std::make_unique(api_->timeSystem()); cluster_manager_factory_ = std::make_unique( admin(), runtime(), stats(), threadLocal(), random(), dnsResolver(), sslContextManager(), - dispatcher(), localInfo(), *secret_manager_, api(), http_context_, accessLogManager(), + dispatcher(), localInfo(), *secret_manager_, *api_, http_context_, accessLogManager(), singletonManager()); config_.initialize(bootstrap, *this, *cluster_manager_factory_); http_context_.setTracer(config_.httpTracer()); diff --git a/source/server/config_validation/server.h b/source/server/config_validation/server.h index faca12ea8ea6f..c6993a479737c 100644 --- a/source/server/config_validation/server.h +++ b/source/server/config_validation/server.h @@ -92,7 +92,7 @@ class ValidationInstance : Logger::Loggable, Http::Context& httpContext() override { return http_context_; } ThreadLocal::Instance& threadLocal() override { return thread_local_; } const LocalInfo::LocalInfo& localInfo() override { return *local_info_; } - Event::TimeSystem& timeSystem() override { return time_system_; } + Event::TimeSystem& timeSystem() override { return api_->timeSystem(); } Envoy::MutexTracer* mutexTracer() override { return mutex_tracer_; } std::chrono::milliseconds statsFlushInterval() const override { @@ -140,7 +140,6 @@ class ValidationInstance : Logger::Loggable, ComponentFactory& component_factory); Options& options_; - Event::TimeSystem& time_system_; Stats::IsolatedStoreImpl& stats_store_; ThreadLocal::InstanceImpl thread_local_; Api::ApiPtr api_; diff --git a/source/server/guarddog_impl.cc b/source/server/guarddog_impl.cc index ecae1349b9a42..6c0d4a7e54007 100644 --- a/source/server/guarddog_impl.cc +++ b/source/server/guarddog_impl.cc @@ -17,8 +17,8 @@ namespace Envoy { namespace Server { GuardDogImpl::GuardDogImpl(Stats::Scope& stats_scope, const Server::Configuration::Main& config, - Event::TimeSystem& time_system, Api::Api& api) - : time_system_(time_system), miss_timeout_(config.wdMissTimeout()), + Api::Api& api) + : time_system_(api.timeSystem()), miss_timeout_(config.wdMissTimeout()), megamiss_timeout_(config.wdMegaMissTimeout()), kill_timeout_(config.wdKillTimeout()), multi_kill_timeout_(config.wdMultiKillTimeout()), loop_interval_([&]() -> std::chrono::milliseconds { diff --git a/source/server/guarddog_impl.h b/source/server/guarddog_impl.h index 27f50eade9058..a1b228f966937 100644 --- a/source/server/guarddog_impl.h +++ b/source/server/guarddog_impl.h @@ -39,8 +39,7 @@ class GuardDogImpl : public GuardDog { * * See the configuration documentation for details on the timeout settings. */ - GuardDogImpl(Stats::Scope& stats_scope, const Server::Configuration::Main& config, - Event::TimeSystem& time_system, Api::Api& api); + GuardDogImpl(Stats::Scope& stats_scope, const Server::Configuration::Main& config, Api::Api& api); ~GuardDogImpl(); /** diff --git a/source/server/listener_manager_impl.cc b/source/server/listener_manager_impl.cc index 0ea1572e6e550..cd2ae8202e600 100644 --- a/source/server/listener_manager_impl.cc +++ b/source/server/listener_manager_impl.cc @@ -665,9 +665,8 @@ void ListenerImpl::setSocket(const Network::SocketSharedPtr& socket) { ListenerManagerImpl::ListenerManagerImpl(Instance& server, ListenerComponentFactory& listener_factory, - WorkerFactory& worker_factory, TimeSource& time_source) - : server_(server), time_source_(time_source), factory_(listener_factory), - stats_(generateStats(server.stats())), + WorkerFactory& worker_factory) + : server_(server), factory_(listener_factory), stats_(generateStats(server.stats())), config_tracker_entry_(server.admin().getConfigTracker().add( "listeners", [this] { return dumpListenerConfigs(); })) { for (uint32_t i = 0; i < server.options().concurrency(); i++) { diff --git a/source/server/listener_manager_impl.h b/source/server/listener_manager_impl.h index e8a5a87051ffe..fd19d5026eab6 100644 --- a/source/server/listener_manager_impl.h +++ b/source/server/listener_manager_impl.h @@ -104,7 +104,7 @@ struct ListenerManagerStats { class ListenerManagerImpl : public ListenerManager, Logger::Loggable { public: ListenerManagerImpl(Instance& server, ListenerComponentFactory& listener_factory, - WorkerFactory& worker_factory, TimeSource& time_source); + WorkerFactory& worker_factory); void onListenerWarmed(ListenerImpl& listener); @@ -124,7 +124,6 @@ class ListenerManagerImpl : public ListenerManager, Logger::Loggable()), - dispatcher_(api_->allocateDispatcher(time_system)), + dispatcher_(api_->allocateDispatcher()), singleton_manager_(new Singleton::ManagerImpl(api_->threadFactory().currentThreadId())), handler_(new ConnectionHandlerImpl(ENVOY_LOGGER(), *dispatcher_)), random_generator_(std::move(random_generator)), listener_component_factory_(*this), - worker_factory_(thread_local_, *api_, hooks, time_system), + worker_factory_(thread_local_, *api_, hooks), dns_resolver_(dispatcher_->createDnsResolver({})), access_log_manager_(*api_, *dispatcher_, access_log_lock), terminated_(false), mutex_tracer_(options.mutexTracingEnabled() ? &Envoy::MutexTracerImpl::getOrCreateTracer() @@ -288,8 +288,8 @@ void InstanceImpl::initialize(Options& options, bootstrap_.overload_manager(), api()); // Workers get created first so they register for thread local updates. - listener_manager_ = std::make_unique(*this, listener_component_factory_, - worker_factory_, time_system_); + listener_manager_ = + std::make_unique(*this, listener_component_factory_, worker_factory_); // The main thread is also registered for thread local updates so that code that does not care // whether it runs on the main thread or on workers can still use TLS. @@ -348,7 +348,7 @@ void InstanceImpl::initialize(Options& options, // GuardDog (deadlock detection) object and thread setup before workers are // started and before our own run() loop runs. - guard_dog_ = std::make_unique(stats_store_, config_, time_system_, api()); + guard_dog_ = std::make_unique(stats_store_, config_, api()); } void InstanceImpl::startWorkers() { diff --git a/source/server/worker_impl.cc b/source/server/worker_impl.cc index 89f21a31f1c22..660d1ac1cf739 100644 --- a/source/server/worker_impl.cc +++ b/source/server/worker_impl.cc @@ -14,7 +14,7 @@ namespace Envoy { namespace Server { WorkerPtr ProdWorkerFactory::createWorker(OverloadManager& overload_manager) { - Event::DispatcherPtr dispatcher(api_.allocateDispatcher(time_system_)); + Event::DispatcherPtr dispatcher(api_.allocateDispatcher()); return WorkerPtr{new WorkerImpl( tls_, hooks_, std::move(dispatcher), Network::ConnectionHandlerPtr{new ConnectionHandlerImpl(ENVOY_LOGGER(), *dispatcher)}, diff --git a/source/server/worker_impl.h b/source/server/worker_impl.h index 5c0e374fdc250..b59c7356f2134 100644 --- a/source/server/worker_impl.h +++ b/source/server/worker_impl.h @@ -19,9 +19,8 @@ namespace Server { class ProdWorkerFactory : public WorkerFactory, Logger::Loggable { public: - ProdWorkerFactory(ThreadLocal::Instance& tls, Api::Api& api, TestHooks& hooks, - Event::TimeSystem& time_system) - : tls_(tls), api_(api), hooks_(hooks), time_system_(time_system) {} + ProdWorkerFactory(ThreadLocal::Instance& tls, Api::Api& api, TestHooks& hooks) + : tls_(tls), api_(api), hooks_(hooks) {} // Server::WorkerFactory WorkerPtr createWorker(OverloadManager& overload_manager) override; @@ -30,7 +29,6 @@ class ProdWorkerFactory : public WorkerFactory, Logger::Loggable> callbacks_; FilesystemEdsSubscriptionImpl subscription_; diff --git a/test/common/event/BUILD b/test/common/event/BUILD index 2ecbb8a213540..0a5ad582e66b2 100644 --- a/test/common/event/BUILD +++ b/test/common/event/BUILD @@ -17,7 +17,6 @@ envoy_cc_test( "//source/common/event:dispatcher_lib", "//source/common/stats:isolated_store_lib", "//test/mocks:common_lib", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) @@ -32,7 +31,6 @@ envoy_cc_test( "//source/common/stats:isolated_store_lib", "//test/mocks:common_lib", "//test/test_common:environment_lib", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/common/event/dispatched_thread_impl_test.cc b/test/common/event/dispatched_thread_impl_test.cc index 1971ee014621a..fc9ba00435fbd 100644 --- a/test/common/event/dispatched_thread_impl_test.cc +++ b/test/common/event/dispatched_thread_impl_test.cc @@ -10,7 +10,6 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/stats/mocks.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" @@ -24,14 +23,13 @@ namespace Event { class DispatchedThreadTest : public TestBase { protected: DispatchedThreadTest() - : config_(1000, 1000, 1000, 1000), api_(Api::createApiForTest(fakestats_)), - thread_(*api_, test_time_.timeSystem()), - guard_dog_(fakestats_, config_, test_time_.timeSystem(), *api_) {} + : config_(1000, 1000, 1000, 1000), api_(Api::createApiForTest(fakestats_)), thread_(*api_), + guard_dog_(fakestats_, config_, *api_) {} + + void SetUp() override { thread_.start(guard_dog_); } - void SetUp() { thread_.start(guard_dog_); } NiceMock config_; Stats::IsolatedStoreImpl fakestats_; - DangerousDeprecatedTestTime test_time_; Api::ApiPtr api_; DispatchedThreadImpl thread_; Envoy::Server::GuardDogImpl guard_dog_; diff --git a/test/common/event/dispatcher_impl_test.cc b/test/common/event/dispatcher_impl_test.cc index da48fa793e17c..6677fbfe679d9 100644 --- a/test/common/event/dispatcher_impl_test.cc +++ b/test/common/event/dispatcher_impl_test.cc @@ -9,7 +9,6 @@ #include "test/mocks/common.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" @@ -32,8 +31,7 @@ TEST(DeferredDeleteTest, DeferredDelete) { InSequence s; Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - DangerousDeprecatedTestTime test_time; - DispatcherImpl dispatcher(test_time.timeSystem(), *api); + DispatcherImpl dispatcher(*api); ReadyWatcher watcher1; dispatcher.deferredDelete( @@ -65,8 +63,7 @@ class DispatcherImplTest : public TestBase { protected: DispatcherImplTest() : api_(Api::createApiForTest(stat_store_)), - dispatcher_(std::make_unique(test_time_.timeSystem(), *api_)), - work_finished_(false) { + dispatcher_(std::make_unique(*api_)), work_finished_(false) { dispatcher_thread_ = api_->threadFactory().createThread([this]() { // Must create a keepalive timer to keep the dispatcher from exiting. std::chrono::milliseconds time_interval(500); @@ -83,8 +80,6 @@ class DispatcherImplTest : public TestBase { dispatcher_thread_->join(); } - DangerousDeprecatedTestTime test_time_; - Stats::IsolatedStoreImpl stat_store_; Api::ApiPtr api_; Thread::ThreadPtr dispatcher_thread_; diff --git a/test/common/event/file_event_impl_test.cc b/test/common/event/file_event_impl_test.cc index cb8bec642bf66..d43dbeef0bc40 100644 --- a/test/common/event/file_event_impl_test.cc +++ b/test/common/event/file_event_impl_test.cc @@ -8,7 +8,6 @@ #include "test/mocks/common.h" #include "test/test_common/environment.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" namespace Envoy { @@ -16,8 +15,7 @@ namespace Event { class FileEventImplTest : public TestBase { public: - FileEventImplTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + FileEventImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} void SetUp() override { int rc = socketpair(AF_UNIX, SOCK_DGRAM, 0, fds_); @@ -36,7 +34,6 @@ class FileEventImplTest : public TestBase { int fds_[2]; Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; DispatcherImpl dispatcher_; }; @@ -55,10 +52,9 @@ TEST_P(FileEventImplActivateTest, Activate) { } ASSERT_NE(-1, fd); - DangerousDeprecatedTestTime test_time; Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - DispatcherImpl dispatcher(test_time.timeSystem(), *api); + DispatcherImpl dispatcher(*api); ReadyWatcher read_event; EXPECT_CALL(read_event, ready()).Times(1); ReadyWatcher write_event; diff --git a/test/common/filesystem/BUILD b/test/common/filesystem/BUILD index 9538338b6614c..c34f8969df993 100644 --- a/test/common/filesystem/BUILD +++ b/test/common/filesystem/BUILD @@ -48,6 +48,5 @@ envoy_cc_test( "//source/common/filesystem:watcher_lib", "//source/common/stats:isolated_store_lib", "//test/test_common:environment_lib", - "//test/test_common:test_time_lib", ], ) diff --git a/test/common/filesystem/watcher_impl_test.cc b/test/common/filesystem/watcher_impl_test.cc index a7ab6895f702f..da6b5fd80cddf 100644 --- a/test/common/filesystem/watcher_impl_test.cc +++ b/test/common/filesystem/watcher_impl_test.cc @@ -8,7 +8,6 @@ #include "test/test_common/environment.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" @@ -18,12 +17,10 @@ namespace Filesystem { class WatcherImplTest : public TestBase { protected: - WatcherImplTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + WatcherImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; }; diff --git a/test/common/grpc/google_async_client_impl_test.cc b/test/common/grpc/google_async_client_impl_test.cc index 761ce43fbd61c..73f69db13b9de 100644 --- a/test/common/grpc/google_async_client_impl_test.cc +++ b/test/common/grpc/google_async_client_impl_test.cc @@ -48,7 +48,7 @@ class EnvoyGoogleAsyncClientImplTest : public TestBase { public: EnvoyGoogleAsyncClientImplTest() : stats_store_(new Stats::IsolatedStoreImpl), api_(Api::createApiForTest(*stats_store_)), - dispatcher_(test_time_.timeSystem(), *api_), scope_(stats_store_), + dispatcher_(*api_), scope_(stats_store_), method_descriptor_(helloworld::Greeter::descriptor()->FindMethodByName("SayHello")) { envoy::api::v2::core::GrpcService config; auto* google_grpc = config.mutable_google_grpc(); diff --git a/test/common/grpc/grpc_client_integration_test_harness.h b/test/common/grpc/grpc_client_integration_test_harness.h index 8776208548073..950c087a163c2 100644 --- a/test/common/grpc/grpc_client_integration_test_harness.h +++ b/test/common/grpc/grpc_client_integration_test_harness.h @@ -218,7 +218,7 @@ class GrpcClientIntegrationTest : public GrpcClientIntegrationParamTest { public: GrpcClientIntegrationTest() : method_descriptor_(helloworld::Greeter::descriptor()->FindMethodByName("SayHello")), - api_(Api::createApiForTest(*stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + api_(Api::createApiForTest(*stats_store_, test_time_.timeSystem())), dispatcher_(*api_) {} virtual void initialize() { if (fake_upstream_ == nullptr) { diff --git a/test/common/http/BUILD b/test/common/http/BUILD index d810ea68df6dc..ff05727d307db 100644 --- a/test/common/http/BUILD +++ b/test/common/http/BUILD @@ -54,7 +54,6 @@ envoy_cc_test( "//test/mocks/upstream:upstream_mocks", "//test/test_common:environment_lib", "//test/test_common:network_utility_lib", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/common/http/codec_client_test.cc b/test/common/http/codec_client_test.cc index 0871311e6fbb1..6e38d86bea355 100644 --- a/test/common/http/codec_client_test.cc +++ b/test/common/http/codec_client_test.cc @@ -19,7 +19,6 @@ #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" @@ -60,7 +59,6 @@ class CodecClientTest : public TestBase { ~CodecClientTest() { EXPECT_EQ(0U, client_->numActiveRequests()); } - DangerousDeprecatedTestTime test_time_; Event::MockDispatcher dispatcher_; Network::MockClientConnection* connection_; Http::MockClientConnection* codec_; @@ -262,7 +260,7 @@ TEST_F(CodecClientTest, WatermarkPassthrough) { class CodecNetworkTest : public TestBaseWithParam { public: CodecNetworkTest() : api_(Api::createApiForTest(stats_store_)) { - dispatcher_ = std::make_unique(test_time_.timeSystem(), *api_); + dispatcher_ = std::make_unique(*api_); upstream_listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( socket_.localAddress(), source_address_, Network::Test::createRawBufferSocket(), nullptr); @@ -330,7 +328,6 @@ class CodecNetworkTest : public TestBaseWithParam { protected: Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherPtr dispatcher_; Network::ListenerPtr upstream_listener_; Network::MockListenerCallbacks listener_callbacks_; diff --git a/test/common/http/http1/BUILD b/test/common/http/http1/BUILD index 66da7a23b6e86..e685bff6f3288 100644 --- a/test/common/http/http1/BUILD +++ b/test/common/http/http1/BUILD @@ -45,7 +45,6 @@ envoy_cc_test( "//test/mocks/network:network_mocks", "//test/mocks/runtime:runtime_mocks", "//test/mocks/upstream:upstream_mocks", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/common/http/http1/conn_pool_test.cc b/test/common/http/http1/conn_pool_test.cc index 40c3994e9688a..ae6152f37eb7b 100644 --- a/test/common/http/http1/conn_pool_test.cc +++ b/test/common/http/http1/conn_pool_test.cc @@ -18,7 +18,6 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" @@ -81,8 +80,7 @@ class ConnPoolImplForTest : public ConnPoolImpl { test_client.codec_ = new NiceMock(); test_client.connect_timer_ = new NiceMock(&mock_dispatcher_); std::shared_ptr cluster{new NiceMock()}; - test_client.client_dispatcher_ = - std::make_unique(test_time_.timeSystem(), *api_); + test_client.client_dispatcher_ = std::make_unique(*api_); Network::ClientConnectionPtr connection{test_client.connection_}; test_client.codec_client_ = new CodecClientForTest( std::move(connection), test_client.codec_, @@ -115,7 +113,6 @@ class ConnPoolImplForTest : public ConnPoolImpl { Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::MockDispatcher& mock_dispatcher_; NiceMock* mock_upstream_ready_timer_; std::vector test_clients_; diff --git a/test/common/http/http2/BUILD b/test/common/http/http2/BUILD index 436b29f83860d..bb255b0ba9a31 100644 --- a/test/common/http/http2/BUILD +++ b/test/common/http/http2/BUILD @@ -75,7 +75,6 @@ envoy_cc_test( "//test/mocks/network:network_mocks", "//test/mocks/runtime:runtime_mocks", "//test/mocks/upstream:upstream_mocks", - "//test/test_common:test_time_lib", ], ) diff --git a/test/common/http/http2/conn_pool_test.cc b/test/common/http/http2/conn_pool_test.cc index 0402277c88f00..cd318c0fb6735 100644 --- a/test/common/http/http2/conn_pool_test.cc +++ b/test/common/http/http2/conn_pool_test.cc @@ -16,7 +16,6 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/printers.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "gmock/gmock.h" @@ -83,8 +82,7 @@ class Http2ConnPoolImplTest : public TestBase { test_client.connection_ = new NiceMock(); test_client.codec_ = new NiceMock(); test_client.connect_timer_ = new NiceMock(&dispatcher_); - test_client.client_dispatcher_ = - std::make_unique(test_time_.timeSystem(), *api_); + test_client.client_dispatcher_ = std::make_unique(*api_); EXPECT_CALL(dispatcher_, createClientConnection_(_, _, _, _)) .WillOnce(Return(test_client.connection_)); auto cluster = std::make_shared>(); @@ -120,7 +118,6 @@ class Http2ConnPoolImplTest : public TestBase { Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; NiceMock dispatcher_; std::shared_ptr cluster_{new NiceMock()}; Upstream::HostSharedPtr host_{Upstream::makeTestHost(cluster_, "tcp://127.0.0.1:80")}; diff --git a/test/common/network/BUILD b/test/common/network/BUILD index 0dc910b23e19a..8b356ed2c997e 100644 --- a/test/common/network/BUILD +++ b/test/common/network/BUILD @@ -64,6 +64,7 @@ envoy_cc_test( "//test/test_common:environment_lib", "//test/test_common:network_utility_lib", "//test/test_common:simulated_time_system_lib", + "//test/test_common:test_time_lib", ], ) @@ -85,7 +86,6 @@ envoy_cc_test( "//test/mocks/network:network_mocks", "//test/test_common:environment_lib", "//test/test_common:network_utility_lib", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) @@ -155,7 +155,6 @@ envoy_cc_test( "//test/mocks/server:server_mocks", "//test/test_common:environment_lib", "//test/test_common:network_utility_lib", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/common/network/connection_impl_test.cc b/test/common/network/connection_impl_test.cc index 9f8667b030829..f00422b5125ca 100644 --- a/test/common/network/connection_impl_test.cc +++ b/test/common/network/connection_impl_test.cc @@ -79,9 +79,9 @@ INSTANTIATE_TEST_SUITE_P(IpVersions, ConnectionImplDeathTest, TEST_P(ConnectionImplDeathTest, BadFd) { Stats::IsolatedStoreImpl stats_store; - Api::ApiPtr api = Api::createApiForTest(stats_store); Event::SimulatedTimeSystem time_system; - Event::DispatcherImpl dispatcher(time_system, *api); + Api::ApiPtr api = Api::createApiForTest(stats_store); + Event::DispatcherImpl dispatcher(*api); IoHandlePtr io_handle = std::make_unique(); EXPECT_DEATH_LOG_TO_STDERR( ConnectionImpl(dispatcher, @@ -96,7 +96,7 @@ class ConnectionImplTest : public TestBaseWithParam { void setUpBasicConnection() { if (dispatcher_.get() == nullptr) { - dispatcher_ = std::make_unique(time_system_, *api_); + dispatcher_ = std::make_unique(*api_); } listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); @@ -159,8 +159,8 @@ class ConnectionImplTest : public TestBaseWithParam { ASSERT(dispatcher_.get() == nullptr); MockBufferFactory* factory = new StrictMock; - dispatcher_ = std::make_unique( - time_system_, Buffer::WatermarkFactoryPtr{factory}, *api_); + dispatcher_ = + std::make_unique(Buffer::WatermarkFactoryPtr{factory}, *api_); // The first call to create a client session will get a MockBuffer. // Other calls for server sessions will by default get a normal OwnedImpl. EXPECT_CALL(*factory, create_(_, _)) @@ -272,7 +272,7 @@ TEST_P(ConnectionImplTest, CloseDuringConnectCallback) { } TEST_P(ConnectionImplTest, ImmediateConnectError) { - dispatcher_ = std::make_unique(time_system_, *api_); + dispatcher_ = std::make_unique(*api_); // Using a broadcast/multicast address as the connection destinations address causes an // immediate error return from connect(). @@ -886,7 +886,7 @@ TEST_P(ConnectionImplTest, BindFailureTest) { source_address_ = Network::Address::InstanceConstSharedPtr{ new Network::Address::Ipv6Instance(address_string, 0)}; } - dispatcher_ = std::make_unique(time_system_, *api_); + dispatcher_ = std::make_unique(*api_); listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); client_connection_ = dispatcher_->createClientConnection( @@ -1574,7 +1574,7 @@ class ReadBufferLimitTest : public ConnectionImplTest { public: void readBufferLimitTest(uint32_t read_buffer_limit, uint32_t expected_chunk_size) { const uint32_t buffer_size = 256 * 1024; - dispatcher_ = std::make_unique(time_system_, *api_); + dispatcher_ = std::make_unique(*api_); listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); client_connection_ = dispatcher_->createClientConnection( @@ -1645,12 +1645,11 @@ TEST_P(ReadBufferLimitTest, SomeLimit) { class TcpClientConnectionImplTest : public TestBaseWithParam { protected: - TcpClientConnectionImplTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(time_system_, *api_) {} + TcpClientConnectionImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} Stats::IsolatedStoreImpl stats_store_; - Api::ApiPtr api_; Event::SimulatedTimeSystem time_system_; + Api::ApiPtr api_; Event::DispatcherImpl dispatcher_; }; INSTANTIATE_TEST_SUITE_P(IpVersions, TcpClientConnectionImplTest, @@ -1690,12 +1689,11 @@ TEST_P(TcpClientConnectionImplTest, BadConnectConnRefused) { class PipeClientConnectionImplTest : public TestBase { protected: - PipeClientConnectionImplTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(time_system_, *api_) {} + PipeClientConnectionImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} Stats::IsolatedStoreImpl stats_store_; - Api::ApiPtr api_; Event::SimulatedTimeSystem time_system_; + Api::ApiPtr api_; Event::DispatcherImpl dispatcher_; const std::string path_{TestEnvironment::unixDomainSocketPath("foo")}; }; diff --git a/test/common/network/dns_impl_test.cc b/test/common/network/dns_impl_test.cc index 37cf0080bbc20..d5c0403d592d5 100644 --- a/test/common/network/dns_impl_test.cc +++ b/test/common/network/dns_impl_test.cc @@ -27,7 +27,6 @@ #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "ares.h" @@ -325,12 +324,10 @@ class DnsResolverImplPeer { class DnsImplConstructor : public TestBase { protected: - DnsImplConstructor() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + DnsImplConstructor() : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; }; @@ -407,8 +404,7 @@ TEST_F(DnsImplConstructor, BadCustomResolvers) { class DnsImplTest : public TestBaseWithParam { public: - DnsImplTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + DnsImplTest() : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} void SetUp() override { resolver_ = dispatcher_.createDnsResolver({}); @@ -441,7 +437,6 @@ class DnsImplTest : public TestBaseWithParam { Stats::IsolatedStoreImpl stats_store_; std::unique_ptr listener_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; DnsResolverSharedPtr resolver_; }; diff --git a/test/common/network/listener_impl_test.cc b/test/common/network/listener_impl_test.cc index 0e20d0f103635..05592b2072e45 100644 --- a/test/common/network/listener_impl_test.cc +++ b/test/common/network/listener_impl_test.cc @@ -7,7 +7,6 @@ #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "gmock/gmock.h" @@ -24,8 +23,7 @@ static void errorCallbackTest(Address::IpVersion version) { // test in the forked process to avoid confusion when the fork happens. Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - DangerousDeprecatedTestTime test_time; - Event::DispatcherImpl dispatcher(test_time.timeSystem(), *api); + Event::DispatcherImpl dispatcher(*api); Network::TcpListenSocket socket(Network::Test::getCanonicalLoopbackAddress(version), nullptr, true); @@ -79,13 +77,12 @@ class ListenerImplTest : public TestBaseWithParam { : version_(GetParam()), alt_address_(Network::Test::findOrCheckFreePort( Network::Test::getCanonicalLoopbackAddress(version_), Address::SocketType::Stream)), - api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} const Address::IpVersion version_; const Address::InstanceConstSharedPtr alt_address_; Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; }; INSTANTIATE_TEST_SUITE_P(IpVersions, ListenerImplTest, diff --git a/test/common/network/udp_listener_impl_test.cc b/test/common/network/udp_listener_impl_test.cc index 6c9e9b1926529..ae2639c7a6c56 100644 --- a/test/common/network/udp_listener_impl_test.cc +++ b/test/common/network/udp_listener_impl_test.cc @@ -36,13 +36,13 @@ class TestUdpListenerImpl : public UdpListenerImpl { } }; -class ListenerImplTest : public TestBaseWithParam { +class UdpListenerImplTest : public TestBaseWithParam { protected: - ListenerImplTest() + UdpListenerImplTest() : version_(GetParam()), alt_address_(Network::Test::findOrCheckFreePort( Network::Test::getCanonicalLoopbackAddress(version_), Address::SocketType::Stream)), - api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_) {} + api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_) {} SocketPtr getSocket(Address::SocketType type, const Address::InstanceConstSharedPtr& address, const Network::Socket::OptionsSharedPtr& options, bool bind) { @@ -120,12 +120,12 @@ class ListenerImplTest : public TestBaseWithParam { DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; }; -INSTANTIATE_TEST_CASE_P(IpVersions, ListenerImplTest, +INSTANTIATE_TEST_CASE_P(IpVersions, UdpListenerImplTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); // Test that socket options are set after the listener is setup. -TEST_P(ListenerImplTest, UdpSetListeningSocketOptionsSuccess) { +TEST_P(UdpListenerImplTest, UdpSetListeningSocketOptionsSuccess) { Network::MockListenerCallbacks listener_callbacks; Network::MockConnectionHandler connection_handler; @@ -138,7 +138,7 @@ TEST_P(ListenerImplTest, UdpSetListeningSocketOptionsSuccess) { /** * Tests UDP listener for actual destination and data. */ -TEST_P(ListenerImplTest, UseActualDstUdp) { +TEST_P(UdpListenerImplTest, UseActualDstUdp) { // Setup server socket SocketPtr server_socket = getSocket(Address::SocketType::Datagram, Network::Test::getCanonicalLoopbackAddress(version_), @@ -224,7 +224,7 @@ TEST_P(ListenerImplTest, UseActualDstUdp) { /** * Tests UDP listener for read and write callbacks with actual data. */ -TEST_P(ListenerImplTest, UdpEcho) { +TEST_P(UdpListenerImplTest, UdpEcho) { // Setup server socket SocketPtr server_socket = getSocket(Address::SocketType::Datagram, Network::Test::getCanonicalLoopbackAddress(version_), @@ -358,7 +358,7 @@ TEST_P(ListenerImplTest, UdpEcho) { /** * Tests UDP listener's `enable` and `disable` APIs. */ -TEST_P(ListenerImplTest, UdpListenerEnableDisable) { +TEST_P(UdpListenerImplTest, UdpListenerEnableDisable) { // Setup server socket SocketPtr server_socket = getSocket(Address::SocketType::Datagram, Network::Test::getCanonicalLoopbackAddress(version_), @@ -458,7 +458,7 @@ TEST_P(ListenerImplTest, UdpListenerEnableDisable) { /** * Tests UDP listener's error callback. */ -TEST_P(ListenerImplTest, UdpListenerRecvFromError) { +TEST_P(UdpListenerImplTest, UdpListenerRecvFromError) { // Setup server socket SocketPtr server_socket = getSocket(Address::SocketType::Datagram, Network::Test::getCanonicalLoopbackAddress(version_), diff --git a/test/common/stats/BUILD b/test/common/stats/BUILD index b3d2020e43890..4ceea90e1b3c7 100644 --- a/test/common/stats/BUILD +++ b/test/common/stats/BUILD @@ -151,6 +151,7 @@ envoy_cc_test_binary( "//source/common/stats:thread_local_store_lib", "//source/common/thread_local:thread_local_lib", "//test/test_common:simulated_time_system_lib", + "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/common/stats/thread_local_store_speed_test.cc b/test/common/stats/thread_local_store_speed_test.cc index c23bb1e66520f..8eddd256937de 100644 --- a/test/common/stats/thread_local_store_speed_test.cc +++ b/test/common/stats/thread_local_store_speed_test.cc @@ -12,6 +12,7 @@ #include "test/common/stats/stat_test_utility.h" #include "test/test_common/simulated_time_system.h" +#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "benchmark/benchmark.h" @@ -20,7 +21,8 @@ namespace Envoy { class ThreadLocalStorePerf { public: - ThreadLocalStorePerf() : store_(options_, heap_alloc_), api_(Api::createApiForTest(store_)) { + ThreadLocalStorePerf() + : store_(options_, heap_alloc_), api_(Api::createApiForTest(store_, time_system_)) { store_.setTagProducer(std::make_unique(stats_config_)); } @@ -37,17 +39,17 @@ class ThreadLocalStorePerf { } void initThreading() { - dispatcher_ = std::make_unique(time_system_, *api_); + dispatcher_ = std::make_unique(*api_); tls_ = std::make_unique(); store_.initializeThreading(*dispatcher_, *tls_); } private: + Event::SimulatedTimeSystem time_system_; Stats::StatsOptionsImpl options_; Stats::HeapStatDataAllocator heap_alloc_; Stats::ThreadLocalStoreImpl store_; Api::ApiPtr api_; - Event::SimulatedTimeSystem time_system_; std::unique_ptr dispatcher_; std::unique_ptr tls_; envoy::config::metrics::v2::StatsConfig stats_config_; diff --git a/test/common/thread_local/BUILD b/test/common/thread_local/BUILD index a1e1de967c805..c1d95410e5ab9 100644 --- a/test/common/thread_local/BUILD +++ b/test/common/thread_local/BUILD @@ -17,6 +17,5 @@ envoy_cc_test( "//source/common/stats:isolated_store_lib", "//source/common/thread_local:thread_local_lib", "//test/mocks/event:event_mocks", - "//test/test_common:test_time_lib", ], ) diff --git a/test/common/thread_local/thread_local_impl_test.cc b/test/common/thread_local/thread_local_impl_test.cc index 49e228030d1a4..99ff8eaa426cf 100644 --- a/test/common/thread_local/thread_local_impl_test.cc +++ b/test/common/thread_local/thread_local_impl_test.cc @@ -4,7 +4,6 @@ #include "common/thread_local/thread_local_impl.h" #include "test/mocks/event/mocks.h" -#include "test/test_common/test_time.h" #include "gmock/gmock.h" @@ -117,11 +116,10 @@ TEST_F(ThreadLocalInstanceImplTest, RunOnAllThreads) { TEST(ThreadLocalInstanceImplDispatcherTest, Dispatcher) { InstanceImpl tls; - DangerousDeprecatedTestTime test_time; Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - Event::DispatcherImpl main_dispatcher(test_time.timeSystem(), *api); - Event::DispatcherImpl thread_dispatcher(test_time.timeSystem(), *api); + Event::DispatcherImpl main_dispatcher(*api); + Event::DispatcherImpl thread_dispatcher(*api); tls.registerThread(main_dispatcher, true); tls.registerThread(thread_dispatcher, false); diff --git a/test/common/upstream/hds_test.cc b/test/common/upstream/hds_test.cc index 501aa9aa76929..fc39df03d8784 100644 --- a/test/common/upstream/hds_test.cc +++ b/test/common/upstream/hds_test.cc @@ -46,7 +46,8 @@ class HdsTest : public TestBase { protected: HdsTest() : retry_timer_(new Event::MockTimer()), server_response_timer_(new Event::MockTimer()), - async_client_(new Grpc::MockAsyncClient()), api_(Api::createApiForTest(stats_store_)) { + async_client_(new Grpc::MockAsyncClient()), api_(Api::createApiForTest(stats_store_)), + ssl_context_manager_(api_->timeSystem()) { node_.set_id("hds-node"); } @@ -96,6 +97,7 @@ class HdsTest : public TestBase { return msg; } + Event::SimulatedTimeSystem time_system_; envoy::api::v2::core::Node node_; Event::MockDispatcher dispatcher_; Stats::IsolatedStoreImpl stats_store_; @@ -115,8 +117,8 @@ class HdsTest : public TestBase { Grpc::MockAsyncStream async_stream_; Grpc::MockAsyncClient* async_client_; Runtime::MockLoader runtime_; - Event::SimulatedTimeSystem time_system_; - Extensions::TransportSockets::Tls::ContextManagerImpl ssl_context_manager_{time_system_}; + Api::ApiPtr api_; + Extensions::TransportSockets::Tls::ContextManagerImpl ssl_context_manager_; NiceMock random_; NiceMock log_manager_; NiceMock cm_; @@ -124,7 +126,6 @@ class HdsTest : public TestBase { NiceMock admin_; Singleton::ManagerImpl singleton_manager_{Thread::threadFactoryForTest().currentThreadId()}; NiceMock tls_; - Api::ApiPtr api_; }; // Test that HdsDelegate builds and sends initial message correctly diff --git a/test/config_test/BUILD b/test/config_test/BUILD index 1048b4f8e7840..494341c4b6fd6 100644 --- a/test/config_test/BUILD +++ b/test/config_test/BUILD @@ -44,5 +44,6 @@ envoy_cc_test_library( "//test/mocks/server:server_mocks", "//test/mocks/ssl:ssl_mocks", "//test/test_common:threadsafe_singleton_injector_lib", + "//test/test_common:simulated_time_system_lib", ] + envoy_all_extensions(), ) diff --git a/test/config_test/config_test.cc b/test/config_test/config_test.cc index f7efcaab48630..e9aab4f379564 100644 --- a/test/config_test/config_test.cc +++ b/test/config_test/config_test.cc @@ -106,8 +106,7 @@ class ConfigTest { std::unique_ptr cluster_manager_factory_; NiceMock component_factory_; NiceMock worker_factory_; - Server::ListenerManagerImpl listener_manager_{server_, component_factory_, worker_factory_, - server_.timeSystem()}; + Server::ListenerManagerImpl listener_manager_{server_, component_factory_, worker_factory_}; Runtime::RandomGeneratorImpl random_; NiceMock os_sys_calls_; TestThreadsafeSingletonInjector os_calls{&os_sys_calls_}; diff --git a/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc b/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc index aa56d03ee1e96..edfd1e34cce39 100644 --- a/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc +++ b/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc @@ -9,11 +9,11 @@ namespace Envoy { -class GzipIntegrationTest : public HttpIntegrationTest, +class GzipIntegrationTest : public Event::SimulatedTimeSystem, + public HttpIntegrationTest, public TestBaseWithParam { public: - GzipIntegrationTest() - : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), simTime()) {} + GzipIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {} void SetUp() override { decompressor_.init(window_bits); } void TearDown() override { cleanupUpstreamAndDownstream(); } diff --git a/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc b/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc index 50fae0a437564..cdb8d7c6c126b 100644 --- a/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc +++ b/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc @@ -23,7 +23,6 @@ #include "test/test_common/network_utility.h" #include "test/test_common/printers.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/threadsafe_singleton_injector.h" #include "test/test_common/utility.h" @@ -50,7 +49,7 @@ class ProxyProtocolTest : public TestBaseWithParam, protected Logger::Loggable { public: ProxyProtocolTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_), + : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_), socket_(Network::Test::getCanonicalLoopbackAddress(GetParam()), nullptr, true), connection_handler_(new Server::ConnectionHandlerImpl(ENVOY_LOGGER(), dispatcher_)), name_("proxy"), filter_chain_(Network::Test::createEmptyFilterChainWithRawBufferSockets()) { @@ -151,7 +150,6 @@ class ProxyProtocolTest : public TestBaseWithParam, Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; Network::TcpListenSocket socket_; Network::ConnectionHandlerPtr connection_handler_; @@ -871,7 +869,7 @@ class WildcardProxyProtocolTest : public TestBaseWithParam { public: WildcardProxyProtocolTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_), + : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_), socket_(Network::Test::getAnyAddress(GetParam()), nullptr, true), local_dst_address_(Network::Utility::getAddressWithPort( *Network::Test::getCanonicalLoopbackAddress(GetParam()), @@ -958,7 +956,6 @@ class WildcardProxyProtocolTest : public TestBaseWithParamcreateResourceMonitor(config, context); EXPECT_NE(monitor, nullptr); diff --git a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc index 5b2c5d862d988..4955ef58bd982 100644 --- a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc +++ b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc @@ -7,7 +7,6 @@ #include "test/test_common/environment.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" @@ -46,7 +45,7 @@ class MockedCallbacks : public Server::ResourceMonitor::Callbacks { class InjectedResourceMonitorTest : public TestBase { protected: InjectedResourceMonitorTest() - : api_(Api::createApiForTest(stats_store_)), dispatcher_(test_time_.timeSystem(), *api_), + : api_(Api::createApiForTest(stats_store_)), dispatcher_(*api_), resource_filename_(TestEnvironment::temporaryPath("injected_resource")), file_updater_(resource_filename_), monitor_(createMonitor()) {} @@ -67,7 +66,6 @@ class InjectedResourceMonitorTest : public TestBase { Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; - DangerousDeprecatedTestTime test_time_; Event::DispatcherImpl dispatcher_; const std::string resource_filename_; AtomicFileUpdater file_updater_; diff --git a/test/extensions/transport_sockets/tls/ssl_socket_test.cc b/test/extensions/transport_sockets/tls/ssl_socket_test.cc index 10d4d6e064d44..0be696fe23cad 100644 --- a/test/extensions/transport_sockets/tls/ssl_socket_test.cc +++ b/test/extensions/transport_sockets/tls/ssl_socket_test.cc @@ -183,11 +183,11 @@ void testUtil(const TestUtilOptions& options) { server_tls_context); auto server_cfg = std::make_unique(server_tls_context, server_factory_context); - ContextManagerImpl manager(time_system); + ContextManagerImpl manager(*time_system); ServerSslSocketFactory server_ssl_socket_factory(std::move(server_cfg), manager, server_stats_store, std::vector{}); - Event::DispatcherImpl dispatcher(time_system, *server_api); + Event::DispatcherImpl dispatcher(*server_api); Network::TcpListenSocket socket(Network::Test::getCanonicalLoopbackAddress(options.version()), nullptr, true); Network::MockListenerCallbacks callbacks; @@ -394,7 +394,7 @@ class TestUtilOptionsV2 : public TestUtilOptionsBase { const std::string testUtilV2(const TestUtilOptionsV2& options) { Event::SimulatedTimeSystem time_system; - ContextManagerImpl manager(time_system); + ContextManagerImpl manager(*time_system); std::string new_session = EMPTY_STRING; // SNI-based selection logic isn't happening in SslSocket anymore. @@ -413,7 +413,7 @@ const std::string testUtilV2(const TestUtilOptionsV2& options) { ServerSslSocketFactory server_ssl_socket_factory(std::move(server_cfg), manager, server_stats_store, server_names); - Event::DispatcherImpl dispatcher(time_system, *server_api); + Event::DispatcherImpl dispatcher(*server_api); Network::TcpListenSocket socket(Network::Test::getCanonicalLoopbackAddress(options.version()), nullptr, true); NiceMock callbacks; @@ -588,7 +588,7 @@ void configureServerAndExpiredClientCertificate(envoy::api::v2::Listener& listen class SslSocketTest : public SslCertsTest, public testing::WithParamInterface { protected: - SslSocketTest() : dispatcher_(std::make_unique(time_system_, *api_)) {} + SslSocketTest() : dispatcher_(std::make_unique(*api_)) {} void testClientSessionResumption(const std::string& server_ctx_yaml, const std::string& client_ctx_yaml, bool expect_reuse, @@ -2103,7 +2103,7 @@ void testTicketSessionResumption(const std::string& server_ctx_yaml1, const std::string& client_ctx_yaml, bool expect_reuse, const Network::Address::IpVersion ip_version) { Event::SimulatedTimeSystem time_system; - ContextManagerImpl manager(time_system); + ContextManagerImpl manager(*time_system); Stats::IsolatedStoreImpl server_stats_store; Api::ApiPtr server_api = Api::createApiForTest(server_stats_store); @@ -2131,7 +2131,7 @@ void testTicketSessionResumption(const std::string& server_ctx_yaml1, true); NiceMock callbacks; Network::MockConnectionHandler connection_handler; - Event::DispatcherImpl dispatcher(time_system, *server_api); + Event::DispatcherImpl dispatcher(*server_api); Network::ListenerPtr listener1 = dispatcher.createListener(socket1, callbacks, true, false); Network::ListenerPtr listener2 = dispatcher.createListener(socket2, callbacks, true, false); @@ -2654,7 +2654,7 @@ void SslSocketTest::testClientSessionResumption(const std::string& server_ctx_ya NiceMock callbacks; Network::MockConnectionHandler connection_handler; Api::ApiPtr api = Api::createApiForTest(server_stats_store); - Event::DispatcherImpl dispatcher(time_system_, *server_api); + Event::DispatcherImpl dispatcher(*server_api); Network::ListenerPtr listener = dispatcher.createListener(socket, callbacks, true, false); Network::ConnectionPtr server_connection; @@ -3662,8 +3662,8 @@ class SslReadBufferLimitTest : public SslSocketTest { void singleWriteTest(uint32_t read_buffer_limit, uint32_t bytes_to_write) { MockWatermarkBuffer* client_write_buffer = nullptr; MockBufferFactory* factory = new StrictMock; - dispatcher_ = std::make_unique( - time_system_, Buffer::WatermarkFactoryPtr{factory}, *api_); + dispatcher_ = + std::make_unique(Buffer::WatermarkFactoryPtr{factory}, *api_); // By default, expect 4 buffers to be created - the client and server read and write buffers. EXPECT_CALL(*factory, create_(_, _)) diff --git a/test/integration/echo_integration_test.cc b/test/integration/echo_integration_test.cc index da64a31270779..e91fe26f5ee17 100644 --- a/test/integration/echo_integration_test.cc +++ b/test/integration/echo_integration_test.cc @@ -10,7 +10,7 @@ std::string echo_config; class EchoIntegrationTest : public BaseIntegrationTest, public TestBaseWithParam { public: - EchoIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), echo_config) {} + EchoIntegrationTest() : BaseIntegrationTest(GetParam(), echo_config) {} // Called once by the gtest framework before any EchoIntegrationTests are run. static void SetUpTestSuite() { diff --git a/test/integration/fake_upstream.cc b/test/integration/fake_upstream.cc index 0a48b7e0c526f..2e9bc4786411b 100644 --- a/test/integration/fake_upstream.cc +++ b/test/integration/fake_upstream.cc @@ -374,7 +374,7 @@ FakeUpstream::FakeUpstream(Network::TransportSocketFactoryPtr&& transport_socket Event::TestTimeSystem& time_system, bool enable_half_close) : http_type_(type), socket_(std::move(listen_socket)), api_(Api::createApiForTest(stats_store_)), time_system_(time_system), - dispatcher_(api_->allocateDispatcher(time_system_)), + dispatcher_(api_->allocateDispatcher()), handler_(new Server::ConnectionHandlerImpl(ENVOY_LOGGER(), *dispatcher_)), allow_unexpected_disconnects_(false), enable_half_close_(enable_half_close), listener_(*this), filter_chain_(Network::Test::createEmptyFilterChain(std::move(transport_socket_factory))) { diff --git a/test/integration/http_integration.cc b/test/integration/http_integration.cc index 3b5eba31906a2..a06b8cc67c03c 100644 --- a/test/integration/http_integration.cc +++ b/test/integration/http_integration.cc @@ -204,9 +204,8 @@ HttpIntegrationTest::makeHttpConnection(Network::ClientConnectionPtr&& conn) { HttpIntegrationTest::HttpIntegrationTest(Http::CodecClient::Type downstream_protocol, Network::Address::IpVersion version, - TestTimeSystemPtr time_system, const std::string& config) - : BaseIntegrationTest(version, std::move(time_system), config), - downstream_protocol_(downstream_protocol) { + const std::string& config) + : BaseIntegrationTest(version, config), downstream_protocol_(downstream_protocol) { // Legacy integration tests expect the default listener to be named "http" for lookupPort calls. config_helper_.renameListener("http"); config_helper_.setClientCodec(typeToCodecType(downstream_protocol_)); diff --git a/test/integration/http_integration.h b/test/integration/http_integration.h index a0d2b0d2bc8a9..743b009f0c049 100644 --- a/test/integration/http_integration.h +++ b/test/integration/http_integration.h @@ -80,7 +80,11 @@ typedef std::unique_ptr IntegrationCodecClientPtr; class HttpIntegrationTest : public BaseIntegrationTest { public: HttpIntegrationTest(Http::CodecClient::Type downstream_protocol, - Network::Address::IpVersion version, TestTimeSystemPtr time_system, + Network::Address::IpVersion version, TestTimeSystemPtr, + const std::string& config = ConfigHelper::HTTP_PROXY_CONFIG) + : HttpIntegrationTest(downstream_protocol, version, config) {} + HttpIntegrationTest(Http::CodecClient::Type downstream_protocol, + Network::Address::IpVersion version, const std::string& config = ConfigHelper::HTTP_PROXY_CONFIG); virtual ~HttpIntegrationTest(); diff --git a/test/integration/http_protocol_integration.h b/test/integration/http_protocol_integration.h index 36d47b7a038e7..2939c795612e1 100644 --- a/test/integration/http_protocol_integration.h +++ b/test/integration/http_protocol_integration.h @@ -48,7 +48,7 @@ class HttpProtocolIntegrationTest : public HttpIntegrationTest, protocolTestParamsToString(const ::testing::TestParamInfo& p); HttpProtocolIntegrationTest() - : HttpIntegrationTest(GetParam().downstream_protocol, GetParam().version, realTime()) {} + : HttpIntegrationTest(GetParam().downstream_protocol, GetParam().version) {} void SetUp() override { setDownstreamProtocol(GetParam().downstream_protocol); diff --git a/test/integration/integration.cc b/test/integration/integration.cc index ac57ca81079dc..6147978f30887 100644 --- a/test/integration/integration.cc +++ b/test/integration/integration.cc @@ -227,20 +227,21 @@ void IntegrationTcpClient::ConnectionCallbacks::onEvent(Network::ConnectionEvent } BaseIntegrationTest::BaseIntegrationTest(Network::Address::IpVersion version, - TestTimeSystemPtr time_system, const std::string& config) + const std::string& config) : api_(Api::createApiForTest(stats_store_)), - mock_buffer_factory_(new NiceMock), time_system_(std::move(time_system)), - dispatcher_(new Event::DispatcherImpl( - *time_system_, Buffer::WatermarkFactoryPtr{mock_buffer_factory_}, *api_)), + mock_buffer_factory_(new NiceMock), + dispatcher_( + new Event::DispatcherImpl(Buffer::WatermarkFactoryPtr{mock_buffer_factory_}, *api_)), version_(version), config_helper_(version, *api_, config), default_log_level_(TestEnvironment::getOptions().logLevel()) { + // This is a hack, but there are situations where we disconnect fake upstream connections and // then we expect the server connection pool to get the disconnect before the next test starts. // This does not always happen. This pause should allow the server to pick up the disconnect // notification and clear the pool connection if necessary. A real fix would require adding fairly // complex test hooks to the server and/or spin waiting on stats, neither of which I think are // necessary right now. - time_system_->sleep(std::chrono::milliseconds(10)); + timeSystem().sleep(std::chrono::milliseconds(10)); ON_CALL(*mock_buffer_factory_, create_(_, _)) .WillByDefault(Invoke([](std::function below_low, std::function above_high) -> Buffer::Instance* { @@ -273,10 +274,10 @@ void BaseIntegrationTest::createUpstreams() { for (uint32_t i = 0; i < fake_upstreams_count_; ++i) { if (autonomous_upstream_) { fake_upstreams_.emplace_back( - new AutonomousUpstream(0, upstream_protocol_, version_, *time_system_)); + new AutonomousUpstream(0, upstream_protocol_, version_, timeSystem())); } else { fake_upstreams_.emplace_back( - new FakeUpstream(0, upstream_protocol_, version_, *time_system_, enable_half_close_)); + new FakeUpstream(0, upstream_protocol_, version_, timeSystem(), enable_half_close_)); } } } @@ -369,7 +370,7 @@ void BaseIntegrationTest::createGeneratedApiTestServer(const std::string& bootst const std::vector& port_names) { test_server_ = IntegrationTestServer::create(bootstrap_path, version_, pre_worker_start_test_steps_, deterministic_, - *time_system_, *api_, defer_listener_finalization_); + timeSystem(), *api_, defer_listener_finalization_); if (config_helper_.bootstrap().static_resources().listeners_size() > 0 && !defer_listener_finalization_) { // Wait for listeners to be created before invoking registerTestServerPorts() below, as that @@ -400,7 +401,7 @@ void BaseIntegrationTest::createTestServer(const std::string& json_path, const std::vector& port_names) { test_server_ = createIntegrationTestServer( TestEnvironment::temporaryFileSubstitute(json_path, port_map_, version_), nullptr, - *time_system_); + timeSystem()); registerTestServerPorts(port_names); } diff --git a/test/integration/integration.h b/test/integration/integration.h index ccd662caf39ec..15a77c66d0b67 100644 --- a/test/integration/integration.h +++ b/test/integration/integration.h @@ -132,20 +132,15 @@ class BaseIntegrationTest : Logger::Loggable { public: using TestTimeSystemPtr = std::unique_ptr; - BaseIntegrationTest(Network::Address::IpVersion version, TestTimeSystemPtr time_system, + BaseIntegrationTest(Network::Address::IpVersion version, const std::string& config = ConfigHelper::HTTP_PROXY_CONFIG); + BaseIntegrationTest(Network::Address::IpVersion version, TestTimeSystemPtr, + const std::string& config = ConfigHelper::HTTP_PROXY_CONFIG) + : BaseIntegrationTest(version, config) {} virtual ~BaseIntegrationTest() {} - /** - * Helper function to create a simulated time integration test during construction. - */ - static TestTimeSystemPtr simTime() { return std::make_unique(); } - - /** - * Helper function to create a wall-clock time integration test during construction. - */ - static TestTimeSystemPtr realTime() { return std::make_unique(); } + static TestTimeSystemPtr realTime() { return TestTimeSystemPtr(); } // Initialize the basic proto configuration, create fake upstreams, and start Envoy. virtual void initialize(); @@ -182,7 +177,7 @@ class BaseIntegrationTest : Logger::Loggable { void createApiTestServer(const ApiFilesystemConfig& api_filesystem_config, const std::vector& port_names); - Event::TestTimeSystem& timeSystem() { return *time_system_; } + Event::TestTimeSystem& timeSystem() { return time_system_; } Stats::IsolatedStoreImpl stats_store_; Api::ApiPtr api_; @@ -210,7 +205,7 @@ class BaseIntegrationTest : Logger::Loggable { } private: - TestTimeSystemPtr time_system_; + Event::GlobalTimeSystem time_system_; public: Event::DispatcherPtr dispatcher_; diff --git a/test/integration/integration_admin_test.cc b/test/integration/integration_admin_test.cc index 0dcdf795a00c1..120f7ebbb45bd 100644 --- a/test/integration/integration_admin_test.cc +++ b/test/integration/integration_admin_test.cc @@ -450,12 +450,12 @@ TEST_F(IntegrationAdminIpv4Ipv6Test, Ipv4Ipv6Listen) { // Testing the behavior of StatsMatcher, which allows/denies the instantiation of stats based on // restrictions on their names. class StatsMatcherIntegrationTest - : public HttpIntegrationTest, + : public Event::SimulatedTimeSystem, + public HttpIntegrationTest, public TestBase, public testing::WithParamInterface { public: - StatsMatcherIntegrationTest() - : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), simTime()) {} + StatsMatcherIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {} void initialize() override { config_helper_.addConfigModifier( diff --git a/test/integration/utility.cc b/test/integration/utility.cc index 5eb7c783cc751..f7d46289ceece 100644 --- a/test/integration/utility.cc +++ b/test/integration/utility.cc @@ -61,9 +61,10 @@ IntegrationUtil::makeSingleRequest(const Network::Address::InstanceConstSharedPt const std::string& host, const std::string& content_type) { NiceMock mock_stats_store; - Api::Impl api(std::chrono::milliseconds(9000), Thread::threadFactoryForTest(), mock_stats_store); Event::GlobalTimeSystem time_system; - Event::DispatcherPtr dispatcher(api.allocateDispatcher(*time_system)); + Api::Impl api(std::chrono::milliseconds(9000), Thread::threadFactoryForTest(), mock_stats_store, + time_system); + Event::DispatcherPtr dispatcher(api.allocateDispatcher()); std::shared_ptr cluster{new NiceMock()}; Upstream::HostDescriptionConstSharedPtr host_description{ Upstream::makeTestHostDescription(cluster, "tcp://127.0.0.1:80")}; @@ -112,7 +113,7 @@ RawConnectionDriver::RawConnectionDriver(uint32_t port, Buffer::Instance& initia Network::Address::IpVersion version) { api_ = Api::createApiForTest(stats_store_); Event::GlobalTimeSystem time_system; - dispatcher_ = api_->allocateDispatcher(*time_system); + dispatcher_ = api_->allocateDispatcher(); callbacks_ = std::make_unique(); client_ = dispatcher_->createClientConnection( Network::Utility::resolveUrl( diff --git a/test/mocks/api/BUILD b/test/mocks/api/BUILD index 6a5be0ab4f1e5..65ae8f1431d8a 100644 --- a/test/mocks/api/BUILD +++ b/test/mocks/api/BUILD @@ -18,6 +18,6 @@ envoy_cc_mock( "//source/common/api:os_sys_calls_lib", "//source/common/common:assert_lib", "//test/mocks/filesystem:filesystem_mocks", - "//test/test_common:test_time_system_interface", + "//test/test_common:test_time_lib", ], ) diff --git a/test/mocks/api/mocks.cc b/test/mocks/api/mocks.cc index 4aab4c9c1759e..27fcb28593c45 100644 --- a/test/mocks/api/mocks.cc +++ b/test/mocks/api/mocks.cc @@ -17,6 +17,10 @@ MockApi::MockApi() { ON_CALL(*this, fileSystem()).WillByDefault(ReturnRef(file_s MockApi::~MockApi() {} +Event::DispatcherPtr MockApi::allocateDispatcher() { + return Event::DispatcherPtr{allocateDispatcher_(timeSystem())}; +} + MockOsSysCalls::MockOsSysCalls() { num_writes_ = num_open_ = 0; } MockOsSysCalls::~MockOsSysCalls() {} diff --git a/test/mocks/api/mocks.h b/test/mocks/api/mocks.h index 31dc57f9fe236..e1d495f83a62d 100644 --- a/test/mocks/api/mocks.h +++ b/test/mocks/api/mocks.h @@ -12,7 +12,7 @@ #include "common/api/os_sys_calls_impl.h" #include "test/mocks/filesystem/mocks.h" -#include "test/test_common/test_time_system.h" +#include "test/test_common/test_time.h" #include "gmock/gmock.h" @@ -25,15 +25,15 @@ class MockApi : public Api { ~MockApi(); // Api::Api - Event::DispatcherPtr allocateDispatcher(Event::TimeSystem& time_system) override { - return Event::DispatcherPtr{allocateDispatcher_(time_system)}; - } + Event::DispatcherPtr allocateDispatcher() override; + Event::TimeSystem& timeSystem() override { return time_system_; } MOCK_METHOD1(allocateDispatcher_, Event::Dispatcher*(Event::TimeSystem&)); MOCK_METHOD0(fileSystem, Filesystem::Instance&()); MOCK_METHOD0(threadFactory, Thread::ThreadFactory&()); testing::NiceMock file_system_; + Event::GlobalTimeSystem time_system_; }; class MockOsSysCalls : public OsSysCallsImpl { diff --git a/test/mocks/server/mocks.cc b/test/mocks/server/mocks.cc index c0ab9e59f422e..ce37f26c1ca02 100644 --- a/test/mocks/server/mocks.cc +++ b/test/mocks/server/mocks.cc @@ -179,6 +179,7 @@ MockFactoryContext::MockFactoryContext() ON_CALL(*this, threadLocal()).WillByDefault(ReturnRef(thread_local_)); ON_CALL(*this, admin()).WillByDefault(ReturnRef(admin_)); ON_CALL(*this, listenerScope()).WillByDefault(ReturnRef(listener_scope_)); + ON_CALL(*this, api()).WillByDefault(ReturnRef(api_)); ON_CALL(*this, timeSource()).WillByDefault(ReturnRef(time_system_)); ON_CALL(*this, overloadManager()).WillByDefault(ReturnRef(overload_manager_)); ON_CALL(*this, api()).WillByDefault(ReturnRef(api_)); diff --git a/test/server/BUILD b/test/server/BUILD index 0ba84d4870b45..813ac24ee5267 100644 --- a/test/server/BUILD +++ b/test/server/BUILD @@ -174,6 +174,7 @@ envoy_cc_test( "//test/test_common:environment_lib", "//test/test_common:registry_lib", "//test/test_common:simulated_time_system_lib", + "//test/test_common:test_time_lib", "//test/test_common:threadsafe_singleton_injector_lib", ], ) @@ -251,7 +252,6 @@ envoy_cc_test( "//test/mocks/network:network_mocks", "//test/mocks/server:server_mocks", "//test/mocks/thread_local:thread_local_mocks", - "//test/test_common:test_time_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/server/config_validation/BUILD b/test/server/config_validation/BUILD index 6015d898495c1..a1e274b2ebd9b 100644 --- a/test/server/config_validation/BUILD +++ b/test/server/config_validation/BUILD @@ -18,7 +18,6 @@ envoy_cc_test( "//source/server/config_validation:dns_lib", "//test/mocks/http:http_mocks", "//test/mocks/upstream:upstream_mocks", - "//test/test_common:test_time_lib", ], ) diff --git a/test/server/config_validation/async_client_test.cc b/test/server/config_validation/async_client_test.cc index 7dfc5e3a6e6b6..dceb4dafafb3e 100644 --- a/test/server/config_validation/async_client_test.cc +++ b/test/server/config_validation/async_client_test.cc @@ -6,7 +6,6 @@ #include "test/mocks/http/mocks.h" #include "test/mocks/upstream/mocks.h" -#include "test/test_common/test_time.h" namespace Envoy { namespace Http { @@ -16,10 +15,9 @@ TEST(ValidationAsyncClientTest, MockedMethods) { MockAsyncClientCallbacks callbacks; MockAsyncClientStreamCallbacks stream_callbacks; - DangerousDeprecatedTestTime test_time; Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - ValidationAsyncClient client(test_time.timeSystem(), *api); + ValidationAsyncClient client(*api); EXPECT_EQ(nullptr, client.send(std::move(message), callbacks, AsyncClient::RequestOptions())); EXPECT_EQ(nullptr, client.start(stream_callbacks, AsyncClient::StreamOptions())); } diff --git a/test/server/config_validation/cluster_manager_test.cc b/test/server/config_validation/cluster_manager_test.cc index 86a3d9dd7765d..3b976a80f8271 100644 --- a/test/server/config_validation/cluster_manager_test.cc +++ b/test/server/config_validation/cluster_manager_test.cc @@ -19,7 +19,6 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/mocks/upstream/mocks.h" -#include "test/test_common/simulated_time_system.h" #include "test/test_common/utility.h" namespace Envoy { @@ -29,12 +28,11 @@ TEST(ValidationClusterManagerTest, MockedMethods) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api(Api::createApiForTest(stats_store)); NiceMock runtime; - Event::SimulatedTimeSystem time_system; NiceMock tls; NiceMock random; testing::NiceMock secret_manager; auto dns_resolver = std::make_shared>(); - Extensions::TransportSockets::Tls::ContextManagerImpl ssl_context_manager{time_system}; + Extensions::TransportSockets::Tls::ContextManagerImpl ssl_context_manager{api->timeSystem()}; NiceMock dispatcher; LocalInfo::MockLocalInfo local_info; NiceMock admin; diff --git a/test/server/config_validation/dispatcher_test.cc b/test/server/config_validation/dispatcher_test.cc index 7f7342380e721..db5e41dfcce5f 100644 --- a/test/server/config_validation/dispatcher_test.cc +++ b/test/server/config_validation/dispatcher_test.cc @@ -24,9 +24,10 @@ class ConfigValidation : public TestBaseWithParam { ConfigValidation() { Event::Libevent::Global::initialize(); - validation_ = std::make_unique( - std::chrono::milliseconds(1000), Thread::threadFactoryForTest(), stats_store_); - dispatcher_ = validation_->allocateDispatcher(test_time_.timeSystem()); + validation_ = std::make_unique(std::chrono::milliseconds(1000), + Thread::threadFactoryForTest(), + stats_store_, test_time_.timeSystem()); + dispatcher_ = validation_->allocateDispatcher(); } DangerousDeprecatedTestTime test_time_; diff --git a/test/server/guarddog_impl_test.cc b/test/server/guarddog_impl_test.cc index b2bd21eef329b..c61ac7946f347 100644 --- a/test/server/guarddog_impl_test.cc +++ b/test/server/guarddog_impl_test.cc @@ -26,7 +26,7 @@ namespace Server { class GuardDogTestBase : public TestBase { protected: - GuardDogTestBase() : api_(Api::createApiForTest(stats_store_)) {} + GuardDogTestBase() : api_(Api::createApiForTest(stats_store_, time_system_)) {} Event::SimulatedTimeSystem time_system_; Stats::IsolatedStoreImpl stats_store_; @@ -51,7 +51,7 @@ class GuardDogDeathTest : public GuardDogTestBase { */ void SetupForDeath() { InSequence s; - guard_dog_ = std::make_unique(fakestats_, config_kill_, time_system_, *api_); + guard_dog_ = std::make_unique(fakestats_, config_kill_, *api_); unpet_dog_ = guard_dog_->createWatchDog(api_->threadFactory().currentThreadId()); guard_dog_->forceCheckForTest(); time_system_.sleep(std::chrono::milliseconds(500)); @@ -63,7 +63,7 @@ class GuardDogDeathTest : public GuardDogTestBase { */ void SetupForMultiDeath() { InSequence s; - guard_dog_ = std::make_unique(fakestats_, config_multikill_, time_system_, *api_); + guard_dog_ = std::make_unique(fakestats_, config_multikill_, *api_); auto unpet_dog_ = guard_dog_->createWatchDog(api_->threadFactory().currentThreadId()); guard_dog_->forceCheckForTest(); auto second_dog_ = guard_dog_->createWatchDog(api_->threadFactory().currentThreadId()); @@ -120,7 +120,7 @@ TEST_F(GuardDogAlmostDeadTest, NearDeathTest) { // This ensures that if only one thread surpasses the multiple kill threshold // there is no death. The positive case is covered in MultiKillDeathTest. InSequence s; - GuardDogImpl gd(fakestats_, config_multikill_, time_system_, *api_); + GuardDogImpl gd(fakestats_, config_multikill_, *api_); auto unpet_dog = gd.createWatchDog(api_->threadFactory().currentThreadId()); auto pet_dog = gd.createWatchDog(api_->threadFactory().currentThreadId()); // This part "waits" 600 milliseconds while one dog is touched every 100, and @@ -146,7 +146,7 @@ class GuardDogMissTest : public GuardDogTestBase { TEST_F(GuardDogMissTest, MissTest) { // This test checks the actual collected statistics after doing some timer // advances that should and shouldn't increment the counters. - GuardDogImpl gd(stats_store_, config_miss_, time_system_, *api_); + GuardDogImpl gd(stats_store_, config_miss_, *api_); // We'd better start at 0: EXPECT_EQ(0UL, stats_store_.counter("server.watchdog_miss").value()); auto unpet_dog = gd.createWatchDog(api_->threadFactory().currentThreadId()); @@ -165,7 +165,7 @@ TEST_F(GuardDogMissTest, MissTest) { TEST_F(GuardDogMissTest, MegaMissTest) { // This test checks the actual collected statistics after doing some timer // advances that should and shouldn't increment the counters. - GuardDogImpl gd(stats_store_, config_mega_, time_system_, *api_); + GuardDogImpl gd(stats_store_, config_mega_, *api_); auto unpet_dog = gd.createWatchDog(api_->threadFactory().currentThreadId()); // We'd better start at 0: EXPECT_EQ(0UL, stats_store_.counter("server.watchdog_mega_miss").value()); @@ -185,7 +185,7 @@ TEST_F(GuardDogMissTest, MissCountTest) { // This tests a flake discovered in the MissTest where real timeout or // spurious condition_variable wakeup causes the counter to get incremented // more than it should be. - GuardDogImpl gd(stats_store_, config_miss_, time_system_, *api_); + GuardDogImpl gd(stats_store_, config_miss_, *api_); auto sometimes_pet_dog = gd.createWatchDog(api_->threadFactory().currentThreadId()); // These steps are executed once without ever touching the watchdog. // Then the last step is to touch the watchdog and repeat the steps. @@ -225,27 +225,27 @@ TEST_F(GuardDogMissTest, MissCountTest) { TEST_F(GuardDogTestBase, StartStopTest) { NiceMock stats; NiceMock config(0, 0, 0, 0); - GuardDogImpl gd(stats, config, time_system_, *api_); + GuardDogImpl gd(stats, config, *api_); } TEST_F(GuardDogTestBase, LoopIntervalNoKillTest) { NiceMock stats; NiceMock config(40, 50, 0, 0); - GuardDogImpl gd(stats, config, time_system_, *api_); + GuardDogImpl gd(stats, config, *api_); EXPECT_EQ(gd.loopIntervalForTest(), 40); } TEST_F(GuardDogTestBase, LoopIntervalTest) { NiceMock stats; NiceMock config(100, 90, 1000, 500); - GuardDogImpl gd(stats, config, time_system_, *api_); + GuardDogImpl gd(stats, config, *api_); EXPECT_EQ(gd.loopIntervalForTest(), 90); } TEST_F(GuardDogTestBase, WatchDogThreadIdTest) { NiceMock stats; NiceMock config(100, 90, 1000, 500); - GuardDogImpl gd(stats, config, time_system_, *api_); + GuardDogImpl gd(stats, config, *api_); auto watched_dog = gd.createWatchDog(api_->threadFactory().currentThreadId()); EXPECT_EQ(watched_dog->threadId().debugString(), api_->threadFactory().currentThreadId()->debugString()); diff --git a/test/server/listener_manager_impl_test.cc b/test/server/listener_manager_impl_test.cc index 2da9582823033..616b29e36a53c 100644 --- a/test/server/listener_manager_impl_test.cc +++ b/test/server/listener_manager_impl_test.cc @@ -60,8 +60,7 @@ class ListenerManagerImplTest : public TestBase { ListenerManagerImplTest() : api_(Api::createApiForTest(stats_)) { ON_CALL(server_, api()).WillByDefault(ReturnRef(*api_)); EXPECT_CALL(worker_factory_, createWorker_()).WillOnce(Return(worker_)); - manager_ = std::make_unique(server_, listener_factory_, worker_factory_, - time_system_); + manager_ = std::make_unique(server_, listener_factory_, worker_factory_); } /** diff --git a/test/server/worker_impl_test.cc b/test/server/worker_impl_test.cc index 0be4f48732037..06775542ab02d 100644 --- a/test/server/worker_impl_test.cc +++ b/test/server/worker_impl_test.cc @@ -7,7 +7,6 @@ #include "test/mocks/server/mocks.h" #include "test/mocks/thread_local/mocks.h" #include "test/test_common/test_base.h" -#include "test/test_common/test_time.h" #include "test/test_common/utility.h" using testing::_; @@ -31,12 +30,11 @@ class WorkerImplTest : public TestBase { Stats::IsolatedStoreImpl stats_store_; NiceMock tls_; - DangerousDeprecatedTestTime test_time; Network::MockConnectionHandler* handler_ = new Network::MockConnectionHandler(); NiceMock guard_dog_; NiceMock overload_manager_; Api::ApiPtr api_; - Event::DispatcherImpl* dispatcher_ = new Event::DispatcherImpl(test_time.timeSystem(), *api_); + Event::DispatcherImpl* dispatcher_ = new Event::DispatcherImpl(*api_); DefaultTestHooks hooks_; WorkerImpl worker_{tls_, hooks_, diff --git a/test/test_common/BUILD b/test/test_common/BUILD index 0aa8c4956b797..b314e54f0c13e 100644 --- a/test/test_common/BUILD +++ b/test/test_common/BUILD @@ -90,6 +90,7 @@ envoy_cc_test_library( "abseil_strings", ], deps = [ + ":test_time_lib", "//include/envoy/buffer:buffer_interface", "//include/envoy/http:codec_interface", "//include/envoy/network:address_interface", diff --git a/test/test_common/environment.cc b/test/test_common/environment.cc index 5097558f1ff95..266a9a446676a 100644 --- a/test/test_common/environment.cc +++ b/test/test_common/environment.cc @@ -124,7 +124,7 @@ absl::optional TestEnvironment::getOptionalEnvVar(const std::string std::string TestEnvironment::getCheckedEnvVar(const std::string& var) { auto optional = getOptionalEnvVar(var); - RELEASE_ASSERT(optional.has_value(), ""); + RELEASE_ASSERT(optional.has_value(), var); return optional.value(); } diff --git a/test/test_common/utility.cc b/test/test_common/utility.cc index 4b10d5208c446..e88e7a9d4e539 100644 --- a/test/test_common/utility.cc +++ b/test/test_common/utility.cc @@ -38,6 +38,7 @@ #include "common/filesystem/directory.h" #include "test/test_common/printers.h" +#include "test/test_common/test_time.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" @@ -400,11 +401,27 @@ ThreadFactory& threadFactoryForTest() { namespace Api { +class TimeSystemProvider { +protected: + Event::GlobalTimeSystem global_time_system_; +}; + +class TestImpl : public TimeSystemProvider, public Impl { +public: + TestImpl(std::chrono::milliseconds file_flush_interval_msec, + Thread::ThreadFactory& thread_factory, Stats::Store& stats_store) + : Impl(file_flush_interval_msec, thread_factory, stats_store, global_time_system_) {} +}; + ApiPtr createApiForTest(Stats::Store& stat_store) { + return std::make_unique(std::chrono::milliseconds(1000), Thread::threadFactoryForTest(), + stat_store); +} + +ApiPtr createApiForTest(Stats::Store& stat_store, Event::TimeSystem& time_system) { return std::make_unique(std::chrono::milliseconds(1000), Thread::threadFactoryForTest(), - stat_store); + stat_store, time_system); } } // namespace Api - } // namespace Envoy diff --git a/test/test_common/utility.h b/test/test_common/utility.h index 02726229002c2..c61b49b57a01e 100644 --- a/test/test_common/utility.h +++ b/test/test_common/utility.h @@ -527,6 +527,7 @@ ThreadFactory& threadFactoryForTest(); namespace Api { ApiPtr createApiForTest(Stats::Store& stat_store); +ApiPtr createApiForTest(Stats::Store& stat_store, Event::TimeSystem& time_system); } // namespace Api MATCHER_P(HeaderMapEqualIgnoreOrder, rhs, "") { diff --git a/tools/bootstrap2pb.cc b/tools/bootstrap2pb.cc index fb2b539617995..8b298b3da8c49 100644 --- a/tools/bootstrap2pb.cc +++ b/tools/bootstrap2pb.cc @@ -13,6 +13,7 @@ #include "common/api/api_impl.h" #include "common/common/assert.h" +#include "common/event/real_time_system.h" #include "common/protobuf/utility.h" #include "common/stats/isolated_store_impl.h" @@ -28,8 +29,9 @@ int main(int argc, char** argv) { Envoy::PlatformImpl platform_impl_; Envoy::Stats::IsolatedStoreImpl stats_store; - Envoy::Api::Impl api(std::chrono::milliseconds(1000), platform_impl_.threadFactory(), - stats_store); + Envoy::Event::RealTimeSystem time_system; // NO_CHECK_FORMAT(real_time) + Envoy::Api::Impl api(std::chrono::milliseconds(1000), platform_impl_.threadFactory(), stats_store, + time_system); envoy::config::bootstrap::v2::Bootstrap bootstrap; Envoy::MessageUtil::loadFromFile(argv[1], bootstrap, api); diff --git a/tools/v1_to_bootstrap.cc b/tools/v1_to_bootstrap.cc index 74f5763d87adb..48f8861552898 100644 --- a/tools/v1_to_bootstrap.cc +++ b/tools/v1_to_bootstrap.cc @@ -12,6 +12,7 @@ #include "common/api/api_impl.h" #include "common/config/bootstrap_json.h" +#include "common/event/real_time_system.h" #include "common/json/json_loader.h" #include "common/protobuf/utility.h" #include "common/stats/isolated_store_impl.h" @@ -28,8 +29,9 @@ int main(int argc, char** argv) { Envoy::PlatformImpl platform_impl_; Envoy::Stats::IsolatedStoreImpl stats_store; - Envoy::Api::Impl api(std::chrono::milliseconds(1000), platform_impl_.threadFactory(), - stats_store); + Envoy::Event::RealTimeSystem time_system; // NO_CHECK_FORMAT(real_time) + Envoy::Api::Impl api(std::chrono::milliseconds(1000), platform_impl_.threadFactory(), stats_store, + time_system); envoy::config::bootstrap::v2::Bootstrap bootstrap; auto config_json = Envoy::Json::Factory::loadFromFile(argv[1], api); From a06b9a8b352dc5d81e515bbbaea78f9b43ba7d20 Mon Sep 17 00:00:00 2001 From: Dan Rosen Date: Tue, 5 Feb 2019 12:50:08 -0500 Subject: [PATCH 21/51] upstream: host weight ranges from 1 to 128 (#5831) Fix some incorrect comments about the range of valid host weights, and updated Maglev LB implementation to assume weights are always non-zero. Risk Level: Low Testing: Existing tests, including maglev_lb_test and upstream_impl_test. Signed-off-by: Dan Rosen --- include/envoy/upstream/upstream.h | 6 +++-- source/common/upstream/maglev_lb.cc | 37 ++++++++++++++++------------- 2 files changed, 25 insertions(+), 18 deletions(-) diff --git a/include/envoy/upstream/upstream.h b/include/envoy/upstream/upstream.h index 610338d44b223..e280ab7f515f7 100644 --- a/include/envoy/upstream/upstream.h +++ b/include/envoy/upstream/upstream.h @@ -164,12 +164,14 @@ class Host : virtual public HostDescription { virtual void setOutlierDetector(Outlier::DetectorHostMonitorPtr&& outlier_detector) PURE; /** - * @return the current load balancing weight of the host, in the range 1-100. + * @return the current load balancing weight of the host, in the range 1-128 (see + * envoy.api.v2.endpoint.Endpoint.load_balancing_weight). */ virtual uint32_t weight() const PURE; /** - * Set the current load balancing weight of the host, in the range 1-100. + * Set the current load balancing weight of the host, in the range 1-128 (see + * envoy.api.v2.endpoint.Endpoint.load_balancing_weight). */ virtual void weight(uint32_t new_weight) PURE; diff --git a/source/common/upstream/maglev_lb.cc b/source/common/upstream/maglev_lb.cc index 8e3e91359722d..292f901aed4c7 100644 --- a/source/common/upstream/maglev_lb.cc +++ b/source/common/upstream/maglev_lb.cc @@ -13,17 +13,25 @@ MaglevTable::MaglevTable(const HostsPerLocality& hosts_per_locality, // not good!). ASSERT(Primes::isPrime(table_size)); + // Sanity-check that the locality weights, if provided, line up with the hosts per locality. + if (locality_weights != nullptr) { + ASSERT(locality_weights->size() == hosts_per_locality.get().size()); + } + // Compute host weight combined with locality weight where applicable. const auto effective_weight = [&locality_weights](uint32_t host_weight, uint32_t locality_index) -> uint32_t { - if (locality_weights == nullptr || locality_weights->empty()) { + ASSERT(host_weight != 0); + if (locality_weights == nullptr) { return host_weight; } else { - return host_weight * (*locality_weights)[locality_index]; + auto locality_weight = (*locality_weights)[locality_index]; + ASSERT(locality_weight != 0); + return host_weight * locality_weight; } }; - // Compute maximum host weight. If this is zero, we are doing unweighted Maglev. + // Compute maximum host weight. uint32_t max_host_weight = 0; uint32_t total_hosts = 0; for (uint32_t i = 0; i < hosts_per_locality.get().size(); ++i) { @@ -46,8 +54,7 @@ MaglevTable::MaglevTable(const HostsPerLocality& hosts_per_locality, const std::string& address = host->address()->asString(); table_build_entries.emplace_back(host, HashUtil::xxHash64(address) % table_size_, (HashUtil::xxHash64(address, 1) % (table_size_ - 1)) + 1, - max_host_weight > 0 ? effective_weight(host->weight(), i) - : 0); + effective_weight(host->weight(), i)); } } @@ -57,18 +64,16 @@ MaglevTable::MaglevTable(const HostsPerLocality& hosts_per_locality, while (true) { for (uint64_t i = 0; i < table_build_entries.size(); i++) { TableBuildEntry& entry = table_build_entries[i]; - // Only consider weight if we are doing weighted Maglev. - if (max_host_weight > 0) { - // Counts are in units of max_host_weight. To understand how counts_ and - // weight_ are used below, consider a host with weight equal to - // max_host_weight. This would be picked on every single iteration. If - // it had weight equal to backend_weight_scale / 3, then this would only - // happen every 3 iterations, etc. - if (iteration * entry.weight_ < entry.counts_) { - continue; - } - entry.counts_ += max_host_weight; + // Counts are in units of max_host_weight. To understand how counts_ and + // weight_ are used below, consider a host with weight equal to + // max_host_weight. This would be picked on every single iteration. If + // it had weight equal to backend_weight_scale / 3, then this would only + // happen every 3 iterations, etc. + if (iteration * entry.weight_ < entry.counts_) { + ASSERT(max_host_weight > 1); + continue; } + entry.counts_ += max_host_weight; uint64_t c = permutation(entry); while (table_[c] != nullptr) { entry.next_++; From f23d8084aecabbe850caf598b3caaa89ef312ec2 Mon Sep 17 00:00:00 2001 From: Sergey Glushchenko Date: Tue, 5 Feb 2019 20:25:29 +0100 Subject: [PATCH 22/51] filesystem: path sanity checking for fileReadToEnd(). (#5765) Do not allow Filesystem::fileReadToEnd() for files in /dev, /proc and /sys. Risk Level: Low Testing: New unit test. Fixes: #3170 Signed-off-by: Sergey Glushchenko --- source/common/filesystem/filesystem_impl.cc | 4 ++++ test/common/filesystem/filesystem_impl_test.cc | 6 ++++++ .../injected_resource/injected_resource_monitor_test.cc | 2 +- 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/source/common/filesystem/filesystem_impl.cc b/source/common/filesystem/filesystem_impl.cc index 06492edac6ab4..1fd3ce8a455cd 100644 --- a/source/common/filesystem/filesystem_impl.cc +++ b/source/common/filesystem/filesystem_impl.cc @@ -70,6 +70,10 @@ ssize_t InstanceImpl::fileSize(const std::string& path) { } std::string InstanceImpl::fileReadToEnd(const std::string& path) { + if (illegalPath(path)) { + throw EnvoyException(fmt::format("Invalid path: {}", path)); + } + std::ios::sync_with_stdio(false); std::ifstream file(path); diff --git a/test/common/filesystem/filesystem_impl_test.cc b/test/common/filesystem/filesystem_impl_test.cc index 3bc30c6a14c7c..3f675d9696165 100644 --- a/test/common/filesystem/filesystem_impl_test.cc +++ b/test/common/filesystem/filesystem_impl_test.cc @@ -97,6 +97,12 @@ TEST_F(FileSystemImplTest, fileReadToEndDoesNotExist) { EnvoyException); } +TEST_F(FileSystemImplTest, fileReadToEndBlacklisted) { + EXPECT_THROW(file_system_.fileReadToEnd("/dev/urandom"), EnvoyException); + EXPECT_THROW(file_system_.fileReadToEnd("/proc/cpuinfo"), EnvoyException); + EXPECT_THROW(file_system_.fileReadToEnd("/sys/block/sda/dev"), EnvoyException); +} + TEST_F(FileSystemImplTest, CanonicalPathSuccess) { EXPECT_EQ("/", file_system_.canonicalPath("//").rc_); } diff --git a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc index 4955ef58bd982..a173600bfff2d 100644 --- a/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc +++ b/test/extensions/resource_monitors/injected_resource/injected_resource_monitor_test.cc @@ -97,7 +97,7 @@ TEST_F(InjectedResourceMonitorTest, ReportsErrorForOutOfRangePressure) { } TEST_F(InjectedResourceMonitorTest, ReportsErrorOnFileRead) { - EXPECT_CALL(cb_, onFailure(ExceptionContains("unable to read file"))); + EXPECT_CALL(cb_, onFailure(ExceptionContains("Invalid path"))); monitor_->updateResourceUsage(cb_); } From 6b216b3abeb655f52f4890d93232b1e73545b775 Mon Sep 17 00:00:00 2001 From: Kyle Larose Date: Tue, 5 Feb 2019 15:03:59 -0500 Subject: [PATCH 23/51] upstream: add connpool map (#5670) This class allows clients to map keys to connection pools, returning the existing pool if it already exists. Signed-off-by: Kyle Larose --- source/common/common/BUILD | 6 + .../common/common/debug_recursion_checker.h | 42 ++++ source/common/upstream/BUILD | 19 ++ .../common/upstream/cluster_manager_impl.cc | 107 +++++--- source/common/upstream/cluster_manager_impl.h | 14 +- source/common/upstream/conn_pool_map.h | 61 +++++ source/common/upstream/conn_pool_map_impl.h | 67 +++++ test/common/upstream/BUILD | 13 + .../upstream/conn_pool_map_impl_test.cc | 235 ++++++++++++++++++ 9 files changed, 522 insertions(+), 42 deletions(-) create mode 100644 source/common/common/debug_recursion_checker.h create mode 100644 source/common/upstream/conn_pool_map.h create mode 100644 source/common/upstream/conn_pool_map_impl.h create mode 100644 test/common/upstream/conn_pool_map_impl_test.cc diff --git a/source/common/common/BUILD b/source/common/common/BUILD index 76ed1b37bc4bf..6b1d9c0209868 100644 --- a/source/common/common/BUILD +++ b/source/common/common/BUILD @@ -21,6 +21,12 @@ envoy_cc_library( deps = [":minimal_logger_lib"], ) +envoy_cc_library( + name = "debug_recursion_checker_lib", + hdrs = ["debug_recursion_checker.h"], + deps = [":assert_lib"], +) + envoy_cc_library( name = "backoff_lib", srcs = ["backoff_strategy.cc"], diff --git a/source/common/common/debug_recursion_checker.h b/source/common/common/debug_recursion_checker.h new file mode 100644 index 0000000000000..e2ab275ca219d --- /dev/null +++ b/source/common/common/debug_recursion_checker.h @@ -0,0 +1,42 @@ +#pragma once + +#include "common/common/assert.h" + +namespace Envoy { +namespace Common { +/** + * A helper class to assert that a call is not recursive. + */ +class DebugRecursionChecker { +public: + void enter() { + ASSERT(!entered_, "A resource should only be entered once"); +#if !defined(NDEBUG) + entered_ = true; +#endif // !defined(NDEBUG) + } + + void exit() { +#if !defined(NDEBUG) + entered_ = false; +#endif // !defined(NDEBUG) + } + +private: + bool entered_ = false; +}; + +class AutoDebugRecursionChecker { +public: + explicit AutoDebugRecursionChecker(DebugRecursionChecker& checker) : checker_(checker) { + checker.enter(); + } + + ~AutoDebugRecursionChecker() { checker_.exit(); } + +private: + DebugRecursionChecker& checker_; +}; + +} // namespace Common +} // namespace Envoy diff --git a/source/common/upstream/BUILD b/source/common/upstream/BUILD index 6a1b53f365bd4..aaad5800e0d1a 100644 --- a/source/common/upstream/BUILD +++ b/source/common/upstream/BUILD @@ -60,12 +60,31 @@ envoy_cc_library( "//source/common/protobuf:utility_lib", "//source/common/router:shadow_writer_lib", "//source/common/tcp:conn_pool_lib", + "//source/common/upstream:conn_pool_map", + "//source/common/upstream:conn_pool_map_impl_lib", "//source/common/upstream:upstream_lib", "@envoy_api//envoy/admin/v2alpha:config_dump_cc", "@envoy_api//envoy/api/v2/core:base_cc", ], ) +envoy_cc_library( + name = "conn_pool_map", + hdrs = ["conn_pool_map.h"], + deps = [ + "//include/envoy/event:dispatcher_interface", + "//source/common/common:debug_recursion_checker_lib", + ], +) + +envoy_cc_library( + name = "conn_pool_map_impl_lib", + hdrs = ["conn_pool_map_impl.h"], + deps = [ + ":conn_pool_map", + ], +) + envoy_cc_library( name = "edf_scheduler_lib", hdrs = ["edf_scheduler.h"], diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index dd11deb034f13..46d96b2320ac9 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -30,6 +30,7 @@ #include "common/router/shadow_writer_impl.h" #include "common/tcp/conn_pool.h" #include "common/upstream/cds_api_impl.h" +#include "common/upstream/conn_pool_map_impl.h" #include "common/upstream/load_balancer_impl.h" #include "common/upstream/maglev_lb.h" #include "common/upstream/original_dst_cluster.h" @@ -817,9 +818,9 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::~ThreadLocalClusterManagerImp void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools(const HostVector& hosts) { for (const HostSharedPtr& host : hosts) { { - auto container = host_http_conn_pool_map_.find(host); - if (container != host_http_conn_pool_map_.end()) { - drainConnPools(host, container->second); + auto container = getHttpConnPoolsContainer(host); + if (container != nullptr) { + drainConnPools(host, *container); } } { @@ -833,38 +834,49 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools(const Hos void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools( HostSharedPtr old_host, ConnPoolsContainer& container) { - container.drains_remaining_ += container.pools_.size(); - - for (const auto& pair : container.pools_) { - pair.second->addDrainedCallback([this, old_host]() -> void { - if (destroying_) { - // It is possible for a connection pool to fire drain callbacks during destruction. Instead - // of checking if old_host actually exists in the map, it's clearer and cleaner to keep - // track of destruction as a separate state and check for it here. This also allows us to - // do this check here versus inside every different connection pool implementation. - return; - } + container.drains_remaining_ += container.pools_->size(); + + // Make a copy to protect against erasure in the callback. + std::shared_ptr pools = container.pools_; + pools->addDrainedCallback([this, old_host]() -> void { + if (destroying_) { + // It is possible for a connection pool to fire drain callbacks during destruction. Instead + // of checking if old_host actually exists in the map, it's clearer and cleaner to keep + // track of destruction as a separate state and check for it here. This also allows us to + // do this check here versus inside every different connection pool implementation. + return; + } - ConnPoolsContainer& container = host_http_conn_pool_map_[old_host]; - ASSERT(container.drains_remaining_ > 0); - container.drains_remaining_--; - if (container.drains_remaining_ == 0) { - for (auto& pair : container.pools_) { - thread_local_dispatcher_.deferredDelete(std::move(pair.second)); - } - host_http_conn_pool_map_.erase(old_host); - } - }); + ConnPoolsContainer* to_clear = getHttpConnPoolsContainer(old_host); + if (to_clear == nullptr) { + // This could happen if we have cleaned out the host before iterating through every connection + // pool. Handle it by just continuing. + return; + } - // The above addDrainedCallback() drain completion callback might execute immediately. This can - // then effectively nuke 'container', which means we can't continue to loop on its contents - // (we're done here). - if (host_http_conn_pool_map_.count(old_host) == 0) { - break; + ASSERT(to_clear->drains_remaining_ > 0); + to_clear->drains_remaining_--; + if (to_clear->drains_remaining_ == 0 && to_clear->ready_to_drain_) { + clearContainer(old_host, *to_clear); } + }); + + // We need to hold off on actually emptying out the container until we have finished processing + // `addDrainedCallback`. If we do not, then it's possible that the container could be erased in + // the middle of its iteration, which leads to undefined behaviour. We handle that case by + // checking here to see if the drains have completed. + container.ready_to_drain_ = true; + if (container.drains_remaining_ == 0) { + clearContainer(old_host, container); } } +void ClusterManagerImpl::ThreadLocalClusterManagerImpl::clearContainer( + HostSharedPtr old_host, ConnPoolsContainer& container) { + container.pools_->clear(); + host_http_conn_pool_map_.erase(old_host); +} + void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainTcpConnPools( HostSharedPtr old_host, TcpConnPoolsContainer& container) { container.drains_remaining_ += container.pools_.size(); @@ -946,12 +958,9 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::onHostHealthFailure( // more targeted. ThreadLocalClusterManagerImpl& config = tls.getTyped(); { - const auto& container = config.host_http_conn_pool_map_.find(host); - if (container != config.host_http_conn_pool_map_.end()) { - for (const auto& pair : container->second.pools_) { - const Http::ConnectionPool::InstancePtr& pool = pair.second; - pool->drainConnections(); - } + const auto container = config.getHttpConnPoolsContainer(host); + if (container != nullptr) { + container->pools_->drainConnections(); } } { @@ -986,6 +995,21 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::onHostHealthFailure( } } +ClusterManagerImpl::ThreadLocalClusterManagerImpl::ConnPoolsContainer* +ClusterManagerImpl::ThreadLocalClusterManagerImpl::getHttpConnPoolsContainer( + const HostConstSharedPtr& host, bool allocate) { + auto container_iter = host_http_conn_pool_map_.find(host); + if (container_iter == host_http_conn_pool_map_.end()) { + if (!allocate) { + return nullptr; + } + ConnPoolsContainer container{thread_local_dispatcher_}; + container_iter = host_http_conn_pool_map_.emplace(host, std::move(container)).first; + } + + return &container_iter->second; +} + ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::ClusterEntry( ThreadLocalClusterManagerImpl& parent, ClusterInfoConstSharedPtr cluster, const LoadBalancerFactorySharedPtr& lb_factory) @@ -1092,14 +1116,17 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::connPool( } } - ConnPoolsContainer& container = parent_.host_http_conn_pool_map_[host]; - if (!container.pools_[hash_key]) { - container.pools_[hash_key] = parent_.parent_.factory_.allocateConnPool( + ConnPoolsContainer& container = *parent_.getHttpConnPoolsContainer(host, true); + + // Note: to simplify this, we assume that the factory is only called in the scope of this + // function. Otherwise, we'd need to capture a few of these variables by value. + Http::ConnectionPool::Instance& pool = container.pools_->getPool(hash_key, [&]() { + return parent_.parent_.factory_.allocateConnPool( parent_.thread_local_dispatcher_, host, priority, protocol, have_options ? context->downstreamConnection()->socketOptions() : nullptr); - } + }); - return container.pools_[hash_key].get(); + return &pool; } Tcp::ConnectionPool::Instance* diff --git a/source/common/upstream/cluster_manager_impl.h b/source/common/upstream/cluster_manager_impl.h index f9a3bf5abc870..04431ca14742e 100644 --- a/source/common/upstream/cluster_manager_impl.h +++ b/source/common/upstream/cluster_manager_impl.h @@ -22,6 +22,7 @@ #include "common/config/grpc_mux_impl.h" #include "common/http/async_client_impl.h" +#include "common/upstream/conn_pool_map.h" #include "common/upstream/load_stats_reporter.h" #include "common/upstream/upstream_impl.h" @@ -231,9 +232,14 @@ class ClusterManagerImpl : public ClusterManager, Logger::Loggable, Http::ConnectionPool::InstancePtr> ConnPools; + ConnPoolsContainer(Event::Dispatcher& dispatcher) + : pools_{std::make_shared(dispatcher)} {} - ConnPools pools_; + typedef ConnPoolMap, Http::ConnectionPool::Instance> ConnPools; + + // This is a shared_ptr so we can keep it alive while cleaning up. + std::shared_ptr pools_; + bool ready_to_drain_{false}; uint64_t drains_remaining_{}; }; @@ -307,6 +313,7 @@ class ClusterManagerImpl : public ClusterManager, Logger::Loggable thread_local_clusters_; diff --git a/source/common/upstream/conn_pool_map.h b/source/common/upstream/conn_pool_map.h new file mode 100644 index 0000000000000..c602c5dd96bc2 --- /dev/null +++ b/source/common/upstream/conn_pool_map.h @@ -0,0 +1,61 @@ +#pragma once + +#include + +#include "envoy/event/dispatcher.h" + +#include "common/common/debug_recursion_checker.h" + +#include "absl/container/flat_hash_map.h" + +namespace Envoy { +namespace Upstream { +/** + * A class mapping keys to connection pools, with some recycling logic built in. + */ +template class ConnPoolMap { +public: + using PoolFactory = std::function()>; + using DrainedCb = std::function; + + ConnPoolMap(Event::Dispatcher& dispatcher); + ~ConnPoolMap(); + /** + * Returns an existing pool for `key`, or creates a new one using `factory`. Note that it is + * possible for this to fail if a limit on the number of pools allowed is reached. + * @return The pool corresponding to `key`, or `absl::nullopt`. + */ + POOL_TYPE& getPool(KEY_TYPE key, const PoolFactory& factory); + + /** + * @return the number of pools. + */ + size_t size() const; + + /** + * Destroys all mapped pools. + */ + void clear(); + + /** + * Adds a drain callback to all mapped pools. Any future mapped pools with have the callback + * automatically added. Be careful with the callback. If it itself calls into `this`, modifying + * the state of `this`, there is a good chance it will cause corruption due to the callback firing + * immediately. + */ + void addDrainedCallback(const DrainedCb& cb); + + /** + * Instructs each connection pool to drain its connections. + */ + void drainConnections(); + +private: + absl::flat_hash_map> active_pools_; + Event::Dispatcher& thread_local_dispatcher_; + std::vector cached_callbacks_; + Common::DebugRecursionChecker recursion_checker_; +}; + +} // namespace Upstream +} // namespace Envoy diff --git a/source/common/upstream/conn_pool_map_impl.h b/source/common/upstream/conn_pool_map_impl.h new file mode 100644 index 0000000000000..518805106ca93 --- /dev/null +++ b/source/common/upstream/conn_pool_map_impl.h @@ -0,0 +1,67 @@ +#pragma once + +#include "common/upstream/conn_pool_map.h" + +namespace Envoy { +namespace Upstream { + +template +ConnPoolMap::ConnPoolMap(Envoy::Event::Dispatcher& dispatcher) + : thread_local_dispatcher_(dispatcher) {} + +template +ConnPoolMap::~ConnPoolMap() = default; + +template +POOL_TYPE& ConnPoolMap::getPool(KEY_TYPE key, const PoolFactory& factory) { + Common::AutoDebugRecursionChecker assert_not_in(recursion_checker_); + // TODO(klarose): Consider how we will change the connection pool's configuration in the future. + // The plan is to change the downstream socket options... We may want to take those as a parameter + // here. Maybe we'll pass them to the factory function? + auto inserted = active_pools_.emplace(key, nullptr); + + // If we inserted a new element, create a pool and assign it to the iterator. Tell it about any + // cached callbacks. + if (inserted.second) { + inserted.first->second = factory(); + for (const auto& cb : cached_callbacks_) { + inserted.first->second->addDrainedCallback(cb); + } + } + + return *inserted.first->second; +} + +template +size_t ConnPoolMap::size() const { + return active_pools_.size(); +} + +template void ConnPoolMap::clear() { + Common::AutoDebugRecursionChecker assert_not_in(recursion_checker_); + for (auto& pool_pair : active_pools_) { + thread_local_dispatcher_.deferredDelete(std::move(pool_pair.second)); + } + + active_pools_.clear(); +} + +template +void ConnPoolMap::addDrainedCallback(const DrainedCb& cb) { + Common::AutoDebugRecursionChecker assert_not_in(recursion_checker_); + for (auto& pool_pair : active_pools_) { + pool_pair.second->addDrainedCallback(cb); + } + + cached_callbacks_.emplace_back(std::move(cb)); +} + +template +void ConnPoolMap::drainConnections() { + Common::AutoDebugRecursionChecker assert_not_in(recursion_checker_); + for (auto& pool_pair : active_pools_) { + pool_pair.second->drainConnections(); + } +} +} // namespace Upstream +} // namespace Envoy diff --git a/test/common/upstream/BUILD b/test/common/upstream/BUILD index cddee4ad412fd..f40a35b0d640b 100644 --- a/test/common/upstream/BUILD +++ b/test/common/upstream/BUILD @@ -60,6 +60,19 @@ envoy_cc_test( ], ) +envoy_cc_test( + name = "conn_pool_map_impl_test", + srcs = ["conn_pool_map_impl_test.cc"], + deps = [ + "//include/envoy/http:conn_pool_interface", + "//source/common/upstream:conn_pool_map_impl_lib", + "//test/mocks:common_lib", + "//test/mocks/event:event_mocks", + "//test/mocks/http:conn_pool_mocks", + "//test/test_common:utility_lib", + ], +) + envoy_cc_test( name = "edf_scheduler_test", srcs = ["edf_scheduler_test.cc"], diff --git a/test/common/upstream/conn_pool_map_impl_test.cc b/test/common/upstream/conn_pool_map_impl_test.cc new file mode 100644 index 0000000000000..11de76b94ea6d --- /dev/null +++ b/test/common/upstream/conn_pool_map_impl_test.cc @@ -0,0 +1,235 @@ +#include +#include + +#include "envoy/http/conn_pool.h" + +#include "common/upstream/conn_pool_map_impl.h" + +#include "test/mocks/common.h" +#include "test/mocks/event/mocks.h" +#include "test/mocks/http/conn_pool.h" +#include "test/test_common/test_base.h" +#include "test/test_common/utility.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +using testing::Invoke; +using testing::NiceMock; +using testing::SaveArg; + +namespace Envoy { +namespace Upstream { + +class ConnPoolMapImplTest : public TestBase { +public: + // Note, we could test with Http::ConnectionPool::MockInstance here, which would simplify the + // test. However, it's nice to test against an actual interface we'll be using. + using TestMap = ConnPoolMap; + using TestMapPtr = std::unique_ptr; + + TestMapPtr makeTestMap() { return std::make_unique(dispatcher_); } + + TestMap::PoolFactory getBasicFactory() { + return [&]() { + auto pool = std::make_unique>(); + mock_pools_.push_back(pool.get()); + return pool; + }; + } + + TestMap::PoolFactory getFactoryExpectDrainedCb(Http::ConnectionPool::Instance::DrainedCb* cb) { + return [this, cb]() { + auto pool = std::make_unique>(); + EXPECT_CALL(*pool, addDrainedCallback(_)).WillOnce(SaveArg<0>(cb)); + mock_pools_.push_back(pool.get()); + return pool; + }; + } + +protected: + NiceMock dispatcher_; + std::vector*> mock_pools_; +}; + +TEST_F(ConnPoolMapImplTest, TestMapIsEmptyOnConstruction) { + TestMapPtr test_map = makeTestMap(); + + EXPECT_EQ(test_map->size(), 0); +} + +TEST_F(ConnPoolMapImplTest, TestAddingAConnPoolIncreasesSize) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + EXPECT_EQ(test_map->size(), 1); +} + +TEST_F(ConnPoolMapImplTest, TestAddingTwoConnPoolsIncreasesSize) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + test_map->getPool(2, getBasicFactory()); + EXPECT_EQ(test_map->size(), 2); +} + +TEST_F(ConnPoolMapImplTest, TestConnPoolReturnedMatchesCreated) { + TestMapPtr test_map = makeTestMap(); + + Http::ConnectionPool::Instance& pool = test_map->getPool(1, getBasicFactory()); + EXPECT_EQ(&pool, mock_pools_[0]); +} + +TEST_F(ConnPoolMapImplTest, TestConnSecondPoolReturnedMatchesCreated) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + Http::ConnectionPool::Instance& pool = test_map->getPool(2, getBasicFactory()); + EXPECT_EQ(&pool, mock_pools_[1]); +} + +TEST_F(ConnPoolMapImplTest, TestMultipleOfSameKeyReturnsOriginal) { + TestMapPtr test_map = makeTestMap(); + + Http::ConnectionPool::Instance& pool1 = test_map->getPool(1, getBasicFactory()); + Http::ConnectionPool::Instance& pool2 = test_map->getPool(2, getBasicFactory()); + + EXPECT_EQ(&pool1, &test_map->getPool(1, getBasicFactory())); + EXPECT_EQ(&pool2, &test_map->getPool(2, getBasicFactory())); + EXPECT_EQ(test_map->size(), 2); +} + +TEST_F(ConnPoolMapImplTest, TestEmptyClerWorks) { + TestMapPtr test_map = makeTestMap(); + + test_map->clear(); + EXPECT_EQ(test_map->size(), 0); +} + +TEST_F(ConnPoolMapImplTest, TestClearEmptiesOutMap) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + test_map->getPool(2, getBasicFactory()); + + test_map->clear(); + EXPECT_EQ(test_map->size(), 0); +} + +TEST_F(ConnPoolMapImplTest, CallbacksPassedToPools) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + test_map->getPool(2, getBasicFactory()); + Http::ConnectionPool::Instance::DrainedCb cb1; + EXPECT_CALL(*mock_pools_[0], addDrainedCallback(_)).WillOnce(SaveArg<0>(&cb1)); + Http::ConnectionPool::Instance::DrainedCb cb2; + EXPECT_CALL(*mock_pools_[1], addDrainedCallback(_)).WillOnce(SaveArg<0>(&cb2)); + + ReadyWatcher watcher; + test_map->addDrainedCallback([&watcher] { watcher.ready(); }); + + EXPECT_CALL(watcher, ready()).Times(2); + cb1(); + cb2(); +} + +// Tests that if we add the callback first, it is passed along when pools are created later. +TEST_F(ConnPoolMapImplTest, CallbacksCachedAndPassedOnCreation) { + TestMapPtr test_map = makeTestMap(); + + ReadyWatcher watcher; + test_map->addDrainedCallback([&watcher] { watcher.ready(); }); + + Http::ConnectionPool::Instance::DrainedCb cb1; + test_map->getPool(1, getFactoryExpectDrainedCb(&cb1)); + + Http::ConnectionPool::Instance::DrainedCb cb2; + test_map->getPool(2, getFactoryExpectDrainedCb(&cb2)); + + EXPECT_CALL(watcher, ready()).Times(2); + cb1(); + cb2(); +} + +// Tests that if we drain connections on an empty map, nothing happens. +TEST_F(ConnPoolMapImplTest, EmptyMapDrainConnectionsNop) { + TestMapPtr test_map = makeTestMap(); + test_map->drainConnections(); +} + +// Tests that we forward drainConnections to the pools. +TEST_F(ConnPoolMapImplTest, DrainConnectionsForwarded) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + test_map->getPool(2, getBasicFactory()); + EXPECT_CALL(*mock_pools_[0], drainConnections()); + EXPECT_CALL(*mock_pools_[1], drainConnections()); + + test_map->drainConnections(); +} + +TEST_F(ConnPoolMapImplTest, ClearDefersDelete) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + test_map->getPool(2, getBasicFactory()); + test_map->clear(); + + EXPECT_EQ(dispatcher_.to_delete_.size(), 2); +} + +// The following tests only die in debug builds, so don't run them if this isn't one. +#if !defined(NDEBUG) +class ConnPoolMapImplDeathTest : public ConnPoolMapImplTest {}; + +TEST_F(ConnPoolMapImplDeathTest, ReentryClearTripsAssert) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + ON_CALL(*mock_pools_[0], addDrainedCallback(_)) + .WillByDefault(Invoke([](Http::ConnectionPool::Instance::DrainedCb cb) { cb(); })); + + EXPECT_DEATH_LOG_TO_STDERR(test_map->addDrainedCallback([&test_map] { test_map->clear(); }), + ".*Details: A resource should only be entered once"); +} + +TEST_F(ConnPoolMapImplDeathTest, ReentryGetPoolTripsAssert) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + ON_CALL(*mock_pools_[0], addDrainedCallback(_)) + .WillByDefault(Invoke([](Http::ConnectionPool::Instance::DrainedCb cb) { cb(); })); + + EXPECT_DEATH_LOG_TO_STDERR( + test_map->addDrainedCallback([&test_map, this] { test_map->getPool(2, getBasicFactory()); }), + ".*Details: A resource should only be entered once"); +} + +TEST_F(ConnPoolMapImplDeathTest, ReentryDrainConnectionsTripsAssert) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + ON_CALL(*mock_pools_[0], addDrainedCallback(_)) + .WillByDefault(Invoke([](Http::ConnectionPool::Instance::DrainedCb cb) { cb(); })); + + EXPECT_DEATH_LOG_TO_STDERR( + test_map->addDrainedCallback([&test_map] { test_map->drainConnections(); }), + ".*Details: A resource should only be entered once"); +} + +TEST_F(ConnPoolMapImplDeathTest, ReentryAddDrainedCallbackTripsAssert) { + TestMapPtr test_map = makeTestMap(); + + test_map->getPool(1, getBasicFactory()); + ON_CALL(*mock_pools_[0], addDrainedCallback(_)) + .WillByDefault(Invoke([](Http::ConnectionPool::Instance::DrainedCb cb) { cb(); })); + + EXPECT_DEATH_LOG_TO_STDERR( + test_map->addDrainedCallback([&test_map] { test_map->addDrainedCallback([]() {}); }), + ".*Details: A resource should only be entered once"); +} +#endif // !defined(NDEBUG) +} // namespace Upstream +} // namespace Envoy From 98a441f153fbecf3f7fc4c6135ed1bbcf9c7e49f Mon Sep 17 00:00:00 2001 From: htuch Date: Tue, 5 Feb 2019 15:50:41 -0500 Subject: [PATCH 24/51] build: fix oss-fuzz build. (#5843) Due to the external_cmake changes (amongst others), we've regressed on the fuzzer build. We need to do the final link now inside the cc_binary, as external_cmake has issues with transitivity and unrelated binaries (see https://github.com/bazelbuild/rules_foreign_cc/issues/222). Risk level: Low Testing: oss-fuzz Docker build for Envoy's fuzzers. Signed-off-by: Harvey Tuch --- bazel/envoy_build_system.bzl | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/bazel/envoy_build_system.bzl b/bazel/envoy_build_system.bzl index a8b314a8677d9..437b12c086a24 100644 --- a/bazel/envoy_build_system.bzl +++ b/bazel/envoy_build_system.bzl @@ -357,10 +357,15 @@ def envoy_cc_fuzz_test(name, corpus, deps = [], tags = [], **kwargs): }), tags = tags, ) + + # This target exists only for + # https://github.com/google/oss-fuzz/blob/master/projects/envoy/build.sh. It won't yield + # anything useful on its own, as it expects to be run in an environment where the linker options + # provide a path to FuzzingEngine. native.cc_binary( name = name + "_driverless", copts = envoy_copts("@envoy", test = True), - linkopts = envoy_test_linkopts(), + linkopts = ["-lFuzzingEngine"] + envoy_test_linkopts(), linkstatic = 1, testonly = 1, deps = [":" + test_lib_name], From 8ddd3b7ceefc5116c80457528b9c876f172e3ff1 Mon Sep 17 00:00:00 2001 From: ZHANG Dapeng Date: Tue, 5 Feb 2019 17:09:23 -0800 Subject: [PATCH 25/51] api: fix wrong java_package option in a proto file (#5853) Signed-off-by: Penn (Dapeng) Zhang --- api/envoy/config/common/tap/v2alpha/common.proto | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/envoy/config/common/tap/v2alpha/common.proto b/api/envoy/config/common/tap/v2alpha/common.proto index a7b587e3ba38c..a52016d81a6fb 100644 --- a/api/envoy/config/common/tap/v2alpha/common.proto +++ b/api/envoy/config/common/tap/v2alpha/common.proto @@ -8,7 +8,7 @@ package envoy.config.common.tap.v2alpha; option java_outer_classname = "CommonProto"; option java_multiple_files = true; -option java_package = "io.envoyproxy.envoy.service.tap.v2alpha"; +option java_package = "io.envoyproxy.envoy.config.common.tap.v2alpha"; // [#protodoc-title: Common tap extension configuration] From f9107b26ccca409a13716b7b094bd87fec9765fb Mon Sep 17 00:00:00 2001 From: Bill DeCoste Date: Tue, 5 Feb 2019 17:09:43 -0800 Subject: [PATCH 26/51] add assertion for null/reset connection file event (#5848) Signed-off-by: William DeCoste --- source/common/network/connection_impl.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/source/common/network/connection_impl.cc b/source/common/network/connection_impl.cc index 91947d04fa39a..84a9289071a7f 100644 --- a/source/common/network/connection_impl.cc +++ b/source/common/network/connection_impl.cc @@ -386,6 +386,7 @@ void ConnectionImpl::write(Buffer::Instance& data, bool end_stream) { // doWriteReady into thinking the socket is connected. On macOS, the underlying write may fail // with a connection error if a call to write(2) occurs before the connection is completed. if (!connecting_) { + ASSERT(file_event_ != nullptr, "ConnectionImpl file event was unexpectedly reset"); file_event_->activate(Event::FileReadyType::Write); } } From cfd8fab879b14f55f396f79b48e336fbb7cbca25 Mon Sep 17 00:00:00 2001 From: htuch Date: Wed, 6 Feb 2019 10:20:31 -0500 Subject: [PATCH 27/51] fuzz: avoid leaking time system singleton. (#5850) * fuzz: avoid leaking time system singleton. Previously we were seeing: FAIL: Active singletons exist: Unexpected active singleton: N5Envoy5Event25SingletonTimeSystemHelperE at the end of each fuzz test. Risk level: Low Testing: bazel test //test/common/access_log:access_log_formatter_fuzz_test --test_output=streamed --test_arg="-l trace" -c dbg --config=clang-asan --test_output=all Signed-off-by: Harvey Tuch --- test/fuzz/main.cc | 34 +++++++++++++++++++--------------- 1 file changed, 19 insertions(+), 15 deletions(-) diff --git a/test/fuzz/main.cc b/test/fuzz/main.cc index 023a5078cc1ca..6d54b325850a4 100644 --- a/test/fuzz/main.cc +++ b/test/fuzz/main.cc @@ -52,21 +52,25 @@ int main(int argc, char** argv) { RELEASE_ASSERT(argc >= 2, ""); // Consider any file after the test path which doesn't have a - prefix to be a corpus entry. uint32_t input_args = 0; - Envoy::Stats::IsolatedStoreImpl stats_store; - Envoy::Api::ApiPtr api = Envoy::Api::createApiForTest(stats_store); - for (int i = 1; i < argc; ++i) { - const std::string arg{argv[i]}; - if (arg.empty() || arg[0] == '-') { - break; - } - ++input_args; - // Outputs from envoy_directory_genrule might be directories or we might - // have artisanal files. - if (api->fileSystem().directoryExists(arg)) { - const auto paths = Envoy::TestUtility::listFiles(arg, true); - Envoy::test_corpus_.insert(Envoy::test_corpus_.begin(), paths.begin(), paths.end()); - } else { - Envoy::test_corpus_.emplace_back(arg); + // Ensure we cleanup API resources before we jump into the tests, the test API creates a singleton + // time system that we don't want to leak into gtest. + { + Envoy::Stats::IsolatedStoreImpl stats_store; + Envoy::Api::ApiPtr api = Envoy::Api::createApiForTest(stats_store); + for (int i = 1; i < argc; ++i) { + const std::string arg{argv[i]}; + if (arg.empty() || arg[0] == '-') { + break; + } + ++input_args; + // Outputs from envoy_directory_genrule might be directories or we might + // have artisanal files. + if (api->fileSystem().directoryExists(arg)) { + const auto paths = Envoy::TestUtility::listFiles(arg, true); + Envoy::test_corpus_.insert(Envoy::test_corpus_.begin(), paths.begin(), paths.end()); + } else { + Envoy::test_corpus_.emplace_back(arg); + } } } argc -= input_args; From 13a3bbc9359eda8b5201864fd2f09d9fe8924a9d Mon Sep 17 00:00:00 2001 From: Lizan Zhou Date: Wed, 6 Feb 2019 07:32:03 -0800 Subject: [PATCH 28/51] ci: collect bazel profile and store in artifacts (#5857) Signed-off-by: Lizan Zhou --- .circleci/config.yml | 19 +++++++++++++------ ci/build_setup.sh | 6 +++++- ci/do_ci.sh | 8 ++++++++ 3 files changed, 26 insertions(+), 7 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 290475d9b52a1..93d74d757170c 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -22,7 +22,8 @@ jobs: - run: ci/docker_push.sh - run: ci/docker_tag.sh - store_artifacts: - path: /build/envoy/generated/failed-testlogs + path: /build/envoy/generated + destination: / asan: executor: ubuntu-build steps: @@ -33,7 +34,8 @@ jobs: - checkout - run: ci/do_circle_ci.sh bazel.asan - store_artifacts: - path: /build/envoy/generated/failed-testlogs + path: /build/envoy/generated + destination: / tsan: executor: ubuntu-build steps: @@ -41,7 +43,9 @@ jobs: - checkout - run: ci/do_circle_ci.sh bazel.tsan - store_artifacts: - path: /build/envoy/generated/failed-testlogs + path: /build/envoy/generated + destination: / + compile_time_options: executor: ubuntu-build steps: @@ -49,7 +53,8 @@ jobs: - checkout - run: ci/do_circle_ci.sh bazel.compile_time_options - store_artifacts: - path: /build/envoy/generated/failed-testlogs + path: /build/envoy/generated + destination: / api: executor: ubuntu-build steps: @@ -61,7 +66,8 @@ jobs: - "fb:f3:fe:be:1c:b2:ec:b6:25:f9:7b:a6:87:54:02:8c" - run: ci/api_mirror.sh - store_artifacts: - path: /build/envoy/generated/failed-testlogs + path: /build/envoy/generated + destination: / filter_example_mirror: executor: ubuntu-build steps: @@ -105,7 +111,8 @@ jobs: no_output_timeout: 60m - run: ci/coverage_publish.sh - store_artifacts: - path: /build/envoy/generated/coverage + path: /build/envoy/generated + destination: / clang_tidy: executor: ubuntu-build diff --git a/ci/build_setup.sh b/ci/build_setup.sh index ac65f1da4fabd..e586191606967 100755 --- a/ci/build_setup.sh +++ b/ci/build_setup.sh @@ -64,7 +64,7 @@ BAZEL_OPTIONS="--package_path %workspace%:${ENVOY_SRCDIR}" export BAZEL_QUERY_OPTIONS="${BAZEL_OPTIONS}" export BAZEL_BUILD_OPTIONS="--strategy=Genrule=standalone --spawn_strategy=standalone \ --verbose_failures ${BAZEL_OPTIONS} --action_env=HOME --action_env=PYTHONUSERBASE \ - --jobs=${NUM_CPUS} --show_task_finish ${BAZEL_BUILD_EXTRA_OPTIONS}" + --jobs=${NUM_CPUS} --show_task_finish --experimental_generate_json_trace_profile ${BAZEL_BUILD_EXTRA_OPTIONS}" export BAZEL_TEST_OPTIONS="${BAZEL_BUILD_OPTIONS} --test_env=HOME --test_env=PYTHONUSERBASE \ --test_env=UBSAN_OPTIONS=print_stacktrace=1 \ --cache_test_results=no --test_output=all ${BAZEL_EXTRA_TEST_OPTIONS}" @@ -109,6 +109,10 @@ mkdir -p "${ENVOY_COVERAGE_DIR}" export ENVOY_FAILED_TEST_LOGS="${ENVOY_BUILD_DIR}"/generated/failed-testlogs mkdir -p "${ENVOY_FAILED_TEST_LOGS}" +# This is where we copy the build profile to. +export ENVOY_BUILD_PROFILE="${ENVOY_BUILD_DIR}"/generated/build-profile +mkdir -p "${ENVOY_BUILD_PROFILE}" + # This is where we build for bazel.release* and bazel.dev. export ENVOY_CI_DIR="${ENVOY_SRCDIR}"/ci diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 5a8085a46fa11..f31ae0d30ff55 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -16,6 +16,10 @@ fi echo "building using ${NUM_CPUS} CPUs" +function collect_build_profile() { + cp -f "$(bazel info output_base)/command.profile" "${ENVOY_BUILD_PROFILE}/$1.profile" || true +} + function bazel_with_collection() { declare -r BAZEL_OUTPUT="${ENVOY_SRCDIR}"/bazel.output.txt bazel $* | tee "${BAZEL_OUTPUT}" @@ -30,12 +34,14 @@ function bazel_with_collection() { done exit "${BAZEL_STATUS}" fi + collect_build_profile $1 } function bazel_release_binary_build() { echo "Building..." cd "${ENVOY_CI_DIR}" bazel build ${BAZEL_BUILD_OPTIONS} -c opt //source/exe:envoy-static + collect_build_profile release_build # Copy the envoy-static binary somewhere that we can access outside of the # container. cp -f \ @@ -54,6 +60,7 @@ function bazel_debug_binary_build() { echo "Building..." cd "${ENVOY_CI_DIR}" bazel build ${BAZEL_BUILD_OPTIONS} -c dbg //source/exe:envoy-static + collect_build_profile debug_build # Copy the envoy-static binary somewhere that we can access outside of the # container. cp -f \ @@ -248,6 +255,7 @@ elif [[ "$1" == "bazel.coverage" ]]; then # directory. Wow. cd "${ENVOY_BUILD_DIR}" SRCDIR="${GCOVR_DIR}" "${ENVOY_SRCDIR}"/test/run_envoy_bazel_coverage.sh + collect_build_profile coverage exit 0 elif [[ "$1" == "bazel.clang_tidy" ]]; then setup_clang_toolchain From efed749b6a6071ee849c6466510011435691e90f Mon Sep 17 00:00:00 2001 From: Bill DeCoste Date: Wed, 6 Feb 2019 10:25:56 -0800 Subject: [PATCH 29/51] move ssl implementation dependent tests to extensions (#5778) Description: Moves integration tests that are dependent on the ssl implementation (e.g. boringssl vs openssl) to extensions. See #5762 Risk Level: Low Testing: All standard tests passing Docs Change: None Release Notes: None Signed-off-by: William DeCoste --- ci/do_ci.sh | 2 +- .../transport_sockets/tls/integration/BUILD | 35 +++++++++++++++++++ .../tls}/integration/ssl_integration_test.cc | 4 +-- .../tls}/integration/ssl_integration_test.h | 0 test/integration/BUILD | 27 -------------- test/integration/xfcc_integration_test.cc | 1 - 6 files changed, 38 insertions(+), 31 deletions(-) create mode 100644 test/extensions/transport_sockets/tls/integration/BUILD rename test/{ => extensions/transport_sockets/tls}/integration/ssl_integration_test.cc (99%) rename test/{ => extensions/transport_sockets/tls}/integration/ssl_integration_test.h (100%) diff --git a/ci/do_ci.sh b/ci/do_ci.sh index f31ae0d30ff55..e85a6eba21b33 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -137,7 +137,7 @@ elif [[ "$1" == "bazel.asan" ]]; then rm -rf "${TAP_TMP}" mkdir -p "${TAP_TMP}" bazel_with_collection test ${BAZEL_TEST_OPTIONS} -c dbg --config=clang-asan \ - @envoy//test/integration:ssl_integration_test \ + @envoy//test/extensions/transport_sockets/tls/integration:ssl_integration_test \ --test_env=TAP_PATH="${TAP_TMP}/tap" # Verify that some pb_text files have been created. We can't check for pcap, # since tcpdump is not available in general due to CircleCI lack of support diff --git a/test/extensions/transport_sockets/tls/integration/BUILD b/test/extensions/transport_sockets/tls/integration/BUILD new file mode 100644 index 0000000000000..685bc87ae57aa --- /dev/null +++ b/test/extensions/transport_sockets/tls/integration/BUILD @@ -0,0 +1,35 @@ +licenses(["notice"]) # Apache 2 + +load( + "//bazel:envoy_build_system.bzl", + "envoy_cc_test", + "envoy_package", +) + +envoy_package() + +envoy_cc_test( + name = "ssl_integration_test", + srcs = [ + "ssl_integration_test.cc", + "ssl_integration_test.h", + ], + data = [ + "//test/config/integration/certs", + ], + deps = [ + "//source/common/event:dispatcher_includes", + "//source/common/event:dispatcher_lib", + "//source/common/network:connection_lib", + "//source/common/network:utility_lib", + "//source/extensions/filters/listener/tls_inspector:config", + "//source/extensions/transport_sockets/tls:config", + "//source/extensions/transport_sockets/tls:context_config_lib", + "//source/extensions/transport_sockets/tls:context_lib", + "//test/integration:http_integration_lib", + "//test/mocks/secret:secret_mocks", + "//test/test_common:utility_lib", + "@envoy_api//envoy/config/transport_socket/tap/v2alpha:tap_cc", + "@envoy_api//envoy/data/tap/v2alpha:transport_cc", + ], +) diff --git a/test/integration/ssl_integration_test.cc b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc similarity index 99% rename from test/integration/ssl_integration_test.cc rename to test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc index 99d13f7b62a2c..2877ef3e884df 100644 --- a/test/integration/ssl_integration_test.cc +++ b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc @@ -13,14 +13,14 @@ #include "extensions/transport_sockets/tls/context_config_impl.h" #include "extensions/transport_sockets/tls/context_manager_impl.h" +#include "test/integration/integration.h" +#include "test/integration/utility.h" #include "test/test_common/network_utility.h" #include "test/test_common/test_base.h" #include "test/test_common/utility.h" #include "absl/strings/match.h" #include "gmock/gmock.h" -#include "integration.h" -#include "utility.h" using testing::Return; diff --git a/test/integration/ssl_integration_test.h b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.h similarity index 100% rename from test/integration/ssl_integration_test.h rename to test/extensions/transport_sockets/tls/integration/ssl_integration_test.h diff --git a/test/integration/BUILD b/test/integration/BUILD index 41ea56a0626c2..7dacd21b4b7c0 100644 --- a/test/integration/BUILD +++ b/test/integration/BUILD @@ -534,32 +534,6 @@ envoy_cc_test( ], ) -envoy_cc_test( - name = "ssl_integration_test", - srcs = [ - "ssl_integration_test.cc", - "ssl_integration_test.h", - ], - data = [ - "//test/config/integration/certs", - ], - deps = [ - ":http_integration_lib", - "//source/common/event:dispatcher_includes", - "//source/common/event:dispatcher_lib", - "//source/common/network:connection_lib", - "//source/common/network:utility_lib", - "//source/extensions/filters/listener/tls_inspector:config", - "//source/extensions/transport_sockets/tls:config", - "//source/extensions/transport_sockets/tls:context_config_lib", - "//source/extensions/transport_sockets/tls:context_lib", - "//test/mocks/secret:secret_mocks", - "//test/test_common:utility_lib", - "@envoy_api//envoy/config/transport_socket/tap/v2alpha:tap_cc", - "@envoy_api//envoy/data/tap/v2alpha:transport_cc", - ], -) - envoy_cc_test( name = "tcp_proxy_integration_test", srcs = [ @@ -639,7 +613,6 @@ envoy_cc_test( envoy_cc_test( name = "xfcc_integration_test", srcs = [ - "ssl_integration_test.h", "xfcc_integration_test.cc", "xfcc_integration_test.h", ], diff --git a/test/integration/xfcc_integration_test.cc b/test/integration/xfcc_integration_test.cc index 2d98a774389b2..71625cd5c9d2a 100644 --- a/test/integration/xfcc_integration_test.cc +++ b/test/integration/xfcc_integration_test.cc @@ -22,7 +22,6 @@ #include "gmock/gmock.h" #include "integration.h" -#include "ssl_integration_test.h" #include "utility.h" namespace Envoy { From f2511a39cf2c4fe392d5499e854c39f262712100 Mon Sep 17 00:00:00 2001 From: Joshua Marantz Date: Wed, 6 Feb 2019 17:49:50 -0500 Subject: [PATCH 30/51] Fix all tests that were failing the test-base assert due to multi-inheritance order. (#5855) Signed-off-by: Joshua Marantz Previously the TestBase destructor was running the singleton quiescence check and printing the results, but not actually failing the tests.. There are two changes here: * use a RELEASE_ASSERT in the quiescence check helper function, rather than returning a bool * change a bunch of tests that multiply inherited from the TestBase class to always specify the TestBase class first. --- .../config/filesystem_subscription_impl_test.cc | 2 +- test/common/config/grpc_subscription_impl_test.cc | 2 +- test/common/config/http_subscription_impl_test.cc | 2 +- test/common/upstream/health_checker_impl_test.cc | 6 +++--- .../http_grpc/grpc_access_log_integration_test.cc | 4 ++-- .../http/cors/cors_filter_integration_test.cc | 4 ++-- .../reverse_bridge_integration_test.cc | 4 ++-- .../grpc_json_transcoder_integration_test.cc | 4 ++-- .../http/gzip/gzip_filter_integration_test.cc | 6 +++--- .../filters/http/lua/lua_integration_test.cc | 4 ++-- .../http/squash/squash_filter_integration_test.cc | 4 ++-- .../http/tap/tap_filter_integration_test.cc | 4 ++-- .../network/mysql_proxy/mysql_codec_test.cc | 2 +- .../network/mysql_proxy/mysql_command_test.cc | 2 +- .../network/mysql_proxy/mysql_filter_test.cc | 2 +- .../network/mysql_proxy/mysql_integration_test.cc | 6 +++--- .../filters/network/rbac/integration_test.cc | 4 ++-- .../filters/network/thrift_proxy/config_test.cc | 14 +++++++------- .../filters/network/thrift_proxy/decoder_test.cc | 3 +-- .../network/thrift_proxy/integration_test.cc | 4 ++-- .../filters/network/thrift_proxy/router_test.cc | 6 +++--- .../thrift_proxy/thrift_object_impl_test.cc | 2 +- .../thrift_proxy/translation_integration_test.cc | 6 +++--- .../metrics_service_integration_test.cc | 4 ++-- .../alts/alts_integration_test.cc | 4 ++-- .../tls/integration/ssl_integration_test.cc | 6 +++--- .../tls/integration/ssl_integration_test.h | 4 ++-- test/integration/ads_integration_test.cc | 10 +++++----- test/integration/cds_integration_test.cc | 2 +- test/integration/echo_integration_test.cc | 4 ++-- test/integration/eds_integration_test.cc | 4 ++-- test/integration/hds_integration_test.cc | 4 ++-- test/integration/header_integration_test.cc | 4 ++-- test/integration/http2_integration_test.h | 4 ++-- test/integration/http2_upstream_integration_test.h | 4 ++-- test/integration/http_protocol_integration.h | 4 ++-- test/integration/integration_admin_test.cc | 6 +++--- test/integration/integration_test.h | 4 ++-- test/integration/load_stats_integration_test.cc | 4 ++-- test/integration/proxy_proto_integration_test.h | 4 ++-- test/integration/ratelimit_integration_test.cc | 4 ++-- test/integration/sds_dynamic_integration_test.cc | 4 ++-- test/integration/sds_static_integration_test.cc | 8 ++++---- test/integration/stats_integration_test.cc | 4 ++-- test/integration/tcp_conn_pool_integration_test.cc | 4 ++-- test/integration/tcp_proxy_integration_test.h | 4 ++-- test/integration/uds_integration_test.h | 8 ++++---- test/integration/xds_integration_test.cc | 4 ++-- test/integration/xfcc_integration_test.h | 4 ++-- test/test_common/test_base.cc | 11 +++++------ test/test_common/test_base.h | 2 +- test/test_runner.h | 4 +--- 52 files changed, 115 insertions(+), 119 deletions(-) diff --git a/test/common/config/filesystem_subscription_impl_test.cc b/test/common/config/filesystem_subscription_impl_test.cc index c1582b0f45574..c088e2329a70e 100644 --- a/test/common/config/filesystem_subscription_impl_test.cc +++ b/test/common/config/filesystem_subscription_impl_test.cc @@ -12,7 +12,7 @@ namespace Envoy { namespace Config { namespace { -class FilesystemSubscriptionImplTest : public FilesystemSubscriptionTestHarness, public TestBase {}; +class FilesystemSubscriptionImplTest : public TestBase, public FilesystemSubscriptionTestHarness {}; // Validate that the client can recover from bad JSON responses. TEST_F(FilesystemSubscriptionImplTest, BadJsonRecovery) { diff --git a/test/common/config/grpc_subscription_impl_test.cc b/test/common/config/grpc_subscription_impl_test.cc index 1c2f1c987e87b..d9ae80c5b98cd 100644 --- a/test/common/config/grpc_subscription_impl_test.cc +++ b/test/common/config/grpc_subscription_impl_test.cc @@ -7,7 +7,7 @@ namespace Envoy { namespace Config { namespace { -class GrpcSubscriptionImplTest : public GrpcSubscriptionTestHarness, public TestBase {}; +class GrpcSubscriptionImplTest : public TestBase, public GrpcSubscriptionTestHarness {}; // Validate that stream creation results in a timer based retry and can recover. TEST_F(GrpcSubscriptionImplTest, StreamCreationFailure) { diff --git a/test/common/config/http_subscription_impl_test.cc b/test/common/config/http_subscription_impl_test.cc index 05d5c19cf5cda..1b1a5f830c0e5 100644 --- a/test/common/config/http_subscription_impl_test.cc +++ b/test/common/config/http_subscription_impl_test.cc @@ -7,7 +7,7 @@ namespace Envoy { namespace Config { namespace { -class HttpSubscriptionImplTest : public HttpSubscriptionTestHarness, public TestBase {}; +class HttpSubscriptionImplTest : public TestBase, public HttpSubscriptionTestHarness {}; // Validate that the client can recover from a remote fetch failure. TEST_F(HttpSubscriptionImplTest, OnRequestReset) { diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index 77cf92c352370..767d2d955cea6 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -2751,7 +2751,7 @@ class GrpcHealthCheckerImplTestBase { std::list codec_index_{}; }; -class GrpcHealthCheckerImplTest : public GrpcHealthCheckerImplTestBase, public TestBase {}; +class GrpcHealthCheckerImplTest : public TestBase, public GrpcHealthCheckerImplTestBase {}; // Test single host check success. TEST_F(GrpcHealthCheckerImplTest, Success) { testSingleHostSuccess(absl::nullopt); } @@ -3379,8 +3379,8 @@ TEST_F(GrpcHealthCheckerImplTest, GoAwayBetweenChecks) { } class BadResponseGrpcHealthCheckerImplTest - : public GrpcHealthCheckerImplTestBase, - public TestBaseWithParam {}; + : public TestBaseWithParam, + public GrpcHealthCheckerImplTestBase {}; INSTANTIATE_TEST_SUITE_P( BadResponse, BadResponseGrpcHealthCheckerImplTest, diff --git a/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc b/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc index 16015e13764cd..fc55d6b334fe1 100644 --- a/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc +++ b/test/extensions/access_loggers/http_grpc/grpc_access_log_integration_test.cc @@ -16,8 +16,8 @@ using testing::AssertionResult; namespace Envoy { namespace { -class AccessLogIntegrationTest : public HttpIntegrationTest, - public Grpc::GrpcClientIntegrationParamTest { +class AccessLogIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, + public HttpIntegrationTest { public: AccessLogIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, ipVersion(), realTime()) {} diff --git a/test/extensions/filters/http/cors/cors_filter_integration_test.cc b/test/extensions/filters/http/cors/cors_filter_integration_test.cc index b5880df48a807..9ecaa5169d254 100644 --- a/test/extensions/filters/http/cors/cors_filter_integration_test.cc +++ b/test/extensions/filters/http/cors/cors_filter_integration_test.cc @@ -5,8 +5,8 @@ namespace Envoy { -class CorsFilterIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class CorsFilterIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: CorsFilterIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc b/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc index eb07083c764ec..bd05ee035e92c 100644 --- a/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc +++ b/test/extensions/filters/http/grpc_http1_reverse_bridge/reverse_bridge_integration_test.cc @@ -17,8 +17,8 @@ namespace Envoy { // Tests a downstream HTTP2 client sending gRPC requests that are converted into HTTP/1.1 for a // HTTP1 upstream. -class ReverseBridgeIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class ReverseBridgeIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: ReverseBridgeIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc b/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc index 64c63b6cbfdc8..097976311912a 100644 --- a/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc +++ b/test/extensions/filters/http/grpc_json_transcoder/grpc_json_transcoder_integration_test.cc @@ -20,8 +20,8 @@ using Envoy::ProtobufWkt::Empty; namespace Envoy { -class GrpcJsonTranscoderIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class GrpcJsonTranscoderIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: GrpcJsonTranscoderIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc b/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc index edfd1e34cce39..ba88a4779847b 100644 --- a/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc +++ b/test/extensions/filters/http/gzip/gzip_filter_integration_test.cc @@ -9,9 +9,9 @@ namespace Envoy { -class GzipIntegrationTest : public Event::SimulatedTimeSystem, - public HttpIntegrationTest, - public TestBaseWithParam { +class GzipIntegrationTest : public TestBaseWithParam, + public Event::SimulatedTimeSystem, + public HttpIntegrationTest { public: GzipIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {} diff --git a/test/extensions/filters/http/lua/lua_integration_test.cc b/test/extensions/filters/http/lua/lua_integration_test.cc index 9af429f4aef6c..9e5c8232105b5 100644 --- a/test/extensions/filters/http/lua/lua_integration_test.cc +++ b/test/extensions/filters/http/lua/lua_integration_test.cc @@ -7,8 +7,8 @@ namespace Envoy { namespace { -class LuaIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class LuaIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: LuaIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/squash/squash_filter_integration_test.cc b/test/extensions/filters/http/squash/squash_filter_integration_test.cc index 1ad01eb2283dc..03bdbef324e7b 100644 --- a/test/extensions/filters/http/squash/squash_filter_integration_test.cc +++ b/test/extensions/filters/http/squash/squash_filter_integration_test.cc @@ -16,8 +16,8 @@ using Envoy::Protobuf::util::MessageDifferencer; namespace Envoy { -class SquashFilterIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class SquashFilterIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: SquashFilterIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/extensions/filters/http/tap/tap_filter_integration_test.cc b/test/extensions/filters/http/tap/tap_filter_integration_test.cc index 84c3623d640d1..19a69cc9cd180 100644 --- a/test/extensions/filters/http/tap/tap_filter_integration_test.cc +++ b/test/extensions/filters/http/tap/tap_filter_integration_test.cc @@ -8,8 +8,8 @@ namespace Envoy { namespace { -class TapIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class TapIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: TapIntegrationTest() // Note: This test must use HTTP/2 because of the lack of early close detection for diff --git a/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc index e724eb6011990..6fff42542e5fc 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_codec_test.cc @@ -20,7 +20,7 @@ constexpr int MYSQL_UT_LAST_ID = 0; constexpr int MYSQL_UT_SERVER_OK = 0; constexpr int MYSQL_UT_SERVER_WARNINGS = 0x0001; -class MySQLCodecTest : public MySQLTestUtils, public TestBase { +class MySQLCodecTest : public TestBase, public MySQLTestUtils { protected: uint64_t offset_{0}; }; diff --git a/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc index ce6cc1795045f..3baa435ca7705 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_command_test.cc @@ -16,7 +16,7 @@ namespace Extensions { namespace NetworkFilters { namespace MySQLProxy { -class MySQLCommandTest : public MySQLTestUtils, public TestBase { +class MySQLCommandTest : public TestBase, public MySQLTestUtils { public: int encodeQuery(std::string query, hsql::SQLParserResult& result) { Command mysql_cmd_encode{}; diff --git a/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc index cd5e80a547f5e..3cfa5970e621b 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_filter_test.cc @@ -17,7 +17,7 @@ namespace MySQLProxy { constexpr int SESSIONS = 5; -class MySQLFilterTest : public MySQLTestUtils, public TestBase { +class MySQLFilterTest : public TestBase, public MySQLTestUtils { public: MySQLFilterTest() { ENVOY_LOG_MISC(info, "test"); } diff --git a/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc b/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc index 0c5adcb1691c9..5080a6a696ace 100644 --- a/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc +++ b/test/extensions/filters/network/mysql_proxy/mysql_integration_test.cc @@ -26,9 +26,9 @@ namespace MySQLProxy { constexpr int SESSIONS = 5; -class MySQLIntegrationTest : public MySQLTestUtils, - public BaseIntegrationTest, - public TestBaseWithParam { +class MySQLIntegrationTest : public TestBaseWithParam, + public MySQLTestUtils, + public BaseIntegrationTest { std::string mysqlConfig() { return TestEnvironment::readFileToStringForTest(TestEnvironment::runfilesPath( "test/extensions/filters/network/mysql_proxy/mysql_test_config.yaml")); diff --git a/test/extensions/filters/network/rbac/integration_test.cc b/test/extensions/filters/network/rbac/integration_test.cc index 2e1d83186b9b4..6dd1a9c55acfd 100644 --- a/test/extensions/filters/network/rbac/integration_test.cc +++ b/test/extensions/filters/network/rbac/integration_test.cc @@ -15,8 +15,8 @@ std::string rbac_config; } // namespace class RoleBasedAccessControlNetworkFilterIntegrationTest - : public BaseIntegrationTest, - public TestBaseWithParam { + : public TestBaseWithParam, + public BaseIntegrationTest { public: RoleBasedAccessControlNetworkFilterIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), rbac_config) {} diff --git a/test/extensions/filters/network/thrift_proxy/config_test.cc b/test/extensions/filters/network/thrift_proxy/config_test.cc index df1765741e06b..43bff26d92176 100644 --- a/test/extensions/filters/network/thrift_proxy/config_test.cc +++ b/test/extensions/filters/network/thrift_proxy/config_test.cc @@ -67,20 +67,20 @@ class ThriftFilterConfigTestBase { ThriftProxyFilterConfigFactory factory_; }; -class ThriftFilterConfigTest : public ThriftFilterConfigTestBase, public TestBase {}; +class ThriftFilterConfigTest : public TestBase, public ThriftFilterConfigTestBase {}; class ThriftFilterTransportConfigTest - : public ThriftFilterConfigTestBase, - public TestBaseWithParam< - envoy::config::filter::network::thrift_proxy::v2alpha1::TransportType> {}; + : public TestBaseWithParam< + envoy::config::filter::network::thrift_proxy::v2alpha1::TransportType>, + public ThriftFilterConfigTestBase {}; INSTANTIATE_TEST_SUITE_P(TransportTypes, ThriftFilterTransportConfigTest, testing::ValuesIn(getTransportTypes())); class ThriftFilterProtocolConfigTest - : public ThriftFilterConfigTestBase, - public TestBaseWithParam< - envoy::config::filter::network::thrift_proxy::v2alpha1::ProtocolType> {}; + : public TestBaseWithParam< + envoy::config::filter::network::thrift_proxy::v2alpha1::ProtocolType>, + public ThriftFilterConfigTestBase {}; INSTANTIATE_TEST_SUITE_P(ProtocolTypes, ThriftFilterProtocolConfigTest, testing::ValuesIn(getProtocolTypes())); diff --git a/test/extensions/filters/network/thrift_proxy/decoder_test.cc b/test/extensions/filters/network/thrift_proxy/decoder_test.cc index 8cfa92bc37433..600ba07578398 100644 --- a/test/extensions/filters/network/thrift_proxy/decoder_test.cc +++ b/test/extensions/filters/network/thrift_proxy/decoder_test.cc @@ -204,8 +204,7 @@ INSTANTIATE_TEST_SUITE_P(NonValueProtocolStates, DecoderStateMachineNonValueTest ProtocolState::SetBegin, ProtocolState::SetEnd), protoStateParamToString); -class DecoderStateMachineTest : public DecoderStateMachineTestBase, public TestBase {}; - +class DecoderStateMachineTest : public TestBase, public DecoderStateMachineTestBase {}; class DecoderStateMachineValueTest : public DecoderStateMachineTestBase, public TestBaseWithParam {}; diff --git a/test/extensions/filters/network/thrift_proxy/integration_test.cc b/test/extensions/filters/network/thrift_proxy/integration_test.cc index afe0d34a869f6..78c45c7e88038 100644 --- a/test/extensions/filters/network/thrift_proxy/integration_test.cc +++ b/test/extensions/filters/network/thrift_proxy/integration_test.cc @@ -15,8 +15,8 @@ namespace NetworkFilters { namespace ThriftProxy { class ThriftConnManagerIntegrationTest - : public BaseThriftIntegrationTest, - public TestBaseWithParam> { + : public TestBaseWithParam>, + public BaseThriftIntegrationTest { public: static void SetUpTestSuite() { thrift_config_ = ConfigHelper::BASE_CONFIG + R"EOF( diff --git a/test/extensions/filters/network/thrift_proxy/router_test.cc b/test/extensions/filters/network/thrift_proxy/router_test.cc index 082328dfad5d0..0d7fc51152bc6 100644 --- a/test/extensions/filters/network/thrift_proxy/router_test.cc +++ b/test/extensions/filters/network/thrift_proxy/router_test.cc @@ -328,11 +328,11 @@ class ThriftRouterTestBase { NiceMock upstream_connection_; }; -class ThriftRouterTest : public ThriftRouterTestBase, public TestBase { +class ThriftRouterTest : public TestBase, public ThriftRouterTestBase { public: }; -class ThriftRouterFieldTypeTest : public ThriftRouterTestBase, public TestBaseWithParam { +class ThriftRouterFieldTypeTest : public TestBaseWithParam, public ThriftRouterTestBase { public: }; @@ -341,7 +341,7 @@ INSTANTIATE_TEST_SUITE_P(PrimitiveFieldTypes, ThriftRouterFieldTypeTest, FieldType::I64, FieldType::Double, FieldType::String), fieldTypeParamToString); -class ThriftRouterContainerTest : public ThriftRouterTestBase, public TestBaseWithParam { +class ThriftRouterContainerTest : public TestBaseWithParam, public ThriftRouterTestBase { public: }; diff --git a/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc b/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc index 6b209fcc54bd7..0a3e51a0b4e68 100644 --- a/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc +++ b/test/extensions/filters/network/thrift_proxy/thrift_object_impl_test.cc @@ -142,7 +142,7 @@ class ThriftObjectImplTestBase { Buffer::OwnedImpl buffer_; }; -class ThriftObjectImplTest : public ThriftObjectImplTestBase, public TestBase {}; +class ThriftObjectImplTest : public TestBase, public ThriftObjectImplTestBase {}; // Test parsing an empty struct (just a stop field). TEST_F(ThriftObjectImplTest, ParseEmptyStruct) { diff --git a/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc b/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc index 3db1c54e6ba71..a6bf575be40ab 100644 --- a/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc +++ b/test/extensions/filters/network/thrift_proxy/translation_integration_test.cc @@ -17,9 +17,9 @@ namespace NetworkFilters { namespace ThriftProxy { class ThriftTranslationIntegrationTest - : public BaseThriftIntegrationTest, - public TestBaseWithParam< - std::tuple> { + : public TestBaseWithParam< + std::tuple>, + public BaseThriftIntegrationTest { public: static void SetUpTestSuite() { thrift_config_ = ConfigHelper::BASE_CONFIG + R"EOF( diff --git a/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc b/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc index 476dce27a5d49..2aee01ad2ebd9 100644 --- a/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc +++ b/test/extensions/stats_sinks/metrics_service/metrics_service_integration_test.cc @@ -16,8 +16,8 @@ using testing::AssertionResult; namespace Envoy { namespace { -class MetricsServiceIntegrationTest : public HttpIntegrationTest, - public Grpc::GrpcClientIntegrationParamTest { +class MetricsServiceIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, + public HttpIntegrationTest { public: MetricsServiceIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, ipVersion(), realTime()) {} diff --git a/test/extensions/transport_sockets/alts/alts_integration_test.cc b/test/extensions/transport_sockets/alts/alts_integration_test.cc index c4edaaac6d92c..eb2f744563c7c 100644 --- a/test/extensions/transport_sockets/alts/alts_integration_test.cc +++ b/test/extensions/transport_sockets/alts/alts_integration_test.cc @@ -25,8 +25,8 @@ namespace Extensions { namespace TransportSockets { namespace Alts { -class AltsIntegrationTestBase : public HttpIntegrationTest, - public TestBaseWithParam { +class AltsIntegrationTestBase : public TestBaseWithParam, + public HttpIntegrationTest { public: AltsIntegrationTestBase(const std::string& server_peer_identity, const std::string& client_peer_identity, bool server_connect_handshaker, diff --git a/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc index 2877ef3e884df..319bc6833d56e 100644 --- a/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc +++ b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc @@ -175,9 +175,9 @@ TEST_P(SslIntegrationTest, AdminCertEndpoint) { // Validate certificate selection across different certificate types and client TLS versions. class SslCertficateIntegrationTest - : public SslIntegrationTestBase, - public TestBaseWithParam> { + : public TestBaseWithParam< + std::tuple>, + public SslIntegrationTestBase { public: SslCertficateIntegrationTest() : SslIntegrationTestBase(std::get<0>(GetParam())) { server_tlsv1_3_ = true; diff --git a/test/extensions/transport_sockets/tls/integration/ssl_integration_test.h b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.h index f28a9343803b7..b85383e2ea3f9 100644 --- a/test/extensions/transport_sockets/tls/integration/ssl_integration_test.h +++ b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.h @@ -43,8 +43,8 @@ class SslIntegrationTestBase : public HttpIntegrationTest { std::unique_ptr context_manager_; }; -class SslIntegrationTest : public SslIntegrationTestBase, - public TestBaseWithParam { +class SslIntegrationTest : public TestBaseWithParam, + public SslIntegrationTestBase { public: SslIntegrationTest() : SslIntegrationTestBase(GetParam()) {} void TearDown() override { SslIntegrationTestBase::TearDown(); }; diff --git a/test/integration/ads_integration_test.cc b/test/integration/ads_integration_test.cc index e2f7294b9ee3a..1b461c251cc9d 100644 --- a/test/integration/ads_integration_test.cc +++ b/test/integration/ads_integration_test.cc @@ -56,7 +56,7 @@ const std::string config = R"EOF( port_value: 0 )EOF"; -class AdsIntegrationTest : public HttpIntegrationTest, public Grpc::GrpcClientIntegrationParamTest { +class AdsIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, public HttpIntegrationTest { public: AdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, ipVersion(), realTime(), config) { @@ -542,8 +542,8 @@ TEST_P(AdsIntegrationTest, RdsAfterLdsWithRdsChange) { makeSingleRequest(); } -class AdsFailIntegrationTest : public HttpIntegrationTest, - public Grpc::GrpcClientIntegrationParamTest { +class AdsFailIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, + public HttpIntegrationTest { public: AdsFailIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, ipVersion(), realTime(), config) { @@ -582,8 +582,8 @@ TEST_P(AdsFailIntegrationTest, ConnectDisconnect) { xds_stream_->finishGrpcStream(Grpc::Status::Internal); } -class AdsConfigIntegrationTest : public HttpIntegrationTest, - public Grpc::GrpcClientIntegrationParamTest { +class AdsConfigIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, + public HttpIntegrationTest { public: AdsConfigIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, ipVersion(), realTime(), config) { diff --git a/test/integration/cds_integration_test.cc b/test/integration/cds_integration_test.cc index 9958c2d58c9c3..0976272c3a18a 100644 --- a/test/integration/cds_integration_test.cc +++ b/test/integration/cds_integration_test.cc @@ -79,7 +79,7 @@ const char Config[] = R"EOF( const char ClusterName[] = "cluster_0"; const int UpstreamIndex = 1; -class CdsIntegrationTest : public HttpIntegrationTest, public Grpc::GrpcClientIntegrationParamTest { +class CdsIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, public HttpIntegrationTest { public: CdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, ipVersion(), realTime(), Config) {} diff --git a/test/integration/echo_integration_test.cc b/test/integration/echo_integration_test.cc index e91fe26f5ee17..e9fb0513f555b 100644 --- a/test/integration/echo_integration_test.cc +++ b/test/integration/echo_integration_test.cc @@ -7,8 +7,8 @@ namespace Envoy { std::string echo_config; -class EchoIntegrationTest : public BaseIntegrationTest, - public TestBaseWithParam { +class EchoIntegrationTest : public TestBaseWithParam, + public BaseIntegrationTest { public: EchoIntegrationTest() : BaseIntegrationTest(GetParam(), echo_config) {} diff --git a/test/integration/eds_integration_test.cc b/test/integration/eds_integration_test.cc index 7412163d7661e..a17d7b72bcd1a 100644 --- a/test/integration/eds_integration_test.cc +++ b/test/integration/eds_integration_test.cc @@ -12,8 +12,8 @@ namespace { // Integration test for EDS features. EDS is consumed via filesystem // subscription. -class EdsIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class EdsIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: EdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/integration/hds_integration_test.cc b/test/integration/hds_integration_test.cc index 8b0e9468c1ca9..26e829a731738 100644 --- a/test/integration/hds_integration_test.cc +++ b/test/integration/hds_integration_test.cc @@ -23,8 +23,8 @@ namespace Envoy { namespace { -class HdsIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class HdsIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: HdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/integration/header_integration_test.cc b/test/integration/header_integration_test.cc index 40c0672504c8a..3151ce85cdbda 100644 --- a/test/integration/header_integration_test.cc +++ b/test/integration/header_integration_test.cc @@ -149,8 +149,8 @@ stat_prefix: header_test } // namespace class HeaderIntegrationTest - : public HttpIntegrationTest, - public TestBaseWithParam> { + : public TestBaseWithParam>, + public HttpIntegrationTest { public: HeaderIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, std::get<0>(GetParam()), realTime()) {} diff --git a/test/integration/http2_integration_test.h b/test/integration/http2_integration_test.h index c63d60ba0dfe9..21e29f28bdb97 100644 --- a/test/integration/http2_integration_test.h +++ b/test/integration/http2_integration_test.h @@ -4,8 +4,8 @@ #include "test/test_common/test_base.h" namespace Envoy { -class Http2IntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class Http2IntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: Http2IntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} diff --git a/test/integration/http2_upstream_integration_test.h b/test/integration/http2_upstream_integration_test.h index 0bcb228acbd79..41e5d8d8c31b7 100644 --- a/test/integration/http2_upstream_integration_test.h +++ b/test/integration/http2_upstream_integration_test.h @@ -4,8 +4,8 @@ #include "test/test_common/test_base.h" namespace Envoy { -class Http2UpstreamIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class Http2UpstreamIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: Http2UpstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) {} diff --git a/test/integration/http_protocol_integration.h b/test/integration/http_protocol_integration.h index 2939c795612e1..f89914f8d339b 100644 --- a/test/integration/http_protocol_integration.h +++ b/test/integration/http_protocol_integration.h @@ -25,8 +25,8 @@ struct HttpProtocolTestParams { // TEST_P(MyTest, TestInstance) { // .... // } -class HttpProtocolIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class HttpProtocolIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: // By default returns 8 combinations of // [HTTP upstream / HTTP downstream] x [Ipv4, IPv6] diff --git a/test/integration/integration_admin_test.cc b/test/integration/integration_admin_test.cc index 120f7ebbb45bd..f642c03fbe679 100644 --- a/test/integration/integration_admin_test.cc +++ b/test/integration/integration_admin_test.cc @@ -416,7 +416,7 @@ TEST_P(IntegrationAdminTest, AdminCpuProfilerStart) { EXPECT_STREQ("200", response->headers().Status()->value().c_str()); } -class IntegrationAdminIpv4Ipv6Test : public HttpIntegrationTest, public TestBase { +class IntegrationAdminIpv4Ipv6Test : public TestBase, public HttpIntegrationTest { public: IntegrationAdminIpv4Ipv6Test() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, Network::Address::IpVersion::v4, @@ -450,9 +450,9 @@ TEST_F(IntegrationAdminIpv4Ipv6Test, Ipv4Ipv6Listen) { // Testing the behavior of StatsMatcher, which allows/denies the instantiation of stats based on // restrictions on their names. class StatsMatcherIntegrationTest - : public Event::SimulatedTimeSystem, + : public TestBase, + public Event::SimulatedTimeSystem, public HttpIntegrationTest, - public TestBase, public testing::WithParamInterface { public: StatsMatcherIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam()) {} diff --git a/test/integration/integration_test.h b/test/integration/integration_test.h index 7d4e8c61c7f54..1e4d34968bd4e 100644 --- a/test/integration/integration_test.h +++ b/test/integration/integration_test.h @@ -5,8 +5,8 @@ // A test class for testing HTTP/1.1 upstream and downstreams namespace Envoy { -class IntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class IntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: IntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} }; diff --git a/test/integration/load_stats_integration_test.cc b/test/integration/load_stats_integration_test.cc index aeef4cc7ee8a1..da2092b64e595 100644 --- a/test/integration/load_stats_integration_test.cc +++ b/test/integration/load_stats_integration_test.cc @@ -14,8 +14,8 @@ namespace Envoy { namespace { -class LoadStatsIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class LoadStatsIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: LoadStatsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) { diff --git a/test/integration/proxy_proto_integration_test.h b/test/integration/proxy_proto_integration_test.h index 5f663e6b9f51a..877448355b8ee 100644 --- a/test/integration/proxy_proto_integration_test.h +++ b/test/integration/proxy_proto_integration_test.h @@ -8,8 +8,8 @@ #include "test/test_common/test_base.h" namespace Envoy { -class ProxyProtoIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class ProxyProtoIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: ProxyProtoIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) { diff --git a/test/integration/ratelimit_integration_test.cc b/test/integration/ratelimit_integration_test.cc index ae0bc73b5fcac..c1bde758c0d99 100644 --- a/test/integration/ratelimit_integration_test.cc +++ b/test/integration/ratelimit_integration_test.cc @@ -14,8 +14,8 @@ namespace Envoy { namespace { // Tests Ratelimit functionality with config in filter. -class RatelimitIntegrationTest : public HttpIntegrationTest, - public Grpc::GrpcClientIntegrationParamTest { +class RatelimitIntegrationTest : public Grpc::GrpcClientIntegrationParamTest, + public HttpIntegrationTest { public: RatelimitIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, ipVersion(), realTime()) {} diff --git a/test/integration/sds_dynamic_integration_test.cc b/test/integration/sds_dynamic_integration_test.cc index e1d026a10defa..427f113372b43 100644 --- a/test/integration/sds_dynamic_integration_test.cc +++ b/test/integration/sds_dynamic_integration_test.cc @@ -41,8 +41,8 @@ const envoy::service::discovery::v2::SdsDummy _sds_dummy; // Sds integration base class with following support: // * functions to create sds upstream, and send sds response // * functions to create secret protobuf. -class SdsDynamicIntegrationBaseTest : public HttpIntegrationTest, - public Grpc::GrpcClientIntegrationParamTest { +class SdsDynamicIntegrationBaseTest : public Grpc::GrpcClientIntegrationParamTest, + public HttpIntegrationTest { public: SdsDynamicIntegrationBaseTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, ipVersion(), realTime()), diff --git a/test/integration/sds_static_integration_test.cc b/test/integration/sds_static_integration_test.cc index 9fa494a7992ee..21e9e58cb8574 100644 --- a/test/integration/sds_static_integration_test.cc +++ b/test/integration/sds_static_integration_test.cc @@ -33,8 +33,8 @@ using testing::Return; namespace Envoy { namespace Ssl { -class SdsStaticDownstreamIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class SdsStaticDownstreamIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: SdsStaticDownstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} @@ -105,8 +105,8 @@ TEST_P(SdsStaticDownstreamIntegrationTest, RouterRequestAndResponseWithGiantBody testRouterRequestAndResponseWithBody(16 * 1024 * 1024, 16 * 1024 * 1024, false, &creator); } -class SdsStaticUpstreamIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class SdsStaticUpstreamIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: SdsStaticUpstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, GetParam(), realTime()) {} diff --git a/test/integration/stats_integration_test.cc b/test/integration/stats_integration_test.cc index 4d36b4d8c5a7a..c69466b12b79f 100644 --- a/test/integration/stats_integration_test.cc +++ b/test/integration/stats_integration_test.cc @@ -11,8 +11,8 @@ namespace Envoy { namespace { -class StatsIntegrationTest : public BaseIntegrationTest, - public TestBaseWithParam { +class StatsIntegrationTest : public TestBaseWithParam, + public BaseIntegrationTest { public: StatsIntegrationTest() : BaseIntegrationTest(GetParam(), realTime()) {} diff --git a/test/integration/tcp_conn_pool_integration_test.cc b/test/integration/tcp_conn_pool_integration_test.cc index 5ca30b0e8ed7a..091d58266e340 100644 --- a/test/integration/tcp_conn_pool_integration_test.cc +++ b/test/integration/tcp_conn_pool_integration_test.cc @@ -111,8 +111,8 @@ class TestFilterConfigFactory : public Server::Configuration::NamedNetworkFilter } // namespace -class TcpConnPoolIntegrationTest : public BaseIntegrationTest, - public TestBaseWithParam { +class TcpConnPoolIntegrationTest : public TestBaseWithParam, + public BaseIntegrationTest { public: TcpConnPoolIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), tcp_conn_pool_config), diff --git a/test/integration/tcp_proxy_integration_test.h b/test/integration/tcp_proxy_integration_test.h index 317846879781a..3093263f9b71b 100644 --- a/test/integration/tcp_proxy_integration_test.h +++ b/test/integration/tcp_proxy_integration_test.h @@ -9,8 +9,8 @@ namespace Envoy { namespace { -class TcpProxyIntegrationTest : public BaseIntegrationTest, - public TestBaseWithParam { +class TcpProxyIntegrationTest : public TestBaseWithParam, + public BaseIntegrationTest { public: TcpProxyIntegrationTest() : BaseIntegrationTest(GetParam(), realTime(), ConfigHelper::TCP_PROXY_CONFIG) { diff --git a/test/integration/uds_integration_test.h b/test/integration/uds_integration_test.h index 7cb73485c2205..a66b0e37d501f 100644 --- a/test/integration/uds_integration_test.h +++ b/test/integration/uds_integration_test.h @@ -14,8 +14,8 @@ namespace Envoy { class UdsUpstreamIntegrationTest - : public HttpIntegrationTest, - public TestBaseWithParam> { + : public TestBaseWithParam>, + public HttpIntegrationTest { public: UdsUpstreamIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, std::get<0>(GetParam()), realTime()), @@ -45,8 +45,8 @@ class UdsUpstreamIntegrationTest }; class UdsListenerIntegrationTest - : public HttpIntegrationTest, - public TestBaseWithParam> { + : public TestBaseWithParam>, + public HttpIntegrationTest { public: UdsListenerIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP1, std::get<0>(GetParam()), realTime()), diff --git a/test/integration/xds_integration_test.cc b/test/integration/xds_integration_test.cc index ebe86cb9332c3..430066e4151b4 100644 --- a/test/integration/xds_integration_test.cc +++ b/test/integration/xds_integration_test.cc @@ -6,8 +6,8 @@ namespace Envoy { namespace { // This is a minimal litmus test for the v2 xDS APIs. -class XdsIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class XdsIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: XdsIntegrationTest() : HttpIntegrationTest(Http::CodecClient::Type::HTTP2, GetParam(), realTime()) { diff --git a/test/integration/xfcc_integration_test.h b/test/integration/xfcc_integration_test.h index 780e36f6ebbf7..3ff75c516fe6d 100644 --- a/test/integration/xfcc_integration_test.h +++ b/test/integration/xfcc_integration_test.h @@ -19,8 +19,8 @@ using testing::ReturnRef; namespace Envoy { namespace Xfcc { -class XfccIntegrationTest : public HttpIntegrationTest, - public TestBaseWithParam { +class XfccIntegrationTest : public TestBaseWithParam, + public HttpIntegrationTest { public: const std::string previous_xfcc_ = "By=spiffe://lyft.com/frontend;Hash=123456;URI=spiffe://lyft.com/testclient"; diff --git a/test/test_common/test_base.cc b/test/test_common/test_base.cc index 2e5b9d72bb301..0a10e332ac4a4 100644 --- a/test/test_common/test_base.cc +++ b/test/test_common/test_base.cc @@ -1,17 +1,16 @@ #include "test/test_common/test_base.h" +#include "common/common/assert.h" + #include "test/test_common/global.h" namespace Envoy { -bool TestBase::checkSingletonQuiescensce() { +void TestBase::checkSingletonQuiescensce() { // Check that all singletons have been destroyed. std::string active_singletons = Envoy::Test::Globals::describeActiveSingletons(); - if (!active_singletons.empty()) { - std::cerr << "\n\nFAIL: Active singletons exist:\n" << active_singletons << std::endl; - return false; - } - return true; + RELEASE_ASSERT(active_singletons.empty(), + absl::StrCat("FAIL: Active singletons exist:\n", active_singletons)); } TestBase::~TestBase() { checkSingletonQuiescensce(); } diff --git a/test/test_common/test_base.h b/test/test_common/test_base.h index fc0396fcc2c90..defb51b17ad5f 100644 --- a/test/test_common/test_base.h +++ b/test/test_common/test_base.h @@ -21,7 +21,7 @@ namespace Envoy { // be a tax paid by every test method in the codebase. class TestBase : public ::testing::Test { public: - static bool checkSingletonQuiescensce(); + static void checkSingletonQuiescensce(); ~TestBase() override; }; diff --git a/test/test_runner.h b/test/test_runner.h index 34754d376de16..8070c127c126f 100644 --- a/test/test_runner.h +++ b/test/test_runner.h @@ -48,9 +48,7 @@ class TestRunner { int exit_status = RUN_ALL_TESTS(); // Check that all singletons have been destroyed. - if (!TestBase::checkSingletonQuiescensce()) { - exit_status = EXIT_FAILURE; - } + TestBase::checkSingletonQuiescensce(); return exit_status; } From 5fd128d63810919840917bdf7da2d018edc5e32f Mon Sep 17 00:00:00 2001 From: htuch Date: Wed, 6 Feb 2019 18:23:29 -0500 Subject: [PATCH 31/51] maglev: fix handling of unspecified locality weights. (#5863) The config fuzzer showed that the locality weight assertion in https://github.com/envoyproxy/envoy/pull/5831 was too strong. Extant behavior was and is that if locality weight is not specified and locality LB weighting, we should just ignore the locality. Fixes oss-fuzz issue https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=12923. Risk level: Low Testing: Corpus entry and unit test added. Signed-off-by: Harvey Tuch --- api/envoy/api/v2/endpoint/endpoint.proto | 4 +- source/common/upstream/maglev_lb.cc | 18 ++++-- test/common/upstream/maglev_lb_test.cc | 22 ++++++- ...testcase-config_fuzz_test-5067970991095808 | 58 +++++++++++++++++++ 4 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 test/server/server_corpus/clusterfuzz-testcase-config_fuzz_test-5067970991095808 diff --git a/api/envoy/api/v2/endpoint/endpoint.proto b/api/envoy/api/v2/endpoint/endpoint.proto index c458884c3a2bf..1d5d07f54d422 100644 --- a/api/envoy/api/v2/endpoint/endpoint.proto +++ b/api/envoy/api/v2/endpoint/endpoint.proto @@ -111,8 +111,8 @@ message LocalityLbEndpoints { // Locality weights are only considered when :ref:`locality weighted load // balancing ` is // configured. These weights are ignored otherwise. If no weights are - // specified when locality weighted load balancing is enabled, the cluster is - // assumed to have a weight of 1. + // specified when locality weighted load balancing is enabled, the locality is + // assigned no load. // // .. attention:: // diff --git a/source/common/upstream/maglev_lb.cc b/source/common/upstream/maglev_lb.cc index 292f901aed4c7..701e325b40190 100644 --- a/source/common/upstream/maglev_lb.cc +++ b/source/common/upstream/maglev_lb.cc @@ -26,7 +26,7 @@ MaglevTable::MaglevTable(const HostsPerLocality& hosts_per_locality, return host_weight; } else { auto locality_weight = (*locality_weights)[locality_index]; - ASSERT(locality_weight != 0); + // This might be zero, since locality weight might not be specified. return host_weight * locality_weight; } }; @@ -52,12 +52,22 @@ MaglevTable::MaglevTable(const HostsPerLocality& hosts_per_locality, for (uint32_t i = 0; i < hosts_per_locality.get().size(); ++i) { for (const auto& host : hosts_per_locality.get()[i]) { const std::string& address = host->address()->asString(); - table_build_entries.emplace_back(host, HashUtil::xxHash64(address) % table_size_, - (HashUtil::xxHash64(address, 1) % (table_size_ - 1)) + 1, - effective_weight(host->weight(), i)); + const uint32_t weight = effective_weight(host->weight(), i); + // If weight is zero, it should be totally excluded from table building + // below. + if (weight > 0) { + table_build_entries.emplace_back(host, HashUtil::xxHash64(address) % table_size_, + (HashUtil::xxHash64(address, 1) % (table_size_ - 1)) + 1, + weight); + } } } + // We can't do anything sensible with no table entries. + if (table_build_entries.empty()) { + return; + } + table_.resize(table_size_); uint64_t table_index = 0; uint32_t iteration = 1; diff --git a/test/common/upstream/maglev_lb_test.cc b/test/common/upstream/maglev_lb_test.cc index 34f196251da7f..895eb040e2e23 100644 --- a/test/common/upstream/maglev_lb_test.cc +++ b/test/common/upstream/maglev_lb_test.cc @@ -151,12 +151,13 @@ TEST_F(MaglevLoadBalancerTest, LocalityWeightedSameLocalityWeights) { // invert the Weighted effective weights). TEST_F(MaglevLoadBalancerTest, LocalityWeightedDifferentLocalityWeights) { host_set_.hosts_ = {makeTestHost(info_, "tcp://127.0.0.1:90", 1), - makeTestHost(info_, "tcp://127.0.0.1:91", 2)}; + makeTestHost(info_, "tcp://127.0.0.1:91", 2), + makeTestHost(info_, "tcp://127.0.0.1:92", 3)}; host_set_.healthy_hosts_ = host_set_.hosts_; host_set_.hosts_per_locality_ = - makeHostsPerLocality({{host_set_.hosts_[0]}, {host_set_.hosts_[1]}}); + makeHostsPerLocality({{host_set_.hosts_[0]}, {host_set_.hosts_[2]}, {host_set_.hosts_[1]}}); host_set_.healthy_hosts_per_locality_ = host_set_.hosts_per_locality_; - LocalityWeightsConstSharedPtr locality_weights{new LocalityWeights{8, 2}}; + LocalityWeightsConstSharedPtr locality_weights{new LocalityWeights{8, 0, 2}}; host_set_.locality_weights_ = locality_weights; host_set_.runCallbacks({}, {}); init(17); @@ -187,6 +188,21 @@ TEST_F(MaglevLoadBalancerTest, LocalityWeightedDifferentLocalityWeights) { } } +// Locality weighted with all localities zero weighted. +TEST_F(MaglevLoadBalancerTest, LocalityWeightedAllZeroLocalityWeights) { + host_set_.hosts_ = {makeTestHost(info_, "tcp://127.0.0.1:90", 1)}; + host_set_.healthy_hosts_ = host_set_.hosts_; + host_set_.hosts_per_locality_ = makeHostsPerLocality({{host_set_.hosts_[0]}}); + host_set_.healthy_hosts_per_locality_ = host_set_.hosts_per_locality_; + LocalityWeightsConstSharedPtr locality_weights{new LocalityWeights{0}}; + host_set_.locality_weights_ = locality_weights; + host_set_.runCallbacks({}, {}); + init(17); + LoadBalancerPtr lb = lb_->factory()->create(); + TestLoadBalancerContext context(0); + EXPECT_EQ(nullptr, lb->chooseHost(&context)); +} + // Validate that when we are in global panic and have localities, we get sane // results (fall back to non-healthy hosts). TEST_F(MaglevLoadBalancerTest, LocalityWeightedGlobalPanic) { diff --git a/test/server/server_corpus/clusterfuzz-testcase-config_fuzz_test-5067970991095808 b/test/server/server_corpus/clusterfuzz-testcase-config_fuzz_test-5067970991095808 new file mode 100644 index 0000000000000..ff46d4c233387 --- /dev/null +++ b/test/server/server_corpus/clusterfuzz-testcase-config_fuzz_test-5067970991095808 @@ -0,0 +1,58 @@ +static_resources { + clusters { + name: "6" + connect_timeout { + seconds: 2321 + } + lb_policy: MAGLEV + hosts { + pipe { + path: "=" + } + } + hosts { + pipe { + path: "=" + } + } + hosts { + pipe { + path: "t" + } + } + max_requests_per_connection { + value: 67108864 + } + dns_lookup_family: V4_ONLY + outlier_detection { + success_rate_minimum_hosts { + value: 4096 + } + } + common_lb_config { + locality_weighted_lb_config { + } + } + } +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/envoy.api.v2.route.Route" + value: "\022*J :2222222222222222222222222\022" + } +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/envoy.api.v2.route.Route" + value: "\022*J.:*static\'_resourc\022es {(\n cluster`s" + } +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/envoy.api.v2.route.Route" + value: "\022*J :2222222222222222222222221\022" + } +} +stats_flush_interval { + nanos: 2883584 +} From 8faf79befac0fa8f2cf513c3a13c55b4863211a2 Mon Sep 17 00:00:00 2001 From: Louis-Etienne Date: Wed, 6 Feb 2019 22:18:08 -0500 Subject: [PATCH 32/51] Fix the Jaeger Native Tracing example (#5866) Currently the Jaeger Native Tracing example doesn't work. When running it, I realized that the container built by`Dockerfile-frontenvoy` doesn't have `wget` installed. Because `curl` is already being installed by `Dockerfile-frontenvoy`, I decided to install it in `Dockerfile-service` as well and switch the `install-jaeger-plugin.sh` to `curl` instead of `wget` Risk Level: Low Testing: Follow the instruction here to run the example: https://www.envoyproxy.io/docs/envoy/latest/start/sandboxes/jaeger_native_tracing Signed-off-by: Louis-Etienne Dorval --- examples/front-proxy/Dockerfile-service | 2 +- examples/jaeger-native-tracing/install-jaeger-plugin.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/front-proxy/Dockerfile-service b/examples/front-proxy/Dockerfile-service index e3ccd82f96f93..ba7e5dbd2f011 100644 --- a/examples/front-proxy/Dockerfile-service +++ b/examples/front-proxy/Dockerfile-service @@ -1,6 +1,6 @@ FROM envoyproxy/envoy-alpine:latest -RUN apk update && apk add python3 bash +RUN apk update && apk add python3 bash curl RUN pip3 install -q Flask==0.11.1 requests==2.18.4 RUN mkdir /code ADD ./service.py /code diff --git a/examples/jaeger-native-tracing/install-jaeger-plugin.sh b/examples/jaeger-native-tracing/install-jaeger-plugin.sh index 5bdbb73c495e6..74576be5247eb 100755 --- a/examples/jaeger-native-tracing/install-jaeger-plugin.sh +++ b/examples/jaeger-native-tracing/install-jaeger-plugin.sh @@ -1,3 +1,3 @@ #!/usr/bin/env bash JAEGER_VERSION=v0.4.2 -wget -O /usr/local/lib/libjaegertracing_plugin.so https://github.com/jaegertracing/jaeger-client-cpp/releases/download/$JAEGER_VERSION/libjaegertracing_plugin.linux_amd64.so +curl -Lo /usr/local/lib/libjaegertracing_plugin.so https://github.com/jaegertracing/jaeger-client-cpp/releases/download/$JAEGER_VERSION/libjaegertracing_plugin.linux_amd64.so From 28fbbaa76026f52412c2550ff78664ca79c35487 Mon Sep 17 00:00:00 2001 From: Rama Chavali Date: Thu, 7 Feb 2019 09:02:46 +0530 Subject: [PATCH 33/51] api: add control plane identifier (#5860) This PR adds API support required for #5770 . Once #5844 lands, I will output it using the text stat. Risk Level: Low Testing: N/A Signed-off-by: Rama Chavali --- api/envoy/api/v2/core/base.proto | 8 ++++++++ api/envoy/api/v2/discovery.proto | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/api/envoy/api/v2/core/base.proto b/api/envoy/api/v2/core/base.proto index 3d03b3eb467ae..94c6bfbe9389f 100644 --- a/api/envoy/api/v2/core/base.proto +++ b/api/envoy/api/v2/core/base.proto @@ -240,3 +240,11 @@ message RuntimeFractionalPercent { // Runtime key for a YAML representation of a FractionalPercent. string runtime_key = 2; } + +// Identifies a specific ControlPlane instance that Envoy is connected to. +message ControlPlane { + // An opaque control plane identifier that uniquely identifies an instance + // of control plane. This can be used to identify which control plane instance, + // the Envoy is connected to. + string identifier = 1; +} diff --git a/api/envoy/api/v2/discovery.proto b/api/envoy/api/v2/discovery.proto index 17e5cfdcc38d6..ff04dc20f8b41 100644 --- a/api/envoy/api/v2/discovery.proto +++ b/api/envoy/api/v2/discovery.proto @@ -96,6 +96,10 @@ message DiscoveryResponse { // DiscoveryRequest bearing the nonce. The nonce is optional and is not // required for non-stream based xDS implementations. string nonce = 5; + + // [#not-implemented-hide:] + // The control plane instance that sent the response. + core.ControlPlane control_plane = 6; } // IncrementalDiscoveryRequest and IncrementalDiscoveryResponse are used in a From dded66ab8a003b1f2f355601b2763ddf0cc84dab Mon Sep 17 00:00:00 2001 From: Per Lundberg Date: Thu, 7 Feb 2019 20:47:35 +0200 Subject: [PATCH 34/51] README.md: Fix Ubuntu package list (#5679) - `realpath` is now in `coreutils`. Signed-off-by: Per Lundberg --- bazel/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bazel/README.md b/bazel/README.md index a8c315b989ef7..dbf95368f4523 100644 --- a/bazel/README.md +++ b/bazel/README.md @@ -33,9 +33,9 @@ On Ubuntu, run the following command: sudo apt-get install \ libtool \ cmake \ - realpath \ clang-format-7 \ automake \ + make \ ninja-build \ curl \ unzip From 53148176cd9a5248cf76ceefa33ac1caa24d6401 Mon Sep 17 00:00:00 2001 From: curiouserrandy Date: Thu, 7 Feb 2019 14:01:15 -0500 Subject: [PATCH 35/51] Make Envoy::Server::Options argument to Envoy::Server::InstanceImpl const (#5793) Signed-off-by: Randy Smith --- include/envoy/server/instance.h | 2 +- source/exe/main_common.cc | 2 +- source/exe/main_common.h | 4 ++-- source/server/config_validation/server.cc | 6 +++--- source/server/config_validation/server.h | 10 +++++----- source/server/hot_restart_impl.cc | 4 ++-- source/server/hot_restart_impl.h | 6 +++--- source/server/server.cc | 8 ++++---- source/server/server.h | 12 ++++++------ test/mocks/server/mocks.h | 2 +- 10 files changed, 28 insertions(+), 28 deletions(-) diff --git a/include/envoy/server/instance.h b/include/envoy/server/instance.h index 5bda8f1a27f7f..14e8dd2ffd537 100644 --- a/include/envoy/server/instance.h +++ b/include/envoy/server/instance.h @@ -135,7 +135,7 @@ class Instance { /** * @return the server's CLI options. */ - virtual Options& options() PURE; + virtual const Options& options() PURE; /** * @return RandomGenerator& the random generator for the server. diff --git a/source/exe/main_common.cc b/source/exe/main_common.cc index eed67ec4fff14..ef0d642e7fd7b 100644 --- a/source/exe/main_common.cc +++ b/source/exe/main_common.cc @@ -41,7 +41,7 @@ Runtime::LoaderPtr ProdComponentFactory::createRuntime(Server::Instance& server, return Server::InstanceUtil::createRuntime(server, config); } -MainCommonBase::MainCommonBase(OptionsImpl& options, Event::TimeSystem& time_system, +MainCommonBase::MainCommonBase(const OptionsImpl& options, Event::TimeSystem& time_system, TestHooks& test_hooks, Server::ComponentFactory& component_factory, std::unique_ptr&& random_generator, Thread::ThreadFactory& thread_factory) diff --git a/source/exe/main_common.h b/source/exe/main_common.h index d67acce589854..2af78ce27c71a 100644 --- a/source/exe/main_common.h +++ b/source/exe/main_common.h @@ -33,7 +33,7 @@ class MainCommonBase { public: // Consumer must guarantee that all passed references are alive until this object is // destructed. - MainCommonBase(OptionsImpl& options, Event::TimeSystem& time_system, TestHooks& test_hooks, + MainCommonBase(const OptionsImpl& options, Event::TimeSystem& time_system, TestHooks& test_hooks, Server::ComponentFactory& component_factory, std::unique_ptr&& random_generator, Thread::ThreadFactory& thread_factory); @@ -63,7 +63,7 @@ class MainCommonBase { const AdminRequestFn& handler); protected: - Envoy::OptionsImpl& options_; + const Envoy::OptionsImpl& options_; Server::ComponentFactory& component_factory_; Thread::ThreadFactory& thread_factory_; diff --git a/source/server/config_validation/server.cc b/source/server/config_validation/server.cc index b2220e00acb5d..82481e8a7cadc 100644 --- a/source/server/config_validation/server.cc +++ b/source/server/config_validation/server.cc @@ -17,7 +17,7 @@ namespace Envoy { namespace Server { -bool validateConfig(Options& options, Network::Address::InstanceConstSharedPtr local_address, +bool validateConfig(const Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory, Thread::ThreadFactory& thread_factory) { Thread::MutexBasicLockable access_log_lock; Stats::IsolatedStoreImpl stats_store; @@ -34,7 +34,7 @@ bool validateConfig(Options& options, Network::Address::InstanceConstSharedPtr l } } -ValidationInstance::ValidationInstance(Options& options, Event::TimeSystem& time_system, +ValidationInstance::ValidationInstance(const Options& options, Event::TimeSystem& time_system, Network::Address::InstanceConstSharedPtr local_address, Stats::IsolatedStoreImpl& store, Thread::BasicLockable& access_log_lock, @@ -56,7 +56,7 @@ ValidationInstance::ValidationInstance(Options& options, Event::TimeSystem& time } } -void ValidationInstance::initialize(Options& options, +void ValidationInstance::initialize(const Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory) { // See comments on InstanceImpl::initialize() for the overall flow here. diff --git a/source/server/config_validation/server.h b/source/server/config_validation/server.h index c6993a479737c..a8f5c35e48d8b 100644 --- a/source/server/config_validation/server.h +++ b/source/server/config_validation/server.h @@ -34,7 +34,7 @@ namespace Server { * validateConfig() takes over from main() for a config-validation run of Envoy. It returns true if * the config is valid, false if invalid. */ -bool validateConfig(Options& options, Network::Address::InstanceConstSharedPtr local_address, +bool validateConfig(const Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory, Thread::ThreadFactory& thread_factory); /** @@ -54,7 +54,7 @@ class ValidationInstance : Logger::Loggable, public ListenerComponentFactory, public WorkerFactory { public: - ValidationInstance(Options& options, Event::TimeSystem& time_system, + ValidationInstance(const Options& options, Event::TimeSystem& time_system, Network::Address::InstanceConstSharedPtr local_address, Stats::IsolatedStoreImpl& store, Thread::BasicLockable& access_log_lock, ComponentFactory& component_factory, Thread::ThreadFactory& thread_factory); @@ -85,7 +85,7 @@ class ValidationInstance : Logger::Loggable, Singleton::Manager& singletonManager() override { return *singleton_manager_; } OverloadManager& overloadManager() override { return *overload_manager_; } bool healthCheckFailed() override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } - Options& options() override { return options_; } + const Options& options() override { return options_; } time_t startTimeCurrentEpoch() override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } time_t startTimeFirstEpoch() override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } Stats::Store& stats() override { return stats_store_; } @@ -136,10 +136,10 @@ class ValidationInstance : Logger::Loggable, } private: - void initialize(Options& options, Network::Address::InstanceConstSharedPtr local_address, + void initialize(const Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory); - Options& options_; + const Options& options_; Stats::IsolatedStoreImpl& stats_store_; ThreadLocal::InstanceImpl thread_local_; Api::ApiPtr api_; diff --git a/source/server/hot_restart_impl.cc b/source/server/hot_restart_impl.cc index f9791d3b927a4..334ec322ecf13 100644 --- a/source/server/hot_restart_impl.cc +++ b/source/server/hot_restart_impl.cc @@ -40,7 +40,7 @@ static BlockMemoryHashSetOptions blockMemHashOptions(uint64_t max_stats) { return hash_set_options; } -SharedMemory& SharedMemory::initialize(uint64_t stats_set_size, Options& options) { +SharedMemory& SharedMemory::initialize(uint64_t stats_set_size, const Options& options) { Api::OsSysCalls& os_sys_calls = Api::OsSysCallsSingleton::get(); const uint64_t entry_size = Stats::RawStatData::structSizeWithOptions(options.statsOptions()); @@ -122,7 +122,7 @@ std::string SharedMemory::version(uint64_t max_num_stats, stats_options.maxNameLength()); } -HotRestartImpl::HotRestartImpl(Options& options) +HotRestartImpl::HotRestartImpl(const Options& options) : options_(options), stats_set_options_(blockMemHashOptions(options.maxStats())), shmem_(SharedMemory::initialize( Stats::RawStatDataSet::numBytes(stats_set_options_, options_.statsOptions()), options_)), diff --git a/source/server/hot_restart_impl.h b/source/server/hot_restart_impl.h index 9db5d5a672a88..5d432c42ad441 100644 --- a/source/server/hot_restart_impl.h +++ b/source/server/hot_restart_impl.h @@ -47,7 +47,7 @@ class SharedMemory { * Initialize the shared memory segment, depending on whether we should be the first running * envoy, or a host restarted envoy process. */ - static SharedMemory& initialize(uint64_t stats_set_size, Options& options); + static SharedMemory& initialize(uint64_t stats_set_size, const Options& options); /** * Initialize a pthread mutex for process shared locking. @@ -114,7 +114,7 @@ class ProcessSharedMutex : public Thread::BasicLockable { */ class HotRestartImpl : public HotRestart, Logger::Loggable { public: - HotRestartImpl(Options& options); + HotRestartImpl(const Options& options); // Server::HotRestart void drainParentListeners() override; @@ -206,7 +206,7 @@ class HotRestartImpl : public HotRestart, Logger::Loggable { static std::string versionHelper(uint64_t max_num_stats, const Stats::StatsOptions& stats_options, Stats::RawStatDataSet& stats_set); - Options& options_; + const Options& options_; BlockMemoryHashSetOptions stats_set_options_; SharedMemory& shmem_; std::unique_ptr stats_set_ GUARDED_BY(stat_lock_); diff --git a/source/server/server.cc b/source/server/server.cc index 475c23b60e2a9..1b50c92f868e3 100644 --- a/source/server/server.cc +++ b/source/server/server.cc @@ -45,7 +45,7 @@ namespace Envoy { namespace Server { -InstanceImpl::InstanceImpl(Options& options, Event::TimeSystem& time_system, +InstanceImpl::InstanceImpl(const Options& options, Event::TimeSystem& time_system, Network::Address::InstanceConstSharedPtr local_address, TestHooks& hooks, HotRestart& restarter, Stats::StoreRoot& store, Thread::BasicLockable& access_log_lock, @@ -171,7 +171,7 @@ bool InstanceImpl::healthCheckFailed() { return server_stats_->live_.value() == InstanceUtil::BootstrapVersion InstanceUtil::loadBootstrapConfig(envoy::config::bootstrap::v2::Bootstrap& bootstrap, - Options& options, Api::Api& api) { + const Options& options, Api::Api& api) { const std::string& config_path = options.configPath(); const std::string& config_yaml = options.configYaml(); @@ -194,7 +194,7 @@ InstanceUtil::loadBootstrapConfig(envoy::config::bootstrap::v2::Bootstrap& boots return BootstrapVersion::V2; } -void InstanceImpl::initialize(Options& options, +void InstanceImpl::initialize(const Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory) { ENVOY_LOG(info, "initializing epoch {} (hot restart version={})", options.restartEpoch(), @@ -394,7 +394,7 @@ void InstanceImpl::loadServerFlags(const absl::optional& flags_path uint64_t InstanceImpl::numConnections() { return listener_manager_->numConnections(); } -RunHelper::RunHelper(Instance& instance, Options& options, Event::Dispatcher& dispatcher, +RunHelper::RunHelper(Instance& instance, const Options& options, Event::Dispatcher& dispatcher, Upstream::ClusterManager& cm, AccessLog::AccessLogManager& access_log_manager, InitManagerImpl& init_manager, OverloadManager& overload_manager, std::function workers_start_cb) { diff --git a/source/server/server.h b/source/server/server.h index 9063332f4dd62..4580d1799cbd2 100644 --- a/source/server/server.h +++ b/source/server/server.h @@ -111,7 +111,7 @@ class InstanceUtil : Logger::Loggable { * @return BootstrapVersion to indicate which version of the API was parsed. */ static BootstrapVersion loadBootstrapConfig(envoy::config::bootstrap::v2::Bootstrap& bootstrap, - Options& options, Api::Api& api); + const Options& options, Api::Api& api); }; /** @@ -120,7 +120,7 @@ class InstanceUtil : Logger::Loggable { */ class RunHelper : Logger::Loggable { public: - RunHelper(Instance& instance, Options& options, Event::Dispatcher& dispatcher, + RunHelper(Instance& instance, const Options& options, Event::Dispatcher& dispatcher, Upstream::ClusterManager& cm, AccessLog::AccessLogManager& access_log_manager, InitManagerImpl& init_manager, OverloadManager& overload_manager, std::function workers_start_cb); @@ -140,7 +140,7 @@ class InstanceImpl : Logger::Loggable, public Instance { /** * @throw EnvoyException if initialization fails. */ - InstanceImpl(Options& options, Event::TimeSystem& time_system, + InstanceImpl(const Options& options, Event::TimeSystem& time_system, Network::Address::InstanceConstSharedPtr local_address, TestHooks& hooks, HotRestart& restarter, Stats::StoreRoot& store, Thread::BasicLockable& access_log_lock, ComponentFactory& component_factory, @@ -176,7 +176,7 @@ class InstanceImpl : Logger::Loggable, public Instance { void shutdownAdmin() override; Singleton::Manager& singletonManager() override { return *singleton_manager_; } bool healthCheckFailed() override; - Options& options() override { return options_; } + const Options& options() override { return options_; } time_t startTimeCurrentEpoch() override { return start_time_; } time_t startTimeFirstEpoch() override { return original_start_time_; } Stats::Store& stats() override { return stats_store_; } @@ -192,7 +192,7 @@ class InstanceImpl : Logger::Loggable, public Instance { private: ProtobufTypes::MessagePtr dumpBootstrapConfig(); void flushStats(); - void initialize(Options& options, Network::Address::InstanceConstSharedPtr local_address, + void initialize(const Options& options, Network::Address::InstanceConstSharedPtr local_address, ComponentFactory& component_factory); void loadServerFlags(const absl::optional& flags_path); uint64_t numConnections(); @@ -200,7 +200,7 @@ class InstanceImpl : Logger::Loggable, public Instance { void terminate(); bool shutdown_; - Options& options_; + const Options& options_; Event::TimeSystem& time_system_; HotRestart& restarter_; const time_t start_time_; diff --git a/test/mocks/server/mocks.h b/test/mocks/server/mocks.h index 74d48128444ed..a816b319f4b7c 100644 --- a/test/mocks/server/mocks.h +++ b/test/mocks/server/mocks.h @@ -339,7 +339,7 @@ class MockInstance : public Instance { MOCK_METHOD0(initManager, Init::Manager&()); MOCK_METHOD0(listenerManager, ListenerManager&()); MOCK_METHOD0(mutexTracer, Envoy::MutexTracer*()); - MOCK_METHOD0(options, Options&()); + MOCK_METHOD0(options, const Options&()); MOCK_METHOD0(overloadManager, OverloadManager&()); MOCK_METHOD0(random, Runtime::RandomGenerator&()); MOCK_METHOD0(runtime, Runtime::Loader&()); From e458dfa17e240cfac4294bca3c2003b1248d6a22 Mon Sep 17 00:00:00 2001 From: curiouserrandy Date: Thu, 7 Feb 2019 14:01:36 -0500 Subject: [PATCH 36/51] Modified docs and variable names (#5776) * Modified docs and variable names Signed-off-by: Randy Smith * Changed name in a couple of neglected files Signed-off-by: Randy Smith * Fixed format Signed-off-by: Randy Smith * Fix typo Signed-off-by: Randy Smith * Changed name of coroutines Signed-off-by: Randy Smith * Fixed format Signed-off-by: Randy Smith --- test/integration/ads_integration_test.cc | 2 +- test/integration/header_integration_test.cc | 2 +- test/integration/integration.cc | 10 +++++----- test/integration/integration.h | 8 +++++--- test/integration/sds_dynamic_integration_test.cc | 12 ++++++------ test/integration/server.cc | 16 ++++++++++------ test/integration/server.h | 4 ++-- 7 files changed, 30 insertions(+), 24 deletions(-) diff --git a/test/integration/ads_integration_test.cc b/test/integration/ads_integration_test.cc index 1b461c251cc9d..5688617365187 100644 --- a/test/integration/ads_integration_test.cc +++ b/test/integration/ads_integration_test.cc @@ -644,7 +644,7 @@ TEST_P(AdsIntegrationTest, XdsBatching) { static_resources->add_listeners()->MergeFrom(buildListener("rds_listener2", "route_config2")); }); - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createXdsConnection(); ASSERT_TRUE(xds_connection_->waitForNewStream(*dispatcher_, xds_stream_)); xds_stream_->startGrpcStream(); diff --git a/test/integration/header_integration_test.cc b/test/integration/header_integration_test.cc index 3151ce85cdbda..05b7cce9d4ab6 100644 --- a/test/integration/header_integration_test.cc +++ b/test/integration/header_integration_test.cc @@ -338,7 +338,7 @@ class HeaderIntegrationTest void initialize() override { if (use_eds_) { - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { AssertionResult result = fake_upstreams_[1]->waitForHttpConnection(*dispatcher_, eds_connection_); RELEASE_ASSERT(result, result.message()); diff --git a/test/integration/integration.cc b/test/integration/integration.cc index 6147978f30887..5b8de6e6495a9 100644 --- a/test/integration/integration.cc +++ b/test/integration/integration.cc @@ -368,9 +368,9 @@ void BaseIntegrationTest::registerTestServerPorts(const std::vector void BaseIntegrationTest::createGeneratedApiTestServer(const std::string& bootstrap_path, const std::vector& port_names) { - test_server_ = IntegrationTestServer::create(bootstrap_path, version_, - pre_worker_start_test_steps_, deterministic_, - timeSystem(), *api_, defer_listener_finalization_); + test_server_ = IntegrationTestServer::create(bootstrap_path, version_, on_server_init_function_, + deterministic_, timeSystem(), *api_, + defer_listener_finalization_); if (config_helper_.bootstrap().static_resources().listeners_size() > 0 && !defer_listener_finalization_) { // Wait for listeners to be created before invoking registerTestServerPorts() below, as that @@ -424,9 +424,9 @@ void BaseIntegrationTest::sendRawHttpAndWaitForResponse(int port, const char* ra IntegrationTestServerPtr BaseIntegrationTest::createIntegrationTestServer(const std::string& bootstrap_path, - std::function pre_worker_start_test_steps, + std::function on_server_init_function, Event::TestTimeSystem& time_system) { - return IntegrationTestServer::create(bootstrap_path, version_, pre_worker_start_test_steps, + return IntegrationTestServer::create(bootstrap_path, version_, on_server_init_function, deterministic_, time_system, *api_, defer_listener_finalization_); } diff --git a/test/integration/integration.h b/test/integration/integration.h index 15a77c66d0b67..85cf2acaf168a 100644 --- a/test/integration/integration.h +++ b/test/integration/integration.h @@ -229,7 +229,7 @@ class BaseIntegrationTest : Logger::Loggable { // Will not return until that server is listening. virtual IntegrationTestServerPtr createIntegrationTestServer(const std::string& bootstrap_path, - std::function pre_worker_start_steps, + std::function on_server_init_function, Event::TestTimeSystem& time_system); bool initialized() const { return initialized_; } @@ -238,8 +238,10 @@ class BaseIntegrationTest : Logger::Loggable { Network::Address::IpVersion version_; // The config for envoy start-up. ConfigHelper config_helper_; - // Steps that should be done prior to the workers starting. E.g., xDS pre-init. - std::function pre_worker_start_test_steps_; + + // Steps that should be done in parallel with the envoy server starting. E.g., xDS + // pre-init, control plane synchronization needed for server start. + std::function on_server_init_function_; std::vector> fake_upstreams_; // Target number of upstreams. diff --git a/test/integration/sds_dynamic_integration_test.cc b/test/integration/sds_dynamic_integration_test.cc index 427f113372b43..432222f7b5b03 100644 --- a/test/integration/sds_dynamic_integration_test.cc +++ b/test/integration/sds_dynamic_integration_test.cc @@ -199,7 +199,7 @@ INSTANTIATE_TEST_SUITE_P(IpVersionsClientType, SdsDynamicDownstreamIntegrationTe // A test that SDS server send a good server secret for a static listener. // The first ssl request should be OK. TEST_P(SdsDynamicDownstreamIntegrationTest, BasicSuccess) { - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getServerSecret()); }; @@ -215,7 +215,7 @@ TEST_P(SdsDynamicDownstreamIntegrationTest, BasicSuccess) { // The first ssl request should fail at connecting. // then SDS send a good server secret, the second request should be OK. TEST_P(SdsDynamicDownstreamIntegrationTest, WrongSecretFirst) { - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getWrongSecret(server_cert_)); }; @@ -296,7 +296,7 @@ INSTANTIATE_TEST_SUITE_P(IpVersionsClientType, SdsDynamicDownstreamCertValidatio // A test that SDS server send a good certificate validation context for a static listener. // The first ssl request should be OK. TEST_P(SdsDynamicDownstreamCertValidationContextTest, BasicSuccess) { - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getCvcSecret()); }; @@ -313,7 +313,7 @@ TEST_P(SdsDynamicDownstreamCertValidationContextTest, BasicSuccess) { // The first ssl request should be OK. TEST_P(SdsDynamicDownstreamCertValidationContextTest, CombinedCertValidationContextSuccess) { enableCombinedValidationContext(true); - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getCvcSecretWithOnlyTrustedCa()); }; @@ -375,7 +375,7 @@ INSTANTIATE_TEST_SUITE_P(IpVersions, SdsDynamicUpstreamIntegrationTest, // To test a static cluster with sds. SDS send a good client secret first. // The first request should work. TEST_P(SdsDynamicUpstreamIntegrationTest, BasicSuccess) { - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getClientSecret()); }; @@ -400,7 +400,7 @@ TEST_P(SdsDynamicUpstreamIntegrationTest, BasicSuccess) { // The first request should fail with 503, then SDS sends a good client secret, // the second request should work. TEST_P(SdsDynamicUpstreamIntegrationTest, WrongSecretFirst) { - pre_worker_start_test_steps_ = [this]() { + on_server_init_function_ = [this]() { createSdsStream(*(fake_upstreams_[1])); sendSdsResponse(getWrongSecret(client_cert_)); }; diff --git a/test/integration/server.cc b/test/integration/server.cc index 4fa5551d9fa0d..ad6581f1ee0a3 100644 --- a/test/integration/server.cc +++ b/test/integration/server.cc @@ -45,11 +45,11 @@ OptionsImpl createTestOptionsImpl(const std::string& config_path, const std::str IntegrationTestServerPtr IntegrationTestServer::create( const std::string& config_path, const Network::Address::IpVersion version, - std::function pre_worker_start_test_steps, bool deterministic, + std::function on_server_init_function, bool deterministic, Event::TestTimeSystem& time_system, Api::Api& api, bool defer_listener_finalization) { IntegrationTestServerPtr server{ std::make_unique(time_system, api, config_path)}; - server->start(version, pre_worker_start_test_steps, deterministic, defer_listener_finalization); + server->start(version, on_server_init_function, deterministic, defer_listener_finalization); return server; } @@ -64,16 +64,20 @@ void IntegrationTestServer::waitUntilListenersReady() { } void IntegrationTestServer::start(const Network::Address::IpVersion version, - std::function pre_worker_start_test_steps, - bool deterministic, bool defer_listener_finalization) { + std::function on_server_init_function, bool deterministic, + bool defer_listener_finalization) { ENVOY_LOG(info, "starting integration test server"); ASSERT(!thread_); thread_ = api_.threadFactory().createThread( [version, deterministic, this]() -> void { threadRoutine(version, deterministic); }); // If any steps need to be done prior to workers starting, do them now. E.g., xDS pre-init. - if (pre_worker_start_test_steps != nullptr) { - pre_worker_start_test_steps(); + // Note that there is no synchronization guaranteeing this happens either + // before workers starting or after server start. Any needed synchronization must occur in the + // routines. These steps are executed at this point in the code to allow server initialization to + // be dependent on them (e.g. control plane peers). + if (on_server_init_function != nullptr) { + on_server_init_function(); } // Wait for the server to be created and the number of initial listeners to wait for to be set. diff --git a/test/integration/server.h b/test/integration/server.h index ca03050c9b97d..3652119081244 100644 --- a/test/integration/server.h +++ b/test/integration/server.h @@ -174,7 +174,7 @@ class IntegrationTestServer : public Logger::Loggable, public: static IntegrationTestServerPtr create(const std::string& config_path, const Network::Address::IpVersion version, - std::function pre_worker_start_test_steps, + std::function on_server_init_function, bool deterministic, Event::TestTimeSystem& time_system, Api::Api& api, bool defer_listener_finalization = false); // Note that the derived class is responsible for tearing down the server in its @@ -191,7 +191,7 @@ class IntegrationTestServer : public Logger::Loggable, on_worker_listener_removed_cb_ = on_worker_listener_removed; } void start(const Network::Address::IpVersion version, - std::function pre_worker_start_test_steps, bool deterministic, + std::function on_server_init_function, bool deterministic, bool defer_listener_finalization); void waitForCounterGe(const std::string& name, uint64_t value) override { From c54274a79f0d908a09fb1fa08b199f8b1f0c5ae8 Mon Sep 17 00:00:00 2001 From: htuch Date: Thu, 7 Feb 2019 14:26:25 -0500 Subject: [PATCH 37/51] router: fix null-terminator issue in path replacement. (#5867) Fixes oss-fuzz issue https://oss-fuzz.com/testcase-detail/5137346677178368. Risk level: Low Testing: Corpus entry added. Signed-off-by: Harvey Tuch --- source/common/router/config_impl.cc | 2 +- ...-testcase-route_fuzz_test-5137346677178368 | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 test/common/router/route_corpus/clusterfuzz-testcase-route_fuzz_test-5137346677178368 diff --git a/source/common/router/config_impl.cc b/source/common/router/config_impl.cc index 100e897e96594..834ca0f6c4b2d 100644 --- a/source/common/router/config_impl.cc +++ b/source/common/router/config_impl.cc @@ -493,7 +493,7 @@ void RouteEntryImplBase::finalizePathHeader(Http::HeaderMap& headers, return; } - std::string path = headers.Path()->value().c_str(); + std::string path = std::string(headers.Path()->value().c_str(), headers.Path()->value().size()); if (insert_envoy_original_path) { headers.insertEnvoyOriginalPath().value(*headers.Path()); } diff --git a/test/common/router/route_corpus/clusterfuzz-testcase-route_fuzz_test-5137346677178368 b/test/common/router/route_corpus/clusterfuzz-testcase-route_fuzz_test-5137346677178368 new file mode 100644 index 0000000000000..e2475a16a4ff0 --- /dev/null +++ b/test/common/router/route_corpus/clusterfuzz-testcase-route_fuzz_test-5137346677178368 @@ -0,0 +1,21 @@ +config { + virtual_hosts { + name: " " + domains: "*" + routes { + match { + regex: ".*" + } + route { + cluster: "}" + prefix_rewrite: "%" + } + } + } +} +headers { + headers { + key: ":path" + value: "\001\000" + } +} From cd5dc017825d64b960723417633cdafe0fb07413 Mon Sep 17 00:00:00 2001 From: htuch Date: Thu, 7 Feb 2019 14:26:58 -0500 Subject: [PATCH 38/51] socket_option: don't set socket IP socket options on pipes. (#5870) Fixes oss-fuzz issue https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=12293. Risk level: Low Testing: Corpus entry and unit test added. Signed-off-by: Harvey Tuch --- .../network/addr_family_aware_socket_option_impl.cc | 11 +++++++++-- .../addr_family_aware_socket_option_impl_test.cc | 9 +++++++++ ...erfuzz-testcase-server_fuzz_test-5755877701713920 | 12 ++++++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 test/server/server_corpus/clusterfuzz-testcase-server_fuzz_test-5755877701713920 diff --git a/source/common/network/addr_family_aware_socket_option_impl.cc b/source/common/network/addr_family_aware_socket_option_impl.cc index 7fbce801960db..c5c4acbdcaba7 100644 --- a/source/common/network/addr_family_aware_socket_option_impl.cc +++ b/source/common/network/addr_family_aware_socket_option_impl.cc @@ -11,6 +11,13 @@ namespace Envoy { namespace Network { namespace { +Address::IpVersion getVersionFromAddress(Address::InstanceConstSharedPtr addr) { + if (addr->ip() != nullptr) { + return addr->ip()->version(); + } + throw EnvoyException("Unable to set socket option on non-IP sockets"); +} + absl::optional getVersionFromSocket(const Socket& socket) { try { // We have local address when the socket is used in a listener but have to @@ -18,10 +25,10 @@ absl::optional getVersionFromSocket(const Socket& socket) { // TODO(htuch): Figure out a way to obtain a consistent interface for IP // version from socket. if (socket.localAddress()) { - return absl::optional(socket.localAddress()->ip()->version()); + return absl::optional(getVersionFromAddress(socket.localAddress())); } else { return absl::optional( - Address::addressFromFd(socket.ioHandle().fd())->ip()->version()); + getVersionFromAddress(Address::addressFromFd(socket.ioHandle().fd()))); } } catch (const EnvoyException&) { // Ignore, we get here because we failed in getsockname(). diff --git a/test/common/network/addr_family_aware_socket_option_impl_test.cc b/test/common/network/addr_family_aware_socket_option_impl_test.cc index 2780f788546d9..442c68ae108c5 100644 --- a/test/common/network/addr_family_aware_socket_option_impl_test.cc +++ b/test/common/network/addr_family_aware_socket_option_impl_test.cc @@ -19,6 +19,15 @@ TEST_F(AddrFamilyAwareSocketOptionImplTest, SetOptionFailure) { EXPECT_LOG_CONTAINS("warning", "Failed to set IP socket option on non-IP socket", EXPECT_FALSE(socket_option.setOption( socket_, envoy::api::v2::core::SocketOption::STATE_PREBIND))); + + Address::InstanceConstSharedPtr pipe_address = + std::make_shared("/foo"); + { + EXPECT_CALL(socket_, localAddress).WillRepeatedly(testing::ReturnRef(pipe_address)); + EXPECT_LOG_CONTAINS("warning", "Failed to set IP socket option on non-IP socket", + EXPECT_FALSE(socket_option.setOption( + socket_, envoy::api::v2::core::SocketOption::STATE_PREBIND))); + } } // If a platform supports IPv4 socket option variant for an IPv4 address, it works diff --git a/test/server/server_corpus/clusterfuzz-testcase-server_fuzz_test-5755877701713920 b/test/server/server_corpus/clusterfuzz-testcase-server_fuzz_test-5755877701713920 new file mode 100644 index 0000000000000..f0ac04d436ee3 --- /dev/null +++ b/test/server/server_corpus/clusterfuzz-testcase-server_fuzz_test-5755877701713920 @@ -0,0 +1,12 @@ +static_resources { + listeners { + address { + pipe { + } + } + filter_chains { + } + freebind { + } + } +} From b2218acfc0cc5a52258b750486f626013374b51c Mon Sep 17 00:00:00 2001 From: Joshua Marantz Date: Thu, 7 Feb 2019 14:52:41 -0500 Subject: [PATCH 39/51] test: Make the creation of a test time system threadsafe (#5849) * Make the creation of a test time system threadsafe. I am not aware of a situation where we might race the creation of our thread-system singleton between two threads, but it's not that hard or slow to make that work. So it seems easier to do this proactively than to wait for a flake. Signed-off-by: Joshua Marantz --- test/common/stats/symbol_table_impl_test.cc | 14 ++------ test/test_common/BUILD | 1 + test/test_common/test_time.cc | 8 +++++ test/test_common/test_time.h | 8 +---- test/test_common/test_time_system.cc | 19 ++++++++++ test/test_common/test_time_system.h | 40 +++++++++++---------- 6 files changed, 53 insertions(+), 37 deletions(-) create mode 100644 test/test_common/test_time_system.cc diff --git a/test/common/stats/symbol_table_impl_test.cc b/test/common/stats/symbol_table_impl_test.cc index 571f2665d9471..eb1c531cf3068 100644 --- a/test/common/stats/symbol_table_impl_test.cc +++ b/test/common/stats/symbol_table_impl_test.cc @@ -367,6 +367,8 @@ TEST_P(StatNameTest, JoinAllEmpty) { EXPECT_EQ("", table_->toString(StatName(joined.get()))); } +// Validates that we don't get tsan or other errors when concurrently creating +// a large number of stats. TEST_P(StatNameTest, RacingSymbolCreation) { Thread::ThreadFactory& thread_factory = Thread::threadFactoryForTest(); MutexTracerImpl& mutex_tracer = MutexTracerImpl::getOrCreateTracer(); @@ -406,21 +408,9 @@ TEST_P(StatNameTest, RacingSymbolCreation) { int64_t create_contentions = mutex_tracer.numContentions(); ENVOY_LOG_MISC(info, "Number of contentions: {}", create_contentions); - // But when we access the already-existing symbols, we guarantee that no - // further mutex contentions occur. - int64_t start_contentions = mutex_tracer.numContentions(); access.setReady(); accesses.Wait(); - // With fake symbol tables, there are no contentions as there are is no state - // in the symbol table to lock. This is why fake symbol tables are a safe way - // to transition the codebase to use the SymbolTable API without impacting - // hot-path performance. - if (GetParam() == SymbolTableType::Fake) { - EXPECT_EQ(create_contentions, mutex_tracer.numContentions()); - EXPECT_EQ(start_contentions, create_contentions); - } - // In a perfect world, we could use reader-locks in the SymbolTable // implementation, and there should be zero additional contentions // after latching 'create_contentions' above. And we can definitely diff --git a/test/test_common/BUILD b/test/test_common/BUILD index b314e54f0c13e..83a43c77e4ab5 100644 --- a/test/test_common/BUILD +++ b/test/test_common/BUILD @@ -179,6 +179,7 @@ envoy_cc_test_library( envoy_cc_test_library( name = "test_time_system_interface", + srcs = ["test_time_system.cc"], hdrs = ["test_time_system.h"], deps = [ ":global_lib", diff --git a/test/test_common/test_time.cc b/test/test_common/test_time.cc index 24bd072e6b4fb..3b97d7f6afb36 100644 --- a/test/test_common/test_time.cc +++ b/test/test_common/test_time.cc @@ -10,6 +10,14 @@ DangerousDeprecatedTestTime::DangerousDeprecatedTestTime() {} namespace Event { +TestTimeSystem& GlobalTimeSystem::timeSystem() { + // TODO(#4160): Switch default to SimulatedTimeSystem. + auto make_real_time_system = []() -> std::unique_ptr { + return std::make_unique(); + }; + return singleton_->timeSystem(make_real_time_system); +} + void TestRealTimeSystem::sleep(const Duration& duration) { std::this_thread::sleep_for(duration); } Thread::CondVar::WaitStatus TestRealTimeSystem::waitFor(Thread::MutexBasicLockable& lock, diff --git a/test/test_common/test_time.h b/test/test_common/test_time.h index ea0411f6a2c95..ca659426d044d 100644 --- a/test/test_common/test_time.h +++ b/test/test_common/test_time.h @@ -31,13 +31,7 @@ class TestRealTimeSystem : public TestTimeSystem { class GlobalTimeSystem : public DelegatingTestTimeSystemBase { public: - TestTimeSystem& timeSystem() override { - if (singleton_->timeSystem() == nullptr) { - // TODO(#4160): Switch default to SimulatedTimeSystem. - singleton_->set(new TestRealTimeSystem); - } - return *singleton_->timeSystem(); - } + TestTimeSystem& timeSystem() override; private: Test::Global singleton_; diff --git a/test/test_common/test_time_system.cc b/test/test_common/test_time_system.cc new file mode 100644 index 0000000000000..a24763e9c07db --- /dev/null +++ b/test/test_common/test_time_system.cc @@ -0,0 +1,19 @@ +#include "test/test_common/test_time_system.h" + +#include "envoy/event/timer.h" + +#include "common/common/thread.h" + +namespace Envoy { +namespace Event { + +TestTimeSystem& SingletonTimeSystemHelper::timeSystem(const MakeTimeSystemFn& make_time_system) { + Thread::LockGuard lock(mutex_); + if (time_system_ == nullptr) { + time_system_ = make_time_system(); + } + return *time_system_; +} + +} // namespace Event +} // namespace Envoy diff --git a/test/test_common/test_time_system.h b/test/test_common/test_time_system.h index cced13dbb6b93..864b4a4286be8 100644 --- a/test/test_common/test_time_system.h +++ b/test/test_common/test_time_system.h @@ -61,15 +61,19 @@ class SingletonTimeSystemHelper { public: SingletonTimeSystemHelper() : time_system_(nullptr) {} - void set(TestTimeSystem* time_system) { - RELEASE_ASSERT(time_system_ == nullptr, "Unexpected reset of SingletonTimeSystemHelper"); - time_system_.reset(time_system); - } + using MakeTimeSystemFn = std::function()>; - TestTimeSystem* timeSystem() { return time_system_.get(); } + /** + * Returns a singleton time-system, creating a default one of there's not + * one already. This method is thread-safe. + * + * @return the time system. + */ + TestTimeSystem& timeSystem(const MakeTimeSystemFn& make_time_system); private: - std::unique_ptr time_system_; + std::unique_ptr time_system_ GUARDED_BY(mutex_); + Thread::MutexBasicLockable mutex_; }; // Implements the TestTimeSystem interface, delegating implementation of all @@ -106,22 +110,22 @@ template class DelegatingTestTimeSystemBase : public T template class DelegatingTestTimeSystem : public DelegatingTestTimeSystemBase { public: - DelegatingTestTimeSystem() { - TestTimeSystem* time_system = singleton_->timeSystem(); - if (time_system == nullptr) { - time_system_ = new TimeSystemVariant; - singleton_->set(time_system_); - } else { - time_system_ = dynamic_cast(time_system); - RELEASE_ASSERT(time_system_, "Two different types of time-systems allocated"); - } - } + DelegatingTestTimeSystem() : time_system_(initTimeSystem()) {} - TimeSystemVariant& timeSystem() override { return *time_system_; } + TimeSystemVariant& timeSystem() override { return time_system_; } private: - TimeSystemVariant* time_system_; + TimeSystemVariant& initTimeSystem() { + auto make_time_system = []() -> std::unique_ptr { + return std::make_unique(); + }; + auto time_system = dynamic_cast(&singleton_->timeSystem(make_time_system)); + RELEASE_ASSERT(time_system, "Two different types of time-systems allocated"); + return *time_system; + } + Test::Global singleton_; + TimeSystemVariant& time_system_; }; } // namespace Event From 6061f6ce562337e3e6c9641c0001b6e9dc7195ee Mon Sep 17 00:00:00 2001 From: htuch Date: Thu, 7 Feb 2019 17:01:05 -0500 Subject: [PATCH 40/51] build: fix ubsan oss-fuzz build. (#5875) We were still failing ClusterFuzz builds for ubsan, another external_cmake regression. Risk level: Low Testing: oss-fuzz undefined Docker build. Signed-off-by: Harvey Tuch --- bazel/cc_wrapper.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/bazel/cc_wrapper.py b/bazel/cc_wrapper.py index 78fa90fbb6e0f..bd7098950dad2 100755 --- a/bazel/cc_wrapper.py +++ b/bazel/cc_wrapper.py @@ -39,7 +39,8 @@ def main(): # # Similar behavior exists for Clang's `-stdlib=libc++` flag, so we handle # it in the same test. - if "-static-libstdc++" in sys.argv[1:] or "-stdlib=libc++" in sys.argv[1:]: + if ("-static-libstdc++" in sys.argv[1:] or "-stdlib=libc++" in sys.argv[1:] or + "-std=c++0x" in sys.argv[1:]): compiler = envoy_real_cxx else: compiler = envoy_real_cc @@ -62,7 +63,7 @@ def main(): # unless the user has explicitly set environment variables # before starting Bazel. But here in $PWD is the Bazel sandbox, # which will be deleted automatically after the compiler exits. - (flagfile_fd, flagfile_path) = tempfile.mkstemp(dir='./', suffix=".linker-params") + (flagfile_fd, flagfile_path) = tempfile.mkstemp(dir="./", suffix=".linker-params") with closing_fd(flagfile_fd): sanitize_flagfile(arg[len("-Wl,@"):], flagfile_fd) argv.append("-Wl,@" + flagfile_path) From 4fe9806cd9e834567ae95effe33ef6465ef421a9 Mon Sep 17 00:00:00 2001 From: Bill DeCoste Date: Thu, 7 Feb 2019 16:02:58 -0800 Subject: [PATCH 41/51] fix EVP_MD_CTX instantiation for openssl (#5877) Modify EVP_MD_CTX instantiation in common/crypto to support openssl. Instantiating via "EVP_MD_CTX ctx" fails compilation. Openssl required EVP_MD_CTX_new(). Risk Level: Low Testing: Standard tests pass Signed-off-by: William DeCoste --- source/common/crypto/utility.cc | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/source/common/crypto/utility.cc b/source/common/crypto/utility.cc index e5c5f80e72d40..885b4c0bbcaba 100644 --- a/source/common/crypto/utility.cc +++ b/source/common/crypto/utility.cc @@ -13,19 +13,20 @@ namespace Crypto { std::vector Utility::getSha256Digest(const Buffer::Instance& buffer) { std::vector digest(SHA256_DIGEST_LENGTH); - EVP_MD_CTX ctx; - auto rc = EVP_DigestInit(&ctx, EVP_sha256()); + EVP_MD_CTX* ctx(EVP_MD_CTX_new()); + auto rc = EVP_DigestInit(ctx, EVP_sha256()); RELEASE_ASSERT(rc == 1, "Failed to init digest context"); const auto num_slices = buffer.getRawSlices(nullptr, 0); STACK_ARRAY(slices, Buffer::RawSlice, num_slices); buffer.getRawSlices(slices.begin(), num_slices); for (const auto& slice : slices) { - rc = EVP_DigestUpdate(&ctx, slice.mem_, slice.len_); + rc = EVP_DigestUpdate(ctx, slice.mem_, slice.len_); RELEASE_ASSERT(rc == 1, "Failed to update digest"); } unsigned int len; - rc = EVP_DigestFinal(&ctx, digest.data(), &len); + rc = EVP_DigestFinal(ctx, digest.data(), &len); RELEASE_ASSERT(rc == 1, "Failed to finalize digest"); + EVP_MD_CTX_free(ctx); return digest; } From c450760d0c546385962605382f0b6b5dcb1a8a84 Mon Sep 17 00:00:00 2001 From: curiouserrandy Date: Thu, 7 Feb 2019 19:04:17 -0500 Subject: [PATCH 42/51] Shift test_base library to testonly+basic_cc_library. (#5865) Mark //test/test_common:test_base testonly for environments that enforce that bit. Risk Level: Low: Build change, any errors should be quick to surface. Testing: Built all of envoy. Signed-off-by: Randy Smith --- bazel/envoy_build_system.bzl | 34 +++++++++++++++++++++++++++++----- test/test_common/BUILD | 4 ++-- 2 files changed, 31 insertions(+), 7 deletions(-) diff --git a/bazel/envoy_build_system.bzl b/bazel/envoy_build_system.bzl index 437b12c086a24..ed64bdada2bf4 100644 --- a/bazel/envoy_build_system.bzl +++ b/bazel/envoy_build_system.bzl @@ -416,9 +416,9 @@ def envoy_cc_test( shard_count = shard_count, ) -# Envoy C++ test related libraries (that want gtest, gmock) should be specified -# with this function. -def envoy_cc_test_library( +# Envoy C++ related test infrastructure (that want gtest, gmock, but may be +# relied on by envoy_cc_test_library) should use this function. +def envoy_cc_test_infrastructure_library( name, srcs = [], hdrs = [], @@ -436,14 +436,38 @@ def envoy_cc_test_library( testonly = 1, deps = deps + [envoy_external_dep_path(dep) for dep in external_deps] + [ envoy_external_dep_path("googletest"), - repository + "//test/test_common:printers_includes", - repository + "//test/test_common:test_base", ], tags = tags, alwayslink = 1, linkstatic = 1, ) +# Envoy C++ test related libraries (that want gtest, gmock) should be specified +# with this function. +def envoy_cc_test_library( + name, + srcs = [], + hdrs = [], + data = [], + external_deps = [], + deps = [], + repository = "", + tags = []): + deps = deps + [ + repository + "//test/test_common:printers_includes", + repository + "//test/test_common:test_base", + ] + envoy_cc_test_infrastructure_library( + name, + srcs, + hdrs, + data, + external_deps, + deps, + repository, + tags, + ) + # Envoy test binaries should be specified with this function. def envoy_cc_test_binary( name, diff --git a/test/test_common/BUILD b/test/test_common/BUILD index 83a43c77e4ab5..6a19c4e5a2ec5 100644 --- a/test/test_common/BUILD +++ b/test/test_common/BUILD @@ -5,6 +5,7 @@ load( "envoy_basic_cc_library", "envoy_cc_library", "envoy_cc_test", + "envoy_cc_test_infrastructure_library", "envoy_cc_test_library", "envoy_package", ) @@ -156,12 +157,11 @@ envoy_cc_test( ], ) -envoy_cc_library( +envoy_cc_test_infrastructure_library( name = "test_base", srcs = ["test_base.cc"], hdrs = ["test_base.h"], deps = [ - "//external:googletest", "//test/test_common:global_lib", ], ) From 24e2e0e735347a0440fe456ddc328053ba095daa Mon Sep 17 00:00:00 2001 From: Ismo Puustinen Date: Fri, 8 Feb 2019 03:29:46 +0200 Subject: [PATCH 43/51] tools: fix compilation db generation for VSCode. (#5873) Change the gen_compilation_database.py command to accept a --vscode flag. If this flag is on, create such a compilation database which can be used by Visual Studio Code for code analysis. At the moment it only changes "-iquote" compiler options to old-style "-I" options to prevent Visual Studio Code from falling back to tag parser mode. *Risk Level*: low *Testing*: Visual Studio Code v1.31 *Docs Changes*: N/A *Release Notes*: N/A Signed-off-by: Ismo Puustinen --- tools/gen_compilation_database.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tools/gen_compilation_database.py b/tools/gen_compilation_database.py index f55b6edf2ebc9..8bf23a171b80d 100755 --- a/tools/gen_compilation_database.py +++ b/tools/gen_compilation_database.py @@ -38,14 +38,19 @@ def isCompileTarget(target, args): return True -def modifyCompileCommand(target): - cxx, options = target["command"].split(" ", 1) +def modifyCompileCommand(target, args): + _, options = target["command"].split(" ", 1) # Workaround for bazel added C++11 options, those doesn't affect build itself but # clang-tidy will misinterpret them. options = options.replace("-std=c++0x ", "") options = options.replace("-std=c++11 ", "") + if args.vscode: + # Visual Studio Code doesn't seem to like "-iquote". Replace it with + # old-style "-I". + options = options.replace("-iquote ", "-I ") + if isHeader(target["file"]): options += " -Wno-pragma-once-outside-header -Wno-unused-const-variable" options += " -Wno-unused-function" @@ -58,7 +63,7 @@ def fixCompilationDatabase(args): with open("compile_commands.json", "r") as db_file: db = json.load(db_file) - db = [modifyCompileCommand(target) for target in db if isCompileTarget(target, args)] + db = [modifyCompileCommand(target, args) for target in db if isCompileTarget(target, args)] # Remove to avoid writing into symlink os.remove("compile_commands.json") @@ -72,6 +77,7 @@ def fixCompilationDatabase(args): parser.add_argument('--include_external', action='store_true') parser.add_argument('--include_genfiles', action='store_true') parser.add_argument('--include_headers', action='store_true') + parser.add_argument('--vscode', action='store_true') parser.add_argument( 'bazel_targets', nargs='*', default=["//source/...", "//test/...", "//tools/..."]) args = parser.parse_args() From f679d8a322ea5ec8b460a02f99c0991add8a44f6 Mon Sep 17 00:00:00 2001 From: htuch Date: Thu, 7 Feb 2019 23:32:22 -0500 Subject: [PATCH 44/51] config_validation: fix heap-use-after-free. (#5847) Same issue as in #4940, but on the config_validation side. Risk level: Low Testing: corpus entry added. Signed-off-by: Harvey Tuch --- source/server/config_validation/server.h | 4 +- source/server/server.h | 2 + ...inimized-config_fuzz_test-5762646786179072 | 395 ++++++++++++++++++ 3 files changed, 400 insertions(+), 1 deletion(-) create mode 100644 test/server/server_corpus/clusterfuzz-testcase-minimized-config_fuzz_test-5762646786179072 diff --git a/source/server/config_validation/server.h b/source/server/config_validation/server.h index a8f5c35e48d8b..052d747f92fa4 100644 --- a/source/server/config_validation/server.h +++ b/source/server/config_validation/server.h @@ -154,8 +154,10 @@ class ValidationInstance : Logger::Loggable, AccessLog::AccessLogManagerImpl access_log_manager_; std::unique_ptr cluster_manager_factory_; InitManagerImpl init_manager_; - std::unique_ptr listener_manager_; + // secret_manager_ must come before listener_manager_, since there may be active filter chains + // referencing it, so need to destruct these first. std::unique_ptr secret_manager_; + std::unique_ptr listener_manager_; std::unique_ptr overload_manager_; MutexTracer* mutex_tracer_; Http::ContextImpl http_context_; diff --git a/source/server/server.h b/source/server/server.h index 4580d1799cbd2..0b0d0ae9b4cc3 100644 --- a/source/server/server.h +++ b/source/server/server.h @@ -210,6 +210,8 @@ class InstanceImpl : Logger::Loggable, public Instance { Assert::ActionRegistrationPtr assert_action_registration_; ThreadLocal::Instance& thread_local_; Api::ApiPtr api_; + // secret_manager_ must come before dispatcher_, since there may be active connections + // referencing it, so need to destruct these first. std::unique_ptr secret_manager_; Event::DispatcherPtr dispatcher_; std::unique_ptr admin_; diff --git a/test/server/server_corpus/clusterfuzz-testcase-minimized-config_fuzz_test-5762646786179072 b/test/server/server_corpus/clusterfuzz-testcase-minimized-config_fuzz_test-5762646786179072 new file mode 100644 index 0000000000000..36099b8b2fd3c --- /dev/null +++ b/test/server/server_corpus/clusterfuzz-testcase-minimized-config_fuzz_test-5762646786179072 @@ -0,0 +1,395 @@ +node { id: " " cluster: " " } static_resources { listeners { address { pipe { path: " " } } filter_chains { tls_context { common_tls_context { tls_params { tls_minimum_protocol_version: TLSv1_2 tls_maximum_protocol_version: TLSv1_3 cipher_suites: " " ecdh_curves: " " } tls_certificate_sds_secret_configs { sds_config { api_config_source { cluster_names: "" cluster_names: "" cluster_names: "" cluster_names: "" cluster_names: "" cluster_names: "" cluster_names: "" cluster_names: "" cluster_names: "" } } } validation_context_sds_secret_config { sds_config { ads { } } } } require_client_certificate { value: true } } } metadata { filter_metadata { key: "" value { + } + } + filter_metadata { + key: "\000\000\000" + value { + } + } + filter_metadata { + key: "\000\000\000\014" + value { + fields { + key: "" + value { + } + } + } + } + filter_metadata { + key: "\000\000\010\010" + value { + } + } + filter_metadata { + key: "\000\000\024\024" + value { + } + } + filter_metadata { + key: "\000\004\004\004" + value { + } + } + filter_metadata { + key: "\000\004\027\000\010\010" + value { + } + } + filter_metadata { + key: "\000\005\010" + value { + } + } + filter_metadata { + key: "\000\020\001\010" + value { + } + } + filter_metadata { + key: "\004\000\000\004" + value { + } + } + filter_metadata { + key: "\024\020n" + value { + } + } + filter_metadata { + key: " " + value { + } + } + filter_metadata { + key: "\"" + value { + } + } + filter_metadata { + key: "4" + value { + } + } + filter_metadata { + key: "B" + value { + } + } + filter_metadata { + key: "LN~NNNN" + value { + } + } + filter_metadata { + key: "M" + value { + } + } + filter_metadata { + key: "M" + value { + } + } + filter_metadata { + key: "NH~=LZ" + value { + } + } + filter_metadata { + key: "NL/EN/X" + value { + } + } + filter_metadata { + key: "NL/LNNX" + value { + } + } + filter_metadata { + key: "NNMn!mN" + value { + } + } + filter_metadata { + key: "NNNHH^" + value { + } + } + filter_metadata { + key: "NNNHNNN" + value { + } + } + filter_metadata { + key: "NNNH`NN" + value { + fields { + key: "[" + value { + } + } + } + } + filter_metadata { + key: "NNNLNNN" + value { + } + } + filter_metadata { + key: "NNNN~L^" + value { + } + } + filter_metadata { + key: "NNN~=LZ" + value { + } + } + filter_metadata { + key: "envoy.hnnection_managemananer" + value { + } + } + filter_metadata { + key: "f&fff$f2fff" + value { + } + } + filter_metadata { + key: "f&fffnameff" + } + filter_metadata { + key: "ffQff$fffff" + value { + fields { + key: "\000\000\000\005" + value { + } + } + } + } + filter_metadata { + key: "ffff$ffffff" + value { + } + } + filter_metadata { + key: "fffff$fff$f" + value { + } + } + filter_metadata { + key: "ffffffQf@ff" + value { + } + } + filter_metadata { + key: "ffffffffff&" + value { + } + } + filter_metadata { + key: "ffffffffnf&" + value { + } + } + filter_metadata { + key: "nAm!" + value { + } + } + filter_metadata { + key: "p" + value { + } + } + filter_metadata { + key: "t=L^NNN" + value { + } + } + filter_metadata { + key: "u" + value { + fields { + key: "\000\000\000\005" + value { + } + } + } + } + filter_metadata { + key: "}fffv$fffff" + value { + } + } + filter_metadata { + key: "\312\277 " + value { + } + } + filter_metadata { + key: "\314\200`282366920938463463374607431768211455stati\020alt" + value { + } + } + filter_metadata { + key: "\314\200`282366929384634633744607431768211455stati\000alt" + value { + } + } + filter_metadata { + key: "\314\200`282366929384634669293846432337611455stati\000alt" + value { + } + } + filter_metadata { + key: "\314\200\340282366920938463463374607431768211455static_resources {\n clusters {\n he\000alt" + value { + } + } + filter_metadata { + key: "\343\203\262\"88GIHT98\361\241\254\243\341\277\236`28236692093:463463374607431768211203\363\213\207\222\361\221\226\240\005" + value { + } + } + filter_metadata { + key: "\343\203\262\"88GIHT98\361\241\254\243\341\277\236`28:366920938463463374607431712163208\363\213\207\222\321\221\314\240\005" + value { + } + } + } + tcp_fast_open_queue_length { + } + } +} +dynamic_resources { + ads_config { + api_type: GRPC + grpc_services { + google_grpc { + target_uri: "*" + stat_prefix: " " + } + } + } +} +stats_sinks { + name: "!" +} +stats_sinks { +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.prlue" + } +} +stats_sinks { +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.prlue" + } +} +stats_sinks { +} +stats_sinks { + name: "\005" +} +stats_sinks { + name: "\005" + typed_config { + type_url: "type.googleapis.com/google.protobuf.Value" + value: "2\366\337\303\377\007!\253" + } +} +stats_sinks { +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.protobuf.Value" + value: "2\366\337\303\377\007!\253" + } +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/envoy.api.v2.route.Route" + value: "d" + } +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.protobuf.ListValue" + value: "2\366\337\303\377\007!\253" + } +} +stats_sinks { + name: "tsy.googtati" + typed_config { + type_url: "type.googleapiobuf.Value" + } +} +stats_sinks { + name: "," +} +stats_sinks { + name: "\005" +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.protobuf.Value" + value: "2\366\337\303\377\007!\253" + } +} +stats_sinks { + name: "," +} +stats_sinks { + name: "," + typed_config { + type_url: "type.googleapis.com/google.protobuf.Value" + value: "2\366\337\303\377\007!\253" + } +} +stats_sinks { +} +stats_sinks { +} +stats_sinks { + name: "\005" +} +stats_sinks { +} +stats_sinks { +} +stats_sinks { +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.prlue" + } +} +stats_sinks { +} +stats_sinks { +} +stats_sinks { + name: "\005" +} +stats_sinks { + typed_config { + type_url: "type.googleapis.com/google.protobuf.ListValue" + } +} +hds_config { + cluster_names: "" + cluster_names: "" + cluster_names: "" + cluster_names: "" + cluster_names: "" + cluster_names: "" + cluster_names: "" + cluster_names: "" + cluster_names: "" +} From 0c7d4a0f6dc945067709101279a2e5bfcbfceb20 Mon Sep 17 00:00:00 2001 From: Frank Date: Thu, 7 Feb 2019 23:56:51 -0500 Subject: [PATCH 45/51] docs: update bazel README to include virtualenv (#5864) Using buildifier failed without virtualenv so noting in the bazel README file. Also did some cleanup of the ordered list to always use "1.", see https://guides.github.com/features/mastering-markdown/#syntax. Risk Level: Low Signed-off-by: Frank Fort --- bazel/README.md | 88 +++++++++++++++++++++++++------------------------ 1 file changed, 45 insertions(+), 43 deletions(-) diff --git a/bazel/README.md b/bazel/README.md index dbf95368f4523..276075061551b 100644 --- a/bazel/README.md +++ b/bazel/README.md @@ -27,49 +27,51 @@ up-to-date with the latest security patches. See for how to update or override dependencies. 1. Install the latest version of [Bazel](https://bazel.build/versions/master/docs/install.html) in your environment. -2. Install external dependencies libtool, cmake, ninja, realpath and curl libraries separately. -On Ubuntu, run the following command: -``` -sudo apt-get install \ - libtool \ - cmake \ - clang-format-7 \ - automake \ - make \ - ninja-build \ - curl \ - unzip -``` - -On Fedora (maybe also other red hat distros), run the following: -``` -dnf install cmake libtool libstdc++ ninja-build lld patch -``` - -On macOS, you'll need to install several dependencies. This can be accomplished via [Homebrew](https://brew.sh/): -``` -brew install coreutils wget cmake libtool go bazel automake ninja llvm@7 -``` -_notes_: `coreutils` is used for `realpath`, `gmd5sum` and `gsha256sum`; `llvm@7` is used for `clang-format` - -Envoy compiles and passes tests with the version of clang installed by XCode 9.3.0: -Apple LLVM version 9.1.0 (clang-902.0.30). - -In order for bazel to be aware of the tools installed by brew, the PATH -variable must be set for bazel builds. This can be accomplished by setting -this in your `$HOME/.bazelrc` file: - -``` -build --action_env=PATH="/usr/local/bin:/opt/local/bin:/usr/bin:/bin" -``` - -Alternatively, you can pass `--action_env` on the command line when running -`bazel build`/`bazel test`. - -3. Install Golang on your machine. This is required as part of building [BoringSSL](https://boringssl.googlesource.com/boringssl/+/HEAD/BUILDING.md) -and also for [Buildifer](https://github.com/bazelbuild/buildtools) which is used for formatting bazel BUILD files. -4. `go get github.com/bazelbuild/buildtools/buildifier` to install buildifier -5. `bazel build //source/exe:envoy-static` from the Envoy source directory. +1. Install external dependencies libtool, cmake, ninja, realpath and curl libraries separately. + On Ubuntu, run the following command: + ``` + sudo apt-get install \ + libtool \ + cmake \ + clang-format-7 \ + automake \ + make \ + ninja-build \ + curl \ + unzip \ + virtualenv + ``` + + On Fedora (maybe also other red hat distros), run the following: + ``` + dnf install cmake libtool libstdc++ ninja-build lld patch + ``` + + On macOS, you'll need to install several dependencies. This can be accomplished via [Homebrew](https://brew.sh/): + ``` + brew install coreutils wget cmake libtool go bazel automake ninja llvm@7 + ``` + _notes_: `coreutils` is used for `realpath`, `gmd5sum` and `gsha256sum`; `llvm@7` is used for `clang-format` + + Envoy compiles and passes tests with the version of clang installed by XCode 9.3.0: + Apple LLVM version 9.1.0 (clang-902.0.30). + + In order for bazel to be aware of the tools installed by brew, the PATH + variable must be set for bazel builds. This can be accomplished by setting + this in your `$HOME/.bazelrc` file: + + ``` + build --action_env=PATH="/usr/local/bin:/opt/local/bin:/usr/bin:/bin" + ``` + + Alternatively, you can pass `--action_env` on the command line when running + `bazel build`/`bazel test`. + +1. Install Golang on your machine. This is required as part of building [BoringSSL](https://boringssl.googlesource.com/boringssl/+/HEAD/BUILDING.md) + and also for [Buildifer](https://github.com/bazelbuild/buildtools) which is used for formatting bazel BUILD files. +1. `go get -u github.com/bazelbuild/buildtools/buildifier` to install buildifier. You may need to set `BUILDIFIER_BIN` to `$GOPATH/bin/buildifier` + in your shell for buildifier to work. +1. `bazel build //source/exe:envoy-static` from the Envoy source directory. ## Building Bazel with the CI Docker image From 8c6bf40042543713eb7493e0d4ff29b312c78772 Mon Sep 17 00:00:00 2001 From: Snow Pettersen Date: Thu, 7 Feb 2019 21:07:13 -0800 Subject: [PATCH 46/51] upstream: add support for setting degraded through LoadAssignment (#5649) Adds a DEGRADED HealthStatus value that can be set on a host through LoadAssignment, allowing for a host to be marked degraded without the need for active health checking. Moves the mapping of EDS flag to health flag to inside `registerHostForPriority`, which means that we're now consistently setting the EDS health flag for EDS/STATIC/STRICT_DNS/LOGICAL_DNS. Simplifies the check for whether the health flag value of a host has changed during EDS updates. Adds tests for the EDS mapping as well as tests to verify that we're honoring the EDS flag for non-EDS cluster types. Risk Level: High, substantial refactoring of how we determine whether health flag has changed. Testing: UTs coverage for new health flag values. Docs Changes: n/a Release Notes: n/a Fixes #5637 #5063 Signed-off-by: Snow Pettersen --- api/envoy/api/v2/core/health_check.proto | 3 + include/envoy/upstream/upstream.h | 4 +- source/common/upstream/eds.cc | 2 +- .../upstream/health_discovery_service.cc | 11 ++- source/common/upstream/logical_dns_cluster.cc | 3 +- source/common/upstream/logical_dns_cluster.h | 2 +- .../common/upstream/original_dst_cluster.cc | 11 ++- source/common/upstream/upstream_impl.cc | 93 +++++++++++-------- source/common/upstream/upstream_impl.h | 19 ++-- source/server/http/admin.cc | 12 ++- test/common/upstream/eds_test.cc | 30 ++++++ .../upstream/load_balancer_simulation_test.cc | 3 +- test/common/upstream/upstream_impl_test.cc | 64 ++++++++++++- test/common/upstream/utility.h | 9 +- test/integration/eds_integration_test.cc | 28 ++++-- test/server/http/admin_test.cc | 4 +- 16 files changed, 216 insertions(+), 82 deletions(-) diff --git a/api/envoy/api/v2/core/health_check.proto b/api/envoy/api/v2/core/health_check.proto index 65102d613dc81..74b0249834598 100644 --- a/api/envoy/api/v2/core/health_check.proto +++ b/api/envoy/api/v2/core/health_check.proto @@ -254,4 +254,7 @@ enum HealthStatus { // Health check timed out. This is part of HDS and is interpreted by Envoy as // *UNHEALTHY*. TIMEOUT = 4; + + // Degraded. + DEGRADED = 5; } diff --git a/include/envoy/upstream/upstream.h b/include/envoy/upstream/upstream.h index e280ab7f515f7..20028c32669a3 100644 --- a/include/envoy/upstream/upstream.h +++ b/include/envoy/upstream/upstream.h @@ -48,7 +48,9 @@ class Host : virtual public HostDescription { /* The host is currently marked as unhealthy by EDS. */ \ m(FAILED_EDS_HEALTH, 0x04) \ /* The host is currently marked as degraded through active health checking. */ \ - m(DEGRADED_ACTIVE_HC, 0x08) + m(DEGRADED_ACTIVE_HC, 0x08) \ + /* The host is currently marked as degraded by EDS. */ \ + m(DEGRADED_EDS_HEALTH, 0x10) // clang-format on #define DECLARE_ENUM(name, value) name = value, diff --git a/source/common/upstream/eds.cc b/source/common/upstream/eds.cc index 835820a7badc9..f1895f37a88ad 100644 --- a/source/common/upstream/eds.cc +++ b/source/common/upstream/eds.cc @@ -75,7 +75,7 @@ void EdsClusterImpl::onConfigUpdate(const ResourceVector& resources, const std:: for (const auto& lb_endpoint : locality_lb_endpoint.lb_endpoints()) { priority_state_manager.registerHostForPriority( "", resolveProtoAddress(lb_endpoint.endpoint().address()), locality_lb_endpoint, - lb_endpoint, Host::HealthFlag::FAILED_EDS_HEALTH); + lb_endpoint); } } diff --git a/source/common/upstream/health_discovery_service.cc b/source/common/upstream/health_discovery_service.cc index 624f5b8e86243..ae44def4a796f 100644 --- a/source/common/upstream/health_discovery_service.cc +++ b/source/common/upstream/health_discovery_service.cc @@ -204,11 +204,12 @@ HdsCluster::HdsCluster(Server::Admin& admin, Runtime::Loader& runtime, dispatcher, random, singleton_manager, tls, api}); for (const auto& host : cluster.hosts()) { - initial_hosts_->emplace_back(new HostImpl( - info_, "", Network::Address::resolveProtoAddress(host), - envoy::api::v2::core::Metadata::default_instance(), 1, - envoy::api::v2::core::Locality().default_instance(), - envoy::api::v2::endpoint::Endpoint::HealthCheckConfig().default_instance(), 0)); + initial_hosts_->emplace_back( + new HostImpl(info_, "", Network::Address::resolveProtoAddress(host), + envoy::api::v2::core::Metadata::default_instance(), 1, + envoy::api::v2::core::Locality().default_instance(), + envoy::api::v2::endpoint::Endpoint::HealthCheckConfig().default_instance(), 0, + envoy::api::v2::core::HealthStatus::UNKNOWN)); } initialize([] {}); } diff --git a/source/common/upstream/logical_dns_cluster.cc b/source/common/upstream/logical_dns_cluster.cc index e98ba6fc5c79f..c5bcc8bbb67df 100644 --- a/source/common/upstream/logical_dns_cluster.cc +++ b/source/common/upstream/logical_dns_cluster.cc @@ -112,8 +112,7 @@ void LogicalDnsCluster::startResolve() { const auto& locality_lb_endpoint = localityLbEndpoint(); PriorityStateManager priority_state_manager(*this, local_info_); priority_state_manager.initializePriorityFor(locality_lb_endpoint); - priority_state_manager.registerHostForPriority(logical_host_, locality_lb_endpoint, - lbEndpoint(), absl::nullopt); + priority_state_manager.registerHostForPriority(logical_host_, locality_lb_endpoint); const uint32_t priority = locality_lb_endpoint.priority(); priority_state_manager.updateClusterPrioritySet( diff --git a/source/common/upstream/logical_dns_cluster.h b/source/common/upstream/logical_dns_cluster.h index 90479696c4428..b75b7858da03b 100644 --- a/source/common/upstream/logical_dns_cluster.h +++ b/source/common/upstream/logical_dns_cluster.h @@ -47,7 +47,7 @@ class LogicalDnsCluster : public ClusterImplBase { parent.lbEndpoint().load_balancing_weight().value(), parent.localityLbEndpoint().locality(), parent.lbEndpoint().endpoint().health_check_config(), - parent.localityLbEndpoint().priority()), + parent.localityLbEndpoint().priority(), parent.lbEndpoint().health_status()), parent_(parent) {} // Upstream::Host diff --git a/source/common/upstream/original_dst_cluster.cc b/source/common/upstream/original_dst_cluster.cc index 2e4232095059e..1b54ca9f4faef 100644 --- a/source/common/upstream/original_dst_cluster.cc +++ b/source/common/upstream/original_dst_cluster.cc @@ -77,11 +77,12 @@ HostConstSharedPtr OriginalDstCluster::LoadBalancer::chooseHost(LoadBalancerCont Network::Address::InstanceConstSharedPtr host_ip_port( Network::Utility::copyInternetAddressAndPort(*dst_ip)); // Create a host we can use immediately. - host.reset(new HostImpl( - info_, info_->name() + dst_addr.asString(), std::move(host_ip_port), - envoy::api::v2::core::Metadata::default_instance(), 1, - envoy::api::v2::core::Locality().default_instance(), - envoy::api::v2::endpoint::Endpoint::HealthCheckConfig().default_instance(), 0)); + host.reset( + new HostImpl(info_, info_->name() + dst_addr.asString(), std::move(host_ip_port), + envoy::api::v2::core::Metadata::default_instance(), 1, + envoy::api::v2::core::Locality().default_instance(), + envoy::api::v2::endpoint::Endpoint::HealthCheckConfig().default_instance(), + 0, envoy::api::v2::core::HealthStatus::UNKNOWN)); ENVOY_LOG(debug, "Created host {}.", host->address()->asString()); // Add the new host to the map. We just failed to find it in diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index 3229e67a74464..e232be55eb270 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -170,6 +170,30 @@ parseExtensionProtocolOptions(const envoy::api::v2::Cluster& config) { return options; } +// Updates the health flags for an existing host to match the new host. +// @param updated_host the new host to read health flag values from. +// @param existing_host the host to update. +// @param flag the health flag to update. +// @return bool whether the flag update caused the host health to change. +bool updateHealthFlag(const Host& updated_host, Host& existing_host, Host::HealthFlag flag) { + // Check if the health flag has changed. + if (existing_host.healthFlagGet(flag) != updated_host.healthFlagGet(flag)) { + // Keep track of the previous health value of the host. + const auto previous_health = existing_host.health(); + + if (updated_host.healthFlagGet(flag)) { + existing_host.healthFlagSet(flag); + } else { + existing_host.healthFlagClear(flag); + } + + // Rebuild if changing the flag affected the host health. + return previous_health != existing_host.health(); + } + + return false; +} + } // namespace Host::CreateConnectionData HostImpl::createConnection( @@ -179,6 +203,24 @@ Host::CreateConnectionData HostImpl::createConnection( shared_from_this()}; } +void HostImpl::setEdsHealthFlag(envoy::api::v2::core::HealthStatus health_status) { + switch (health_status) { + case envoy::api::v2::core::HealthStatus::UNHEALTHY: + FALLTHRU; + case envoy::api::v2::core::HealthStatus::DRAINING: + FALLTHRU; + case envoy::api::v2::core::HealthStatus::TIMEOUT: + healthFlagSet(Host::HealthFlag::FAILED_EDS_HEALTH); + break; + case envoy::api::v2::core::HealthStatus::DEGRADED: + healthFlagSet(Host::HealthFlag::DEGRADED_EDS_HEALTH); + break; + default:; + break; + // No health flags should be set. + } +} + Host::CreateConnectionData HostImpl::createHealthCheckConnection(Event::Dispatcher& dispatcher) const { return {createConnection(dispatcher, *cluster_, healthCheckAddress(), nullptr, nullptr), @@ -863,32 +905,22 @@ void PriorityStateManager::initializePriorityFor( void PriorityStateManager::registerHostForPriority( const std::string& hostname, Network::Address::InstanceConstSharedPtr address, const envoy::api::v2::endpoint::LocalityLbEndpoints& locality_lb_endpoint, - const envoy::api::v2::endpoint::LbEndpoint& lb_endpoint, - const absl::optional health_checker_flag) { + const envoy::api::v2::endpoint::LbEndpoint& lb_endpoint) { const HostSharedPtr host( new HostImpl(parent_.info(), hostname, address, lb_endpoint.metadata(), lb_endpoint.load_balancing_weight().value(), locality_lb_endpoint.locality(), - lb_endpoint.endpoint().health_check_config(), locality_lb_endpoint.priority())); - registerHostForPriority(host, locality_lb_endpoint, lb_endpoint, health_checker_flag); + lb_endpoint.endpoint().health_check_config(), locality_lb_endpoint.priority(), + lb_endpoint.health_status())); + registerHostForPriority(host, locality_lb_endpoint); } void PriorityStateManager::registerHostForPriority( const HostSharedPtr& host, - const envoy::api::v2::endpoint::LocalityLbEndpoints& locality_lb_endpoint, - const envoy::api::v2::endpoint::LbEndpoint& lb_endpoint, - const absl::optional health_checker_flag) { + const envoy::api::v2::endpoint::LocalityLbEndpoints& locality_lb_endpoint) { const uint32_t priority = locality_lb_endpoint.priority(); // Should be called after initializePriorityFor. ASSERT(priority_state_[priority].first); priority_state_[priority].first->emplace_back(host); - if (health_checker_flag.has_value()) { - const auto& health_status = lb_endpoint.health_status(); - if (health_status == envoy::api::v2::core::HealthStatus::UNHEALTHY || - health_status == envoy::api::v2::core::HealthStatus::DRAINING || - health_status == envoy::api::v2::core::HealthStatus::TIMEOUT) { - priority_state_[priority].first->back()->healthFlagSet(health_checker_flag.value()); - } - } } void PriorityStateManager::updateClusterPrioritySet( @@ -982,7 +1014,7 @@ StaticClusterImpl::StaticClusterImpl( for (const auto& lb_endpoint : locality_lb_endpoint.lb_endpoints()) { priority_state_manager_->registerHostForPriority( "", resolveProtoAddress(lb_endpoint.endpoint().address()), locality_lb_endpoint, - lb_endpoint, absl::nullopt); + lb_endpoint); } } } @@ -1069,24 +1101,10 @@ bool BaseDynamicClusterImpl::updateDynamicHostList(const HostVector& new_hosts, max_host_weight = host->weight(); } - if (existing_host->second->healthFlagGet(Host::HealthFlag::FAILED_EDS_HEALTH) != - host->healthFlagGet(Host::HealthFlag::FAILED_EDS_HEALTH)) { - // TODO(snowp): To accommodate degraded, this bit should be checking for any changes - // to the health flag, not just healthy vs not healthy. - const bool previously_healthy = existing_host->second->health() == Host::Health::Healthy; - if (host->healthFlagGet(Host::HealthFlag::FAILED_EDS_HEALTH)) { - existing_host->second->healthFlagSet(Host::HealthFlag::FAILED_EDS_HEALTH); - // If the host was previously healthy and we're now unhealthy, we need to - // rebuild. - hosts_changed |= previously_healthy; - } else { - existing_host->second->healthFlagClear(Host::HealthFlag::FAILED_EDS_HEALTH); - // If the host was previously unhealthy and now healthy, we need to - // rebuild. - hosts_changed |= - !previously_healthy && existing_host->second->health() == Host::Health::Healthy; - } - } + hosts_changed |= + updateHealthFlag(*host, *existing_host->second, Host::HealthFlag::FAILED_EDS_HEALTH); + hosts_changed |= + updateHealthFlag(*host, *existing_host->second, Host::HealthFlag::DEGRADED_EDS_HEALTH); // Did metadata change? const bool metadata_changed = !Protobuf::util::MessageDifferencer::Equivalent( @@ -1259,8 +1277,7 @@ void StrictDnsClusterImpl::updateAllHosts(const HostVector& hosts_added, priority_state_manager.initializePriorityFor(target->locality_lb_endpoint_); for (const HostSharedPtr& host : target->hosts_) { if (target->locality_lb_endpoint_.priority() == current_priority) { - priority_state_manager.registerHostForPriority(host, target->locality_lb_endpoint_, - target->lb_endpoint_, absl::nullopt); + priority_state_manager.registerHostForPriority(host, target->locality_lb_endpoint_); } } } @@ -1309,7 +1326,7 @@ void StrictDnsClusterImpl::ResolveTarget::startResolve() { parent_.info_, dns_address_, Network::Utility::getAddressWithPort(*address, port_), lb_endpoint_.metadata(), lb_endpoint_.load_balancing_weight().value(), locality_lb_endpoint_.locality(), lb_endpoint_.endpoint().health_check_config(), - locality_lb_endpoint_.priority())); + locality_lb_endpoint_.priority(), lb_endpoint_.health_status())); } HostVector hosts_added; @@ -1337,4 +1354,4 @@ void StrictDnsClusterImpl::ResolveTarget::startResolve() { } } // namespace Upstream -} // namespace Envoy \ No newline at end of file +} // namespace Envoy diff --git a/source/common/upstream/upstream_impl.h b/source/common/upstream/upstream_impl.h index 09ca654183538..ba40c584a4aa0 100644 --- a/source/common/upstream/upstream_impl.h +++ b/source/common/upstream/upstream_impl.h @@ -162,10 +162,11 @@ class HostImpl : public HostDescriptionImpl, const envoy::api::v2::core::Metadata& metadata, uint32_t initial_weight, const envoy::api::v2::core::Locality& locality, const envoy::api::v2::endpoint::Endpoint::HealthCheckConfig& health_check_config, - uint32_t priority) + uint32_t priority, const envoy::api::v2::core::HealthStatus health_status) : HostDescriptionImpl(cluster, hostname, address, metadata, locality, health_check_config, priority), used_(true) { + setEdsHealthFlag(health_status); weight(initial_weight); } @@ -206,7 +207,8 @@ class HostImpl : public HostDescriptionImpl, } // Only possible option at this point is that the host is degraded. - ASSERT(health_flags_ == static_cast(HealthFlag::DEGRADED_ACTIVE_HC)); + ASSERT(healthFlagGet(HealthFlag::DEGRADED_ACTIVE_HC) || + healthFlagGet(HealthFlag::DEGRADED_EDS_HEALTH)); return Host::Health::Degraded; } @@ -223,6 +225,8 @@ class HostImpl : public HostDescriptionImpl, Network::TransportSocketOptionsSharedPtr transport_socket_options); private: + void setEdsHealthFlag(envoy::api::v2::core::HealthStatus health_status); + std::atomic health_flags_{}; ActiveHealthFailureType active_health_failure_type_{}; std::atomic weight_; @@ -666,14 +670,11 @@ class PriorityStateManager : protected Logger::Loggable { registerHostForPriority(const std::string& hostname, Network::Address::InstanceConstSharedPtr address, const envoy::api::v2::endpoint::LocalityLbEndpoints& locality_lb_endpoint, - const envoy::api::v2::endpoint::LbEndpoint& lb_endpoint, - const absl::optional health_checker_flag); + const envoy::api::v2::endpoint::LbEndpoint& lb_endpoint); - void - registerHostForPriority(const HostSharedPtr& host, - const envoy::api::v2::endpoint::LocalityLbEndpoints& locality_lb_endpoint, - const envoy::api::v2::endpoint::LbEndpoint& lb_endpoint, - const absl::optional health_checker_flag); + void registerHostForPriority( + const HostSharedPtr& host, + const envoy::api::v2::endpoint::LocalityLbEndpoints& locality_lb_endpoint); void updateClusterPrioritySet(const uint32_t priority, HostVectorSharedPtr&& current_hosts, diff --git a/source/server/http/admin.cc b/source/server/http/admin.cc index ade0137129bfc..4d60e0ed7aa85 100644 --- a/source/server/http/admin.cc +++ b/source/server/http/admin.cc @@ -169,10 +169,14 @@ void setHealthFlag(Upstream::Host::HealthFlag flag, const Upstream::Host& host, host.healthFlagGet(Upstream::Host::HealthFlag::FAILED_OUTLIER_CHECK)); break; case Upstream::Host::HealthFlag::FAILED_EDS_HEALTH: - health_status.set_eds_health_status( - host.healthFlagGet(Upstream::Host::HealthFlag::FAILED_EDS_HEALTH) - ? envoy::api::v2::core::HealthStatus::UNHEALTHY - : envoy::api::v2::core::HealthStatus::HEALTHY); + case Upstream::Host::HealthFlag::DEGRADED_EDS_HEALTH: + if (host.healthFlagGet(Upstream::Host::HealthFlag::FAILED_EDS_HEALTH)) { + health_status.set_eds_health_status(envoy::api::v2::core::HealthStatus::UNHEALTHY); + } else if (host.healthFlagGet(Upstream::Host::HealthFlag::DEGRADED_EDS_HEALTH)) { + health_status.set_eds_health_status(envoy::api::v2::core::HealthStatus::DEGRADED); + } else { + health_status.set_eds_health_status(envoy::api::v2::core::HealthStatus::HEALTHY); + } break; case Upstream::Host::HealthFlag::DEGRADED_ACTIVE_HC: health_status.set_failed_active_degraded_check( diff --git a/test/common/upstream/eds_test.cc b/test/common/upstream/eds_test.cc index be98cdf9f97eb..e0af3c27f5a11 100644 --- a/test/common/upstream/eds_test.cc +++ b/test/common/upstream/eds_test.cc @@ -339,6 +339,7 @@ TEST_F(EdsTest, EndpointHealthStatus) { {envoy::api::v2::core::HealthStatus::UNHEALTHY, Host::Health::Unhealthy}, {envoy::api::v2::core::HealthStatus::DRAINING, Host::Health::Unhealthy}, {envoy::api::v2::core::HealthStatus::TIMEOUT, Host::Health::Unhealthy}, + {envoy::api::v2::core::HealthStatus::DEGRADED, Host::Health::Degraded}, }; int port = 80; @@ -423,6 +424,35 @@ TEST_F(EdsTest, EndpointHealthStatus) { hosts[0]->healthFlagClear(Host::HealthFlag::FAILED_ACTIVE_HC); EXPECT_EQ(Host::Health::Healthy, hosts[0]->health()); } + + const auto rebuild_container = stats_.counter("cluster.name.update_no_rebuild").value(); + // Now mark host 0 degraded via EDS, it should be degraded. + endpoints->mutable_lb_endpoints(0)->set_health_status( + envoy::api::v2::core::HealthStatus::DEGRADED); + VERBOSE_EXPECT_NO_THROW(cluster_->onConfigUpdate(resources, "")); + { + auto& hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); + EXPECT_EQ(Host::Health::Degraded, hosts[0]->health()); + } + + // We should rebuild the cluster since we went from healthy -> degraded. + EXPECT_EQ(rebuild_container, stats_.counter("cluster.name.update_no_rebuild").value()); + + // Now mark the host as having been degraded through active hc. + cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[0]->healthFlagSet( + Host::HealthFlag::DEGRADED_ACTIVE_HC); + + // Now mark host 0 healthy via EDS, it should still be degraded. + endpoints->mutable_lb_endpoints(0)->set_health_status( + envoy::api::v2::core::HealthStatus::HEALTHY); + VERBOSE_EXPECT_NO_THROW(cluster_->onConfigUpdate(resources, "")); + { + auto& hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); + EXPECT_EQ(Host::Health::Degraded, hosts[0]->health()); + } + + // Since the host health didn't change, expect no rebuild. + EXPECT_EQ(rebuild_container + 1, stats_.counter("cluster.name.update_no_rebuild").value()); } // Validate that onConfigUpdate() removes endpoints that are marked as healthy diff --git a/test/common/upstream/load_balancer_simulation_test.cc b/test/common/upstream/load_balancer_simulation_test.cc index 14267d825b685..a02c9674395c7 100644 --- a/test/common/upstream/load_balancer_simulation_test.cc +++ b/test/common/upstream/load_balancer_simulation_test.cc @@ -29,7 +29,8 @@ static HostSharedPtr newTestHost(Upstream::ClusterInfoConstSharedPtr cluster, return HostSharedPtr{ new HostImpl(cluster, "", Network::Utility::resolveUrl(url), envoy::api::v2::core::Metadata::default_instance(), weight, locality, - envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 0)}; + envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 0, + envoy::api::v2::core::HealthStatus::UNKNOWN)}; } // Simulate weighted LR load balancer. diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index a84e7b834b985..358ce56188502 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -455,6 +455,7 @@ TEST_F(StrictDnsClusterImplTest, LoadAssignmentBasic) { port_value: 11001 health_check_config: port_value: 8000 + health_status: DEGRADED - endpoint: address: socket_address: @@ -524,6 +525,10 @@ TEST_F(StrictDnsClusterImplTest, LoadAssignmentBasic) { EXPECT_EQ("localhost1", cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]->hostname()); EXPECT_EQ("localhost1", cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[1]->hostname()); EXPECT_EQ(100, cluster.prioritySet().hostSetsPerPriority()[0]->overprovisioningFactor()); + EXPECT_EQ(Host::Health::Degraded, + cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]->health()); + EXPECT_EQ(Host::Health::Degraded, + cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[1]->health()); // This is the first time we received an update for localhost1, we expect to rebuild. EXPECT_EQ(0UL, stats_.counter("cluster.name.update_no_rebuild").value()); @@ -582,7 +587,8 @@ TEST_F(StrictDnsClusterImplTest, LoadAssignmentBasic) { std::list({"127.0.0.3:11001", "10.0.0.1:11002"}), ContainerEq(hostListToAddresses(cluster.prioritySet().hostSetsPerPriority()[0]->hosts()))); - EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); + EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); + EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->degradedHosts().size()); EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->hostsPerLocality().get().size()); EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHostsPerLocality().get().size()); @@ -596,7 +602,8 @@ TEST_F(StrictDnsClusterImplTest, LoadAssignmentBasic) { EXPECT_THAT(std::list({"127.0.0.3:11001", "10.0.0.1:11002", "10.0.0.1:11002"}), ContainerEq(hostListToAddresses(hosts))); - EXPECT_EQ(3UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); + EXPECT_EQ(2UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); + EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->degradedHosts().size()); EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->hostsPerLocality().get().size()); EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->healthyHostsPerLocality().get().size()); @@ -816,7 +823,8 @@ TEST(HostImplTest, HostnameCanaryAndLocality) { locality.set_sub_zone("world"); HostImpl host(cluster.info_, "lyft.com", Network::Utility::resolveUrl("tcp://10.0.0.1:1234"), metadata, 1, locality, - envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 1); + envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 1, + envoy::api::v2::core::HealthStatus::UNKNOWN); EXPECT_EQ(cluster.info_.get(), &host.cluster()); EXPECT_EQ("lyft.com", host.hostname()); EXPECT_TRUE(host.canary()); @@ -844,6 +852,18 @@ TEST(HostImplTest, HealthFlags) { // If the degraded flag is the only thing set, host is degraded. host->healthFlagClear(Host::HealthFlag::FAILED_ACTIVE_HC); EXPECT_EQ(Host::Health::Degraded, host->health()); + + // If the EDS and active degraded flag is set, host is degraded. + host->healthFlagSet(Host::HealthFlag::DEGRADED_EDS_HEALTH); + EXPECT_EQ(Host::Health::Degraded, host->health()); + + // If only the EDS degraded is set, host is degraded. + host->healthFlagClear(Host::HealthFlag::DEGRADED_ACTIVE_HC); + EXPECT_EQ(Host::Health::Degraded, host->health()); + + // If EDS and failed active hc is set, host is unhealthy. + host->healthFlagSet(Host::HealthFlag::FAILED_ACTIVE_HC); + EXPECT_EQ(Host::Health::Unhealthy, host->health()); } class StaticClusterImplTest : public TestBase, public UpstreamImplTestBase {}; @@ -1040,6 +1060,44 @@ TEST_F(StaticClusterImplTest, LoadAssignmentLocality) { EXPECT_FALSE(cluster.info()->addedViaApi()); } +// Validates that setting an EDS health value through LoadAssignment is honored for static clusters. +TEST_F(StaticClusterImplTest, LoadAssignmentEdsHealth) { + const std::string yaml = R"EOF( + name: staticcluster + connect_timeout: 0.25s + type: STATIC + lb_policy: ROUND_ROBIN + load_assignment: + policy: + overprovisioning_factor: 100 + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: 10.0.0.1 + port_value: 443 + health_check_config: + port_value: 8000 + health_status: DEGRADED + )EOF"; + + NiceMock cm; + envoy::api::v2::Cluster cluster_config = parseClusterFromV2Yaml(yaml); + Envoy::Stats::ScopePtr scope = stats_.createScope(fmt::format( + "cluster.{}.", cluster_config.alt_stat_name().empty() ? cluster_config.name() + : cluster_config.alt_stat_name())); + Envoy::Server::Configuration::TransportSocketFactoryContextImpl factory_context( + admin_, ssl_context_manager_, *scope, cm_, local_info_, dispatcher_, random_, stats_, + singleton_manager_, tls_, *api_); + StaticClusterImpl cluster(cluster_config, runtime_, factory_context, std::move(scope), false); + cluster.initialize([] {}); + + EXPECT_EQ(1UL, cluster.prioritySet().hostSetsPerPriority()[0]->degradedHosts().size()); + EXPECT_EQ(Host::Health::Degraded, + cluster.prioritySet().hostSetsPerPriority()[0]->hosts()[0]->health()); +} + TEST_F(StaticClusterImplTest, AltStatName) { const std::string yaml = R"EOF( name: staticcluster diff --git a/test/common/upstream/utility.h b/test/common/upstream/utility.h index be3373ced54b6..7eec5f8d21954 100644 --- a/test/common/upstream/utility.h +++ b/test/common/upstream/utility.h @@ -79,7 +79,8 @@ inline HostSharedPtr makeTestHost(ClusterInfoConstSharedPtr cluster, const std:: return HostSharedPtr{new HostImpl( cluster, "", Network::Utility::resolveUrl(url), envoy::api::v2::core::Metadata::default_instance(), weight, envoy::api::v2::core::Locality(), - envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 0)}; + envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 0, + envoy::api::v2::core::HealthStatus::UNKNOWN)}; } inline HostSharedPtr makeTestHost(ClusterInfoConstSharedPtr cluster, const std::string& url, @@ -88,7 +89,8 @@ inline HostSharedPtr makeTestHost(ClusterInfoConstSharedPtr cluster, const std:: return HostSharedPtr{ new HostImpl(cluster, "", Network::Utility::resolveUrl(url), metadata, weight, envoy::api::v2::core::Locality(), - envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 0)}; + envoy::api::v2::endpoint::Endpoint::HealthCheckConfig::default_instance(), 0, + envoy::api::v2::core::HealthStatus::UNKNOWN)}; } inline HostSharedPtr @@ -97,7 +99,8 @@ makeTestHost(ClusterInfoConstSharedPtr cluster, const std::string& url, uint32_t weight = 1) { return HostSharedPtr{new HostImpl(cluster, "", Network::Utility::resolveUrl(url), envoy::api::v2::core::Metadata::default_instance(), weight, - envoy::api::v2::core::Locality(), health_check_config, 0)}; + envoy::api::v2::core::Locality(), health_check_config, 0, + envoy::api::v2::core::HealthStatus::UNKNOWN)}; } inline HostDescriptionConstSharedPtr makeTestHostDescription(ClusterInfoConstSharedPtr cluster, diff --git a/test/integration/eds_integration_test.cc b/test/integration/eds_integration_test.cc index a17d7b72bcd1a..f1b4d993c3135 100644 --- a/test/integration/eds_integration_test.cc +++ b/test/integration/eds_integration_test.cc @@ -21,7 +21,9 @@ class EdsIntegrationTest : public TestBaseWithParam // We need to supply the endpoints via EDS to provide health status. Use a // filesystem delivery to simplify test mechanics. void setEndpoints(uint32_t total_endpoints, uint32_t healthy_endpoints, + uint32_t degraded_endpoints, absl::optional overprovisioning_factor = absl::nullopt) { + ASSERT(total_endpoints >= healthy_endpoints + degraded_endpoints); envoy::api::v2::ClusterLoadAssignment cluster_load_assignment; cluster_load_assignment.set_cluster_name("cluster_0"); if (overprovisioning_factor.has_value()) { @@ -33,7 +35,11 @@ class EdsIntegrationTest : public TestBaseWithParam for (uint32_t i = 0; i < total_endpoints; ++i) { auto* endpoint = locality_lb_endpoints->add_lb_endpoints(); setUpstreamAddress(i, *endpoint); - if (i >= healthy_endpoints) { + // First N endpoints are degraded, next M are healthy and the remaining endpoints are + // unhealthy. + if (i < degraded_endpoints) { + endpoint->set_health_status(envoy::api::v2::core::HealthStatus::DEGRADED); + } else if (i >= healthy_endpoints + degraded_endpoints) { endpoint->set_health_status(envoy::api::v2::core::HealthStatus::UNHEALTHY); } } @@ -51,7 +57,7 @@ class EdsIntegrationTest : public TestBaseWithParam eds_cluster_config->mutable_eds_config()->set_path(eds_helper_.eds_path()); }); HttpIntegrationTest::initialize(); - setEndpoints(0, 0); + setEndpoints(0, 0, 0); } EdsHelper eds_helper_; @@ -68,32 +74,38 @@ TEST_P(EdsIntegrationTest, HealthUpdate) { EXPECT_EQ(0, test_server_->gauge("cluster.cluster_0.membership_total")->value()); EXPECT_EQ(0, test_server_->gauge("cluster.cluster_0.membership_healthy")->value()); // 2/2 healthy endpoints. - setEndpoints(2, 2); + setEndpoints(2, 2, 0); EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.membership_change")->value()); EXPECT_EQ(2, test_server_->gauge("cluster.cluster_0.membership_total")->value()); EXPECT_EQ(2, test_server_->gauge("cluster.cluster_0.membership_healthy")->value()); // Drop to 0/2 healthy endpoints. - setEndpoints(2, 0); + setEndpoints(2, 0, 0); EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.membership_change")->value()); EXPECT_EQ(2, test_server_->gauge("cluster.cluster_0.membership_total")->value()); EXPECT_EQ(0, test_server_->gauge("cluster.cluster_0.membership_healthy")->value()); // Increase to 1/2 healthy endpoints. - setEndpoints(2, 1); + setEndpoints(2, 1, 0); EXPECT_EQ(1, test_server_->counter("cluster.cluster_0.membership_change")->value()); EXPECT_EQ(2, test_server_->gauge("cluster.cluster_0.membership_total")->value()); EXPECT_EQ(1, test_server_->gauge("cluster.cluster_0.membership_healthy")->value()); // Add host and modify health to 2/3 healthy endpoints. - setEndpoints(3, 2); + setEndpoints(3, 2, 0); EXPECT_EQ(2, test_server_->counter("cluster.cluster_0.membership_change")->value()); EXPECT_EQ(3, test_server_->gauge("cluster.cluster_0.membership_total")->value()); EXPECT_EQ(2, test_server_->gauge("cluster.cluster_0.membership_healthy")->value()); + // Modify health to 2/3 healthy and 1/3 degraded. + setEndpoints(3, 2, 1); + EXPECT_EQ(2, test_server_->counter("cluster.cluster_0.membership_change")->value()); + EXPECT_EQ(3, test_server_->gauge("cluster.cluster_0.membership_total")->value()); + EXPECT_EQ(2, test_server_->gauge("cluster.cluster_0.membership_healthy")->value()); + EXPECT_EQ(1, test_server_->gauge("cluster.cluster_0.membership_degraded")->value()); } // Validate that overprovisioning_factor update are picked up by Envoy. TEST_P(EdsIntegrationTest, OverprovisioningFactorUpdate) { initialize(); // Default overprovisioning factor. - setEndpoints(4, 4); + setEndpoints(4, 4, 0); auto get_and_compare = [this](const uint32_t expected_factor) { const auto& cluster_map = test_server_->server().clusterManager().clusters(); EXPECT_EQ(1, cluster_map.size()); @@ -107,7 +119,7 @@ TEST_P(EdsIntegrationTest, OverprovisioningFactorUpdate) { get_and_compare(Envoy::Upstream::kDefaultOverProvisioningFactor); // Use new overprovisioning factor 200. - setEndpoints(4, 4, 200); + setEndpoints(4, 4, 0, 200); get_and_compare(200); } diff --git a/test/server/http/admin_test.cc b/test/server/http/admin_test.cc index 3dcdf4e56a172..9b679c663881e 100644 --- a/test/server/http/admin_test.cc +++ b/test/server/http/admin_test.cc @@ -1033,6 +1033,8 @@ TEST_P(AdminInstanceTest, ClustersJson) { .WillByDefault(Return(false)); ON_CALL(*host, healthFlagGet(Upstream::Host::HealthFlag::DEGRADED_ACTIVE_HC)) .WillByDefault(Return(true)); + ON_CALL(*host, healthFlagGet(Upstream::Host::HealthFlag::DEGRADED_EDS_HEALTH)) + .WillByDefault(Return(true)); ON_CALL(host->outlier_detector_, successRate()).WillByDefault(Return(43.2)); ON_CALL(*host, weight()).WillByDefault(Return(5)); @@ -1089,7 +1091,7 @@ TEST_P(AdminInstanceTest, ClustersJson) { }, ], "health_status": { - "eds_health_status": "HEALTHY", + "eds_health_status": "DEGRADED", "failed_active_health_check": true, "failed_outlier_check": true, "failed_active_degraded_check": true From 2cf652438d431a4dfcc5bf0081e04c28f2733dd6 Mon Sep 17 00:00:00 2001 From: Bin Wu <46450037+wu-bin@users.noreply.github.com> Date: Fri, 8 Feb 2019 10:55:20 -0500 Subject: [PATCH 47/51] Add quic_logging_impl.(h|cc) to QUICHE platform implementation. (#5758) Add quic_logging_impl.(h|cc) and unit tests to QUICHE platform implementation. QUICHE code uses stream-style logging macros to do logging, e.g.: QUIC_LOG(INFO) << "x = " << x; The implementation in this PR uses a temporary std::ostringstream (one per macro invocation) to convert the stream into a std::string, then send the string to spdlog. Risk Level: minimal: code not used yet Testing: [Unit test in release mode] bazel test --experimental_remap_main_repo -c opt test/extensions/quic_listeners/quiche/platform:quic_platform_test [Unit test in debug mode] bazel test --experimental_remap_main_repo test/extensions/quic_listeners/quiche/platform:quic_platform_test Signed-off-by: Bin Wu --- bazel/external/quiche.BUILD | 2 +- source/common/common/logger.h | 1 + .../quic_listeners/quiche/platform/BUILD | 9 +- .../quiche/platform/quic_logging_impl.cc | 39 +++++ .../quiche/platform/quic_logging_impl.h | 135 +++++++++++++++++ .../quic_listeners/quiche/platform/BUILD | 1 + .../quiche/platform/quic_platform_test.cc | 142 ++++++++++++++++++ tools/spelling_dictionary.txt | 4 + 8 files changed, 331 insertions(+), 2 deletions(-) create mode 100644 source/extensions/quic_listeners/quiche/platform/quic_logging_impl.cc create mode 100644 source/extensions/quic_listeners/quiche/platform/quic_logging_impl.h diff --git a/bazel/external/quiche.BUILD b/bazel/external/quiche.BUILD index 788441bf40533..9a3a6d9a46465 100644 --- a/bazel/external/quiche.BUILD +++ b/bazel/external/quiche.BUILD @@ -122,6 +122,7 @@ cc_library( "quiche/quic/platform/api/quic_fallthrough.h", "quiche/quic/platform/api/quic_flag_utils.h", "quiche/quic/platform/api/quic_iovec.h", + "quiche/quic/platform/api/quic_logging.h", "quiche/quic/platform/api/quic_prefetch.h", "quiche/quic/platform/api/quic_ptr_util.h", "quiche/quic/platform/api/quic_str_cat.h", @@ -142,7 +143,6 @@ cc_library( # "quiche/quic/platform/api/quic_interval.h", # "quiche/quic/platform/api/quic_ip_address_family.h", # "quiche/quic/platform/api/quic_ip_address.h", - # "quiche/quic/platform/api/quic_logging.h", # "quiche/quic/platform/api/quic_lru_cache.h", # "quiche/quic/platform/api/quic_map_util.h", # "quiche/quic/platform/api/quic_mem_slice.h", diff --git a/source/common/common/logger.h b/source/common/common/logger.h index 5b627ea4eef97..ce4da1ab9493b 100644 --- a/source/common/common/logger.h +++ b/source/common/common/logger.h @@ -40,6 +40,7 @@ namespace Logger { FUNCTION(main) \ FUNCTION(misc) \ FUNCTION(mongo) \ + FUNCTION(quic) \ FUNCTION(pool) \ FUNCTION(rbac) \ FUNCTION(redis) \ diff --git a/source/extensions/quic_listeners/quiche/platform/BUILD b/source/extensions/quic_listeners/quiche/platform/BUILD index fb8ffa1ccfeac..d163699de1b93 100644 --- a/source/extensions/quic_listeners/quiche/platform/BUILD +++ b/source/extensions/quic_listeners/quiche/platform/BUILD @@ -4,6 +4,7 @@ load( "//bazel:envoy_build_system.bzl", "envoy_cc_library", "envoy_package", + "envoy_select_quiche", ) envoy_package() @@ -39,6 +40,9 @@ envoy_cc_library( envoy_cc_library( name = "quic_platform_base_impl_lib", + srcs = envoy_select_quiche([ + "quic_logging_impl.cc", + ]), hdrs = [ "quic_aligned_impl.h", "quic_arraysize_impl.h", @@ -55,7 +59,7 @@ envoy_cc_library( "quic_string_impl.h", "quic_string_piece_impl.h", "quic_uint128_impl.h", - ], + ] + envoy_select_quiche(["quic_logging_impl.h"]), external_deps = [ "abseil_base", "abseil_hash", @@ -65,6 +69,9 @@ envoy_cc_library( "abseil_node_hash_set", ], visibility = ["//visibility:public"], + deps = envoy_select_quiche([ + "//source/common/common:assert_lib", + ]), ) envoy_cc_library( diff --git a/source/extensions/quic_listeners/quiche/platform/quic_logging_impl.cc b/source/extensions/quic_listeners/quiche/platform/quic_logging_impl.cc new file mode 100644 index 0000000000000..5f6b16d6fde57 --- /dev/null +++ b/source/extensions/quic_listeners/quiche/platform/quic_logging_impl.cc @@ -0,0 +1,39 @@ +// NOLINT(namespace-envoy) + +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +#include "extensions/quic_listeners/quiche/platform/quic_logging_impl.h" + +#include + +namespace quic { + +namespace { +std::atomic& VerbosityLogThreshold() { + static std::atomic threshold(0); + return threshold; +} +} // namespace + +QuicLogEmitter::QuicLogEmitter(QuicLogLevel level) : level_(level), saved_errno_(errno) {} + +QuicLogEmitter::~QuicLogEmitter() { + if (is_perror_) { + // TODO(wub): Change to a thread-safe version of strerror. + stream_ << ": " << strerror(saved_errno_) << " [" << saved_errno_ << "]"; + } + GetLogger().log(level_, "quic: {}", stream_.str().c_str()); + if (level_ == FATAL) { + abort(); + } +} + +int GetVerbosityLogThreshold() { return VerbosityLogThreshold().load(std::memory_order_relaxed); } + +void SetVerbosityLogThreshold(int new_verbosity) { + VerbosityLogThreshold().store(new_verbosity, std::memory_order_relaxed); +} + +} // namespace quic \ No newline at end of file diff --git a/source/extensions/quic_listeners/quiche/platform/quic_logging_impl.h b/source/extensions/quic_listeners/quiche/platform/quic_logging_impl.h new file mode 100644 index 0000000000000..ff577f0d341c8 --- /dev/null +++ b/source/extensions/quic_listeners/quiche/platform/quic_logging_impl.h @@ -0,0 +1,135 @@ +#pragma once + +// NOLINT(namespace-envoy) + +// This file is part of the QUICHE platform implementation, and is not to be +// consumed or referenced directly by other Envoy code. It serves purely as a +// porting layer for QUICHE. + +#include +#include +#include +#include + +#include "common/common/assert.h" +#include "common/common/logger.h" + +#include "absl/base/optimization.h" + +// TODO(wub): Add CHECK/DCHECK and variants, which are not explicitly exposed by quic_logging.h. +// TODO(wub): Implement quic_mock_log_impl.h for testing. + +// If |condition| is true, use |logstream| to stream the log message and send it to spdlog. +// If |condition| is false, |logstream| will not be instantiated. +// The switch(0) is used to suppress a compiler warning on ambiguous "else". +#define QUIC_LOG_IMPL_INTERNAL(condition, logstream) \ + switch (0) \ + default: \ + if (!(condition)) { \ + } else \ + logstream + +#define QUIC_LOG_IF_IMPL(severity, condition) \ + QUIC_LOG_IMPL_INTERNAL((condition) && quic::IsLogLevelEnabled(quic::severity), \ + quic::QuicLogEmitter(quic::severity).stream()) + +#define QUIC_LOG_IMPL(severity) QUIC_LOG_IF_IMPL(severity, true) + +#define QUIC_VLOG_IF_IMPL(verbosity, condition) \ + QUIC_LOG_IMPL_INTERNAL((condition) && quic::IsVerboseLogEnabled(verbosity), \ + quic::QuicLogEmitter(quic::INFO).stream()) + +#define QUIC_VLOG_IMPL(verbosity) QUIC_VLOG_IF_IMPL(verbosity, true) + +// TODO(wub): Implement QUIC_LOG_FIRST_N_IMPL. +#define QUIC_LOG_FIRST_N_IMPL(severity, n) QUIC_LOG_IMPL(severity) + +// TODO(wub): Implement QUIC_LOG_EVERY_N_SEC_IMPL. +#define QUIC_LOG_EVERY_N_SEC_IMPL(severity, seconds) QUIC_LOG_IMPL(severity) + +#define QUIC_PLOG_IMPL(severity) \ + QUIC_LOG_IMPL_INTERNAL(quic::IsLogLevelEnabled(quic::severity), \ + quic::QuicLogEmitter(quic::severity).SetPerror().stream()) + +#define QUIC_LOG_INFO_IS_ON_IMPL quic::IsLogLevelEnabled(quic::INFO) +#define QUIC_LOG_WARNING_IS_ON_IMPL quic::IsLogLevelEnabled(quic::WARNING) +#define QUIC_LOG_ERROR_IS_ON_IMPL quic::IsLogLevelEnabled(quic::ERROR) + +#ifdef NDEBUG +// Release build +#define QUIC_COMPILED_OUT_LOG() QUIC_LOG_IMPL_INTERNAL(false, quic::NullLogStream().stream()) +#define QUIC_DVLOG_IMPL(verbosity) QUIC_COMPILED_OUT_LOG() +#define QUIC_DVLOG_IF_IMPL(verbosity, condition) QUIC_COMPILED_OUT_LOG() +#define QUIC_DLOG_IMPL(severity) QUIC_COMPILED_OUT_LOG() +#define QUIC_DLOG_IF_IMPL(severity, condition) QUIC_COMPILED_OUT_LOG() +#define QUIC_DLOG_INFO_IS_ON_IMPL 0 +#define QUIC_NOTREACHED_IMPL() +#else +// Debug build +#define QUIC_DVLOG_IMPL(verbosity) QUIC_VLOG_IMPL(verbosity) +#define QUIC_DVLOG_IF_IMPL(verbosity, condition) QUIC_VLOG_IF_IMPL(verbosity, condition) +#define QUIC_DLOG_IMPL(severity) QUIC_LOG_IMPL(severity) +#define QUIC_DLOG_IF_IMPL(severity, condition) QUIC_LOG_IF_IMPL(severity, condition) +#define QUIC_DLOG_INFO_IS_ON_IMPL QUIC_LOG_INFO_IS_ON_IMPL +#define QUIC_NOTREACHED_IMPL() NOT_REACHED_GCOVR_EXCL_LINE +#endif + +#define QUIC_PREDICT_FALSE_IMPL(x) ABSL_PREDICT_FALSE(x) + +namespace quic { + +using QuicLogLevel = spdlog::level::level_enum; + +static const QuicLogLevel INFO = spdlog::level::info; +static const QuicLogLevel WARNING = spdlog::level::warn; +static const QuicLogLevel ERROR = spdlog::level::err; +static const QuicLogLevel FATAL = spdlog::level::critical; + +// DFATAL is FATAL in debug mode, ERROR in release mode. +#ifdef NDEBUG +static const QuicLogLevel DFATAL = ERROR; +#else +static const QuicLogLevel DFATAL = FATAL; +#endif + +class QuicLogEmitter { +public: + explicit QuicLogEmitter(QuicLogLevel level); + + ~QuicLogEmitter(); + + QuicLogEmitter& SetPerror() { + is_perror_ = true; + return *this; + } + + std::ostringstream& stream() { return stream_; } + +private: + const QuicLogLevel level_; + const int saved_errno_; + bool is_perror_ = false; + std::ostringstream stream_; +}; + +class NullLogStream { +public: + NullLogStream& stream() { return *this; } +}; + +template inline NullLogStream& operator<<(NullLogStream& s, const T&) { return s; } + +inline spdlog::logger& GetLogger() { + return Envoy::Logger::Registry::getLog(Envoy::Logger::Id::quic); +} + +inline bool IsLogLevelEnabled(QuicLogLevel level) { return level >= GetLogger().level(); } + +int GetVerbosityLogThreshold(); +void SetVerbosityLogThreshold(int new_verbosity); + +inline bool IsVerboseLogEnabled(int verbosity) { + return IsLogLevelEnabled(INFO) && verbosity <= GetVerbosityLogThreshold(); +} + +} // namespace quic diff --git a/test/extensions/quic_listeners/quiche/platform/BUILD b/test/extensions/quic_listeners/quiche/platform/BUILD index 59fcc209a9ab6..bb0dce1ce507e 100644 --- a/test/extensions/quic_listeners/quiche/platform/BUILD +++ b/test/extensions/quic_listeners/quiche/platform/BUILD @@ -27,6 +27,7 @@ envoy_cc_test( srcs = envoy_select_quiche(["quic_platform_test.cc"]), external_deps = ["quiche_quic_platform"], deps = [ + "//test/test_common:logging_lib", "//test/test_common:utility_lib", ], ) diff --git a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc index 44b343af8efd7..10ff12d307d2a 100644 --- a/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc +++ b/test/extensions/quic_listeners/quiche/platform/quic_platform_test.cc @@ -1,3 +1,4 @@ +#include "test/test_common/logging.h" #include "test/test_common/test_base.h" #include "quiche/quic/platform/api/quic_aligned.h" @@ -6,6 +7,7 @@ #include "quiche/quic/platform/api/quic_containers.h" #include "quiche/quic/platform/api/quic_endian.h" #include "quiche/quic/platform/api/quic_estimate_memory_usage.h" +#include "quiche/quic/platform/api/quic_logging.h" #include "quiche/quic/platform/api/quic_mutex.h" #include "quiche/quic/platform/api/quic_ptr_util.h" #include "quiche/quic/platform/api/quic_string.h" @@ -109,6 +111,146 @@ TEST(QuicPlatformTest, QuicPtrUtil) { EXPECT_EQ("aaa", *p); } +namespace { +class QuicLogThresholdSaver { +public: + QuicLogThresholdSaver() + : level_(quic::GetLogger().level()), verbosity_threshold_(quic::GetVerbosityLogThreshold()) {} + + ~QuicLogThresholdSaver() { + quic::SetVerbosityLogThreshold(verbosity_threshold_); + quic::GetLogger().set_level(level_); + } + +private: + const quic::QuicLogLevel level_; + const int verbosity_threshold_; +}; +} // namespace + +TEST(QuicPlatformTest, QuicLog) { + QuicLogThresholdSaver saver; + + // By default, tests emit logs at level ERROR or higher. + ASSERT_EQ(quic::ERROR, quic::GetLogger().level()); + + int i = 0; + + QUIC_LOG(INFO) << (i = 10); + QUIC_LOG_IF(INFO, false) << i++; + QUIC_LOG_IF(INFO, true) << i++; + EXPECT_EQ(0, i); + + EXPECT_LOG_CONTAINS("error", ": 11", QUIC_LOG(ERROR) << (i = 11)); + EXPECT_EQ(11, i); + + QUIC_LOG_IF(ERROR, false) << i++; + EXPECT_EQ(11, i); + + EXPECT_LOG_CONTAINS("error", ": 11", QUIC_LOG_IF(ERROR, true) << i++); + EXPECT_EQ(12, i); + + // Set QUIC log level to INFO, since VLOG is emitted at the INFO level. + quic::GetLogger().set_level(quic::INFO); + + ASSERT_EQ(0, quic::GetVerbosityLogThreshold()); + + QUIC_VLOG(1) << (i = 1); + EXPECT_EQ(12, i); + + quic::SetVerbosityLogThreshold(1); + + EXPECT_LOG_CONTAINS("info", ": 1", QUIC_VLOG(1) << (i = 1)); + EXPECT_EQ(1, i); + + errno = EINVAL; + EXPECT_LOG_CONTAINS("info", ": 3:", QUIC_PLOG(INFO) << (i = 3)); + EXPECT_EQ(3, i); +} + +#ifdef NDEBUG +#define VALUE_BY_COMPILE_MODE(debug_mode_value, release_mode_value) release_mode_value +#else +#define VALUE_BY_COMPILE_MODE(debug_mode_value, release_mode_value) debug_mode_value +#endif + +TEST(QuicPlatformTest, QuicDLog) { + QuicLogThresholdSaver saver; + + int i = 0; + + quic::GetLogger().set_level(quic::ERROR); + + QUIC_DLOG(INFO) << (i = 10); + QUIC_DLOG_IF(INFO, false) << i++; + QUIC_DLOG_IF(INFO, true) << i++; + EXPECT_EQ(0, i); + + quic::GetLogger().set_level(quic::INFO); + + QUIC_DLOG(INFO) << (i = 10); + QUIC_DLOG_IF(INFO, false) << i++; + EXPECT_EQ(VALUE_BY_COMPILE_MODE(10, 0), i); + + QUIC_DLOG_IF(INFO, true) << (i = 11); + EXPECT_EQ(VALUE_BY_COMPILE_MODE(11, 0), i); + + ASSERT_EQ(0, quic::GetVerbosityLogThreshold()); + + QUIC_DVLOG(1) << (i = 1); + EXPECT_EQ(VALUE_BY_COMPILE_MODE(11, 0), i); + + quic::SetVerbosityLogThreshold(1); + + QUIC_DVLOG(1) << (i = 1); + EXPECT_EQ(VALUE_BY_COMPILE_MODE(1, 0), i); + + QUIC_DVLOG_IF(1, false) << (i = 2); + EXPECT_EQ(VALUE_BY_COMPILE_MODE(1, 0), i); + + QUIC_DVLOG_IF(1, true) << (i = 2); + EXPECT_EQ(VALUE_BY_COMPILE_MODE(2, 0), i); +} + +#undef VALUE_BY_COMPILE_MODE + +// Test the behaviors of the cross products of +// +// {QUIC_LOG, QUIC_DLOG} x {FATAL, DFATAL} x {debug, release} +TEST(QuicPlatformTest, QuicFatalLog) { +#ifdef NDEBUG + // Release build + EXPECT_DEATH(QUIC_LOG(FATAL) << "Should abort 0", "Should abort 0"); + QUIC_LOG(DFATAL) << "Should not abort"; + QUIC_DLOG(FATAL) << "Should compile out"; + QUIC_DLOG(DFATAL) << "Should compile out"; +#else + // Debug build + EXPECT_DEATH(QUIC_LOG(FATAL) << "Should abort 1", "Should abort 1"); + EXPECT_DEATH(QUIC_LOG(DFATAL) << "Should abort 2", "Should abort 2"); + EXPECT_DEATH(QUIC_DLOG(FATAL) << "Should abort 3", "Should abort 3"); + EXPECT_DEATH(QUIC_DLOG(DFATAL) << "Should abort 4", "Should abort 4"); +#endif +} + +TEST(QuicPlatformTest, QuicBranchPrediction) { + quic::GetLogger().set_level(quic::INFO); + + if (QUIC_PREDICT_FALSE(rand() % RAND_MAX == 123456789)) { + QUIC_LOG(INFO) << "Go buy some lottery tickets."; + } else { + QUIC_LOG(INFO) << "As predicted."; + } +} + +TEST(QuicPlatformTest, QuicNotReached) { +#ifdef NDEBUG + QUIC_NOTREACHED(); // Expect no-op. +#else + EXPECT_DEATH(QUIC_NOTREACHED(), "not reached"); +#endif +} + TEST(QuicPlatformTest, QuicMutex) { quic::QuicMutex mu; diff --git a/tools/spelling_dictionary.txt b/tools/spelling_dictionary.txt index f7a4911917f8a..c7e23dce1c860 100644 --- a/tools/spelling_dictionary.txt +++ b/tools/spelling_dictionary.txt @@ -38,9 +38,12 @@ CTX CTXs CVC CX +DCHECK DER DESC +DFATAL DGRAM +DLOG DNS DRYs DS @@ -242,6 +245,7 @@ UTF UUID UUIDs VH +VLOG WKT WRR WS From 8d89d776b4200b800bbeff71992b6506997a610c Mon Sep 17 00:00:00 2001 From: Sam Smith Date: Fri, 8 Feb 2019 12:18:52 -0500 Subject: [PATCH 48/51] build: enable release builds on Windows (#5812) Now that #5218 has been merged, we can enable release builds on Windows. This PR updates `ci/do_ci.ps1` to build release + fastbuild versions in addition to debug versions. It also removes support for build scripts in `ci/build_container/build_recipes/` on Windows, as there is no clean way to pass information from Bazel regarding the type of build to those scripts Risk Level: Low Testing: `bazel build //source/... && bazel test //test/...` Signed-off-by: Sam Smith --- bazel/envoy_build_system.bzl | 51 ++++++++++++ bazel/foreign_cc/BUILD | 90 +++++++++++++--------- bazel/foreign_cc/nghttp2.patch | 23 +++++- bazel/repositories.bat | 4 - bazel/repositories.bzl | 24 ++---- ci/build_container/build_recipes/luajit.sh | 26 +++---- ci/build_setup.ps1 | 2 +- ci/do_ci.ps1 | 59 +++++++++++--- ci/prebuilt/BUILD | 10 +-- 9 files changed, 188 insertions(+), 101 deletions(-) delete mode 100644 bazel/repositories.bat diff --git a/bazel/envoy_build_system.bzl b/bazel/envoy_build_system.bzl index ed64bdada2bf4..1300856e28d41 100644 --- a/bazel/envoy_build_system.bzl +++ b/bazel/envoy_build_system.bzl @@ -1,5 +1,6 @@ load("@com_google_protobuf//:protobuf.bzl", "cc_proto_library", "py_proto_library") load("@envoy_api//bazel:api_build_system.bzl", "api_proto_library") +load("@rules_foreign_cc//tools/build_defs:cmake.bzl", "cmake_external") def envoy_package(): native.package(default_visibility = ["//visibility:public"]) @@ -195,6 +196,56 @@ def envoy_include_prefix(path): return "/".join(path.split("/")[1:]) return None +# External CMake C++ library targets should be specified with this function. This defaults +# to building the dependencies with ninja +def envoy_cmake_external( + name, + cache_entries = {}, + cmake_options = ["-GNinja"], + make_commands = ["ninja", "ninja install"], + lib_source = "", + postfix_script = "", + static_libraries = [], + copy_pdb = False, + pdb_name = "", + cmake_files_dir = "$BUILD_TMPDIR/CMakeFiles"): + # On Windows, we don't want to explicitly set CMAKE_BUILD_TYPE, + # rules_foreign_cc will figure it out for us + cache_entries_no_build_type = {key: cache_entries[key] for key in cache_entries.keys() if key != "CMAKE_BUILD_TYPE"} + + pf = "" + if copy_pdb: + if pdb_name == "": + pdb_name = name + + copy_command = "cp {cmake_files_dir}/{pdb_name}.dir/{pdb_name}.pdb $INSTALLDIR/lib/{pdb_name}.pdb".format(cmake_files_dir = cmake_files_dir, pdb_name = pdb_name) + if postfix_script != "": + copy_command = copy_command + " && " + postfix_script + + pf = select({ + "@envoy//bazel:windows_dbg_build": copy_command, + "//conditions:default": postfix_script, + }) + else: + pf = postfix_script + + cmake_external( + name = name, + cache_entries = select({ + "@envoy//bazel:windows_x86_64": cache_entries_no_build_type, + "//conditions:default": cache_entries, + }), + cmake_options = cmake_options, + generate_crosstool_file = select({ + "@envoy//bazel:windows_x86_64": True, + "//conditions:default": False, + }), + lib_source = lib_source, + make_commands = make_commands, + postfix_script = pf, + static_libraries = static_libraries, + ) + # Envoy C++ library targets that need no transformations or additional dependencies before being # passed to cc_library should be specified with this function. Note: this exists to ensure that # all envoy targets pass through an envoy-declared skylark function where they can be modified diff --git a/bazel/foreign_cc/BUILD b/bazel/foreign_cc/BUILD index d33a80951c61f..03dfedcd42077 100644 --- a/bazel/foreign_cc/BUILD +++ b/bazel/foreign_cc/BUILD @@ -1,43 +1,56 @@ licenses(["notice"]) # Apache 2 -load("//bazel:envoy_build_system.bzl", "envoy_package") -load("@rules_foreign_cc//tools/build_defs:cmake.bzl", "cmake_external") +load("//bazel:envoy_build_system.bzl", "envoy_cmake_external", "envoy_package") envoy_package() -cmake_external( +envoy_cmake_external( name = "ares", cache_entries = { "CARES_SHARED": "no", "CARES_STATIC": "on", "CMAKE_BUILD_TYPE": "RelWithDebInfo", }, - cmake_options = ["-GNinja"], + copy_pdb = True, lib_source = "@com_github_c_ares_c_ares//:all", - make_commands = [ - "ninja", - "ninja install", - ], - static_libraries = ["libcares.a"], + pdb_name = "c-ares", + static_libraries = select({ + "//bazel:windows_x86_64": ["cares.lib"], + "//conditions:default": ["libcares.a"], + }), ) -cmake_external( +envoy_cmake_external( + name = "benchmark", + cache_entries = { + "BENCHMARK_ENABLE_GTEST_TESTS": "OFF", + "BENCHMARK_ENABLE_TESTING": "OFF", + }, + copy_pdb = True, + lib_source = "@com_github_google_benchmark//:all", + postfix_script = "mkdir -p $INSTALLDIR/include/testing/base/public && cp $BUILD_TMPDIR/$INSTALL_PREFIX/include/benchmark/benchmark.h $INSTALLDIR/include/testing/base/public/benchmark.h", + static_libraries = select({ + "//bazel:windows_x86_64": ["benchmark.lib"], + "//conditions:default": ["libbenchmark.a"], + }), +) + +envoy_cmake_external( name = "event", cache_entries = { "EVENT__DISABLE_OPENSSL": "on", "EVENT__DISABLE_REGRESS": "on", "CMAKE_BUILD_TYPE": "Release", }, - cmake_options = ["-GNinja"], + copy_pdb = True, lib_source = "@com_github_libevent_libevent//:all", - make_commands = [ - "ninja", - "ninja install", - ], - static_libraries = ["libevent.a"], + static_libraries = select({ + "//bazel:windows_x86_64": ["event.lib"], + "//conditions:default": ["libevent.a"], + }), ) -cmake_external( +envoy_cmake_external( name = "nghttp2", cache_entries = { "ENABLE_STATIC_LIB": "on", @@ -45,41 +58,44 @@ cmake_external( "CMAKE_BUILD_TYPE": "RelWithDebInfo", "CMAKE_INSTALL_LIBDIR": "lib", }, - cmake_options = ["-GNinja"], + cmake_files_dir = "$BUILD_TMPDIR/lib/CMakeFiles", + copy_pdb = True, lib_source = "@com_github_nghttp2_nghttp2//:all", - make_commands = [ - "ninja", - "ninja install", - ], - static_libraries = ["libnghttp2.a"], + pdb_name = "nghttp2_static", + static_libraries = select({ + "//bazel:windows_x86_64": ["nghttp2_static.lib"], + "//conditions:default": ["libnghttp2_static.a"], + }), ) -cmake_external( +envoy_cmake_external( name = "yaml", cache_entries = { "YAML_CPP_BUILD_TESTS": "off", "YAML_CPP_BUILD_TOOLS": "off", "CMAKE_BUILD_TYPE": "RelWithDebInfo", }, - cmake_options = ["-GNinja"], lib_source = "@com_github_jbeder_yaml_cpp//:all", - make_commands = [ - "ninja", - "ninja install", - ], - static_libraries = ["libyaml-cpp.a"], + static_libraries = select({ + "//bazel:windows_dbg_build": ["libyaml-cppmdd.lib"], + "//bazel:windows_fastbuild_build": ["libyaml-cppmd.lib"], + "//bazel:windows_opt_build": ["libyaml-cppmd.lib"], + "//conditions:default": ["libyaml-cpp.a"], + }), ) -cmake_external( +envoy_cmake_external( name = "zlib", cache_entries = { "CMAKE_BUILD_TYPE": "RelWithDebInfo", }, - cmake_options = ["-GNinja"], + copy_pdb = True, lib_source = "@com_github_madler_zlib//:all", - make_commands = [ - "ninja", - "ninja install", - ], - static_libraries = ["libz.a"], + pdb_name = "zlibstatic", + static_libraries = select({ + "//bazel:windows_dbg_build": ["zlibstaticd.lib"], + "//bazel:windows_fastbuild_build": ["zlibstatic.lib"], + "//bazel:windows_opt_build": ["zlibstatic.lib"], + "//conditions:default": ["libz.a"], + }), ) diff --git a/bazel/foreign_cc/nghttp2.patch b/bazel/foreign_cc/nghttp2.patch index 4cc4ea7b32ae0..7d2fd186f07b0 100644 --- a/bazel/foreign_cc/nghttp2.patch +++ b/bazel/foreign_cc/nghttp2.patch @@ -1,12 +1,29 @@ +diff --git a/CMakeLists.txt b/CMakeLists.txt +index e70d2d49..f9c5340e 100644 +--- a/CMakeLists.txt ++++ b/CMakeLists.txt +@@ -273,7 +273,11 @@ check_type_size("ssize_t" SIZEOF_SSIZE_T) + if(SIZEOF_SSIZE_T STREQUAL "") + # ssize_t is a signed type in POSIX storing at least -1. + # Set it to "int" to match the behavior of AC_TYPE_SSIZE_T (autotools). +- set(ssize_t int) ++ if(WIN32 AND CMAKE_SIZEOF_VOID_P EQUAL 8) ++ set(ssize_t int64_t) ++ else() ++ set(ssize_t int) ++ endif() + endif() + # AC_TYPE_UINT8_T + # AC_TYPE_UINT16_T diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt -index 17e422b2..e58070f5 100644 +index 17e422b2..a10f82a5 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt -@@ -52,6 +52,7 @@ +@@ -56,6 +56,7 @@ if(HAVE_CUNIT OR ENABLE_STATIC_LIB) COMPILE_FLAGS "${WARNCFLAGS}" VERSION ${LT_VERSION} SOVERSION ${LT_SOVERSION} ARCHIVE_OUTPUT_NAME nghttp2 -+ ARCHIVE_OUTPUT_DIRECTORY static ++ ARCHIVE_OUTPUT_NAME nghttp2_static ) target_compile_definitions(nghttp2_static PUBLIC "-DNGHTTP2_STATICLIB") if(ENABLE_STATIC_LIB) diff --git a/bazel/repositories.bat b/bazel/repositories.bat deleted file mode 100644 index 7b66957105932..0000000000000 --- a/bazel/repositories.bat +++ /dev/null @@ -1,4 +0,0 @@ -echo "Start" -@ECHO OFF -%BAZEL_SH% -c "./repositories.sh %*" -exit %ERRORLEVEL% diff --git a/bazel/repositories.bzl b/bazel/repositories.bzl index bb817725ac9f8..75d2d327988d6 100644 --- a/bazel/repositories.bzl +++ b/bazel/repositories.bzl @@ -51,12 +51,15 @@ def _repository_impl(name, **kwargs): ) def _build_recipe_repository_impl(ctxt): + # on Windows, all deps use rules_foreign_cc + if ctxt.os.name.upper().startswith("WINDOWS"): + return + # modify the recipes list based on the build context recipes = _apply_dep_blacklist(ctxt, ctxt.attr.recipes) # Setup the build directory with links to the relevant files. ctxt.symlink(Label("//bazel:repositories.sh"), "repositories.sh") - ctxt.symlink(Label("//bazel:repositories.bat"), "repositories.bat") ctxt.symlink( Label("//ci/build_container:build_and_install_deps.sh"), "build_and_install_deps.sh", @@ -71,25 +74,9 @@ def _build_recipe_repository_impl(ctxt): ctxt.symlink(Label("//ci/prebuilt:BUILD"), "BUILD") # Run the build script. - command = [] - env = {} - if ctxt.os.name.upper().startswith("WINDOWS"): - vc_path = find_vc_path(ctxt) - current_path = get_env_var(ctxt, "PATH", None, False) - env = setup_vc_env_vars(ctxt, vc_path) - env["PATH"] += (";%s" % current_path) - env["CC"] = "cl" - env["CXX"] = "cl" - env["CXXFLAGS"] = "-DNDEBUG" - env["CFLAGS"] = "-DNDEBUG" - command = ["./repositories.bat"] + recipes - else: - command = ["./repositories.sh"] + recipes - print("Fetching external dependencies...") result = ctxt.execute( - command, - environment = env, + ["./repositories.sh"] + recipes, quiet = False, ) print(result.stdout) @@ -478,7 +465,6 @@ def _com_github_nghttp2_nghttp2(): name = "com_github_nghttp2_nghttp2", build_file_content = BUILD_ALL_CONTENT, patch_args = ["-p1"], - patch_cmds = ["find . -name '*.sh' -exec sed -i.orig '1s|#!/usr/bin/env sh\$|/bin/sh\$|' {} +"], patches = ["@envoy//bazel/foreign_cc:nghttp2.patch"], **location ) diff --git a/ci/build_container/build_recipes/luajit.sh b/ci/build_container/build_recipes/luajit.sh index ad10e02e08a48..0484631212bcd 100644 --- a/ci/build_container/build_recipes/luajit.sh +++ b/ci/build_container/build_recipes/luajit.sh @@ -4,6 +4,9 @@ set -e VERSION=2.1.0-beta3 SHA256=409f7fe570d3c16558e594421c47bdd130238323c9d6fd6c83dedd2aaeb082a8 +if [[ "${OS}" == "Windows_NT" ]]; then + exit 0 +fi curl https://github.com/LuaJIT/LuaJIT/archive/v"$VERSION".tar.gz -sLo LuaJIT-"$VERSION".tar.gz \ && echo "$SHA256" LuaJIT-"$VERSION".tar.gz | sha256sum --check @@ -58,21 +61,10 @@ index f56465d..3f4f2fa 100644 EOF cd LuaJIT-"$VERSION" +patch -p1 < ../luajit_make.diff -if [[ "${OS}" == "Windows_NT" ]]; then - cd src - ./msvcbuild.bat debug - - mkdir -p "$THIRDPARTY_BUILD/include/luajit-2.1" - cp *.h* "$THIRDPARTY_BUILD/include/luajit-2.1" - cp luajit.lib "$THIRDPARTY_BUILD/lib" - cp *.pdb "$THIRDPARTY_BUILD/lib" -else - patch -p1 < ../luajit_make.diff - - # Default MACOSX_DEPLOYMENT_TARGET is 10.4, which will fail the build at link time on macOS 10.14: - # ld: library not found for -lgcc_s.10.4 - # This doesn't affect other platforms - MACOSX_DEPLOYMENT_TARGET=10.6 DEFAULT_CC=${CC} TARGET_CFLAGS=${CFLAGS} TARGET_LDFLAGS=${CFLAGS} \ - CFLAGS="" make V=1 PREFIX="$THIRDPARTY_BUILD" install -fi +# Default MACOSX_DEPLOYMENT_TARGET is 10.4, which will fail the build at link time on macOS 10.14: +# ld: library not found for -lgcc_s.10.4 +# This doesn't affect other platforms +MACOSX_DEPLOYMENT_TARGET=10.6 DEFAULT_CC=${CC} TARGET_CFLAGS=${CFLAGS} TARGET_LDFLAGS=${CFLAGS} \ + CFLAGS="" make V=1 PREFIX="$THIRDPARTY_BUILD" install diff --git a/ci/build_setup.ps1 b/ci/build_setup.ps1 index 12a3aeff987f5..d832c1796b29a 100755 --- a/ci/build_setup.ps1 +++ b/ci/build_setup.ps1 @@ -17,6 +17,6 @@ $env:ENVOY_SRCDIR = [System.IO.Path]::GetFullPath("$PSScriptRoot\..") echo "ENVOY_BAZEL_ROOT: $env:ENVOY_BAZEL_ROOT" echo "ENVOY_SRCDIR: $env:ENVOY_SRCDIR" -$env:BAZEL_BASE_OPTIONS="--nomaster_bazelrc --output_base=$env:ENVOY_BAZEL_ROOT --bazelrc=$env:ENVOY_SRCDIR\windows\tools\bazel.rc" +$env:BAZEL_BASE_OPTIONS="--noworkspace_rc --output_base=$env:ENVOY_BAZEL_ROOT --bazelrc=$env:ENVOY_SRCDIR\windows\tools\bazel.rc" $env:BAZEL_BUILD_OPTIONS="--strategy=Genrule=standalone --spawn_strategy=standalone --verbose_failures --jobs=$env:NUM_CPUS --show_task_finish $env:BAZEL_BUILD_EXTRA_OPTIONS" $env:BAZEL_TEST_OPTIONS="$env:BAZEL_BUILD_OPTIONS --cache_test_results=no --test_output=all $env:BAZEL_EXTRA_TEST_OPTIONS" diff --git a/ci/do_ci.ps1 b/ci/do_ci.ps1 index fa0aa691c1a7d..6d85985d89c8f 100755 --- a/ci/do_ci.ps1 +++ b/ci/do_ci.ps1 @@ -4,17 +4,54 @@ trap { $host.SetShouldExit(1) } . "$PSScriptRoot\build_setup.ps1" Write-Host "building using $env:NUM_CPUS CPUs" -function bazel_debug_binary_build() { +function bazel_binary_build($type) { echo "Building..." - pushd "$env:ENVOY_SRCDIR" - bazel $env:BAZEL_BASE_OPTIONS.Split(" ") build $env:BAZEL_BUILD_OPTIONS.Split(" ") -c dbg "//source/exe:envoy-static" - $exit = $LASTEXITCODE - if ($exit -ne 0) { - popd - exit $exit - } - popd + bazel $env:BAZEL_BASE_OPTIONS.Split(" ") build $env:BAZEL_BUILD_OPTIONS.Split(" ") -c $type "//source/exe:envoy-static" + $exit = $LASTEXITCODE + if ($exit -ne 0) { + exit $exit + } } -echo "bazel debug build..." -bazel_debug_binary_build +function bazel_test($type, $test) { + if ($test -ne "") { + bazel $env:BAZEL_BASE_OPTIONS.Split(" ") test $env:BAZEL_TEST_OPTIONS.Split(" ") -c $type $test + } else { + echo "running windows tests" + bazel $env:BAZEL_BASE_OPTIONS.Split(" ") test $env:BAZEL_TEST_OPTIONS.Split(" ") -c $type "//test/..." + } + exit $LASTEXITCODE +} + +$action = $args[0] +$test = $args[1] + +switch ($action) { + "bazel.release" { + echo "bazel release build with tests..." + bazel_binary_build "opt" + bazel_test "opt" "$test" + } + "bazel.release.server_only" { + echo "bazel release build..." + bazel_binary_build "opt" + } + "bazel.debug" { + echo "bazel debug build with tests..." + bazel_binary_build "dbg" + bazel_test "dbg" "$test" + } + "bazel.debug.server_only" { + echo "bazel debug build..." + bazel_binary_build "dbg" + } + "bazel.dev" { + echo "bazel fastbuild build with tests..." + bazel_binary_build "fastbuild" + bazel_test "fastbuild" "$test" + } + default { + echo "unknown action: $action" + exit 1 + } +} diff --git a/ci/prebuilt/BUILD b/ci/prebuilt/BUILD index 090fe800f14c3..1b517df55eb3c 100644 --- a/ci/prebuilt/BUILD +++ b/ci/prebuilt/BUILD @@ -2,17 +2,9 @@ licenses(["notice"]) # Apache 2 package(default_visibility = ["//visibility:public"]) -config_setting( - name = "windows_x86_64", - values = {"cpu": "x64_windows"}, -) - cc_library( name = "luajit", - srcs = select({ - ":windows_x86_64": ["thirdparty_build/lib/luajit.lib"], - "//conditions:default": ["thirdparty_build/lib/libluajit-5.1.a"], - }), + srcs = ["thirdparty_build/lib/libluajit-5.1.a"], hdrs = glob(["thirdparty_build/include/luajit-2.1/*"]), includes = ["thirdparty_build/include"], # TODO(mattklein123): We should strip luajit-2.1 here for consumers. However, if we do that From 39518611c8b40dda702614fae151ae9d83c01665 Mon Sep 17 00:00:00 2001 From: Larry West <31381548+larrywest42@users.noreply.github.com> Date: Fri, 8 Feb 2019 11:45:36 -0800 Subject: [PATCH 49/51] trivia: fix typo in README (#5883) Remove a superfluous line of three back-ticks that caused improper formatting of the http_proxy section. Signed-off-by: Larry West --- ci/README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/ci/README.md b/ci/README.md index 2626dd5fb602d..15fcee177563c 100644 --- a/ci/README.md +++ b/ci/README.md @@ -36,7 +36,6 @@ An example basic invocation to build a developer version of the Envoy static bin ``` The build image defaults to `envoyproxy/envoy-build-ubuntu`, but you can choose build image by setting `IMAGE_NAME` in the environment. -``` In case your setup is behind a proxy, set `http_proxy` and `https_proxy` to the proxy servers before invoking the build. From 925810d00b0d3095a8e67fd4e04e0f597ed188bb Mon Sep 17 00:00:00 2001 From: Quanjie Lin <32855694+quanjielin@users.noreply.github.com> Date: Fri, 8 Feb 2019 13:39:30 -0800 Subject: [PATCH 50/51] use hash func that generates deterministic result for protobuf (#5814) This PR uses hash func that generates deterministic result for proto. Background - When integrate envoy SDS with Istio, we found envoy sends out multiple requests for same sdsconfig(details in #5744); After some debugging, we found the issue describes in [protocolbuffers/protobuf#5668](https://github.com/protocolbuffers/protobuf/issues/5668). Signed-off-by: Quanjie Lin --- source/common/config/config_provider_impl.h | 20 +++++++++---------- source/common/router/rds_impl.cc | 6 ++---- source/common/router/rds_impl.h | 6 +++--- source/common/secret/secret_manager_impl.h | 3 ++- .../config/config_provider_impl_test.cc | 6 +++--- tools/check_format.py | 14 +++++++++++++ tools/check_format_test_helper.py | 3 +++ .../check_format/serialize_as_string.cc | 8 ++++++++ 8 files changed, 45 insertions(+), 21 deletions(-) create mode 100644 tools/testdata/check_format/serialize_as_string.cc diff --git a/source/common/config/config_provider_impl.h b/source/common/config/config_provider_impl.h index 884cbcaf2be31..6a53795481f15 100644 --- a/source/common/config/config_provider_impl.h +++ b/source/common/config/config_provider_impl.h @@ -196,7 +196,7 @@ class ConfigSubscriptionInstanceBase : public Init::Target, } protected: - ConfigSubscriptionInstanceBase(const std::string& name, const std::string& manager_identifier, + ConfigSubscriptionInstanceBase(const std::string& name, const uint64_t manager_identifier, ConfigProviderManagerImplBase& config_provider_manager, TimeSource& time_source, const SystemTime& last_updated, const LocalInfo::LocalInfo& local_info) @@ -222,7 +222,7 @@ class ConfigSubscriptionInstanceBase : public Init::Target, const std::string name_; std::function initialize_callback_; std::unordered_set mutable_config_providers_; - const std::string manager_identifier_; + const uint64_t manager_identifier_; ConfigProviderManagerImplBase& config_provider_manager_; TimeSource& time_source_; SystemTime last_updated_; @@ -346,7 +346,7 @@ class ConfigProviderManagerImplBase : public ConfigProviderManager, public Singl using ConfigProviderMap = std::unordered_map, EnumClassHash>; using ConfigSubscriptionMap = - std::unordered_map>; + std::unordered_map>; ConfigProviderManagerImplBase(Server::Admin& admin, const std::string& config_name); @@ -369,15 +369,15 @@ class ConfigProviderManagerImplBase : public ConfigProviderManager, public Singl * @return std::shared_ptr an existing (if a match is found) or newly allocated subscription. */ template - std::shared_ptr getSubscription( - const Protobuf::Message& config_source_proto, Init::Manager& init_manager, - const std::function& subscription_factory_fn) { + std::shared_ptr + getSubscription(const Protobuf::Message& config_source_proto, Init::Manager& init_manager, + const std::function& subscription_factory_fn) { static_assert(std::is_base_of::value, "T must be a subclass of ConfigSubscriptionInstanceBase"); ConfigSubscriptionInstanceBaseSharedPtr subscription; - const std::string manager_identifier = config_source_proto.SerializeAsString(); + const uint64_t manager_identifier = MessageUtil::hash(config_source_proto); auto it = config_subscriptions_.find(manager_identifier); if (it == config_subscriptions_.end()) { @@ -401,12 +401,12 @@ class ConfigProviderManagerImplBase : public ConfigProviderManager, public Singl } private: - void bindSubscription(const std::string& manager_identifier, + void bindSubscription(const uint64_t manager_identifier, ConfigSubscriptionInstanceBaseSharedPtr& subscription) { config_subscriptions_.insert({manager_identifier, subscription}); } - void unbindSubscription(const std::string& manager_identifier) { + void unbindSubscription(const uint64_t manager_identifier) { config_subscriptions_.erase(manager_identifier); } diff --git a/source/common/router/rds_impl.cc b/source/common/router/rds_impl.cc index 9427ef60025d4..1eb5528a27c88 100644 --- a/source/common/router/rds_impl.cc +++ b/source/common/router/rds_impl.cc @@ -56,7 +56,7 @@ StaticRouteConfigProviderImpl::~StaticRouteConfigProviderImpl() { // initialization needs to be fixed. RdsRouteConfigSubscription::RdsRouteConfigSubscription( const envoy::config::filter::network::http_connection_manager::v2::Rds& rds, - const std::string& manager_identifier, Server::Configuration::FactoryContext& factory_context, + const uint64_t manager_identifier, Server::Configuration::FactoryContext& factory_context, const std::string& stat_prefix, Envoy::Router::RouteConfigProviderManagerImpl& route_config_provider_manager) : route_config_name_(rds.route_config_name()), @@ -194,9 +194,7 @@ Router::RouteConfigProviderPtr RouteConfigProviderManagerImpl::createRdsRouteCon Server::Configuration::FactoryContext& factory_context, const std::string& stat_prefix) { // RdsRouteConfigSubscriptions are unique based on their serialized RDS config. - // TODO(htuch): Full serialization here gives large IDs, could get away with a - // strong hash instead. - const std::string manager_identifier = rds.SerializeAsString(); + const uint64_t manager_identifier = MessageUtil::hash(rds); RdsRouteConfigSubscriptionSharedPtr subscription; diff --git a/source/common/router/rds_impl.h b/source/common/router/rds_impl.h index 12918f6ffe34c..4498eb99bb104 100644 --- a/source/common/router/rds_impl.h +++ b/source/common/router/rds_impl.h @@ -121,7 +121,7 @@ class RdsRouteConfigSubscription RdsRouteConfigSubscription( const envoy::config::filter::network::http_connection_manager::v2::Rds& rds, - const std::string& manager_identifier, Server::Configuration::FactoryContext& factory_context, + const uint64_t manager_identifier, Server::Configuration::FactoryContext& factory_context, const std::string& stat_prefix, RouteConfigProviderManagerImpl& route_config_provider_manager); @@ -134,7 +134,7 @@ class RdsRouteConfigSubscription Stats::ScopePtr scope_; RdsStats stats_; RouteConfigProviderManagerImpl& route_config_provider_manager_; - const std::string manager_identifier_; + const uint64_t manager_identifier_; TimeSource& time_source_; SystemTime last_updated_; absl::optional config_info_; @@ -202,7 +202,7 @@ class RouteConfigProviderManagerImpl : public RouteConfigProviderManager, // TODO(jsedgwick) These two members are prime candidates for the owned-entry list/map // as in ConfigTracker. I.e. the ProviderImpls would have an EntryOwner for these lists // Then the lifetime management stuff is centralized and opaque. - std::unordered_map> + std::unordered_map> route_config_subscriptions_; std::unordered_set static_route_config_providers_; Server::ConfigTracker::EntryOwnerPtr config_tracker_entry_; diff --git a/source/common/secret/secret_manager_impl.h b/source/common/secret/secret_manager_impl.h index 7c00c7ea98a52..aa7ee6e4b2154 100644 --- a/source/common/secret/secret_manager_impl.h +++ b/source/common/secret/secret_manager_impl.h @@ -50,7 +50,8 @@ class SecretManagerImpl : public SecretManager { findOrCreate(const envoy::api::v2::core::ConfigSource& sds_config_source, const std::string& config_name, Server::Configuration::TransportSocketFactoryContext& secret_provider_context) { - const std::string map_key = sds_config_source.SerializeAsString() + config_name; + const std::string map_key = + absl::StrCat(MessageUtil::hash(sds_config_source), ".", config_name); std::shared_ptr secret_provider = dynamic_secret_providers_[map_key].lock(); if (!secret_provider) { diff --git a/test/common/config/config_provider_impl_test.cc b/test/common/config/config_provider_impl_test.cc index 1f355769cda58..1d94dbf4b239f 100644 --- a/test/common/config/config_provider_impl_test.cc +++ b/test/common/config/config_provider_impl_test.cc @@ -42,7 +42,7 @@ class DummyConfigSubscription : public ConfigSubscriptionInstanceBase, Envoy::Config::SubscriptionCallbacks { public: - DummyConfigSubscription(const std::string& manager_identifier, + DummyConfigSubscription(const uint64_t manager_identifier, Server::Configuration::FactoryContext& factory_context, DummyConfigProviderManager& config_provider_manager); @@ -162,7 +162,7 @@ class DummyConfigProviderManager : public ConfigProviderManagerImplBase { const std::string&) override { DummyConfigSubscriptionSharedPtr subscription = getSubscription( config_source_proto, factory_context.initManager(), - [&factory_context](const std::string& manager_identifier, + [&factory_context](const uint64_t manager_identifier, ConfigProviderManagerImplBase& config_provider_manager) -> ConfigSubscriptionInstanceBaseSharedPtr { return std::make_shared( @@ -199,7 +199,7 @@ StaticDummyConfigProvider::StaticDummyConfigProvider( config_(std::make_shared(config_proto)), config_proto_(config_proto) {} DummyConfigSubscription::DummyConfigSubscription( - const std::string& manager_identifier, Server::Configuration::FactoryContext& factory_context, + const uint64_t manager_identifier, Server::Configuration::FactoryContext& factory_context, DummyConfigProviderManager& config_provider_manager) : ConfigSubscriptionInstanceBase( "DummyDS", manager_identifier, config_provider_manager, factory_context.timeSource(), diff --git a/tools/check_format.py b/tools/check_format.py index bfd9c9061aaeb..e9e7594263216 100755 --- a/tools/check_format.py +++ b/tools/check_format.py @@ -42,6 +42,10 @@ # Files in these paths can use std::get_time GET_TIME_WHITELIST = ('./test/test_common/utility.cc') +# Files in these paths can use MessageLite::SerializeAsString +SERIALIZE_AS_STRING_WHITELIST = ('./test/common/protobuf/utility_test.cc', + './test/common/grpc/codec_test.cc') + CLANG_FORMAT_PATH = os.getenv("CLANG_FORMAT", "clang-format-7") BUILDIFIER_PATH = os.getenv("BUILDIFIER_BIN", "$GOPATH/bin/buildifier") ENVOY_BUILD_FIXER_PATH = os.path.join( @@ -223,6 +227,10 @@ def whitelistedForGetTime(file_path): return file_path in GET_TIME_WHITELIST +def whitelistedForSerializeAsString(file_path): + return file_path in SERIALIZE_AS_STRING_WHITELIST + + def findSubstringAndReturnError(pattern, file_path, error_message): with open(file_path) as f: text = f.read() @@ -414,6 +422,12 @@ def checkSourceLine(line, file_path, reportError): if file_path != './test/test_common/test_base.h' and (' testing::Test ' in line or ' testing::TestWithParam' in line): reportError("Derive test classes from TestBase in test/test_common/test_base.h") + if not whitelistedForSerializeAsString(file_path) and 'SerializeAsString' in line: + # The MessageLite::SerializeAsString doesn't generate deterministic serialization, + # use MessageUtil::hash instead. + reportError( + "Don't use MessageLite::SerializeAsString for generating deterministic serialization, use MessageUtil::hash instead." + ) def checkBuildLine(line, file_path, reportError): diff --git a/tools/check_format_test_helper.py b/tools/check_format_test_helper.py index e09015566fdc5..001a3191c6b7e 100755 --- a/tools/check_format_test_helper.py +++ b/tools/check_format_test_helper.py @@ -202,6 +202,9 @@ def checkFileExpectingOK(filename): errors += checkUnfixableError("elvis_operator.cc", "Don't use the '?:' operator") errors += checkUnfixableError("testing_test.cc", "Don't use 'using testing::Test;, elaborate the type instead") + errors += checkUnfixableError( + "serialize_as_string.cc", + "Don't use MessageLite::SerializeAsString for generating deterministic serialization") errors += checkUnfixableError( "version_history.rst", "Version history line malformed. Does not match VERSION_HISTORY_NEW_LINE_REGEX in " diff --git a/tools/testdata/check_format/serialize_as_string.cc b/tools/testdata/check_format/serialize_as_string.cc new file mode 100644 index 0000000000000..705bf5dae77ff --- /dev/null +++ b/tools/testdata/check_format/serialize_as_string.cc @@ -0,0 +1,8 @@ +namespace Envoy { + +void use_serialize_as_string() { + google::protobuf::FieldMask mask; + const std::string key = mask.SerializeAsString(); +} + +} // namespace Envoy From 7acc5d94cfb9cbb9aa8f2b51054d2798dd1842fc Mon Sep 17 00:00:00 2001 From: John Plevyak Date: Mon, 11 Mar 2019 15:40:36 -0700 Subject: [PATCH 51/51] Use new DispatcherImpl interface. --- ci/prebuilt/BUILD | 2 +- test/extensions/wasm/wasm_test.cc | 22 +++++++--------------- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/ci/prebuilt/BUILD b/ci/prebuilt/BUILD index 4d91b535664aa..8fba80bad2d45 100644 --- a/ci/prebuilt/BUILD +++ b/ci/prebuilt/BUILD @@ -28,7 +28,7 @@ cc_library( cc_library( name = "wavm_with_llvm", srcs = select({ - ":windows_x86_64": ["WINDOWS_IS_NOT_SUPPORTED_YET"], + "@envoy//bazel:windows_x86_64": ["WINDOWS_IS_NOT_SUPPORTED_YET"], "//conditions:default": [ # ld: Runtime and WASTParse need to be listed first. "thirdparty_build/lib/WAVM/RelWithDebInfo/libRuntime.a", diff --git a/test/extensions/wasm/wasm_test.cc b/test/extensions/wasm/wasm_test.cc index b087dc1fe7ec9..2f45b06e33efb 100644 --- a/test/extensions/wasm/wasm_test.cc +++ b/test/extensions/wasm/wasm_test.cc @@ -7,7 +7,6 @@ #include "test/mocks/upstream/mocks.h" #include "test/test_common/environment.h" -#include "test/test_common/simulated_time_system.h" #include "test/test_common/utility.h" #include "absl/types/optional.h" @@ -31,9 +30,8 @@ class TestContext : public Extensions::Common::Wasm::Context { TEST(WasmTest, Logging) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - Event::SimulatedTimeSystem time_system; Upstream::MockClusterManager cluster_manager; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_unique("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr); @@ -58,9 +56,8 @@ TEST(WasmTest, Logging) { TEST(WasmTest, BadSignature) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); - Event::SimulatedTimeSystem time_system; Upstream::MockClusterManager cluster_manager; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_shared("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr); @@ -77,8 +74,7 @@ TEST(WasmTest, Segv) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); Upstream::MockClusterManager cluster_manager; - Event::SimulatedTimeSystem time_system; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_shared("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr); @@ -97,8 +93,7 @@ TEST(WasmTest, DivByZero) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); Upstream::MockClusterManager cluster_manager; - Event::SimulatedTimeSystem time_system; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_shared("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr); @@ -118,8 +113,7 @@ TEST(WasmTest, EmscriptenVersion) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); Upstream::MockClusterManager cluster_manager; - Event::SimulatedTimeSystem time_system; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_shared("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr); @@ -140,8 +134,7 @@ TEST(WasmTest, IntrinsicGlobals) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); Upstream::MockClusterManager cluster_manager; - Event::SimulatedTimeSystem time_system; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_shared("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr); @@ -166,8 +159,7 @@ TEST(WasmTest, Asm2Wasm) { Stats::IsolatedStoreImpl stats_store; Api::ApiPtr api = Api::createApiForTest(stats_store); Upstream::MockClusterManager cluster_manager; - Event::SimulatedTimeSystem time_system; - Event::DispatcherImpl dispatcher(time_system, *api); + Event::DispatcherImpl dispatcher(*api); auto wasm = std::make_shared("envoy.wasm.vm.wavm", "", "", cluster_manager, dispatcher); EXPECT_NE(wasm, nullptr);