diff --git a/include/envoy/api/api.h b/include/envoy/api/api.h index 39b4981635686..eece627e00ab5 100644 --- a/include/envoy/api/api.h +++ b/include/envoy/api/api.h @@ -5,6 +5,7 @@ #include "envoy/common/time.h" #include "envoy/event/dispatcher.h" +#include "envoy/event/timer.h" #include "envoy/filesystem/filesystem.h" #include "envoy/stats/store.h" #include "envoy/thread/thread.h" @@ -24,7 +25,7 @@ class Api { * @param time_source the time source. * @return Event::DispatcherPtr which is owned by the caller. */ - virtual Event::DispatcherPtr allocateDispatcher(TimeSource& time_source) PURE; + virtual Event::DispatcherPtr allocateDispatcher(Event::TimeSystem& time_system) PURE; /** * Create/open a local file that supports async appending. diff --git a/include/envoy/common/time.h b/include/envoy/common/time.h index 6fd7e6e7198be..6e9bd6c825824 100644 --- a/include/envoy/common/time.h +++ b/include/envoy/common/time.h @@ -5,6 +5,7 @@ #include "envoy/common/pure.h" namespace Envoy { + /** * Less typing for common system time and steady time type. * @@ -14,76 +15,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/event/BUILD b/include/envoy/event/BUILD index 5ed520850be27..21a344c8324c9 100644 --- a/include/envoy/event/BUILD +++ b/include/envoy/event/BUILD @@ -20,7 +20,8 @@ envoy_cc_library( ":deferred_deletable", ":file_event_interface", ":signal_interface", - ":timer_interface", + "//include/envoy/common:time_interface", + "//include/envoy/event:timer_interface", "//include/envoy/filesystem:filesystem_interface", "//include/envoy/network:connection_handler_interface", "//include/envoy/network:connection_interface", @@ -44,4 +45,7 @@ envoy_cc_library( envoy_cc_library( name = "timer_interface", hdrs = ["timer.h"], + deps = [ + "//source/common/event:libevent_lib", + ], ) diff --git a/include/envoy/event/dispatcher.h b/include/envoy/event/dispatcher.h index 05da014c06a78..634a811f23266 100644 --- a/include/envoy/event/dispatcher.h +++ b/include/envoy/event/dispatcher.h @@ -6,6 +6,7 @@ #include #include +#include "envoy/common/time.h" #include "envoy/event/file_event.h" #include "envoy/event/signal.h" #include "envoy/event/timer.h" @@ -35,12 +36,9 @@ class Dispatcher { /** * Returns a time-source to use with this dispatcher. * - * TODO(#4160) the implementations currently manage timer events that - * ignore the time-source, and thus can't be mocked or faked. So it's - * difficult to mock time in an integration test without mocking out - * the dispatcher. + * TODO(#4160) Rename to timeSystem(). */ - virtual TimeSource& timeSource() PURE; + virtual TimeSystem& timeSource() PURE; /** * Clear any items in the deferred deletion queue. @@ -114,10 +112,10 @@ class Dispatcher { bool hand_off_restored_destination_connections) PURE; /** - * Allocate a timer. @see Event::Timer for docs on how to use the timer. + * Allocate a timer. @see Timer for docs on how to use the timer. * @param cb supplies the callback to invoke when the timer fires. */ - virtual TimerPtr createTimer(TimerCb cb) PURE; + virtual Event::TimerPtr createTimer(TimerCb cb) PURE; /** * Submit an item for deferred delete. @see DeferredDeletable. diff --git a/include/envoy/event/timer.h b/include/envoy/event/timer.h index 8d90cb961094d..05f647a8bceae 100644 --- a/include/envoy/event/timer.h +++ b/include/envoy/event/timer.h @@ -5,10 +5,15 @@ #include #include "envoy/common/pure.h" +#include "envoy/common/time.h" + +#include "common/event/libevent.h" namespace Envoy { namespace Event { +class TimerCB; + /** * Callback invoked when a timer event fires. */ @@ -34,5 +39,32 @@ class Timer { typedef std::unique_ptr TimerPtr; +class Scheduler { +public: + virtual ~Scheduler() {} + + /** + * Creates a timer. + */ + virtual TimerPtr createTimer(const TimerCb& cb) PURE; +}; + +typedef std::unique_ptr SchedulerPtr; + +/** + * Interface providing a mechanism to measure time and set timers that run callbacks + * when the timer fires. + */ +class TimeSystem : public TimeSource { +public: + virtual ~TimeSystem() {} + + /** + * Creates a timer factory. This indirection enables thread-local timer-queue management, + * so servers can have a separate timer-factory in each thread. + */ + virtual SchedulerPtr createScheduler(Libevent::BasePtr&) PURE; +}; + } // namespace Event } // namespace Envoy diff --git a/include/envoy/server/BUILD b/include/envoy/server/BUILD index 3a367b75343fd..ac06cc453b0fe 100644 --- a/include/envoy/server/BUILD +++ b/include/envoy/server/BUILD @@ -93,6 +93,7 @@ envoy_cc_library( ":options_interface", "//include/envoy/access_log:access_log_interface", "//include/envoy/api:api_interface", + "//include/envoy/event:timer_interface", "//include/envoy/http:query_params_interface", "//include/envoy/init:init_interface", "//include/envoy/local_info:local_info_interface", 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/include/envoy/server/instance.h b/include/envoy/server/instance.h index b85c2bc045c6e..855e42d526ba4 100644 --- a/include/envoy/server/instance.h +++ b/include/envoy/server/instance.h @@ -6,6 +6,7 @@ #include "envoy/access_log/access_log.h" #include "envoy/api/api.h" +#include "envoy/event/timer.h" #include "envoy/init/init.h" #include "envoy/local_info/local_info.h" #include "envoy/network/listen_socket.h" @@ -194,8 +195,9 @@ class Instance { /** * @return the time source used for the server. + * TODO(#4160): rename this to timeSystem(). */ - virtual TimeSource& timeSource() PURE; + virtual Event::TimeSystem& timeSource() PURE; /** * @return the flush interval of stats sinks. diff --git a/source/common/api/api_impl.cc b/source/common/api/api_impl.cc index f36aa7a9724be..7e96e0f1a1a55 100644 --- a/source/common/api/api_impl.cc +++ b/source/common/api/api_impl.cc @@ -9,8 +9,8 @@ namespace Envoy { namespace Api { -Event::DispatcherPtr Impl::allocateDispatcher(TimeSource& time_source) { - return Event::DispatcherPtr{new Event::DispatcherImpl(time_source)}; +Event::DispatcherPtr Impl::allocateDispatcher(Event::TimeSystem& time_system) { + return Event::DispatcherPtr{new Event::DispatcherImpl(time_system)}; } Impl::Impl(std::chrono::milliseconds file_flush_interval_msec) diff --git a/source/common/api/api_impl.h b/source/common/api/api_impl.h index 567493fdaa0e2..ef4e84f4c9a8c 100644 --- a/source/common/api/api_impl.h +++ b/source/common/api/api_impl.h @@ -4,6 +4,7 @@ #include #include "envoy/api/api.h" +#include "envoy/event/timer.h" #include "envoy/filesystem/filesystem.h" namespace Envoy { @@ -17,7 +18,7 @@ class Impl : public Api::Api { Impl(std::chrono::milliseconds file_flush_interval_msec); // Api::Api - Event::DispatcherPtr allocateDispatcher(TimeSource& time_source) override; + Event::DispatcherPtr allocateDispatcher(Event::TimeSystem& time_system) override; Filesystem::FileSharedPtr createFile(const std::string& path, Event::Dispatcher& dispatcher, Thread::BasicLockable& lock, Stats::Store& stats_store) override; 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..c9d6101702f40 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-world 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 fa6f4fabb97bb..3481859da1734 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/BUILD b/source/common/event/BUILD index fe1eb52e31092..c221f98a7c080 100644 --- a/source/common/event/BUILD +++ b/source/common/event/BUILD @@ -12,19 +12,17 @@ envoy_cc_library( name = "dispatcher_lib", srcs = [ "dispatcher_impl.cc", - "event_impl_base.cc", "file_event_impl.cc", "signal_impl.cc", - "timer_impl.cc", ], hdrs = [ "signal_impl.h", - "timer_impl.h", ], deps = [ ":dispatcher_includes", + ":real_time_system_lib", + "//include/envoy/common:time_interface", "//include/envoy/event:signal_interface", - "//include/envoy/event:timer_interface", "//include/envoy/network:listen_socket_interface", "//include/envoy/network:listener_interface", "//source/common/common:assert_lib", @@ -35,6 +33,26 @@ envoy_cc_library( ], ) +envoy_cc_library( + name = "real_time_system_lib", + srcs = [ + "event_impl_base.cc", + "real_time_system.cc", + "timer_impl.cc", + ], + hdrs = [ + "event_impl_base.h", + "real_time_system.h", + "timer_impl.h", + ], + deps = [ + ":libevent_lib", + "//include/envoy/event:timer_interface", + "//source/common/common:utility_lib", + "//source/common/event:dispatcher_includes", + ], +) + envoy_cc_library( name = "dispatcher_includes", hdrs = [ diff --git a/source/common/event/dispatched_thread.cc b/source/common/event/dispatched_thread.cc index 9c1906db324b5..acd5882a18d41 100644 --- a/source/common/event/dispatched_thread.cc +++ b/source/common/event/dispatched_thread.cc @@ -2,8 +2,8 @@ #include +#include "envoy/common/time.h" #include "envoy/event/dispatcher.h" -#include "envoy/event/timer.h" #include "envoy/server/configuration.h" #include "common/common/thread.h" diff --git a/source/common/event/dispatched_thread.h b/source/common/event/dispatched_thread.h index e5cd327f72a97..84550f6030de9 100644 --- a/source/common/event/dispatched_thread.h +++ b/source/common/event/dispatched_thread.h @@ -38,7 +38,7 @@ namespace Event { */ class DispatchedThreadImpl : Logger::Loggable { public: - DispatchedThreadImpl(TimeSource& time_source) : dispatcher_(new DispatcherImpl(time_source)) {} + DispatchedThreadImpl(TimeSystem& time_system) : dispatcher_(new DispatcherImpl(time_system)) {} /** * Start the thread. diff --git a/source/common/event/dispatcher_impl.cc b/source/common/event/dispatcher_impl.cc index af409f8cb40a7..533c16fbb3ea4 100644 --- a/source/common/event/dispatcher_impl.cc +++ b/source/common/event/dispatcher_impl.cc @@ -13,7 +13,6 @@ #include "common/common/lock_guard.h" #include "common/event/file_event_impl.h" #include "common/event/signal_impl.h" -#include "common/event/timer_impl.h" #include "common/filesystem/watcher_impl.h" #include "common/network/connection_impl.h" #include "common/network/dns_impl.h" @@ -24,14 +23,15 @@ namespace Envoy { namespace Event { -DispatcherImpl::DispatcherImpl(TimeSource& time_source) - : DispatcherImpl(time_source, Buffer::WatermarkFactoryPtr{new Buffer::WatermarkBufferFactory}) { +DispatcherImpl::DispatcherImpl(TimeSystem& time_system) + : DispatcherImpl(time_system, Buffer::WatermarkFactoryPtr{new Buffer::WatermarkBufferFactory}) { // The dispatcher won't work as expected if libevent hasn't been configured to use threads. RELEASE_ASSERT(Libevent::Global::initialized(), ""); } -DispatcherImpl::DispatcherImpl(TimeSource& time_source, Buffer::WatermarkFactoryPtr&& factory) - : time_source_(time_source), buffer_factory_(std::move(factory)), base_(event_base_new()), +DispatcherImpl::DispatcherImpl(TimeSystem& time_system, Buffer::WatermarkFactoryPtr&& factory) + : time_system_(time_system), buffer_factory_(std::move(factory)), base_(event_base_new()), + scheduler_(time_system_.createScheduler(base_)), deferred_delete_timer_(createTimer([this]() -> void { clearDeferredDeleteList(); })), post_timer_(createTimer([this]() -> void { runPostCallbacks(); })), current_to_delete_(&to_delete_1_) { @@ -117,7 +117,7 @@ DispatcherImpl::createListener(Network::Socket& socket, Network::ListenerCallbac TimerPtr DispatcherImpl::createTimer(TimerCb cb) { ASSERT(isThreadSafe()); - return TimerPtr{new TimerImpl(*this, cb)}; + return scheduler_->createTimer(cb); } void DispatcherImpl::deferredDelete(DeferredDeletablePtr&& to_delete) { diff --git a/source/common/event/dispatcher_impl.h b/source/common/event/dispatcher_impl.h index ffc136e2f8f54..268eb81642d39 100644 --- a/source/common/event/dispatcher_impl.h +++ b/source/common/event/dispatcher_impl.h @@ -22,8 +22,8 @@ namespace Event { */ class DispatcherImpl : Logger::Loggable, public Dispatcher { public: - explicit DispatcherImpl(TimeSource& time_source); - DispatcherImpl(TimeSource& time_source, Buffer::WatermarkFactoryPtr&& factory); + explicit DispatcherImpl(TimeSystem& time_system); + DispatcherImpl(TimeSystem& time_system, Buffer::WatermarkFactoryPtr&& factory); ~DispatcherImpl(); /** @@ -32,7 +32,7 @@ class DispatcherImpl : Logger::Loggable, public Dispatcher { event_base& base() { return *base_; } // Event::Dispatcher - TimeSource& timeSource() override { return time_source_; } + TimeSystem& timeSource() override { return time_system_; } void clearDeferredDeleteList() override; Network::ConnectionPtr createServerConnection(Network::ConnectionSocketPtr&& socket, @@ -68,10 +68,11 @@ class DispatcherImpl : Logger::Loggable, public Dispatcher { return run_tid_ == 0 || run_tid_ == Thread::Thread::currentThreadId(); } - TimeSource time_source_; + TimeSystem& time_system_; Thread::ThreadId run_tid_{}; Buffer::WatermarkFactoryPtr buffer_factory_; Libevent::BasePtr base_; + SchedulerPtr scheduler_; TimerPtr deferred_delete_timer_; TimerPtr post_timer_; std::vector to_delete_1_; diff --git a/source/common/event/real_time_system.cc b/source/common/event/real_time_system.cc new file mode 100644 index 0000000000000..cc20698bd07de --- /dev/null +++ b/source/common/event/real_time_system.cc @@ -0,0 +1,33 @@ +#include "common/event/real_time_system.h" + +#include + +#include "common/common/assert.h" +#include "common/event/event_impl_base.h" +#include "common/event/timer_impl.h" + +#include "event2/event.h" + +namespace Envoy { +namespace Event { +namespace { + +class RealScheduler : public Scheduler { +public: + RealScheduler(Libevent::BasePtr& libevent) : libevent_(libevent) {} + TimerPtr createTimer(const TimerCb& cb) override { + return std::make_unique(libevent_, cb); + }; + +private: + Libevent::BasePtr& libevent_; +}; + +} // namespace + +SchedulerPtr RealTimeSystem::createScheduler(Libevent::BasePtr& libevent) { + return std::make_unique(libevent); +} + +} // namespace Event +} // namespace Envoy diff --git a/source/common/event/real_time_system.h b/source/common/event/real_time_system.h new file mode 100644 index 0000000000000..9ae68c80f56b7 --- /dev/null +++ b/source/common/event/real_time_system.h @@ -0,0 +1,27 @@ +#pragma once + +#include "envoy/event/timer.h" + +#include "common/common/utility.h" + +namespace Envoy { +namespace Event { + +/** + * Real-world time implementation of TimeSystem. + */ +class RealTimeSystem : public TimeSystem { +public: + // TimeSystem + SchedulerPtr createScheduler(Libevent::BasePtr&) override; + + // TimeSource + SystemTime systemTime() override { return time_source_.systemTime(); } + MonotonicTime monotonicTime() override { return time_source_.monotonicTime(); } + +private: + RealTimeSource time_source_; +}; + +} // namespace Event +} // namespace Envoy diff --git a/source/common/event/timer_impl.cc b/source/common/event/timer_impl.cc index 500c42edea6d9..5f5a9d8caab33 100644 --- a/source/common/event/timer_impl.cc +++ b/source/common/event/timer_impl.cc @@ -3,17 +3,16 @@ #include #include "common/common/assert.h" -#include "common/event/dispatcher_impl.h" #include "event2/event.h" namespace Envoy { namespace Event { -TimerImpl::TimerImpl(DispatcherImpl& dispatcher, TimerCb cb) : cb_(cb) { +TimerImpl::TimerImpl(Libevent::BasePtr& libevent, TimerCb cb) : cb_(cb) { ASSERT(cb_); evtimer_assign( - &raw_event_, &dispatcher.base(), + &raw_event_, libevent.get(), [](evutil_socket_t, short, void* arg) -> void { static_cast(arg)->cb_(); }, this); } @@ -23,6 +22,7 @@ void TimerImpl::enableTimer(const std::chrono::milliseconds& d) { if (d.count() == 0) { event_active(&raw_event_, EV_TIMEOUT, 0); } else { + // TODO(#4332): use duration_cast more nicely to clean up this code. std::chrono::microseconds us = std::chrono::duration_cast(d); timeval tv; tv.tv_sec = us.count() / 1000000; diff --git a/source/common/event/timer_impl.h b/source/common/event/timer_impl.h index a55580653f518..25b3ba513101a 100644 --- a/source/common/event/timer_impl.h +++ b/source/common/event/timer_impl.h @@ -4,20 +4,19 @@ #include "envoy/event/timer.h" -#include "common/event/dispatcher_impl.h" #include "common/event/event_impl_base.h" namespace Envoy { namespace Event { /** - * libevent implementation of Event::Timer. + * libevent implementation of Timer. */ class TimerImpl : public Timer, ImplBase { public: - TimerImpl(DispatcherImpl& dispatcher, TimerCb cb); + TimerImpl(Libevent::BasePtr& libevent, TimerCb cb); - // Event::Timer + // Timer void disableTimer() override; void enableTimer(const std::chrono::milliseconds& d) override; diff --git a/source/common/filesystem/filesystem_impl.cc b/source/common/filesystem/filesystem_impl.cc index 8c362b0860417..6d8eb402df7ce 100644 --- a/source/common/filesystem/filesystem_impl.cc +++ b/source/common/filesystem/filesystem_impl.cc @@ -11,8 +11,8 @@ #include #include "envoy/common/exception.h" +#include "envoy/common/time.h" #include "envoy/event/dispatcher.h" -#include "envoy/event/timer.h" #include "common/api/os_sys_calls_impl.h" #include "common/common/assert.h" diff --git a/source/common/http/BUILD b/source/common/http/BUILD index 900442c49b979..4f6fb317de139 100644 --- a/source/common/http/BUILD +++ b/source/common/http/BUILD @@ -110,9 +110,9 @@ envoy_cc_library( ":utility_lib", "//include/envoy/access_log:access_log_interface", "//include/envoy/buffer:buffer_interface", + "//include/envoy/common:time_interface", "//include/envoy/event:deferred_deletable", "//include/envoy/event:dispatcher_interface", - "//include/envoy/event:timer_interface", "//include/envoy/http:codec_interface", "//include/envoy/http:filter_interface", "//include/envoy/http:header_map_interface", diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index 306eab15a8a1a..3c93fb83939d0 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -7,8 +7,8 @@ #include #include "envoy/buffer/buffer.h" +#include "envoy/common/time.h" #include "envoy/event/dispatcher.h" -#include "envoy/event/timer.h" #include "envoy/network/drain_decision.h" #include "envoy/router/router.h" #include "envoy/ssl/connection.h" 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/tcp_proxy/BUILD b/source/common/tcp_proxy/BUILD index 589a6357e238f..7fcc846da64e5 100644 --- a/source/common/tcp_proxy/BUILD +++ b/source/common/tcp_proxy/BUILD @@ -15,8 +15,8 @@ envoy_cc_library( deps = [ "//include/envoy/access_log:access_log_interface", "//include/envoy/buffer:buffer_interface", + "//include/envoy/common:time_interface", "//include/envoy/event:dispatcher_interface", - "//include/envoy/event:timer_interface", "//include/envoy/network:connection_interface", "//include/envoy/network:filter_interface", "//include/envoy/router:router_interface", diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index 7860cdd2c0182..9453725073402 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, time_source_)); } } @@ -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..61ad22afb0dbb 100644 --- a/source/common/upstream/outlier_detection_impl.h +++ b/source/common/upstream/outlier_detection_impl.h @@ -11,6 +11,7 @@ #include "envoy/access_log/access_log.h" #include "envoy/api/v2/cluster/outlier_detection.pb.h" +#include "envoy/common/time.h" #include "envoy/event/timer.h" #include "envoy/http/codes.h" #include "envoy/runtime/runtime.h" @@ -212,7 +213,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 +229,8 @@ class DetectorImpl : public Detector, public std::enable_shared_from_this callbacks_; @@ -261,9 +262,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..61e443fdc450c 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(), ""); @@ -66,7 +65,7 @@ MainCommonBase::MainCommonBase(OptionsImpl& options) restarter_->statsAllocator()); server_ = std::make_unique( - options_, time_source_, local_address, default_test_hooks_, *restarter_, *stats_store_, + options_, time_system_, local_address, default_test_hooks_, *restarter_, *stats_store_, access_log_lock, component_factory_, std::make_unique(), *tls_); break; diff --git a/source/exe/main_common.h b/source/exe/main_common.h index 5355bc2a4f3c6..8cde0859534d6 100644 --- a/source/exe/main_common.h +++ b/source/exe/main_common.h @@ -1,5 +1,6 @@ #pragma once +#include "common/event/real_time_system.h" #include "common/stats/thread_local_store.h" #include "common/thread_local/thread_local_impl.h" @@ -49,9 +50,7 @@ class MainCommonBase { protected: Envoy::OptionsImpl& options_; ProdComponentFactory component_factory_; - ProdSystemTimeSource system_time_source_; - ProdMonotonicTimeSource monotonic_time_source_; - TimeSource time_source_; + Event::RealTimeSystem time_system_; 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/api.cc b/source/server/config_validation/api.cc index 293a3161c7f17..227ed06f4aeb6 100644 --- a/source/server/config_validation/api.cc +++ b/source/server/config_validation/api.cc @@ -8,8 +8,8 @@ namespace Api { ValidationImpl::ValidationImpl(std::chrono::milliseconds file_flush_interval_msec) : Impl(file_flush_interval_msec) {} -Event::DispatcherPtr ValidationImpl::allocateDispatcher(TimeSource& time_source) { - return Event::DispatcherPtr{new Event::ValidationDispatcher(time_source)}; +Event::DispatcherPtr ValidationImpl::allocateDispatcher(Event::TimeSystem& time_system) { + return Event::DispatcherPtr{new Event::ValidationDispatcher(time_system)}; } } // namespace Api diff --git a/source/server/config_validation/api.h b/source/server/config_validation/api.h index 2c568ab4c665e..ef2f71dcbd85d 100644 --- a/source/server/config_validation/api.h +++ b/source/server/config_validation/api.h @@ -1,6 +1,7 @@ #pragma once #include "envoy/api/api.h" +#include "envoy/event/timer.h" #include "envoy/filesystem/filesystem.h" #include "common/api/api_impl.h" @@ -16,7 +17,7 @@ class ValidationImpl : public Impl { public: ValidationImpl(std::chrono::milliseconds file_flush_interval_msec); - Event::DispatcherPtr allocateDispatcher(TimeSource&) override; + Event::DispatcherPtr allocateDispatcher(Event::TimeSystem&) override; }; } // namespace Api diff --git a/source/server/config_validation/async_client.cc b/source/server/config_validation/async_client.cc index 991bbcc44e624..d45c897a2d088 100644 --- a/source/server/config_validation/async_client.cc +++ b/source/server/config_validation/async_client.cc @@ -3,7 +3,8 @@ namespace Envoy { namespace Http { -ValidationAsyncClient::ValidationAsyncClient(TimeSource& time_source) : dispatcher_(time_source) {} +ValidationAsyncClient::ValidationAsyncClient(Event::TimeSystem& time_system) + : dispatcher_(time_system) {} AsyncClient::Request* ValidationAsyncClient::send(MessagePtr&&, Callbacks&, diff --git a/source/server/config_validation/async_client.h b/source/server/config_validation/async_client.h index fa1f768115611..b3a453025d0a1 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(TimeSource& time_source); + ValidationAsyncClient(Event::TimeSystem& time_system); // Http::AsyncClient AsyncClient::Request* send(MessagePtr&& request, Callbacks& callbacks, diff --git a/source/server/config_validation/dispatcher.h b/source/server/config_validation/dispatcher.h index bb1e4d34fc96d..8e51d4b02afca 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(TimeSource& time_source) : DispatcherImpl(time_source) {} + ValidationDispatcher(TimeSystem& time_system) : DispatcherImpl(time_system) {} Network::ClientConnectionPtr createClientConnection(Network::Address::InstanceConstSharedPtr, diff --git a/source/server/config_validation/server.cc b/source/server/config_validation/server.cc index 90b57e8f26228..2d36b7b8c21e1 100644 --- a/source/server/config_validation/server.cc +++ b/source/server/config_validation/server.cc @@ -7,6 +7,7 @@ #include "common/common/version.h" #include "common/config/bootstrap_json.h" #include "common/config/utility.h" +#include "common/event/real_time_system.h" #include "common/local_info/local_info_impl.h" #include "common/protobuf/utility.h" #include "common/singleton/manager_impl.h" @@ -22,10 +23,8 @@ 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); - ValidationInstance server(options, time_source, local_address, stats_store, access_log_lock, + Event::RealTimeSystem time_system; + ValidationInstance server(options, time_system, local_address, stats_store, access_log_lock, component_factory); std::cout << "configuration '" << options.configPath() << "' OK" << std::endl; server.shutdown(); @@ -35,17 +34,17 @@ bool validateConfig(Options& options, Network::Address::InstanceConstSharedPtr l } } -ValidationInstance::ValidationInstance(Options& options, TimeSource& time_source, +ValidationInstance::ValidationInstance(Options& options, Event::TimeSystem& time_system, Network::Address::InstanceConstSharedPtr local_address, Stats::IsolatedStoreImpl& store, Thread::BasicLockable& access_log_lock, ComponentFactory& component_factory) - : options_(options), time_source_(time_source), stats_store_(store), + : options_(options), time_system_(time_system), stats_store_(store), api_(new Api::ValidationImpl(options.fileFlushIntervalMsec())), - dispatcher_(api_->allocateDispatcher(time_source)), + dispatcher_(api_->allocateDispatcher(time_system)), singleton_manager_(new Singleton::ManagerImpl()), access_log_manager_(*api_, *dispatcher_, access_log_lock, store), - listener_manager_(*this, *this, *this, time_source) { + listener_manager_(*this, *this, *this, time_system_) { try { initialize(options, local_address, component_factory); } catch (const EnvoyException& e) { diff --git a/source/server/config_validation/server.h b/source/server/config_validation/server.h index b985dd4955c6f..7e28a076946e3 100644 --- a/source/server/config_validation/server.h +++ b/source/server/config_validation/server.h @@ -2,6 +2,7 @@ #include +#include "envoy/event/timer.h" #include "envoy/server/drain_manager.h" #include "envoy/server/instance.h" #include "envoy/ssl/context_manager.h" @@ -52,7 +53,7 @@ class ValidationInstance : Logger::Loggable, public ListenerComponentFactory, public WorkerFactory { public: - ValidationInstance(Options& options, TimeSource& time_source, + ValidationInstance(Options& options, Event::TimeSystem& time_system, Network::Address::InstanceConstSharedPtr local_address, Stats::IsolatedStoreImpl& store, Thread::BasicLockable& access_log_lock, ComponentFactory& component_factory); @@ -93,7 +94,7 @@ class ValidationInstance : Logger::Loggable, Tracing::HttpTracer& httpTracer() override { return config_->httpTracer(); } ThreadLocal::Instance& threadLocal() override { return thread_local_; } const LocalInfo::LocalInfo& localInfo() override { return *local_info_; } - TimeSource& timeSource() override { return time_source_; } + Event::TimeSystem& timeSource() override { return time_system_; } std::chrono::milliseconds statsFlushInterval() const override { return config_->statsFlushInterval(); @@ -138,7 +139,7 @@ class ValidationInstance : Logger::Loggable, ComponentFactory& component_factory); Options& options_; - TimeSource time_source_; + Event::TimeSystem& time_system_; 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::LoggableallocateDispatcher(time_source)), + dispatcher_(api_->allocateDispatcher(time_system)), singleton_manager_(new Singleton::ManagerImpl()), handler_(new ConnectionHandlerImpl(ENVOY_LOGGER(), *dispatcher_)), random_generator_(std::move(random_generator)), secret_manager_(std::make_unique()), - listener_component_factory_(*this), worker_factory_(thread_local_, *api_, hooks, time_source), + listener_component_factory_(*this), worker_factory_(thread_local_, *api_, hooks, time_system), dns_resolver_(dispatcher_->createDnsResolver({})), access_log_manager_(*api_, *dispatcher_, access_log_lock, store), terminated_(false) { @@ -226,7 +226,7 @@ void InstanceImpl::initialize(Options& options, // Handle configuration that needs to take place prior to the main configuration load. InstanceUtil::loadBootstrapConfig(bootstrap_, options); - bootstrap_config_update_time_ = time_source_.systemTime(); + bootstrap_config_update_time_ = time_system_.systemTime(); // Needs to happen as early as possible in the instantiation to preempt the objects that require // stats. @@ -271,7 +271,7 @@ void InstanceImpl::initialize(Options& options, // Workers get created first so they register for thread local updates. listener_manager_.reset( - new ListenerManagerImpl(*this, listener_component_factory_, worker_factory_, time_source_)); + new ListenerManagerImpl(*this, listener_component_factory_, worker_factory_, time_system_)); // 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. @@ -310,7 +310,7 @@ void InstanceImpl::initialize(Options& options, if (bootstrap_.has_hds_config()) { const auto& hds_config = bootstrap_.hds_config(); async_client_manager_ = std::make_unique( - clusterManager(), thread_local_, time_source_); + clusterManager(), thread_local_, time_system_); hds_delegate_.reset(new Upstream::HdsDelegate( bootstrap_.node(), stats(), Config::Utility::factoryForGrpcApiConfigSource(*async_client_manager_, hds_config, stats()) @@ -330,7 +330,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_.reset(new Server::GuardDogImpl(stats_store_, *config_, time_source_)); + guard_dog_.reset(new Server::GuardDogImpl(stats_store_, *config_, time_system_)); } void InstanceImpl::startWorkers() { diff --git a/source/server/server.h b/source/server/server.h index 71b4af2a7e2b6..4a90b8b138b7c 100644 --- a/source/server/server.h +++ b/source/server/server.h @@ -7,6 +7,7 @@ #include #include +#include "envoy/event/timer.h" #include "envoy/server/configuration.h" #include "envoy/server/drain_manager.h" #include "envoy/server/guarddog.h" @@ -135,7 +136,7 @@ class InstanceImpl : Logger::Loggable, public Instance { /** * @throw EnvoyException if initialization fails. */ - InstanceImpl(Options& options, TimeSource& time_source, + InstanceImpl(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, @@ -179,7 +180,7 @@ class InstanceImpl : Logger::Loggable, public Instance { Tracing::HttpTracer& httpTracer() override; ThreadLocal::Instance& threadLocal() override { return thread_local_; } const LocalInfo::LocalInfo& localInfo() override { return *local_info_; } - TimeSource& timeSource() override { return time_source_; } + Event::TimeSystem& timeSource() override { return time_system_; } std::chrono::milliseconds statsFlushInterval() const override { return config_->statsFlushInterval(); @@ -196,7 +197,7 @@ class InstanceImpl : Logger::Loggable, public Instance { void terminate(); Options& options_; - TimeSource time_source_; + Event::TimeSystem& time_system_; 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.cc b/source/server/worker_impl.cc index 0e1e55e72dcad..e2bc51a029016 100644 --- a/source/server/worker_impl.cc +++ b/source/server/worker_impl.cc @@ -15,7 +15,7 @@ namespace Envoy { namespace Server { WorkerPtr ProdWorkerFactory::createWorker() { - Event::DispatcherPtr dispatcher(api_.allocateDispatcher(time_source_)); + Event::DispatcherPtr dispatcher(api_.allocateDispatcher(time_system_)); 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 3ef7075ee806d..a0375cab25f5a 100644 --- a/source/server/worker_impl.h +++ b/source/server/worker_impl.h @@ -21,8 +21,8 @@ namespace Server { class ProdWorkerFactory : public WorkerFactory, Logger::Loggable { public: ProdWorkerFactory(ThreadLocal::Instance& tls, Api::Api& api, TestHooks& hooks, - TimeSource& time_source) - : tls_(tls), api_(api), hooks_(hooks), time_source_(time_source) {} + Event::TimeSystem& time_system) + : tls_(tls), api_(api), hooks_(hooks), time_system_(time_system) {} // Server::WorkerFactory WorkerPtr createWorker() override; @@ -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 875aa3cd08630..386a3d3503a5c 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 0174acb538de8..1a4edbd15994e 100644 --- a/test/common/config/grpc_mux_impl_test.cc +++ b/test/common/config/grpc_mux_impl_test.cc @@ -34,10 +34,8 @@ 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_) { - dispatcher_.setTimeSource(mock_time_source_); + GrpcMuxImplTest() : async_client_(new Grpc::MockAsyncClient()) { + dispatcher_.setTimeSystem(mock_time_system_); } void setup() { @@ -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_system_; NiceMock local_info_; }; @@ -361,7 +357,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_system_, monotonicTime()) .WillRepeatedly(Return(std::chrono::steady_clock::time_point{})); const auto onReceiveMessage = [&](uint64_t burst) { @@ -387,7 +383,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_system_, 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/network/connection_impl_test.cc b/test/common/network/connection_impl_test.cc index 49755f70a0b79..eef797fee4906 100644 --- a/test/common/network/connection_impl_test.cc +++ b/test/common/network/connection_impl_test.cc @@ -77,8 +77,8 @@ INSTANTIATE_TEST_CASE_P(IpVersions, ConnectionImplDeathTest, TestUtility::ipTestParamsToString); TEST_P(ConnectionImplDeathTest, BadFd) { - MockTimeSource time_source; - Event::DispatcherImpl dispatcher(time_source); + MockTimeSystem time_system; + Event::DispatcherImpl dispatcher(time_system); EXPECT_DEATH_LOG_TO_STDERR( ConnectionImpl(dispatcher, std::make_unique(-1, nullptr, nullptr), Network::Test::createRawBufferSocket(), false), @@ -89,7 +89,7 @@ class ConnectionImplTest : public testing::TestWithParam { public: void setUpBasicConnection() { if (dispatcher_.get() == nullptr) { - dispatcher_.reset(new Event::DispatcherImpl(time_source_)); + dispatcher_.reset(new Event::DispatcherImpl(time_system_)); } listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); @@ -152,7 +152,7 @@ class ConnectionImplTest : public testing::TestWithParam { MockBufferFactory* factory = new StrictMock; dispatcher_.reset( - new Event::DispatcherImpl(time_source_, Buffer::WatermarkFactoryPtr{factory})); + new Event::DispatcherImpl(time_system_, Buffer::WatermarkFactoryPtr{factory})); // 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_(_, _)) @@ -169,7 +169,7 @@ class ConnectionImplTest : public testing::TestWithParam { } protected: - MockTimeSource time_source_; + MockTimeSystem time_system_; Event::DispatcherPtr dispatcher_; Stats::IsolatedStoreImpl stats_store_; Network::TcpListenSocket socket_{Network::Test::getAnyAddress(GetParam()), nullptr, true}; @@ -233,7 +233,7 @@ TEST_P(ConnectionImplTest, CloseDuringConnectCallback) { } TEST_P(ConnectionImplTest, ImmediateConnectError) { - dispatcher_.reset(new Event::DispatcherImpl(time_source_)); + dispatcher_.reset(new Event::DispatcherImpl(time_system_)); // Using a broadcast/multicast address as the connection destiantion address causes an // immediate error return from connect(). @@ -805,7 +805,7 @@ TEST_P(ConnectionImplTest, BindFailureTest) { source_address_ = Network::Address::InstanceConstSharedPtr{ new Network::Address::Ipv6Instance(address_string, 0)}; } - dispatcher_.reset(new Event::DispatcherImpl(time_source_)); + dispatcher_.reset(new Event::DispatcherImpl(time_system_)); listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); client_connection_ = dispatcher_->createClientConnection( @@ -1199,7 +1199,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_.reset(new Event::DispatcherImpl(time_source_)); + dispatcher_.reset(new Event::DispatcherImpl(time_system_)); listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false); client_connection_ = dispatcher_->createClientConnection( @@ -1270,8 +1270,8 @@ TEST_P(ReadBufferLimitTest, SomeLimit) { class TcpClientConnectionImplTest : public testing::TestWithParam { protected: - TcpClientConnectionImplTest() : dispatcher_(time_source_) {} - MockTimeSource time_source_; + TcpClientConnectionImplTest() : dispatcher_(time_system_) {} + MockTimeSystem time_system_; Event::DispatcherImpl dispatcher_; }; INSTANTIATE_TEST_CASE_P(IpVersions, TcpClientConnectionImplTest, @@ -1311,8 +1311,8 @@ TEST_P(TcpClientConnectionImplTest, BadConnectConnRefused) { class PipeClientConnectionImplTest : public testing::Test { protected: - PipeClientConnectionImplTest() : dispatcher_(time_source_) {} - MockTimeSource time_source_; + PipeClientConnectionImplTest() : dispatcher_(time_system_) {} + MockTimeSystem time_system_; Event::DispatcherImpl dispatcher_; const std::string path_{TestEnvironment::unixDomainSocketPath("foo")}; }; 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..94c09fb639410 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_.setTimeSystem(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..1b69bfb2771a6 100644 --- a/test/common/upstream/load_stats_reporter_test.cc +++ b/test/common/upstream/load_stats_reporter_test.cc @@ -27,9 +27,8 @@ 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_) { - dispatcher_.setTimeSource(time_source_); + async_client_(new Grpc::MockAsyncClient()) { + dispatcher_.setTimeSystem(time_system_); } void createLoadStatsReporter() { @@ -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_; + MockTimeSystem time_system_; 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_system_, 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_system_, 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_system_, 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_system_, 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_system_, 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_system_, 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_system_, 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_system_, 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_system_, 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/BUILD b/test/mocks/BUILD index 5327e912a6769..1f132e7b2d4a0 100644 --- a/test/mocks/BUILD +++ b/test/mocks/BUILD @@ -15,6 +15,8 @@ envoy_cc_test_library( deps = [ "//include/envoy/common:time_interface", "//include/envoy/common:token_bucket_interface", + "//include/envoy/event:timer_interface", "//source/common/common:minimal_logger_lib", + "//source/common/event:real_time_system_lib", ], ) diff --git a/test/mocks/api/mocks.h b/test/mocks/api/mocks.h index 82a2eaf7412a3..f8cd0aca1a640 100644 --- a/test/mocks/api/mocks.h +++ b/test/mocks/api/mocks.h @@ -6,6 +6,7 @@ #include "envoy/api/api.h" #include "envoy/api/os_sys_calls.h" #include "envoy/event/dispatcher.h" +#include "envoy/event/timer.h" #include "envoy/stats/store.h" #include "common/api/os_sys_calls_impl.h" @@ -23,11 +24,11 @@ class MockApi : public Api { ~MockApi(); // Api::Api - Event::DispatcherPtr allocateDispatcher(TimeSource& time_source) override { - return Event::DispatcherPtr{allocateDispatcher_(time_source)}; + Event::DispatcherPtr allocateDispatcher(Event::TimeSystem& time_system) override { + return Event::DispatcherPtr{allocateDispatcher_(time_system)}; } - MOCK_METHOD1(allocateDispatcher_, Event::Dispatcher*(TimeSource&)); + MOCK_METHOD1(allocateDispatcher_, Event::Dispatcher*(Event::TimeSystem&)); MOCK_METHOD4(createFile, Filesystem::FileSharedPtr(const std::string& path, Event::Dispatcher& dispatcher, Thread::BasicLockable& lock, Stats::Store& stats_store)); diff --git a/test/mocks/common.cc b/test/mocks/common.cc index 5126b0b1f2b7d..ebacf91a6d528 100644 --- a/test/mocks/common.cc +++ b/test/mocks/common.cc @@ -4,15 +4,12 @@ namespace Envoy { ReadyWatcher::ReadyWatcher() {} ReadyWatcher::~ReadyWatcher() {} -MockSystemTimeSource::MockSystemTimeSource() {} -MockSystemTimeSource::~MockSystemTimeSource() {} - -MockMonotonicTimeSource::MockMonotonicTimeSource() {} -MockMonotonicTimeSource::~MockMonotonicTimeSource() {} - -MockTimeSource::MockTimeSource() : TimeSource(system_, monotonic_) {} +MockTimeSource::MockTimeSource() {} MockTimeSource::~MockTimeSource() {} +MockTimeSystem::MockTimeSystem() {} +MockTimeSystem::~MockTimeSystem() {} + MockTokenBucket::MockTokenBucket() {} MockTokenBucket::~MockTokenBucket() {} diff --git a/test/mocks/common.h b/test/mocks/common.h index adf25120f0658..96ae428bf37d3 100644 --- a/test/mocks/common.h +++ b/test/mocks/common.h @@ -4,8 +4,10 @@ #include "envoy/common/time.h" #include "envoy/common/token_bucket.h" +#include "envoy/event/timer.h" #include "common/common/logger.h" +#include "common/event/real_time_system.h" #include "absl/strings/string_view.h" #include "gmock/gmock.h" @@ -35,29 +37,32 @@ 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 MockTimeSystem : public Event::TimeSystem { +public: + MockTimeSystem(); + ~MockTimeSystem(); + + // TODO(#4160): Eliminate all uses of MockTimeSystem, replacing with SimulatedTimeSystem, + // where timer callbacks are triggered by the advancement of time. This implementation + // matches recent behavior, where real-time timers were created directly in libevent + // by dispatcher_impl.cc. + Event::SchedulerPtr createScheduler(Event::Libevent::BasePtr& base) override { + return real_time_system_.createScheduler(base); + } + MOCK_METHOD0(systemTime, SystemTime()); + MOCK_METHOD0(monotonicTime, MonotonicTime()); + + Event::RealTimeSystem real_time_system_; + MockTimeSource mock_time_source_; }; class MockTokenBucket : public TokenBucket { diff --git a/test/mocks/event/mocks.cc b/test/mocks/event/mocks.cc index dd3273b076f1c..36650b5aff056 100644 --- a/test/mocks/event/mocks.cc +++ b/test/mocks/event/mocks.cc @@ -13,7 +13,7 @@ using testing::SaveArg; namespace Envoy { namespace Event { -MockDispatcher::MockDispatcher() : time_source_(&test_time_.timeSource()) { +MockDispatcher::MockDispatcher() : time_system_(&test_time_.timeSource()) { ON_CALL(*this, clearDeferredDeleteList()).WillByDefault(Invoke([this]() -> void { to_delete_.clear(); })); diff --git a/test/mocks/event/mocks.h b/test/mocks/event/mocks.h index 55b7b29be56c0..915231bddca31 100644 --- a/test/mocks/event/mocks.h +++ b/test/mocks/event/mocks.h @@ -5,11 +5,11 @@ #include #include +#include "envoy/common/time.h" #include "envoy/event/deferred_deletable.h" #include "envoy/event/dispatcher.h" #include "envoy/event/file_event.h" #include "envoy/event/signal.h" -#include "envoy/event/timer.h" #include "envoy/network/connection.h" #include "envoy/network/connection_handler.h" #include "envoy/network/dns.h" @@ -30,10 +30,10 @@ class MockDispatcher : public Dispatcher { MockDispatcher(); ~MockDispatcher(); - void setTimeSource(TimeSource& time_source) { time_source_ = &time_source; } + void setTimeSystem(TimeSystem& time_system) { time_system_ = &time_system; } // Dispatcher - TimeSource& timeSource() override { return *time_source_; } + TimeSystem& timeSource() override { return *time_system_; } Network::ConnectionPtr createServerConnection(Network::ConnectionSocketPtr&& socket, Network::TransportSocketPtr&& transport_socket) override { @@ -65,7 +65,9 @@ class MockDispatcher : public Dispatcher { createListener_(socket, cb, bind_to_port, hand_off_restored_destination_connections)}; } - TimerPtr createTimer(TimerCb cb) override { return TimerPtr{createTimer_(cb)}; } + Event::TimerPtr createTimer(Event::TimerCb cb) override { + return Event::TimerPtr{createTimer_(cb)}; + } void deferredDelete(DeferredDeletablePtr&& to_delete) override { deferredDelete_(to_delete.get()); @@ -99,7 +101,7 @@ class MockDispatcher : public Dispatcher { Network::Listener*(Network::Socket& socket, Network::ListenerCallbacks& cb, bool bind_to_port, bool hand_off_restored_destination_connections)); - MOCK_METHOD1(createTimer_, Timer*(TimerCb cb)); + MOCK_METHOD1(createTimer_, Timer*(Event::TimerCb cb)); MOCK_METHOD1(deferredDelete_, void(DeferredDeletable* to_delete)); MOCK_METHOD0(exit, void()); MOCK_METHOD2(listenForSignal_, SignalEvent*(int signal_num, SignalCb cb)); @@ -109,7 +111,7 @@ class MockDispatcher : public Dispatcher { // TODO(jmarantz): Switch these to using mock-time. DangerousDeprecatedTestTime test_time_; - TimeSource* time_source_; + TimeSystem* time_system_; std::list to_delete_; MockBufferFactory buffer_factory_; @@ -121,11 +123,11 @@ class MockTimer : public Timer { MockTimer(MockDispatcher* dispatcher); ~MockTimer(); - // Event::Timer + // Timer MOCK_METHOD0(disableTimer, void()); MOCK_METHOD1(enableTimer, void(const std::chrono::milliseconds&)); - TimerCb callback_; + Event::TimerCb callback_; }; class MockSignalEvent : public SignalEvent { diff --git a/test/mocks/server/mocks.cc b/test/mocks/server/mocks.cc index 7ea2f3cd4ac1b..3a3e6935b2c3b 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 bd62535f854f1..50f53ccd71c1e 100644 --- a/test/mocks/server/mocks.h +++ b/test/mocks/server/mocks.h @@ -327,7 +327,7 @@ class MockInstance : public Instance { MOCK_METHOD0(httpTracer, Tracing::HttpTracer&()); MOCK_METHOD0(threadLocal, ThreadLocal::Instance&()); MOCK_METHOD0(localInfo, const LocalInfo::LocalInfo&()); - MOCK_METHOD0(timeSource, TimeSource&()); + MOCK_METHOD0(timeSource, Event::TimeSystem&()); MOCK_CONST_METHOD0(statsFlushInterval, std::chrono::milliseconds()); std::unique_ptr secret_manager_; @@ -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/BUILD b/test/test_common/BUILD index 25ecd618efc86..8587b5c8eac2b 100644 --- a/test/test_common/BUILD +++ b/test/test_common/BUILD @@ -124,7 +124,7 @@ envoy_cc_test_library( srcs = ["test_time.cc"], hdrs = ["test_time.h"], deps = [ - "//source/common/common:utility_lib", + "//source/common/event:real_time_system_lib", ], ) 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..a1885808317da 100644 --- a/test/test_common/test_time.h +++ b/test/test_common/test_time.h @@ -1,6 +1,6 @@ #pragma once -#include "common/common/utility.h" +#include "common/event/real_time_system.h" namespace Envoy { @@ -13,16 +13,11 @@ class DangerousDeprecatedTestTime { public: DangerousDeprecatedTestTime(); - TimeSource& timeSource() { return time_source_; } + // TODO(#4160) rename this method and all call-sites to timeSystem(). + Event::TimeSystem& timeSource() { return time_system_; } 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_; + Event::RealTimeSystem time_system_; }; } // namespace Envoy diff --git a/test/tools/router_check/BUILD b/test/tools/router_check/BUILD index 0b0ab09cbc3a6..276fea07bca58 100644 --- a/test/tools/router_check/BUILD +++ b/test/tools/router_check/BUILD @@ -23,6 +23,7 @@ envoy_cc_test_library( ], deps = [ "//source/common/config:rds_json_lib", + "//source/common/event:dispatcher_lib", "//source/common/http:header_map_lib", "//source/common/http:headers_lib", "//source/common/json:json_loader_lib", diff --git a/tools/check_format.py b/tools/check_format.py index 6f643cd6b7f9c..d66918e21da64 100755 --- a/tools/check_format.py +++ b/tools/check_format.py @@ -23,10 +23,12 @@ GOOGLE_PROTOBUF_WHITELIST = ("ci/prebuilt", "source/common/protobuf", "api/test") REPOSITORIES_BZL = "bazel/repositories.bzl" -# 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. +# Files matching these exact names can reference real-world time. These include the class +# definitions for real-world 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/common/event/real_time_system.cc', + './source/common/event/real_time_system.h', './source/exe/main_common.cc', './source/exe/main_common.h', './source/server/config_validation/server.cc', @@ -74,11 +76,11 @@ def whitelistedForProtobufDeps(file_path): return (file_path.endswith(PROTO_SUFFIX) or file_path.endswith(REPOSITORIES_BZL) or \ any(path_segment in file_path for path_segment in GOOGLE_PROTOBUF_WHITELIST)) -# Production time sources should not be instantiated in the source, except for a few +# Real-world 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,9 +162,9 @@ 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: - reportError("Don't reference real-time sources from production code; use injection") + if not whitelistedForRealTime(file_path): + if 'RealTimeSource' in line or 'RealTimeSystem' in line: + reportError("Don't reference real-world time sources from production code; use injection") def checkBuildLine(line, file_path, reportError): if not whitelistedForProtobufDeps(file_path) and '"protobuf"' in line: diff --git a/tools/check_format_test_helper.py b/tools/check_format_test_helper.py index 2d7b02081a34b..9fb5640e8bca2 100755 --- a/tools/check_format_test_helper.py +++ b/tools/check_format_test_helper.py @@ -143,10 +143,10 @@ def checkFileExpectingOK(filename): "Don't use or ") 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_inject_error = ( + "Don't reference real-world time sources from production code; use injection") + errors += fixFileExpectingFailure("real_time_source.cc", real_time_inject_error) + errors += fixFileExpectingFailure("real_time_system.cc", real_time_inject_error) errors += fixFileExpectingNoChange("ok_file.cc") @@ -167,10 +167,8 @@ def checkFileExpectingOK(filename): errors += checkFileExpectingError("bad_envoy_build_sys_ref.BUILD", "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") + errors += checkFileExpectingError("real_time_source.cc", real_time_inject_error) + errors += checkFileExpectingError("real_time_system.cc", real_time_inject_error) 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 diff --git a/tools/testdata/check_format/real_time_system.cc b/tools/testdata/check_format/real_time_system.cc new file mode 100644 index 0000000000000..1509e3f55325e --- /dev/null +++ b/tools/testdata/check_format/real_time_system.cc @@ -0,0 +1,7 @@ +namespace Envoy { + +int foo() { + RealTimeSystem real_time_system; +} + +} // namespace Envoy