diff --git a/include/envoy/common/time.h b/include/envoy/common/time.h index 6fd7e6e7198be..4b9ef6884ac5b 100644 --- a/include/envoy/common/time.h +++ b/include/envoy/common/time.h @@ -14,76 +14,22 @@ namespace Envoy { typedef std::chrono::time_point SystemTime; typedef std::chrono::time_point MonotonicTime; -/** - * Abstraction for getting the current system time. Useful for testing. - * - * TODO(#4160): eliminate this class and pass TimeSource everywhere. - */ -class SystemTimeSource { -public: - virtual ~SystemTimeSource() {} - - /** - * @return the current system time. - */ - virtual SystemTime currentTime() PURE; -}; - -/** - * Abstraction for getting the current monotonically increasing time. Useful for - * testing. - * - * TODO(#4160): eliminate this class and pass TimeSource everywhere. - */ -class MonotonicTimeSource { -public: - virtual ~MonotonicTimeSource() {} - - /** - * @return the current monotonic time. - */ - virtual MonotonicTime currentTime() PURE; -}; - /** * Captures a system-time source, capable of computing both monotonically increasing * and real time. - * - * TODO(#4160): currently this is just a container for SystemTimeSource and - * MonotonicTimeSource but we should clean that up and just have this as the - * base class. Once that's done, TimeSource will be a pure interface. */ class TimeSource { public: - TimeSource(SystemTimeSource& system, MonotonicTimeSource& monotonic) - : system_(system), monotonic_(monotonic) {} + virtual ~TimeSource() {} /** * @return the current system time; not guaranteed to be monotonically increasing. */ - SystemTime systemTime() { return system_.currentTime(); } - + virtual SystemTime systemTime() PURE; /** * @return the current monotonic time. */ - MonotonicTime monotonicTime() { return monotonic_.currentTime(); } - - /** - * Compares two time-sources for equality; this is needed for mocks. - */ - bool operator==(const TimeSource& ts) const { - return &system_ == &ts.system_ && &monotonic_ == &ts.monotonic_; - } - - // TODO(jmarantz): Eliminate these methods and the SystemTimeSource and MonotonicTimeSource - // classes, and change method calls to work directly off of TimeSource. - SystemTimeSource& system() { return system_; } - MonotonicTimeSource& monotonic() { return monotonic_; } - -private: - // These are pointers rather than references in order to support assignment. - SystemTimeSource& system_; - MonotonicTimeSource& monotonic_; + virtual MonotonicTime monotonicTime() PURE; }; } // namespace Envoy diff --git a/include/envoy/server/filter_config.h b/include/envoy/server/filter_config.h index 997d773ad2bcd..c48921e6c5ab4 100644 --- a/include/envoy/server/filter_config.h +++ b/include/envoy/server/filter_config.h @@ -130,13 +130,6 @@ class FactoryContext { */ virtual const envoy::api::v2::core::Metadata& listenerMetadata() const PURE; - /** - * @return SystemTimeSource& a reference to the system time source. - * TODO(#4160): This method should be eliminated, and call-sites and mocks should - * be converted to work with timeSource() below. - */ - virtual SystemTimeSource& systemTimeSource() PURE; - /** * @return TimeSource& a reference to the time source. */ diff --git a/source/common/common/perf_annotation.h b/source/common/common/perf_annotation.h index 36442289704d1..9b0fbcb227e7f 100644 --- a/source/common/common/perf_annotation.h +++ b/source/common/common/perf_annotation.h @@ -87,7 +87,7 @@ class PerfAnnotationContext { absl::string_view description); /** @return MonotonicTime the current time */ - MonotonicTime currentTime() { return time_source_.currentTime(); } + MonotonicTime currentTime() { return time_source_.monotonicTime(); } /** * Renders the aggregated statistics as a string. @@ -141,7 +141,7 @@ class PerfAnnotationContext { #else DurationStatsMap duration_stats_map_; #endif - ProdMonotonicTimeSource time_source_; + RealTimeSource time_source_; }; /** diff --git a/source/common/common/token_bucket_impl.cc b/source/common/common/token_bucket_impl.cc index a46848ad34ff3..07cf3a83c3e59 100644 --- a/source/common/common/token_bucket_impl.cc +++ b/source/common/common/token_bucket_impl.cc @@ -4,15 +4,13 @@ namespace Envoy { -TokenBucketImpl::TokenBucketImpl(uint64_t max_tokens, MonotonicTimeSource& monotonic_time_source, - double fill_rate) +TokenBucketImpl::TokenBucketImpl(uint64_t max_tokens, TimeSource& time_source, double fill_rate) : max_tokens_(max_tokens), fill_rate_(std::abs(fill_rate)), tokens_(max_tokens), - last_fill_(monotonic_time_source.currentTime()), - monotonic_time_source_(monotonic_time_source) {} + last_fill_(time_source.monotonicTime()), time_source_(time_source) {} bool TokenBucketImpl::consume(uint64_t tokens) { if (tokens_ < max_tokens_) { - const auto time_now = monotonic_time_source_.currentTime(); + const auto time_now = time_source_.monotonicTime(); tokens_ = std::min((std::chrono::duration(time_now - last_fill_).count() * fill_rate_) + tokens_, max_tokens_); diff --git a/source/common/common/token_bucket_impl.h b/source/common/common/token_bucket_impl.h index d859424a35b85..37bf0386c2bb4 100644 --- a/source/common/common/token_bucket_impl.h +++ b/source/common/common/token_bucket_impl.h @@ -18,8 +18,7 @@ class TokenBucketImpl : public TokenBucket { * @param fill_rate supplies the number of tokens that will return to the bucket on each second. * The default is 1. */ - explicit TokenBucketImpl(uint64_t max_tokens, MonotonicTimeSource& time_source, - double fill_rate = 1); + explicit TokenBucketImpl(uint64_t max_tokens, TimeSource& time_source, double fill_rate = 1); bool consume(uint64_t tokens = 1) override; @@ -28,7 +27,7 @@ class TokenBucketImpl : public TokenBucket { const double fill_rate_; double tokens_; MonotonicTime last_fill_; - MonotonicTimeSource& monotonic_time_source_; + TimeSource& time_source_; }; } // namespace Envoy diff --git a/source/common/common/utility.h b/source/common/common/utility.h index 0373b4b36c864..d086d720699a6 100644 --- a/source/common/common/utility.h +++ b/source/common/common/utility.h @@ -96,21 +96,13 @@ class AccessLogDateTimeFormatter { }; /** - * Production implementation of SystemTimeSource that returns the current time. + * Real-time implementation of TimeSource. */ -class ProdSystemTimeSource : public SystemTimeSource { +class RealTimeSource : public TimeSource { public: - // SystemTimeSource - SystemTime currentTime() override { return std::chrono::system_clock::now(); } -}; - -/** - * Production implementation of MonotonicTimeSource that returns the current time. - */ -class ProdMonotonicTimeSource : public MonotonicTimeSource { -public: - // MonotonicTimeSource - MonotonicTime currentTime() override { return std::chrono::steady_clock::now(); } + // TimeSource + SystemTime systemTime() override { return std::chrono::system_clock::now(); } + MonotonicTime monotonicTime() override { return std::chrono::steady_clock::now(); } }; /** diff --git a/source/common/config/grpc_mux_impl.cc b/source/common/config/grpc_mux_impl.cc index 0af5b7c50574f..a360909119198 100644 --- a/source/common/config/grpc_mux_impl.cc +++ b/source/common/config/grpc_mux_impl.cc @@ -111,11 +111,9 @@ GrpcMuxWatchPtr GrpcMuxImpl::subscribe(const std::string& type_url, // TODO(gsagula): move TokenBucketImpl params to a config. if (!api_state_[type_url].subscribed_) { // Bucket contains 100 tokens maximum and refills at 5 tokens/sec. - api_state_[type_url].limit_request_ = - std::make_unique(100, time_source_.monotonic(), 5); + api_state_[type_url].limit_request_ = std::make_unique(100, time_source_, 5); // Bucket contains 1 token maximum and refills 1 token on every ~5 seconds. - api_state_[type_url].limit_log_ = - std::make_unique(1, time_source_.monotonic(), 0.2); + api_state_[type_url].limit_log_ = std::make_unique(1, time_source_, 0.2); api_state_[type_url].request_.set_type_url(type_url); api_state_[type_url].request_.mutable_node()->MergeFrom(local_info_.node()); api_state_[type_url].subscribed_ = true; diff --git a/source/common/config/grpc_mux_impl.h b/source/common/config/grpc_mux_impl.h index 0fceb67a45758..ef482b5b75f3b 100644 --- a/source/common/config/grpc_mux_impl.h +++ b/source/common/config/grpc_mux_impl.h @@ -103,7 +103,7 @@ class GrpcMuxImpl : public GrpcMux, std::list subscriptions_; Event::TimerPtr retry_timer_; Runtime::RandomGenerator& random_; - TimeSource time_source_; + TimeSource& time_source_; BackOffStrategyPtr backoff_strategy_; }; diff --git a/source/common/event/dispatcher_impl.h b/source/common/event/dispatcher_impl.h index ffc136e2f8f54..0dcb10f7ab6e7 100644 --- a/source/common/event/dispatcher_impl.h +++ b/source/common/event/dispatcher_impl.h @@ -68,7 +68,7 @@ class DispatcherImpl : Logger::Loggable, public Dispatcher { return run_tid_ == 0 || run_tid_ == Thread::Thread::currentThreadId(); } - TimeSource time_source_; + TimeSource& time_source_; Thread::ThreadId run_tid_{}; Buffer::WatermarkFactoryPtr buffer_factory_; Libevent::BasePtr base_; diff --git a/source/common/router/rds_impl.cc b/source/common/router/rds_impl.cc index 7f6d8184ffbb8..d593f99084503 100644 --- a/source/common/router/rds_impl.cc +++ b/source/common/router/rds_impl.cc @@ -44,7 +44,7 @@ StaticRouteConfigProviderImpl::StaticRouteConfigProviderImpl( Server::Configuration::FactoryContext& factory_context, RouteConfigProviderManagerImpl& route_config_provider_manager) : config_(new ConfigImpl(config, factory_context, true)), route_config_proto_{config}, - last_updated_(factory_context.systemTimeSource().currentTime()), + last_updated_(factory_context.timeSource().systemTime()), route_config_provider_manager_(route_config_provider_manager) { route_config_provider_manager_.static_route_config_providers_.insert(this); } @@ -64,8 +64,8 @@ RdsRouteConfigSubscription::RdsRouteConfigSubscription( scope_(factory_context.scope().createScope(stat_prefix + "rds." + route_config_name_ + ".")), stats_({ALL_RDS_STATS(POOL_COUNTER(*scope_))}), route_config_provider_manager_(route_config_provider_manager), - manager_identifier_(manager_identifier), time_source_(factory_context.systemTimeSource()), - last_updated_(factory_context.systemTimeSource().currentTime()) { + manager_identifier_(manager_identifier), time_source_(factory_context.timeSource()), + last_updated_(factory_context.timeSource().systemTime()) { ::Envoy::Config::Utility::checkLocalInfo("rds", factory_context.localInfo()); subscription_ = Envoy::Config::SubscriptionFactory::subscriptionFromConfigSource< @@ -96,7 +96,7 @@ RdsRouteConfigSubscription::~RdsRouteConfigSubscription() { void RdsRouteConfigSubscription::onConfigUpdate(const ResourceVector& resources, const std::string& version_info) { - last_updated_ = time_source_.currentTime(); + last_updated_ = time_source_.systemTime(); if (resources.empty()) { ENVOY_LOG(debug, "Missing RouteConfiguration for {} in onConfigUpdate()", route_config_name_); diff --git a/source/common/router/rds_impl.h b/source/common/router/rds_impl.h index 8649f71747f5d..12918f6ffe34c 100644 --- a/source/common/router/rds_impl.h +++ b/source/common/router/rds_impl.h @@ -135,7 +135,7 @@ class RdsRouteConfigSubscription RdsStats stats_; RouteConfigProviderManagerImpl& route_config_provider_manager_; const std::string manager_identifier_; - SystemTimeSource& time_source_; + TimeSource& time_source_; SystemTime last_updated_; absl::optional config_info_; envoy::api::v2::RouteConfiguration route_config_proto_; diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index 7860cdd2c0182..4a35cbcb1e1f6 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -186,9 +186,8 @@ ClusterManagerImpl::ClusterManagerImpl(const envoy::config::bootstrap::v2::Boots if (cm_config.has_outlier_detection()) { const std::string event_log_file_path = cm_config.outlier_detection().event_log_path(); if (!event_log_file_path.empty()) { - outlier_event_logger_.reset(new Outlier::EventLoggerImpl( - log_manager, event_log_file_path, dispatcher_.timeSource().system(), - dispatcher_.timeSource().monotonic())); + outlier_event_logger_.reset( + new Outlier::EventLoggerImpl(log_manager, event_log_file_path, dispatcher_.timeSource())); } } @@ -615,7 +614,7 @@ void ClusterManagerImpl::loadCluster(const envoy::api::v2::Cluster& cluster, } cluster_map[cluster_reference.info()->name()] = std::make_unique( - cluster, version_info, added_via_api, std::move(new_cluster), time_source_.system()); + cluster, version_info, added_via_api, std::move(new_cluster), time_source_); const auto cluster_entry_it = cluster_map.find(cluster_reference.info()->name()); // If an LB is thread aware, create it here. The LB is not initialized until cluster pre-init diff --git a/source/common/upstream/cluster_manager_impl.h b/source/common/upstream/cluster_manager_impl.h index 45fa479e7b94f..3ccf0e6c8a693 100644 --- a/source/common/upstream/cluster_manager_impl.h +++ b/source/common/upstream/cluster_manager_impl.h @@ -330,11 +330,10 @@ class ClusterManagerImpl : public ClusterManager, Logger::Loggablecluster().name()); event.mutable_eject_unhealthy_event()->set_failure_type(failure_type); - TimestampUtil::systemClockToTimestamp(system_time_source_.currentTime(), - *event.mutable_timestamp()); + TimestampUtil::systemClockToTimestamp(time_source_.systemTime(), *event.mutable_timestamp()); // Make sure the type enums make it into the JSON const auto json = MessageUtil::getJsonStringFromMessage(event, /* pretty_print */ false, /* always_print_primitive_fields */ true); @@ -305,8 +304,7 @@ void HealthCheckEventLoggerImpl::logAddHealthy( *event.mutable_host() = std::move(address); event.set_cluster_name(host->cluster().name()); event.mutable_add_healthy_event()->set_first_check(first_check); - TimestampUtil::systemClockToTimestamp(system_time_source_.currentTime(), - *event.mutable_timestamp()); + TimestampUtil::systemClockToTimestamp(time_source_.systemTime(), *event.mutable_timestamp()); // Make sure the type enums make it into the JSON const auto json = MessageUtil::getJsonStringFromMessage(event, /* pretty_print */ false, /* always_print_primitive_fields */ true); diff --git a/source/common/upstream/health_checker_base_impl.h b/source/common/upstream/health_checker_base_impl.h index 933136a44757c..684db69981d86 100644 --- a/source/common/upstream/health_checker_base_impl.h +++ b/source/common/upstream/health_checker_base_impl.h @@ -132,9 +132,9 @@ class HealthCheckerImplBase : public HealthChecker, class HealthCheckEventLoggerImpl : public HealthCheckEventLogger { public: - HealthCheckEventLoggerImpl(AccessLog::AccessLogManager& log_manager, - SystemTimeSource& system_time_source, const std::string& file_name) - : system_time_source_(system_time_source), file_(log_manager.createAccessLog(file_name)) {} + HealthCheckEventLoggerImpl(AccessLog::AccessLogManager& log_manager, TimeSource& time_source, + const std::string& file_name) + : time_source_(time_source), file_(log_manager.createAccessLog(file_name)) {} void logEjectUnhealthy(envoy::data::core::v2alpha::HealthCheckerType health_checker_type, const HostDescriptionConstSharedPtr& host, @@ -143,7 +143,7 @@ class HealthCheckEventLoggerImpl : public HealthCheckEventLogger { const HostDescriptionConstSharedPtr& host, bool first_check) override; private: - SystemTimeSource& system_time_source_; + TimeSource& time_source_; Filesystem::FileSharedPtr file_; }; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index d3172183f67c7..6d4abb030671e 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -50,7 +50,7 @@ HealthCheckerFactory::create(const envoy::api::v2::core::HealthCheck& hc_config, HealthCheckEventLoggerPtr event_logger; if (!hc_config.event_log_path().empty()) { event_logger = std::make_unique( - log_manager, dispatcher.timeSource().system(), hc_config.event_log_path()); + log_manager, dispatcher.timeSource(), hc_config.event_log_path()); } switch (hc_config.health_checker_case()) { case envoy::api::v2::core::HealthCheck::HealthCheckerCase::kHttpHealthCheck: diff --git a/source/common/upstream/outlier_detection_impl.cc b/source/common/upstream/outlier_detection_impl.cc index c69a287456037..001110d44d9bd 100644 --- a/source/common/upstream/outlier_detection_impl.cc +++ b/source/common/upstream/outlier_detection_impl.cc @@ -25,7 +25,7 @@ DetectorSharedPtr DetectorImplFactory::createForCluster( Runtime::Loader& runtime, EventLoggerSharedPtr event_logger) { if (cluster_config.has_outlier_detection()) { return DetectorImpl::create(cluster, cluster_config.outlier_detection(), dispatcher, runtime, - dispatcher.timeSource().monotonic(), event_logger); + dispatcher.timeSource(), event_logger); } else { return nullptr; } @@ -130,7 +130,7 @@ DetectorConfig::DetectorConfig(const envoy::api::v2::cluster::OutlierDetection& DetectorImpl::DetectorImpl(const Cluster& cluster, const envoy::api::v2::cluster::OutlierDetection& config, Event::Dispatcher& dispatcher, Runtime::Loader& runtime, - MonotonicTimeSource& time_source, EventLoggerSharedPtr event_logger) + TimeSource& time_source, EventLoggerSharedPtr event_logger) : config_(config), dispatcher_(dispatcher), runtime_(runtime), time_source_(time_source), stats_(generateStats(cluster.info()->statsScope())), interval_timer_(dispatcher.createTimer([this]() -> void { onIntervalTimer(); })), @@ -150,7 +150,7 @@ std::shared_ptr DetectorImpl::create(const Cluster& cluster, const envoy::api::v2::cluster::OutlierDetection& config, Event::Dispatcher& dispatcher, Runtime::Loader& runtime, - MonotonicTimeSource& time_source, EventLoggerSharedPtr event_logger) { + TimeSource& time_source, EventLoggerSharedPtr event_logger) { std::shared_ptr detector( new DetectorImpl(cluster, config, dispatcher, runtime, time_source, event_logger)); detector->initialize(cluster); @@ -268,7 +268,7 @@ void DetectorImpl::ejectHost(HostSharedPtr host, EjectionType type) { if (enforceEjection(type)) { stats_.ejections_active_.inc(); updateEnforcedEjectionStats(type); - host_monitors_[host]->eject(time_source_.currentTime()); + host_monitors_[host]->eject(time_source_.monotonicTime()); runCallbacks(host); if (event_logger_) { @@ -432,7 +432,7 @@ void DetectorImpl::processSuccessRateEjections() { } void DetectorImpl::onIntervalTimer() { - MonotonicTime now = time_source_.currentTime(); + MonotonicTime now = time_source_.monotonicTime(); for (auto host : host_monitors_) { checkHostForUneject(host.first, host.second, now); @@ -486,8 +486,8 @@ void EventLoggerImpl::logEject(HostDescriptionConstSharedPtr host, Detector& det "\"cluster_success_rate_ejection_threshold\": \"{}\"" + "}}\n"; // clang-format on - SystemTime now = time_source_.currentTime(); - MonotonicTime monotonic_now = monotonic_time_source_.currentTime(); + SystemTime now = time_source_.systemTime(); + MonotonicTime monotonic_now = time_source_.monotonicTime(); switch (type) { case EjectionType::Consecutive5xx: @@ -522,8 +522,8 @@ void EventLoggerImpl::logUneject(HostDescriptionConstSharedPtr host) { "\"num_ejections\": {}" + "}}\n"; // clang-format on - SystemTime now = time_source_.currentTime(); - MonotonicTime monotonic_now = monotonic_time_source_.currentTime(); + SystemTime now = time_source_.systemTime(); + MonotonicTime monotonic_now = time_source_.monotonicTime(); file_->write(fmt::format( json, AccessLogDateTimeFormatter::fromTime(now), secsSinceLastAction(host->outlierDetector().lastEjectionTime(), monotonic_now), diff --git a/source/common/upstream/outlier_detection_impl.h b/source/common/upstream/outlier_detection_impl.h index 7b37c393e8b82..09ac638aed551 100644 --- a/source/common/upstream/outlier_detection_impl.h +++ b/source/common/upstream/outlier_detection_impl.h @@ -212,7 +212,7 @@ class DetectorImpl : public Detector, public std::enable_shared_from_this create(const Cluster& cluster, const envoy::api::v2::cluster::OutlierDetection& config, - Event::Dispatcher& dispatcher, Runtime::Loader& runtime, MonotonicTimeSource& time_source, + Event::Dispatcher& dispatcher, Runtime::Loader& runtime, TimeSource& time_source, EventLoggerSharedPtr event_logger); ~DetectorImpl(); @@ -228,8 +228,8 @@ class DetectorImpl : public Detector, public std::enable_shared_from_this callbacks_; @@ -261,9 +261,8 @@ class DetectorImpl : public Detector, public std::enable_shared_from_this& lastActionTime, MonotonicTime now); Filesystem::FileSharedPtr file_; - SystemTimeSource& time_source_; - MonotonicTimeSource& monotonic_time_source_; + TimeSource& time_source_; }; /** diff --git a/source/exe/main_common.cc b/source/exe/main_common.cc index 6c417f7671e1d..66b579d331c10 100644 --- a/source/exe/main_common.cc +++ b/source/exe/main_common.cc @@ -38,8 +38,7 @@ Runtime::LoaderPtr ProdComponentFactory::createRuntime(Server::Instance& server, return Server::InstanceUtil::createRuntime(server, config); } -MainCommonBase::MainCommonBase(OptionsImpl& options) - : options_(options), time_source_(system_time_source_, monotonic_time_source_) { +MainCommonBase::MainCommonBase(OptionsImpl& options) : options_(options) { ares_library_init(ARES_LIB_INIT_ALL); Event::Libevent::Global::initialize(); RELEASE_ASSERT(Envoy::Server::validateProtoDescriptors(), ""); diff --git a/source/exe/main_common.h b/source/exe/main_common.h index 5355bc2a4f3c6..60112d3a63a90 100644 --- a/source/exe/main_common.h +++ b/source/exe/main_common.h @@ -49,9 +49,7 @@ class MainCommonBase { protected: Envoy::OptionsImpl& options_; ProdComponentFactory component_factory_; - ProdSystemTimeSource system_time_source_; - ProdMonotonicTimeSource monotonic_time_source_; - TimeSource time_source_; + RealTimeSource time_source_; DefaultTestHooks default_test_hooks_; std::unique_ptr tls_; std::unique_ptr restarter_; diff --git a/source/extensions/tracers/zipkin/tracer.h b/source/extensions/tracers/zipkin/tracer.h index f177da30a7b12..ab68286b1cbf2 100644 --- a/source/extensions/tracers/zipkin/tracer.h +++ b/source/extensions/tracers/zipkin/tracer.h @@ -116,7 +116,7 @@ class Tracer : public TracerInterface { ReporterPtr reporter_; Runtime::RandomGenerator& random_generator_; const bool trace_id_128bit_; - TimeSource time_source_; + TimeSource& time_source_; }; typedef std::unique_ptr TracerPtr; diff --git a/source/extensions/tracers/zipkin/zipkin_core_types.h b/source/extensions/tracers/zipkin/zipkin_core_types.h index bd83a1fa86074..059191245abc9 100644 --- a/source/extensions/tracers/zipkin/zipkin_core_types.h +++ b/source/extensions/tracers/zipkin/zipkin_core_types.h @@ -562,7 +562,7 @@ class Span : public ZipkinBase { absl::optional trace_id_high_; int64_t monotonic_start_time_; TracerInterface* tracer_; - TimeSource time_source_; + TimeSource& time_source_; }; } // namespace Zipkin diff --git a/source/server/config_validation/server.cc b/source/server/config_validation/server.cc index 90b57e8f26228..3e91399f0f996 100644 --- a/source/server/config_validation/server.cc +++ b/source/server/config_validation/server.cc @@ -22,9 +22,7 @@ bool validateConfig(Options& options, Network::Address::InstanceConstSharedPtr l Stats::IsolatedStoreImpl stats_store; try { - ProdSystemTimeSource system_time_source; - ProdMonotonicTimeSource monotonic_time_source; - TimeSource time_source(system_time_source, monotonic_time_source); + RealTimeSource time_source; ValidationInstance server(options, time_source, local_address, stats_store, access_log_lock, component_factory); std::cout << "configuration '" << options.configPath() << "' OK" << std::endl; diff --git a/source/server/config_validation/server.h b/source/server/config_validation/server.h index b985dd4955c6f..072e4fb6ea857 100644 --- a/source/server/config_validation/server.h +++ b/source/server/config_validation/server.h @@ -138,7 +138,7 @@ class ValidationInstance : Logger::Loggable, ComponentFactory& component_factory); Options& options_; - TimeSource time_source_; + TimeSource& time_source_; Stats::IsolatedStoreImpl& stats_store_; ThreadLocal::InstanceImpl thread_local_; Api::ApiPtr api_; diff --git a/source/server/guarddog_impl.h b/source/server/guarddog_impl.h index 543f7de8e1880..95aebf775c8b6 100644 --- a/source/server/guarddog_impl.h +++ b/source/server/guarddog_impl.h @@ -75,7 +75,7 @@ class GuardDogImpl : public GuardDog { bool megamiss_alerted_{}; }; - TimeSource time_source_; + TimeSource& time_source_; const std::chrono::milliseconds miss_timeout_; const std::chrono::milliseconds megamiss_timeout_; const std::chrono::milliseconds kill_timeout_; diff --git a/source/server/listener_manager_impl.h b/source/server/listener_manager_impl.h index 84ae38aaae206..772ba5e2bc9f9 100644 --- a/source/server/listener_manager_impl.h +++ b/source/server/listener_manager_impl.h @@ -121,7 +121,7 @@ class ListenerManagerImpl : public ListenerManager, Logger::Loggable, public Instance { void terminate(); Options& options_; - TimeSource time_source_; + TimeSource& time_source_; HotRestart& restarter_; const time_t start_time_; time_t original_start_time_; diff --git a/source/server/watchdog_impl.h b/source/server/watchdog_impl.h index 8898d2a07e346..dd0bd7fe580f7 100644 --- a/source/server/watchdog_impl.h +++ b/source/server/watchdog_impl.h @@ -38,7 +38,7 @@ class WatchDogImpl : public WatchDog { private: const int32_t thread_id_; - TimeSource time_source_; + TimeSource& time_source_; std::atomic latest_touch_time_since_epoch_; Event::TimerPtr timer_; const std::chrono::milliseconds timer_interval_; diff --git a/source/server/worker_impl.h b/source/server/worker_impl.h index 3ef7075ee806d..abf52da554df9 100644 --- a/source/server/worker_impl.h +++ b/source/server/worker_impl.h @@ -31,7 +31,7 @@ class ProdWorkerFactory : public WorkerFactory, Logger::Loggable mock_monotonic_time_source_; + NiceMock mock_time_source_; }; // Verifies TokenBucket initialization. TEST_F(TokenBucketImplTest, Initialization) { - TokenBucketImpl token_bucket{1, mock_monotonic_time_source_, -1.0}; + TokenBucketImpl token_bucket{1, mock_time_source_, -1.0}; EXPECT_TRUE(token_bucket.consume()); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()).WillOnce(Return(time_point{})); + EXPECT_CALL(mock_time_source_, monotonicTime()).WillOnce(Return(time_point{})); EXPECT_FALSE(token_bucket.consume()); } // Verifies TokenBucket's maximum capacity. TEST_F(TokenBucketImplTest, MaxBucketSize) { - TokenBucketImpl token_bucket{3, mock_monotonic_time_source_, 1}; + TokenBucketImpl token_bucket{3, mock_time_source_, 1}; EXPECT_TRUE(token_bucket.consume(3)); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .WillOnce(Return(time_point(std::chrono::seconds(10)))); EXPECT_FALSE(token_bucket.consume(4)); @@ -45,35 +45,35 @@ TEST_F(TokenBucketImplTest, MaxBucketSize) { // Verifies that TokenBucket can consume and refill tokens. TEST_F(TokenBucketImplTest, ConsumeAndRefill) { { - TokenBucketImpl token_bucket{10, mock_monotonic_time_source_, 1}; + TokenBucketImpl token_bucket{10, mock_time_source_, 1}; EXPECT_FALSE(token_bucket.consume(20)); EXPECT_TRUE(token_bucket.consume(9)); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()).WillOnce(Return(time_point{})); + EXPECT_CALL(mock_time_source_, monotonicTime()).WillOnce(Return(time_point{})); EXPECT_TRUE(token_bucket.consume()); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .WillOnce(Return(time_point(std::chrono::milliseconds(999)))); EXPECT_FALSE(token_bucket.consume()); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .WillOnce(Return(time_point(std::chrono::milliseconds(5999)))); EXPECT_FALSE(token_bucket.consume(6)); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .WillRepeatedly(Return(time_point(std::chrono::milliseconds(6000)))); EXPECT_TRUE(token_bucket.consume(6)); EXPECT_FALSE(token_bucket.consume()); } - ASSERT_TRUE(Mock::VerifyAndClear(&mock_monotonic_time_source_)); + ASSERT_TRUE(Mock::VerifyAndClear(&mock_time_source_)); { - TokenBucketImpl token_bucket{1, mock_monotonic_time_source_, 0.5}; + TokenBucketImpl token_bucket{1, mock_time_source_, 0.5}; EXPECT_TRUE(token_bucket.consume()); - EXPECT_CALL(mock_monotonic_time_source_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .Times(3) .WillOnce(Return(time_point(std::chrono::milliseconds(500)))) .WillOnce(Return(time_point(std::chrono::milliseconds(1500)))) @@ -83,7 +83,7 @@ TEST_F(TokenBucketImplTest, ConsumeAndRefill) { EXPECT_FALSE(token_bucket.consume()); EXPECT_TRUE(token_bucket.consume()); - ASSERT_TRUE(Mock::VerifyAndClear(&mock_monotonic_time_source_)); + ASSERT_TRUE(Mock::VerifyAndClear(&mock_time_source_)); } } diff --git a/test/common/common/utility_test.cc b/test/common/common/utility_test.cc index aa586715e0767..8123ccff20e73 100644 --- a/test/common/common/utility_test.cc +++ b/test/common/common/utility_test.cc @@ -130,8 +130,8 @@ TEST(DateUtil, All) { } TEST(ProdSystemTimeSourceTest, All) { - ProdSystemTimeSource source; - source.currentTime(); + RealTimeSource source; + source.systemTime(); } TEST(InputConstMemoryStream, All) { diff --git a/test/common/config/grpc_mux_impl_test.cc b/test/common/config/grpc_mux_impl_test.cc index cd2293c5d0e56..010fbe8ab7acc 100644 --- a/test/common/config/grpc_mux_impl_test.cc +++ b/test/common/config/grpc_mux_impl_test.cc @@ -34,9 +34,7 @@ namespace { // is provided in [grpc_]subscription_impl_test.cc. class GrpcMuxImplTest : public testing::Test { public: - GrpcMuxImplTest() - : async_client_(new Grpc::MockAsyncClient()), - mock_time_source_(mock_system_time_, mock_monotonic_time_) { + GrpcMuxImplTest() : async_client_(new Grpc::MockAsyncClient()) { dispatcher_.setTimeSource(mock_time_source_); } @@ -77,9 +75,7 @@ class GrpcMuxImplTest : public testing::Test { Grpc::MockAsyncStream async_stream_; std::unique_ptr grpc_mux_; NiceMock callbacks_; - NiceMock mock_system_time_; - NiceMock mock_monotonic_time_; - TimeSource mock_time_source_; + NiceMock mock_time_source_; NiceMock local_info_; }; @@ -317,7 +313,7 @@ TEST_F(GrpcMuxImplTest, TooManyRequests) { EXPECT_CALL(async_stream_, sendMessage(_, false)).Times(AtLeast(100)); EXPECT_CALL(*async_client_, start(_, _)).WillOnce(Return(&async_stream_)); - EXPECT_CALL(mock_monotonic_time_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .WillRepeatedly(Return(std::chrono::steady_clock::time_point{})); const auto onReceiveMessage = [&](uint64_t burst) { @@ -343,7 +339,7 @@ TEST_F(GrpcMuxImplTest, TooManyRequests) { onReceiveMessage(1)); // Logging limiter waits for 5s, so a second warning message is expected. - EXPECT_CALL(mock_monotonic_time_, currentTime()) + EXPECT_CALL(mock_time_source_, monotonicTime()) .Times(4) .WillOnce(Return(std::chrono::steady_clock::time_point{})) .WillOnce(Return(std::chrono::steady_clock::time_point{std::chrono::seconds(5)})) diff --git a/test/common/router/rds_impl_test.cc b/test/common/router/rds_impl_test.cc index a0657aa985a6c..e7370b8134cf4 100644 --- a/test/common/router/rds_impl_test.cc +++ b/test/common/router/rds_impl_test.cc @@ -69,7 +69,7 @@ class RdsTestBase : public testing::Test { Http::MockAsyncClientRequest request_; Http::AsyncClient::Callbacks* callbacks_{}; Event::MockTimer* interval_timer_{}; - NiceMock system_time_source_; + NiceMock time_source_; }; class RdsImplTest : public RdsTestBase { @@ -370,7 +370,7 @@ class RouteConfigProviderManagerImplTest : public RdsTestBase { Upstream::ClusterManager::ClusterInfoMap cluster_map; Upstream::MockCluster cluster; cluster_map.emplace("foo_cluster", cluster); - ON_CALL(factory_context_, systemTimeSource()).WillByDefault(ReturnRef(system_time_source_)); + ON_CALL(factory_context_, timeSource()).WillByDefault(ReturnRef(time_source_)); EXPECT_CALL(factory_context_.cluster_manager_, clusters()).WillOnce(Return(cluster_map)); EXPECT_CALL(cluster, info()).Times(2); EXPECT_CALL(*cluster.info_, addedViaApi()); @@ -425,9 +425,9 @@ name: foo route: { cluster: baz } )EOF"; - EXPECT_CALL(system_time_source_, currentTime()) + EXPECT_CALL(time_source_, systemTime()) .WillRepeatedly(Return(SystemTime(std::chrono::milliseconds(1234567891234)))); - EXPECT_CALL(factory_context_, systemTimeSource()).WillRepeatedly(ReturnRef(system_time_source_)); + EXPECT_CALL(factory_context_, timeSource()).WillRepeatedly(ReturnRef(time_source_)); // Only static route. RouteConfigProviderPtr static_config = diff --git a/test/common/upstream/cluster_manager_impl_test.cc b/test/common/upstream/cluster_manager_impl_test.cc index 3630c0a1609dc..8d2acf47b304c 100644 --- a/test/common/upstream/cluster_manager_impl_test.cc +++ b/test/common/upstream/cluster_manager_impl_test.cc @@ -163,9 +163,7 @@ envoy::config::bootstrap::v2::Bootstrap parseBootstrapFromV2Yaml(const std::stri class ClusterManagerImplTest : public testing::Test { public: - ClusterManagerImplTest() : time_source_(system_time_source_, monotonic_time_source_) { - factory_.dispatcher_.setTimeSource(time_source_); - } + ClusterManagerImplTest() { factory_.dispatcher_.setTimeSource(time_source_); } void create(const envoy::config::bootstrap::v2::Bootstrap& bootstrap) { cluster_manager_.reset(new ClusterManagerImpl( @@ -240,10 +238,8 @@ class ClusterManagerImplTest : public testing::Test { std::unique_ptr cluster_manager_; AccessLog::MockAccessLogManager log_manager_; NiceMock admin_; - NiceMock system_time_source_; - NiceMock monotonic_time_source_; + NiceMock time_source_; MockLocalClusterUpdate local_cluster_update_; - TimeSource time_source_; }; envoy::config::bootstrap::v2::Bootstrap parseBootstrapFromJson(const std::string& json_string) { @@ -293,7 +289,7 @@ TEST_F(ClusterManagerImplTest, MultipleHealthCheckFail) { } TEST_F(ClusterManagerImplTest, MultipleProtocolCluster) { - EXPECT_CALL(system_time_source_, currentTime()) + EXPECT_CALL(time_source_, systemTime()) .WillRepeatedly(Return(SystemTime(std::chrono::milliseconds(1234567891234)))); const std::string yaml = R"EOF( @@ -770,7 +766,7 @@ TEST_F(ClusterManagerImplTest, ShutdownOrder) { } TEST_F(ClusterManagerImplTest, InitializeOrder) { - EXPECT_CALL(system_time_source_, currentTime()) + EXPECT_CALL(time_source_, systemTime()) .WillRepeatedly(Return(SystemTime(std::chrono::milliseconds(1234567891234)))); const std::string json = fmt::sprintf( @@ -989,7 +985,7 @@ TEST_F(ClusterManagerImplTest, DynamicRemoveWithLocalCluster) { } TEST_F(ClusterManagerImplTest, RemoveWarmingCluster) { - EXPECT_CALL(system_time_source_, currentTime()) + EXPECT_CALL(time_source_, systemTime()) .WillRepeatedly(Return(SystemTime(std::chrono::milliseconds(1234567891234)))); const std::string json = R"EOF( diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index d6aaaaf0b0ce8..5b7f6f3ab34e4 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -3198,12 +3198,12 @@ TEST(HealthCheckEventLoggerImplTest, All) { NiceMock cluster; ON_CALL(*host, cluster()).WillByDefault(ReturnRef(cluster)); - NiceMock system_time_source; - EXPECT_CALL(system_time_source, currentTime()) - // This is rendered as "2009-02-13T23:31:31.234Z". + NiceMock time_source; + EXPECT_CALL(time_source, systemTime()) + // This is rendered as "2009-02-13T23:31:31.234Z".a .WillRepeatedly(Return(SystemTime(std::chrono::milliseconds(1234567891234)))); - HealthCheckEventLoggerImpl event_logger(log_manager, system_time_source, "foo"); + HealthCheckEventLoggerImpl event_logger(log_manager, time_source, "foo"); EXPECT_CALL(*file, write(absl::string_view{ "{\"health_checker_type\":\"HTTP\",\"host\":{\"socket_address\":{" diff --git a/test/common/upstream/load_stats_reporter_test.cc b/test/common/upstream/load_stats_reporter_test.cc index e9faf2501ae64..5ee46d8f953b6 100644 --- a/test/common/upstream/load_stats_reporter_test.cc +++ b/test/common/upstream/load_stats_reporter_test.cc @@ -27,8 +27,7 @@ class LoadStatsReporterTest : public testing::Test { public: LoadStatsReporterTest() : retry_timer_(new Event::MockTimer()), response_timer_(new Event::MockTimer()), - async_client_(new Grpc::MockAsyncClient()), - time_source_(system_time_source_, monotonic_time_source_) { + async_client_(new Grpc::MockAsyncClient()) { dispatcher_.setTimeSource(time_source_); } @@ -76,9 +75,7 @@ class LoadStatsReporterTest : public testing::Test { Event::TimerCb response_timer_cb_; Grpc::MockAsyncStream async_stream_; Grpc::MockAsyncClient* async_client_; - MockSystemTimeSource system_time_source_; - MockMonotonicTimeSource monotonic_time_source_; - TimeSource time_source_; + MockTimeSource time_source_; NiceMock local_info_; }; @@ -96,14 +93,14 @@ TEST_F(LoadStatsReporterTest, TestPubSub) { EXPECT_CALL(*async_client_, start(_, _)).WillOnce(Return(&async_stream_)); EXPECT_CALL(async_stream_, sendMessage(_, _)); createLoadStatsReporter(); - EXPECT_CALL(monotonic_time_source_, currentTime()); + EXPECT_CALL(time_source_, monotonicTime()); deliverLoadStatsResponse({"foo"}); EXPECT_CALL(async_stream_, sendMessage(_, _)); EXPECT_CALL(*response_timer_, enableTimer(std::chrono::milliseconds(42000))); response_timer_cb_(); - EXPECT_CALL(monotonic_time_source_, currentTime()); + EXPECT_CALL(time_source_, monotonicTime()); deliverLoadStatsResponse({"bar"}); EXPECT_CALL(async_stream_, sendMessage(_, _)); @@ -117,7 +114,7 @@ TEST_F(LoadStatsReporterTest, ExistingClusters) { // Initially, we have no clusters to report on. expectSendMessage({}); createLoadStatsReporter(); - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::microseconds(3)))); // Start reporting on foo. NiceMock foo_cluster; @@ -128,7 +125,7 @@ TEST_F(LoadStatsReporterTest, ExistingClusters) { deliverLoadStatsResponse({"foo"}); // Initial stats report for foo on timer tick. foo_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(5); - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::microseconds(4)))); { envoy::api::v2::endpoint::ClusterStats foo_cluster_stats; @@ -146,13 +143,13 @@ TEST_F(LoadStatsReporterTest, ExistingClusters) { bar_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(1); // Start reporting on bar. - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::microseconds(6)))); deliverLoadStatsResponse({"foo", "bar"}); // Stats report foo/bar on timer tick. foo_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(1); bar_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(1); - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .Times(2) .WillRepeatedly(Return(MonotonicTime(std::chrono::microseconds(28)))); { @@ -180,7 +177,7 @@ TEST_F(LoadStatsReporterTest, ExistingClusters) { // Stats report for bar on timer tick. foo_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(5); bar_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(5); - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::microseconds(33)))); { envoy::api::v2::endpoint::ClusterStats bar_cluster_stats; @@ -198,13 +195,13 @@ TEST_F(LoadStatsReporterTest, ExistingClusters) { bar_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(1); // Start tracking foo again, we should forget earlier history for foo. - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::microseconds(43)))); deliverLoadStatsResponse({"foo", "bar"}); // Stats report foo/bar on timer tick. foo_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(1); bar_cluster.info_->load_report_stats_.upstream_rq_dropped_.add(1); - EXPECT_CALL(monotonic_time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .Times(2) .WillRepeatedly(Return(MonotonicTime(std::chrono::microseconds(47)))); { diff --git a/test/common/upstream/outlier_detection_impl_test.cc b/test/common/upstream/outlier_detection_impl_test.cc index 38b2e6dd95772..5ed7ec86a84c4 100644 --- a/test/common/upstream/outlier_detection_impl_test.cc +++ b/test/common/upstream/outlier_detection_impl_test.cc @@ -96,7 +96,7 @@ class OutlierDetectorImplTest : public testing::Test { NiceMock runtime_; Event::MockTimer* interval_timer_ = new Event::MockTimer(&dispatcher_); CallbackChecker checker_; - MockMonotonicTimeSource time_source_; + MockTimeSource time_source_; std::shared_ptr event_logger_{new MockEventLogger()}; envoy::api::v2::cluster::OutlierDetection empty_outlier_detection_; }; @@ -148,7 +148,7 @@ TEST_F(OutlierDetectorImplTest, DestroyWithActive) { detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); loadRq(hosts_[0], 4, Result::REQUEST_FAILED); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -158,7 +158,7 @@ TEST_F(OutlierDetectorImplTest, DestroyWithActive) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); loadRq(failover_hosts_[0], 4, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(failover_hosts_[0])); EXPECT_CALL(*event_logger_, @@ -202,7 +202,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlow5xx) { hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); loadRq(hosts_[0], 4, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -213,14 +213,14 @@ TEST_F(OutlierDetectorImplTest, BasicFlow5xx) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); // Interval that doesn't bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Interval that does bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(30001)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, @@ -234,7 +234,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlow5xx) { hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); loadRq(hosts_[0], 4, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(40000)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -287,7 +287,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailure) { _, EjectionType::Consecutive5xx, false)); loadRq(hosts_[0], 2, 503); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -298,14 +298,14 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailure) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); // Interval that doesn't bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Interval that does bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(30001)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, @@ -319,7 +319,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailure) { hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); loadRq(hosts_[0], 4, 503); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(40000)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -381,7 +381,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailureAnd5xx) { hosts_[0]->outlierDetector().putResponseTime(std::chrono::milliseconds(5)); loadRq(hosts_[0], 4, 503); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -392,14 +392,14 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailureAnd5xx) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); // Interval that doesn't bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); EXPECT_FALSE(hosts_[0]->outlierDetector().lastUnejectionTime()); // Interval that does bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(30001)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, @@ -415,7 +415,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowGatewayFailureAnd5xx) { EXPECT_FALSE(hosts_[0]->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)); loadRq(hosts_[0], 2, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(40000)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -483,7 +483,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowSuccessRate) { loadRq(hosts_, 200, 200); loadRq(hosts_[4], 200, 503); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .Times(2) .WillRepeatedly(Return(MonotonicTime(std::chrono::milliseconds(10000)))); EXPECT_CALL(checker_, check(hosts_[4])); @@ -500,7 +500,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowSuccessRate) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); // Interval that doesn't bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(19999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); @@ -508,7 +508,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowSuccessRate) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); // Interval that does bring the host back in. - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(50001)))); EXPECT_CALL(checker_, check(hosts_[4])); EXPECT_CALL(*event_logger_, @@ -531,7 +531,7 @@ TEST_F(OutlierDetectorImplTest, BasicFlowSuccessRate) { loadRq(hosts_, 25, 200); loadRq(hosts_[4], 25, 503); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(60001)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); @@ -551,7 +551,7 @@ TEST_F(OutlierDetectorImplTest, RemoveWhileEjected) { loadRq(hosts_[0], 4, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -566,7 +566,7 @@ TEST_F(OutlierDetectorImplTest, RemoveWhileEjected) { EXPECT_EQ(0UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(9999)))); EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); interval_timer_->callback_(); @@ -585,7 +585,7 @@ TEST_F(OutlierDetectorImplTest, Overflow) { loadRq(hosts_[0], 4, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -701,7 +701,7 @@ TEST_F(OutlierDetectorImplTest, CrossThreadFailRace) { EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); loadRq(hosts_[0], 1, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -726,7 +726,7 @@ TEST_F(OutlierDetectorImplTest, Consecutive5xxAlreadyEjected) { // Cause a consecutive 5xx error. loadRq(hosts_[0], 4, 500); - EXPECT_CALL(time_source_, currentTime()) + EXPECT_CALL(time_source_, monotonicTime()) .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(0)))); EXPECT_CALL(checker_, check(hosts_[0])); EXPECT_CALL(*event_logger_, logEject(std::static_pointer_cast(hosts_[0]), @@ -753,14 +753,13 @@ TEST(OutlierDetectionEventLoggerImplTest, All) { NiceMock cluster; std::shared_ptr host(new NiceMock()); ON_CALL(*host, cluster()).WillByDefault(ReturnRef(cluster)); - NiceMock time_source; - NiceMock monotonic_time_source; - absl::optional time; + NiceMock time_source; + absl::optional system_time; absl::optional monotonic_time; NiceMock detector; EXPECT_CALL(log_manager, createAccessLog("foo")).WillOnce(Return(file)); - EventLoggerImpl event_logger(log_manager, "foo", time_source, monotonic_time_source); + EventLoggerImpl event_logger(log_manager, "foo", time_source); StringViewSaver log1; EXPECT_CALL(host->outlier_detector_, lastUnejectionTime()).WillOnce(ReturnRef(monotonic_time)); @@ -786,8 +785,8 @@ TEST(OutlierDetectionEventLoggerImplTest, All) { Json::Factory::loadFromString(log2); // now test with time since last action. - time = (time_source.currentTime() - std::chrono::seconds(30)); - monotonic_time = (monotonic_time_source.currentTime() - std::chrono::seconds(30)); + system_time = (time_source.systemTime() - std::chrono::seconds(30)); + monotonic_time = (time_source.monotonicTime() - std::chrono::seconds(30)); StringViewSaver log3; EXPECT_CALL(host->outlier_detector_, lastUnejectionTime()).WillOnce(ReturnRef(monotonic_time)); diff --git a/test/extensions/tracers/zipkin/tracer_test.cc b/test/extensions/tracers/zipkin/tracer_test.cc index 656189f279029..6c21d6f157077 100644 --- a/test/extensions/tracers/zipkin/tracer_test.cc +++ b/test/extensions/tracers/zipkin/tracer_test.cc @@ -40,7 +40,7 @@ class ZipkinTracerTest : public testing::Test { ZipkinTracerTest() : time_source_(test_time_.timeSource()) {} DangerousDeprecatedTestTime test_time_; - TimeSource time_source_; + TimeSource& time_source_; }; TEST_F(ZipkinTracerTest, spanCreation) { @@ -48,8 +48,8 @@ TEST_F(ZipkinTracerTest, spanCreation) { Network::Utility::parseInternetAddressAndPort("127.0.0.1:9000"); NiceMock random_generator; Tracer tracer("my_service_name", addr, random_generator, false, time_source_); - NiceMock mock_start_time; - SystemTime timestamp = mock_start_time.currentTime(); + NiceMock mock_start_time; + SystemTime timestamp = mock_start_time.systemTime(); NiceMock config; ON_CALL(config, operationName()).WillByDefault(Return(Tracing::OperationName::Egress)); @@ -231,8 +231,8 @@ TEST_F(ZipkinTracerTest, finishSpan) { Network::Utility::parseInternetAddressAndPort("127.0.0.1:9000"); NiceMock random_generator; Tracer tracer("my_service_name", addr, random_generator, false, test_time_.timeSource()); - NiceMock mock_start_time; - SystemTime timestamp = mock_start_time.currentTime(); + NiceMock mock_start_time; + SystemTime timestamp = mock_start_time.systemTime(); // ============== // Test finishing a span containing a CS annotation @@ -315,8 +315,8 @@ TEST_F(ZipkinTracerTest, finishNotSampledSpan) { Network::Utility::parseInternetAddressAndPort("127.0.0.1:9000"); NiceMock random_generator; Tracer tracer("my_service_name", addr, random_generator, false, time_source_); - NiceMock mock_start_time; - SystemTime timestamp = mock_start_time.currentTime(); + NiceMock mock_start_time; + SystemTime timestamp = mock_start_time.systemTime(); // ============== // Test finishing a span that is marked as not sampled @@ -344,8 +344,8 @@ TEST_F(ZipkinTracerTest, SpanSampledPropagatedToChild) { Network::Utility::parseInternetAddressAndPort("127.0.0.1:9000"); NiceMock random_generator; Tracer tracer("my_service_name", addr, random_generator, false, time_source_); - NiceMock mock_start_time; - SystemTime timestamp = mock_start_time.currentTime(); + NiceMock mock_start_time; + SystemTime timestamp = mock_start_time.systemTime(); NiceMock config; ON_CALL(config, operationName()).WillByDefault(Return(Tracing::OperationName::Egress)); @@ -373,8 +373,8 @@ TEST_F(ZipkinTracerTest, RootSpan128bitTraceId) { Network::Utility::parseInternetAddressAndPort("127.0.0.1:9000"); NiceMock random_generator; Tracer tracer("my_service_name", addr, random_generator, true, time_source_); - NiceMock mock_start_time; - SystemTime timestamp = mock_start_time.currentTime(); + NiceMock mock_start_time; + SystemTime timestamp = mock_start_time.systemTime(); NiceMock config; ON_CALL(config, operationName()).WillByDefault(Return(Tracing::OperationName::Egress)); diff --git a/test/mocks/common.cc b/test/mocks/common.cc index 5126b0b1f2b7d..e0fce76effc16 100644 --- a/test/mocks/common.cc +++ b/test/mocks/common.cc @@ -4,13 +4,7 @@ namespace Envoy { ReadyWatcher::ReadyWatcher() {} ReadyWatcher::~ReadyWatcher() {} -MockSystemTimeSource::MockSystemTimeSource() {} -MockSystemTimeSource::~MockSystemTimeSource() {} - -MockMonotonicTimeSource::MockMonotonicTimeSource() {} -MockMonotonicTimeSource::~MockMonotonicTimeSource() {} - -MockTimeSource::MockTimeSource() : TimeSource(system_, monotonic_) {} +MockTimeSource::MockTimeSource() {} MockTimeSource::~MockTimeSource() {} MockTokenBucket::MockTokenBucket() {} diff --git a/test/mocks/common.h b/test/mocks/common.h index adf25120f0658..65ed07012b33a 100644 --- a/test/mocks/common.h +++ b/test/mocks/common.h @@ -35,29 +35,13 @@ class ReadyWatcher { MOCK_METHOD0(ready, void()); }; -class MockSystemTimeSource : public SystemTimeSource { -public: - MockSystemTimeSource(); - ~MockSystemTimeSource(); - - MOCK_METHOD0(currentTime, SystemTime()); -}; - -class MockMonotonicTimeSource : public MonotonicTimeSource { -public: - MockMonotonicTimeSource(); - ~MockMonotonicTimeSource(); - - MOCK_METHOD0(currentTime, MonotonicTime()); -}; - class MockTimeSource : public TimeSource { public: MockTimeSource(); ~MockTimeSource(); - MockSystemTimeSource system_; - MockMonotonicTimeSource monotonic_; + MOCK_METHOD0(systemTime, SystemTime()); + MOCK_METHOD0(monotonicTime, MonotonicTime()); }; class MockTokenBucket : public TokenBucket { diff --git a/test/mocks/server/mocks.cc b/test/mocks/server/mocks.cc index 61e3dc6c5cae0..07e068ea0a688 100644 --- a/test/mocks/server/mocks.cc +++ b/test/mocks/server/mocks.cc @@ -148,9 +148,7 @@ MockMain::MockMain(int wd_miss, int wd_megamiss, int wd_kill, int wd_multikill) ON_CALL(*this, wdMultiKillTimeout()).WillByDefault(Return(wd_multikill_)); } -MockFactoryContext::MockFactoryContext() - : singleton_manager_(new Singleton::ManagerImpl()), - time_source_(system_time_source_, monotonic_time_source_) { +MockFactoryContext::MockFactoryContext() : singleton_manager_(new Singleton::ManagerImpl()) { ON_CALL(*this, accessLogManager()).WillByDefault(ReturnRef(access_log_manager_)); ON_CALL(*this, clusterManager()).WillByDefault(ReturnRef(cluster_manager_)); ON_CALL(*this, dispatcher()).WillByDefault(ReturnRef(dispatcher_)); @@ -165,7 +163,6 @@ 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, systemTimeSource()).WillByDefault(ReturnRef(system_time_source_)); ON_CALL(*this, timeSource()).WillByDefault(ReturnRef(time_source_)); } diff --git a/test/mocks/server/mocks.h b/test/mocks/server/mocks.h index e0deddecfc33a..d9ac4a01c3e7a 100644 --- a/test/mocks/server/mocks.h +++ b/test/mocks/server/mocks.h @@ -405,8 +405,6 @@ class MockFactoryContext : public FactoryContext { MOCK_METHOD0(listenerScope, Stats::Scope&()); MOCK_CONST_METHOD0(localInfo, const LocalInfo::LocalInfo&()); MOCK_CONST_METHOD0(listenerMetadata, const envoy::api::v2::core::Metadata&()); - MOCK_METHOD0(systemTimeSource, SystemTimeSource&()); - MOCK_METHOD0(monotonicTimeSource, MonotonicTimeSource&()); MOCK_METHOD0(timeSource, TimeSource&()); testing::NiceMock access_log_manager_; @@ -423,9 +421,7 @@ class MockFactoryContext : public FactoryContext { Singleton::ManagerPtr singleton_manager_; testing::NiceMock admin_; Stats::IsolatedStoreImpl listener_scope_; - testing::NiceMock system_time_source_; - testing::NiceMock monotonic_time_source_; - TimeSource time_source_; + testing::NiceMock time_source_; }; class MockTransportSocketFactoryContext : public TransportSocketFactoryContext { diff --git a/test/mocks/upstream/mocks.cc b/test/mocks/upstream/mocks.cc index 729af9809e758..5be57cff244c8 100644 --- a/test/mocks/upstream/mocks.cc +++ b/test/mocks/upstream/mocks.cc @@ -87,7 +87,7 @@ MockThreadLocalCluster::MockThreadLocalCluster() { MockThreadLocalCluster::~MockThreadLocalCluster() {} -MockClusterManager::MockClusterManager() : time_source_(system_time_, monotonic_time_) { +MockClusterManager::MockClusterManager() { ON_CALL(*this, httpConnPoolForCluster(_, _, _, _)).WillByDefault(Return(&conn_pool_)); ON_CALL(*this, tcpConnPoolForCluster(_, _, _)).WillByDefault(Return(&tcp_conn_pool_)); ON_CALL(*this, httpAsyncClientForCluster(_)).WillByDefault(ReturnRef(async_client_)); diff --git a/test/mocks/upstream/mocks.h b/test/mocks/upstream/mocks.h index 6ba835f06560b..fb0c132421ee6 100644 --- a/test/mocks/upstream/mocks.h +++ b/test/mocks/upstream/mocks.h @@ -237,9 +237,7 @@ class MockClusterManager : public ClusterManager { std::unique_ptr(ClusterUpdateCallbacks& callbacks)); // TODO(jmarantz): Switch these to using mock-time. - ProdSystemTimeSource system_time_; - ProdMonotonicTimeSource monotonic_time_; - TimeSource time_source_; + RealTimeSource time_source_; NiceMock conn_pool_; NiceMock async_client_; diff --git a/test/server/guarddog_impl_test.cc b/test/server/guarddog_impl_test.cc index 84562189ab2df..d3c5c46267b5a 100644 --- a/test/server/guarddog_impl_test.cc +++ b/test/server/guarddog_impl_test.cc @@ -23,11 +23,7 @@ namespace Server { class GuardDogTestBase : public testing::Test { protected: - GuardDogTestBase() : time_source_(system_time_source_, monotonic_time_source_) {} - - NiceMock monotonic_time_source_; - ProdSystemTimeSource system_time_source_; - TimeSource time_source_; + NiceMock time_source_; }; /** @@ -42,7 +38,7 @@ class GuardDogDeathTest : public GuardDogTestBase { GuardDogDeathTest() : config_kill_(1000, 1000, 100, 1000), config_multikill_(1000, 1000, 1000, 500), mock_time_(0) { - ON_CALL(monotonic_time_source_, currentTime()).WillByDefault(testing::Invoke([this]() { + ON_CALL(time_source_, monotonicTime()).WillByDefault(testing::Invoke([this]() { return std::chrono::steady_clock::time_point(std::chrono::milliseconds(mock_time_)); })); } @@ -140,7 +136,7 @@ TEST_F(GuardDogAlmostDeadTest, NearDeathTest) { class GuardDogMissTest : public GuardDogTestBase { protected: GuardDogMissTest() : config_miss_(500, 1000, 0, 0), config_mega_(1000, 500, 0, 0), mock_time_(0) { - ON_CALL(monotonic_time_source_, currentTime()).WillByDefault(testing::Invoke([this]() { + ON_CALL(time_source_, monotonicTime()).WillByDefault(testing::Invoke([this]() { return std::chrono::steady_clock::time_point(std::chrono::milliseconds(mock_time_)); })); } @@ -173,7 +169,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. - ON_CALL(monotonic_time_source_, currentTime()).WillByDefault(testing::Invoke([this]() { + ON_CALL(time_source_, monotonicTime()).WillByDefault(testing::Invoke([this]() { return std::chrono::steady_clock::time_point(std::chrono::milliseconds(mock_time_)); })); GuardDogImpl gd(stats_store_, config_mega_, time_source_); @@ -196,7 +192,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. - ON_CALL(monotonic_time_source_, currentTime()).WillByDefault(testing::Invoke([this]() { + ON_CALL(time_source_, monotonicTime()).WillByDefault(testing::Invoke([this]() { return std::chrono::steady_clock::time_point(std::chrono::milliseconds(mock_time_)); })); GuardDogImpl gd(stats_store_, config_miss_, time_source_); @@ -272,7 +268,6 @@ TEST_F(GuardDogTestBase, WatchDogThreadIdTest) { // The WatchDog/GuardDog relies on this being a lock free atomic for perf reasons so some workaround // will be required if this test starts failing. TEST_F(GuardDogTestBase, AtomicIsAtomicTest) { - ProdMonotonicTimeSource time_source; std::atomic atomic_time; ASSERT_EQ(atomic_time.is_lock_free(), true); } diff --git a/test/server/listener_manager_impl_test.cc b/test/server/listener_manager_impl_test.cc index 1aa358ad19d74..2f2e54e27a822 100644 --- a/test/server/listener_manager_impl_test.cc +++ b/test/server/listener_manager_impl_test.cc @@ -51,7 +51,7 @@ class ListenerHandle { class ListenerManagerImplTest : public testing::Test { public: - ListenerManagerImplTest() : time_source_(system_time_source_, monotonic_time_source_) { + ListenerManagerImplTest() { EXPECT_CALL(worker_factory_, createWorker_()).WillOnce(Return(worker_)); manager_.reset( new ListenerManagerImpl(server_, listener_factory_, worker_factory_, time_source_)); @@ -115,9 +115,7 @@ class ListenerManagerImplTest : public testing::Test { NiceMock worker_factory_; std::unique_ptr manager_; NiceMock guard_dog_; - NiceMock system_time_source_; - ProdMonotonicTimeSource monotonic_time_source_; - TimeSource time_source_; + NiceMock time_source_; }; class ListenerManagerImplWithRealFiltersTest : public ListenerManagerImplTest { @@ -470,7 +468,7 @@ TEST_F(ListenerManagerImplTest, AddListenerOnIpv6OnlySetups) { // Make sure that a listener that is not modifiable cannot be updated or removed. TEST_F(ListenerManagerImplTest, UpdateRemoveNotModifiableListener) { - ON_CALL(system_time_source_, currentTime()) + ON_CALL(time_source_, systemTime()) .WillByDefault(Return(SystemTime(std::chrono::milliseconds(1001001001001)))); InSequence s; @@ -528,7 +526,7 @@ TEST_F(ListenerManagerImplTest, UpdateRemoveNotModifiableListener) { } TEST_F(ListenerManagerImplTest, AddOrUpdateListener) { - ON_CALL(system_time_source_, currentTime()) + ON_CALL(time_source_, systemTime()) .WillByDefault(Return(SystemTime(std::chrono::milliseconds(1001001001001)))); InSequence s; @@ -596,7 +594,7 @@ filter_chains: {} per_connection_buffer_limit_bytes: 10 )EOF"; - ON_CALL(system_time_source_, currentTime()) + ON_CALL(time_source_, systemTime()) .WillByDefault(Return(SystemTime(std::chrono::milliseconds(2002002002002)))); ListenerHandle* listener_foo_update1 = expectListenerCreate(false); @@ -636,7 +634,7 @@ version_info: version2 manager_->addOrUpdateListener(parseListenerFromV2Yaml(listener_foo_update1_yaml), "", true)); checkStats(1, 1, 0, 0, 1, 0); - ON_CALL(system_time_source_, currentTime()) + ON_CALL(time_source_, systemTime()) .WillByDefault(Return(SystemTime(std::chrono::milliseconds(3003003003003)))); // Update foo. Should go into warming, have an immediate warming callback, and start immediate @@ -688,7 +686,7 @@ version_info: version3 worker_->callRemovalCompletion(); checkStats(1, 2, 0, 0, 1, 0); - ON_CALL(system_time_source_, currentTime()) + ON_CALL(time_source_, systemTime()) .WillByDefault(Return(SystemTime(std::chrono::milliseconds(4004004004004)))); // Add bar listener. @@ -710,7 +708,7 @@ filter_chains: {} worker_->callAddCompletion(true); checkStats(2, 2, 0, 0, 2, 0); - ON_CALL(system_time_source_, currentTime()) + ON_CALL(time_source_, systemTime()) .WillByDefault(Return(SystemTime(std::chrono::milliseconds(5005005005005)))); // Add baz listener, this time requiring initializing. diff --git a/test/test_common/test_time.cc b/test/test_common/test_time.cc index 266b070f2de9e..72cfedd2900a6 100644 --- a/test/test_common/test_time.cc +++ b/test/test_common/test_time.cc @@ -4,7 +4,6 @@ namespace Envoy { -DangerousDeprecatedTestTime::DangerousDeprecatedTestTime() - : time_source_(system_time_, monotonic_time_) {} +DangerousDeprecatedTestTime::DangerousDeprecatedTestTime() {} } // namespace Envoy diff --git a/test/test_common/test_time.h b/test/test_common/test_time.h index d57fda8761438..e9fb4057dd344 100644 --- a/test/test_common/test_time.h +++ b/test/test_common/test_time.h @@ -16,13 +16,7 @@ class DangerousDeprecatedTestTime { TimeSource& timeSource() { return time_source_; } private: - // TODO(#4160): Add a 'mode' enum arg to the constructor, which - // instantiates mock or perhaps fake time here rather than real-time, which is - // makes testing non-deterministic and hard to debug. It should be easy, on - // a test-by-test basis, to switch to mock time. - ProdSystemTimeSource system_time_; - ProdMonotonicTimeSource monotonic_time_; - TimeSource time_source_; + RealTimeSource time_source_; }; } // namespace Envoy diff --git a/tools/check_format.py b/tools/check_format.py index 6f643cd6b7f9c..1c42780050d15 100755 --- a/tools/check_format.py +++ b/tools/check_format.py @@ -26,7 +26,7 @@ # Files matching these exact names can reference prod time. These include the class # definitions for prod time, the construction of them in main(), and perf annotation. # For now it includes the validation server but that really should be injected too. -PROD_TIME_WHITELIST = ('./source/common/common/utility.h', +REAL_TIME_WHITELIST = ('./source/common/common/utility.h', './source/exe/main_common.cc', './source/exe/main_common.h', './source/server/config_validation/server.cc', @@ -77,8 +77,8 @@ def whitelistedForProtobufDeps(file_path): # Production time sources should not be instantiated in the source, except for a few # specific cases. They should be passed down from where they are instantied to where # they need to be used, e.g. through the ServerInstance, Dispatcher, or ClusterManager. -def whitelistedForProdTime(file_path): - return file_path in PROD_TIME_WHITELIST or file_path.startswith('./test/') +def whitelistedForRealTime(file_path): + return file_path in REAL_TIME_WHITELIST or file_path.startswith('./test/') def findSubstringAndReturnError(pattern, file_path, error_message): with open(file_path) as f: @@ -160,8 +160,8 @@ def checkSourceLine(line, file_path, reportError): # comments, for example this one. reportError("Don't use or , switch to " "Thread::MutexBasicLockable in source/common/common/thread.h") - if not whitelistedForProdTime(file_path): - if 'ProdSystemTimeSource' in line or 'ProdMonotonicTimeSource' in line: + if not whitelistedForRealTime(file_path): + if 'RealTimeSource' in line: reportError("Don't reference real-time sources from production code; use injection") def checkBuildLine(line, file_path, reportError): diff --git a/tools/check_format_test_helper.py b/tools/check_format_test_helper.py index 2d7b02081a34b..d3004ba5a962b 100755 --- a/tools/check_format_test_helper.py +++ b/tools/check_format_test_helper.py @@ -144,9 +144,7 @@ def checkFileExpectingOK(filename): errors += fixFileExpectingFailure("condition_variable_any.cc", "Don't use or ") errors += fixFileExpectingFailure( - "prod_system_time.cc", "Don't reference real-time sources from production code; use injection") - errors += fixFileExpectingFailure( - "prod_monotonic_time.cc", "Don't reference real-time sources from production code; use injection") + "real_time_source.cc", "Don't reference real-time sources from production code; use injection") errors += fixFileExpectingNoChange("ok_file.cc") @@ -168,9 +166,7 @@ def checkFileExpectingOK(filename): "Superfluous '@envoy//' prefix") errors += checkFileExpectingError("proto_format.proto", "clang-format check failed") errors += checkFileExpectingError( - "prod_system_time.cc", "Don't reference real-time sources from production code; use injection") - errors += checkFileExpectingError( - "prod_monotonic_time.cc", "Don't reference real-time sources from production code; use injection") + "real_time_source.cc", "Don't reference real-time sources from production code; use injection") errors += checkFileExpectingOK("ok_file.cc") diff --git a/tools/testdata/check_format/prod_monotonic_time.cc b/tools/testdata/check_format/prod_monotonic_time.cc deleted file mode 100644 index 10bcfc7c5d3e1..0000000000000 --- a/tools/testdata/check_format/prod_monotonic_time.cc +++ /dev/null @@ -1,4 +0,0 @@ -int foo() { - ProdSystemTimeSource system_time; - ProdMonotonicTimeSource monotonic_time; -} diff --git a/tools/testdata/check_format/prod_system_time.cc b/tools/testdata/check_format/prod_system_time.cc deleted file mode 100644 index a533661b9805e..0000000000000 --- a/tools/testdata/check_format/prod_system_time.cc +++ /dev/null @@ -1,3 +0,0 @@ -int foo() { - ProdMonotonicTimeSource monotonic_time; -} diff --git a/tools/testdata/check_format/real_time_source.cc b/tools/testdata/check_format/real_time_source.cc new file mode 100644 index 0000000000000..60ec14e5c1781 --- /dev/null +++ b/tools/testdata/check_format/real_time_source.cc @@ -0,0 +1,7 @@ +namespace Envoy { + +int foo() { + RealTimeSource real_time_source; +} + +} // namespace Envoy