diff --git a/envoy/stream_info/stream_info.h b/envoy/stream_info/stream_info.h index 631a4d254eefa..503252c5990f3 100644 --- a/envoy/stream_info/stream_info.h +++ b/envoy/stream_info/stream_info.h @@ -358,13 +358,6 @@ class UpstreamInfo { */ virtual Ssl::ConnectionInfoConstSharedPtr upstreamSslConnection() const PURE; - /** - * Sets the upstream timing information for this stream. This is useful for - * when multiple upstream requests are issued and we want to save timing - * information for the one that "wins". - */ - virtual void setUpstreamTiming(const UpstreamTiming& upstream_timing) PURE; - /* * @return the upstream timing for this stream * */ @@ -451,11 +444,6 @@ class StreamInfo { */ virtual bool intersectResponseFlags(uint64_t response_flags) const PURE; - /** - * @param host the selected upstream host for the request. - */ - virtual void onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) PURE; - /** * @param std::string name denotes the name of the route. */ @@ -522,19 +510,6 @@ class StreamInfo { */ virtual MonotonicTime startTimeMonotonic() const PURE; - /** - * @return the duration between the last byte of the request was received and the start of the - * request. - */ - virtual absl::optional lastDownstreamRxByteReceived() const PURE; - - /** - * Sets the upstream timing information for this stream. This is useful for - * when multiple upstream requests are issued and we want to save timing - * information for the one that "wins". - */ - virtual void setUpstreamTiming(const UpstreamTiming& upstream_timing) PURE; - /** * Sets the upstream information for this stream. */ @@ -546,50 +521,6 @@ class StreamInfo { virtual std::shared_ptr upstreamInfo() PURE; virtual OptRef upstreamInfo() const PURE; - /** - * Returns the upstream timing information for this stream. - * It is not expected that the fields in upstreamTiming() will be set until - * the upstream request is complete. - */ - virtual UpstreamTiming& upstreamTiming() PURE; - - /** - * @return the duration between the first byte of the request was sent upstream and the start of - * the request. There may be a considerable delta between lastDownstreamByteReceived and this - * value due to filters. - */ - virtual absl::optional firstUpstreamTxByteSent() const PURE; - - /** - * @return the duration between the last byte of the request was sent upstream and the start of - * the request. - */ - virtual absl::optional lastUpstreamTxByteSent() const PURE; - - /** - * @return the duration between the first byte of the response is received from upstream and the - * start of the request. - */ - virtual absl::optional firstUpstreamRxByteReceived() const PURE; - - /** - * @return the duration between the last byte of the response is received from upstream and the - * start of the request. - */ - virtual absl::optional lastUpstreamRxByteReceived() const PURE; - /** - * @return the duration between the first byte of the response is sent downstream and the start of - * the request. There may be a considerable delta between lastUpstreamByteReceived and this value - * due to filters. - */ - virtual absl::optional firstDownstreamTxByteSent() const PURE; - - /** - * @return the duration between the last byte of the response is sent downstream and the start of - * the request. - */ - virtual absl::optional lastDownstreamTxByteSent() const PURE; - /** * @return the total duration of the request (i.e., when the request's ActiveStream is destroyed) * and may be longer than lastDownstreamTxByteSent. @@ -606,6 +537,7 @@ class StreamInfo { * @return the downstream timing information. */ virtual DownstreamTiming& downstreamTiming() PURE; + virtual OptRef downstreamTiming() const PURE; /** * @param bytes_sent denotes the number of bytes to add to total sent bytes. @@ -632,23 +564,6 @@ class StreamInfo { */ virtual uint64_t responseFlags() const PURE; - /** - * @return upstream host description. - */ - virtual Upstream::HostDescriptionConstSharedPtr upstreamHost() const PURE; - - /** - * @param upstream_local_address sets the local address of the upstream connection. Note that it - * can be different than the local address of the downstream connection. - */ - virtual void setUpstreamLocalAddress( - const Network::Address::InstanceConstSharedPtr& upstream_local_address) PURE; - - /** - * @return the upstream local address. - */ - virtual const Network::Address::InstanceConstSharedPtr& upstreamLocalAddress() const PURE; - /** * @return whether the request is a health check request or not. */ @@ -664,18 +579,6 @@ class StreamInfo { */ virtual const Network::ConnectionInfoProvider& downstreamAddressProvider() const PURE; - /** - * @param connection_info sets the upstream ssl connection. - */ - virtual void - setUpstreamSslConnection(const Ssl::ConnectionInfoConstSharedPtr& ssl_connection_info) PURE; - - /** - * @return the upstream SSL connection. This will be nullptr if the upstream - * connection does not use SSL. - */ - virtual Ssl::ConnectionInfoConstSharedPtr upstreamSslConnection() const PURE; - /** * @return const Router::RouteConstSharedPtr Get the route selected for this request. */ @@ -705,25 +608,6 @@ class StreamInfo { virtual const FilterStateSharedPtr& filterState() PURE; virtual const FilterState& filterState() const PURE; - /** - * Filter State object to be shared between upstream and downstream filters. - * @param pointer to upstream connections filter state. - * @return pointer to filter state to be used by upstream connections. - */ - virtual const FilterStateSharedPtr& upstreamFilterState() const PURE; - virtual void setUpstreamFilterState(const FilterStateSharedPtr& filter_state) PURE; - - /** - * @param failure_reason the upstream transport failure reason. - */ - virtual void setUpstreamTransportFailureReason(absl::string_view failure_reason) PURE; - - /** - * @return const std::string& the upstream transport failure reason, e.g. certificate validation - * failed. - */ - virtual const std::string& upstreamTransportFailureReason() const PURE; - /** * @param headers request headers. */ @@ -778,16 +662,6 @@ class StreamInfo { */ virtual const std::string& filterChainName() const PURE; - /** - * @param connection ID of the upstream connection. - */ - virtual void setUpstreamConnectionId(uint64_t id) PURE; - - /** - * @return the ID of the upstream connection, or absl::nullopt if not available. - */ - virtual absl::optional upstreamConnectionId() const PURE; - /** * @param attempt_count, the number of times the request was attempted upstream. */ diff --git a/source/common/formatter/substitution_formatter.cc b/source/common/formatter/substitution_formatter.cc index 42a790b9d9c32..0cc4e370e5b32 100644 --- a/source/common/formatter/substitution_formatter.cc +++ b/source/common/formatter/substitution_formatter.cc @@ -690,23 +690,27 @@ StreamInfoFormatter::StreamInfoFormatter(const std::string& field_name) { if (field_name == "REQUEST_DURATION") { field_extractor_ = std::make_unique( [](const StreamInfo::StreamInfo& stream_info) { - return stream_info.lastDownstreamRxByteReceived(); + StreamInfo::TimingUtility timing(stream_info); + return timing.lastDownstreamRxByteReceived(); }); } else if (field_name == "REQUEST_TX_DURATION") { field_extractor_ = std::make_unique( [](const StreamInfo::StreamInfo& stream_info) { - return stream_info.lastUpstreamTxByteSent(); + StreamInfo::TimingUtility timing(stream_info); + return timing.lastUpstreamTxByteSent(); }); } else if (field_name == "RESPONSE_DURATION") { field_extractor_ = std::make_unique( [](const StreamInfo::StreamInfo& stream_info) { - return stream_info.firstUpstreamRxByteReceived(); + StreamInfo::TimingUtility timing(stream_info); + return timing.firstUpstreamRxByteReceived(); }); } else if (field_name == "RESPONSE_TX_DURATION") { field_extractor_ = std::make_unique( [](const StreamInfo::StreamInfo& stream_info) { - auto downstream = stream_info.lastDownstreamTxByteSent(); - auto upstream = stream_info.firstUpstreamRxByteReceived(); + StreamInfo::TimingUtility timing(stream_info); + auto downstream = timing.lastDownstreamTxByteSent(); + auto upstream = timing.firstUpstreamRxByteReceived(); absl::optional result; if (downstream && upstream) { @@ -790,9 +794,13 @@ StreamInfoFormatter::StreamInfoFormatter(const std::string& field_name) { return StreamInfo::ResponseFlagUtils::toShortString(stream_info); }); } else if (field_name == "UPSTREAM_HOST") { - field_extractor_ = - StreamInfoAddressFieldExtractor::withPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.upstreamHost() ? stream_info.upstreamHost()->address() : nullptr; + field_extractor_ = StreamInfoAddressFieldExtractor::withPort( + [](const StreamInfo::StreamInfo& stream_info) + -> std::shared_ptr { + if (stream_info.upstreamInfo() && stream_info.upstreamInfo()->upstreamHost()) { + return stream_info.upstreamInfo()->upstreamHost()->address(); + } + return nullptr; }); } else if (field_name == "UPSTREAM_CLUSTER") { field_extractor_ = std::make_unique( @@ -814,9 +822,13 @@ StreamInfoFormatter::StreamInfoFormatter(const std::string& field_name) { : absl::make_optional(upstream_cluster_name); }); } else if (field_name == "UPSTREAM_LOCAL_ADDRESS") { - field_extractor_ = - StreamInfoAddressFieldExtractor::withPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.upstreamLocalAddress(); + field_extractor_ = StreamInfoAddressFieldExtractor::withPort( + [](const StreamInfo::StreamInfo& stream_info) + -> std::shared_ptr { + if (stream_info.upstreamInfo().has_value()) { + return stream_info.upstreamInfo().value().get().upstreamLocalAddress(); + } + return nullptr; }); } else if (field_name == "UPSTREAM_REQUEST_ATTEMPT_COUNT") { field_extractor_ = std::make_unique( @@ -942,8 +954,9 @@ StreamInfoFormatter::StreamInfoFormatter(const std::string& field_name) { field_extractor_ = std::make_unique( [](const StreamInfo::StreamInfo& stream_info) { absl::optional result; - if (!stream_info.upstreamTransportFailureReason().empty()) { - result = stream_info.upstreamTransportFailureReason(); + if (stream_info.upstreamInfo().has_value() && + !stream_info.upstreamInfo().value().get().upstreamTransportFailureReason().empty()) { + result = stream_info.upstreamInfo().value().get().upstreamTransportFailureReason(); } return result; }); diff --git a/source/common/http/filter_manager.h b/source/common/http/filter_manager.h index 758d046e249d0..09e493a7ff19c 100644 --- a/source/common/http/filter_manager.h +++ b/source/common/http/filter_manager.h @@ -631,9 +631,6 @@ class OverridableRemoteConnectionInfoSetterStreamInfo : public StreamInfo::Strea Ssl::ConnectionInfoConstSharedPtr sslConnection() const override { return StreamInfoImpl::downstreamAddressProvider().sslConnection(); } - Ssl::ConnectionInfoConstSharedPtr upstreamSslConnection() const override { - return StreamInfoImpl::upstreamSslConnection(); - } void dumpState(std::ostream& os, int indent_level) const override { StreamInfoImpl::dumpState(os, indent_level); diff --git a/source/common/network/connection_impl.cc b/source/common/network/connection_impl.cc index ad3b80033e809..2d4f847a8c458 100644 --- a/source/common/network/connection_impl.cc +++ b/source/common/network/connection_impl.cc @@ -848,6 +848,7 @@ ClientConnectionImpl::ClientConnectionImpl( false), stream_info_(dispatcher_.timeSource(), socket_->connectionInfoProviderSharedPtr()) { + stream_info_.setUpstreamInfo(std::make_shared()); // There are no meaningful socket options or source address semantics for // non-IP sockets, so skip. if (socket_->connectionInfoProviderSharedPtr()->remoteAddress()->ip() == nullptr) { @@ -891,7 +892,7 @@ void ClientConnectionImpl::connect() { socket_->connectionInfoProvider().remoteAddress()->asString()); const Api::SysCallIntResult result = socket_->connect(socket_->connectionInfoProvider().remoteAddress()); - stream_info_.upstreamTiming().onUpstreamConnectStart(dispatcher_.timeSource()); + stream_info_.upstreamInfo()->upstreamTiming().onUpstreamConnectStart(dispatcher_.timeSource()); if (result.return_value_ == 0) { // write will become ready. ASSERT(connecting_); @@ -921,7 +922,7 @@ void ClientConnectionImpl::connect() { } void ClientConnectionImpl::onConnected() { - stream_info_.upstreamTiming().onUpstreamConnectComplete(dispatcher_.timeSource()); + stream_info_.upstreamInfo()->upstreamTiming().onUpstreamConnectComplete(dispatcher_.timeSource()); ConnectionImpl::onConnected(); } diff --git a/source/common/quic/envoy_quic_client_session.cc b/source/common/quic/envoy_quic_client_session.cc index 6811493834b3e..96461564ad282 100644 --- a/source/common/quic/envoy_quic_client_session.cc +++ b/source/common/quic/envoy_quic_client_session.cc @@ -21,7 +21,9 @@ EnvoyQuicClientSession::EnvoyQuicClientSession( quic::QuicSpdyClientSession(config, supported_versions, connection.release(), server_id, crypto_config.get(), push_promise_index), crypto_config_(crypto_config), crypto_stream_factory_(crypto_stream_factory), - quic_stat_names_(quic_stat_names), scope_(scope) {} + quic_stat_names_(quic_stat_names), scope_(scope) { + streamInfo().setUpstreamInfo(std::make_shared()); +} EnvoyQuicClientSession::~EnvoyQuicClientSession() { ASSERT(!connection()->connected()); @@ -31,7 +33,7 @@ EnvoyQuicClientSession::~EnvoyQuicClientSession() { absl::string_view EnvoyQuicClientSession::requestedServerName() const { return server_id().host(); } void EnvoyQuicClientSession::connect() { - streamInfo().upstreamTiming().onUpstreamConnectStart(dispatcher_.timeSource()); + streamInfo().upstreamInfo()->upstreamTiming().onUpstreamConnectStart(dispatcher_.timeSource()); dynamic_cast(network_connection_) ->setUpConnectionSocket( *static_cast(connection())->connectionSocket(), *this); @@ -133,8 +135,9 @@ void EnvoyQuicClientSession::OnTlsHandshakeComplete() { // before use. This may result in OnCanCreateNewOutgoingStream with zero // available streams. OnCanCreateNewOutgoingStream(false); - streamInfo().upstreamTiming().onUpstreamConnectComplete(dispatcher_.timeSource()); - streamInfo().upstreamTiming().onUpstreamHandshakeComplete(dispatcher_.timeSource()); + streamInfo().upstreamInfo()->upstreamTiming().onUpstreamConnectComplete(dispatcher_.timeSource()); + streamInfo().upstreamInfo()->upstreamTiming().onUpstreamHandshakeComplete( + dispatcher_.timeSource()); raiseConnectionEvent(Network::ConnectionEvent::Connected); } diff --git a/source/common/router/header_formatter.cc b/source/common/router/header_formatter.cc index 009e706f5009c..ade0952822b6c 100644 --- a/source/common/router/header_formatter.cc +++ b/source/common/router/header_formatter.cc @@ -96,8 +96,8 @@ parseMetadataField(absl::string_view params_str, bool upstream = true) { return [upstream, params](const Envoy::StreamInfo::StreamInfo& stream_info) -> std::string { const envoy::config::core::v3::Metadata* metadata = nullptr; - if (upstream) { - Upstream::HostDescriptionConstSharedPtr host = stream_info.upstreamHost(); + if (upstream && stream_info.upstreamInfo()) { + Upstream::HostDescriptionConstSharedPtr host = stream_info.upstreamInfo()->upstreamHost(); if (!host) { return std::string(); } @@ -330,8 +330,8 @@ StreamInfoHeaderFormatter::StreamInfoHeaderFormatter(absl::string_view field_nam field_extractor_ = parseSubstitutionFormatField(field_name, formatter_map_); } else if (field_name == "UPSTREAM_REMOTE_ADDRESS") { field_extractor_ = [](const Envoy::StreamInfo::StreamInfo& stream_info) -> std::string { - if (stream_info.upstreamHost()) { - return stream_info.upstreamHost()->address()->asString(); + if (stream_info.upstreamInfo() && stream_info.upstreamInfo()->upstreamHost()) { + return stream_info.upstreamInfo()->upstreamHost()->address()->asString(); } return ""; }; diff --git a/source/common/router/router.cc b/source/common/router/router.cc index 98bec7fb9b8df..3decaf89bdbfe 100644 --- a/source/common/router/router.cc +++ b/source/common/router/router.cc @@ -898,12 +898,6 @@ void Filter::onDestroy() { void Filter::onResponseTimeout() { ENVOY_STREAM_LOG(debug, "upstream timeout", *callbacks_); - // If we had an upstream request that got a "good" response, save its - // upstream timing information into the downstream stream info. - if (final_upstream_request_) { - callbacks_->streamInfo().setUpstreamTiming(final_upstream_request_->upstreamTiming()); - } - // Reset any upstream requests that are still in flight. while (!upstream_requests_.empty()) { UpstreamRequestPtr upstream_request = @@ -1167,7 +1161,6 @@ void Filter::onUpstreamReset(Http::StreamResetReason reset_reason, ? ", transport failure reason: " : "", transport_failure_reason); - callbacks_->streamInfo().setUpstreamTransportFailureReason(transport_failure_reason); const std::string& basic_details = downstream_response_started_ ? StreamInfo::ResponseCodeDetails::get().LateUpstreamReset : StreamInfo::ResponseCodeDetails::get().EarlyUpstreamReset; @@ -1410,14 +1403,8 @@ void Filter::onUpstreamHeaders(uint64_t response_code, Http::ResponseHeaderMapPt downstream_response_started_ = true; final_upstream_request_ = &upstream_request; - // In upstream request hedging scenarios the upstream connection ID set in onPoolReady might not - // be the connection ID of the upstream connection that ended up receiving upstream headers. Thus - // reset the upstream connection ID here with the ID of the connection that ultimately was the - // transport for the final upstream request. - if (final_upstream_request_->streamInfo().upstreamConnectionId().has_value()) { - callbacks_->streamInfo().setUpstreamConnectionId( - final_upstream_request_->streamInfo().upstreamConnectionId().value()); - } + // Make sure that for request hedging, we end up with the correct final upstream info. + callbacks_->streamInfo().setUpstreamInfo(final_upstream_request_->streamInfo().upstreamInfo()); resetOtherUpstreams(upstream_request); if (end_stream) { onUpstreamComplete(upstream_request); @@ -1474,8 +1461,6 @@ void Filter::onUpstreamComplete(UpstreamRequest& upstream_request) { if (!downstream_end_stream_) { upstream_request.resetStream(); } - callbacks_->streamInfo().setUpstreamTiming(final_upstream_request_->upstreamTiming()); - Event::Dispatcher& dispatcher = callbacks_->dispatcher(); std::chrono::milliseconds response_time = std::chrono::duration_cast( dispatcher.timeSource().monotonicTime() - downstream_request_complete_time_); diff --git a/source/common/router/upstream_request.cc b/source/common/router/upstream_request.cc index 8b9baba46cfde..3640d6b0dbf2d 100644 --- a/source/common/router/upstream_request.cc +++ b/source/common/router/upstream_request.cc @@ -60,6 +60,8 @@ UpstreamRequest::UpstreamRequest(RouterFilterInterface& parent, span_->setTag(Tracing::Tags::get().RetryCount, std::to_string(parent.attemptCount() - 1)); } } + stream_info_.setUpstreamInfo(std::make_shared()); + parent_.callbacks()->streamInfo().setUpstreamInfo(stream_info_.upstreamInfo()); stream_info_.healthCheck(parent_.callbacks()->streamInfo().healthCheck()); absl::optional cluster_info = @@ -115,7 +117,6 @@ UpstreamRequest::~UpstreamRequest() { } } - stream_info_.setUpstreamTiming(upstream_timing_); stream_info_.onRequestComplete(); for (const auto& upstream_log : parent_.config().upstream_logs_) { upstream_log->log(parent_.downstreamHeaders(), upstream_headers_.get(), @@ -162,7 +163,7 @@ void UpstreamRequest::decodeHeaders(Http::ResponseHeaderMapPtr&& headers, bool e // TODO(rodaine): This is actually measuring after the headers are parsed and not the first // byte. - upstream_timing_.onFirstUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource()); + upstreamTiming().onFirstUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource()); maybeEndDecode(end_stream); awaiting_headers_ = false; @@ -219,15 +220,15 @@ void UpstreamRequest::decodeMetadata(Http::MetadataMapPtr&& metadata_map) { void UpstreamRequest::maybeEndDecode(bool end_stream) { if (end_stream) { - upstream_timing_.onLastUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource()); + upstreamTiming().onLastUpstreamRxByteReceived(parent_.callbacks()->dispatcher().timeSource()); decode_complete_ = true; } } void UpstreamRequest::onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) { - stream_info_.onUpstreamHostSelected(host); + StreamInfo::UpstreamInfo& upstream_info = *streamInfo().upstreamInfo(); + upstream_info.setUpstreamHost(host); upstream_host_ = host; - parent_.callbacks()->streamInfo().onUpstreamHostSelected(host); parent_.onUpstreamHostSelected(host); } @@ -260,7 +261,7 @@ void UpstreamRequest::encodeData(Buffer::Instance& data, bool end_stream) { stream_info_.addBytesSent(data.length()); upstream_->encodeData(data, end_stream); if (end_stream) { - upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); + upstreamTiming().onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); } } } @@ -277,7 +278,7 @@ void UpstreamRequest::encodeTrailers(const Http::RequestTrailerMap& trailers) { ENVOY_STREAM_LOG(trace, "proxying trailers", *parent_.callbacks()); upstream_->encodeTrailers(trailers); - upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); + upstreamTiming().onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); } } @@ -427,29 +428,22 @@ void UpstreamRequest::onPoolReady( stream_info_.protocol(protocol.value()); } + parent_.callbacks()->streamInfo().setUpstreamInfo(stream_info_.upstreamInfo()); if (info.upstreamInfo().has_value()) { auto& upstream_timing = info.upstreamInfo().value().get().upstreamTiming(); - upstream_timing_.upstream_connect_start_ = upstream_timing.upstream_connect_start_; - upstream_timing_.upstream_connect_complete_ = upstream_timing.upstream_connect_complete_; - upstream_timing_.upstream_handshake_complete_ = upstream_timing.upstream_handshake_complete_; + upstreamTiming().upstream_connect_start_ = upstream_timing.upstream_connect_start_; + upstreamTiming().upstream_connect_complete_ = upstream_timing.upstream_connect_complete_; + upstreamTiming().upstream_handshake_complete_ = upstream_timing.upstream_handshake_complete_; } - stream_info_.setUpstreamFilterState(std::make_shared( + StreamInfo::UpstreamInfo& upstream_info = *stream_info_.upstreamInfo(); + upstream_info.setUpstreamFilterState(std::make_shared( info.filterState().parent()->parent(), StreamInfo::FilterState::LifeSpan::Request)); - parent_.callbacks()->streamInfo().setUpstreamFilterState( - std::make_shared(info.filterState().parent()->parent(), - StreamInfo::FilterState::LifeSpan::Request)); - stream_info_.setUpstreamLocalAddress(upstream_local_address); - parent_.callbacks()->streamInfo().setUpstreamLocalAddress(upstream_local_address); - - stream_info_.setUpstreamSslConnection(info.downstreamAddressProvider().sslConnection()); - parent_.callbacks()->streamInfo().setUpstreamSslConnection( - info.downstreamAddressProvider().sslConnection()); + upstream_info.setUpstreamLocalAddress(upstream_local_address); + upstream_info.setUpstreamSslConnection(info.downstreamAddressProvider().sslConnection()); if (info.downstreamAddressProvider().connectionID().has_value()) { - stream_info_.setUpstreamConnectionId(info.downstreamAddressProvider().connectionID().value()); - parent_.callbacks()->streamInfo().setUpstreamConnectionId( - info.downstreamAddressProvider().connectionID().value()); + upstream_info.setUpstreamConnectionId(info.downstreamAddressProvider().connectionID().value()); } stream_info_.setUpstreamBytesMeter(upstream_->bytesMeter()); @@ -478,7 +472,7 @@ void UpstreamRequest::onPoolReady( span_->injectContext(*parent_.downstreamHeaders()); } - upstream_timing_.onFirstUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); + upstreamTiming().onFirstUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); // Make sure that when we are forwarding CONNECT payload we do not do so until // the upstream has accepted the CONNECT request. @@ -549,7 +543,7 @@ void UpstreamRequest::encodeBodyAndTrailers() { } if (encode_complete_) { - upstream_timing_.onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); + upstreamTiming().onLastUpstreamTxByteSent(parent_.callbacks()->dispatcher().timeSource()); } } } diff --git a/source/common/router/upstream_request.h b/source/common/router/upstream_request.h index c5a6272f470e6..de02565a67586 100644 --- a/source/common/router/upstream_request.h +++ b/source/common/router/upstream_request.h @@ -104,7 +104,6 @@ class UpstreamRequest : public Logger::Loggable, outlier_detection_timeout_recorded_ = recorded; } bool outlierDetectionTimeoutRecorded() { return outlier_detection_timeout_recorded_; } - const StreamInfo::UpstreamTiming& upstreamTiming() { return upstream_timing_; } void retried(bool value) { retried_ = value; } bool retried() { return retried_; } bool grpcRqSuccessDeferred() { return grpc_rq_success_deferred_; } @@ -122,6 +121,9 @@ class UpstreamRequest : public Logger::Loggable, StreamInfo::StreamInfo& streamInfo() { return stream_info_; } private: + StreamInfo::UpstreamTiming& upstreamTiming() { + return stream_info_.upstreamInfo()->upstreamTiming(); + } bool shouldSendEndStream() { // Only encode end stream if the full request has been received, the body // has been sent, and any trailers or metadata have also been sent. @@ -147,7 +149,6 @@ class UpstreamRequest : public Logger::Loggable, DownstreamWatermarkManager downstream_watermark_manager_{*this}; Tracing::SpanPtr span_; StreamInfo::StreamInfoImpl stream_info_; - StreamInfo::UpstreamTiming upstream_timing_; const MonotonicTime start_time_; // This is wrapped in an optional, since we want to avoid computing zero size headers when in // reality we just didn't get a response back. diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 9fdc38fb6d39f..93911c54067e1 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -47,9 +47,6 @@ struct UpstreamInfoImpl : public UpstreamInfo { Ssl::ConnectionInfoConstSharedPtr upstreamSslConnection() const override { return upstream_ssl_info_; } - void setUpstreamTiming(const UpstreamTiming& upstream_timing) override { - upstream_timing_ = upstream_timing; - } UpstreamTiming& upstreamTiming() override { return upstream_timing_; } const UpstreamTiming& upstreamTiming() const override { return upstream_timing_; } const Network::Address::InstanceConstSharedPtr& upstreamLocalAddress() const override { @@ -129,90 +126,16 @@ struct StreamInfoImpl : public StreamInfo { start_time_monotonic_); } - void maybeCreateUpstreamInfo() { - if (!upstream_info_) { - upstream_info_ = std::make_shared(); - } - } - - void setUpstreamConnectionId(uint64_t id) override { - maybeCreateUpstreamInfo(); - upstream_info_->setUpstreamConnectionId(id); - } - - absl::optional upstreamConnectionId() const override { - if (!upstream_info_) { - return absl::nullopt; - } - return upstream_info_->upstreamConnectionId(); - } - - absl::optional lastDownstreamRxByteReceived() const override { - if (!downstream_timing_.has_value()) { - return absl::nullopt; - } - return duration(downstream_timing_.value().lastDownstreamRxByteReceived()); - } - - void setUpstreamTiming(const UpstreamTiming& upstream_timing) override { - maybeCreateUpstreamInfo(); - upstream_info_->setUpstreamTiming(upstream_timing); - } - void setUpstreamInfo(std::shared_ptr info) override { upstream_info_ = info; } + std::shared_ptr upstreamInfo() override { return upstream_info_; } + OptRef upstreamInfo() const override { if (!upstream_info_) { return {}; } return *upstream_info_; } - UpstreamTiming& upstreamTiming() override { - maybeCreateUpstreamInfo(); - return upstream_info_->upstreamTiming(); - } - - absl::optional firstUpstreamTxByteSent() const override { - if (!upstream_info_) { - return absl::nullopt; - } - return duration(upstream_info_->upstreamTiming().first_upstream_tx_byte_sent_); - } - - absl::optional lastUpstreamTxByteSent() const override { - if (!upstream_info_) { - return absl::nullopt; - } - return duration(upstream_info_->upstreamTiming().last_upstream_tx_byte_sent_); - } - - absl::optional firstUpstreamRxByteReceived() const override { - if (!upstream_info_) { - return absl::nullopt; - } - return duration(upstream_info_->upstreamTiming().first_upstream_rx_byte_received_); - } - - absl::optional lastUpstreamRxByteReceived() const override { - if (!upstream_info_) { - return absl::nullopt; - } - return duration(upstream_info_->upstreamTiming().last_upstream_rx_byte_received_); - } - - absl::optional firstDownstreamTxByteSent() const override { - if (!downstream_timing_.has_value()) { - return absl::nullopt; - } - return duration(downstream_timing_.value().firstDownstreamTxByteSent()); - } - - absl::optional lastDownstreamTxByteSent() const override { - if (!downstream_timing_.has_value()) { - return absl::nullopt; - } - return duration(downstream_timing_.value().lastDownstreamTxByteSent()); - } absl::optional requestComplete() const override { return duration(final_time_); @@ -229,6 +152,12 @@ struct StreamInfoImpl : public StreamInfo { } return downstream_timing_.value(); } + OptRef downstreamTiming() const override { + if (!downstream_timing_.has_value()) { + return {}; + } + return {*downstream_timing_}; + } void addBytesReceived(uint64_t bytes_received) override { bytes_received_ += bytes_received; } @@ -274,18 +203,6 @@ struct StreamInfoImpl : public StreamInfo { uint64_t responseFlags() const override { return response_flags_; } - void onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) override { - maybeCreateUpstreamInfo(); - upstream_info_->setUpstreamHost(host); - } - - Upstream::HostDescriptionConstSharedPtr upstreamHost() const override { - if (!upstream_info_) { - return nullptr; - } - return upstream_info_->upstreamHost(); - } - void setRouteName(absl::string_view route_name) override { route_name_ = std::string(route_name); } @@ -300,19 +217,6 @@ struct StreamInfoImpl : public StreamInfo { return virtual_cluster_name_; } - void setUpstreamLocalAddress( - const Network::Address::InstanceConstSharedPtr& upstream_local_address) override { - maybeCreateUpstreamInfo(); - upstream_info_->setUpstreamLocalAddress(upstream_local_address); - } - - const Network::Address::InstanceConstSharedPtr& upstreamLocalAddress() const override { - if (!upstream_info_) { - return legacy_upstream_local_address_; - } - return upstream_info_->upstreamLocalAddress(); - } - bool healthCheck() const override { return health_check_request_; } void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } @@ -321,15 +225,6 @@ struct StreamInfoImpl : public StreamInfo { return *downstream_connection_info_provider_; } - void setUpstreamSslConnection(const Ssl::ConnectionInfoConstSharedPtr& connection_info) override { - maybeCreateUpstreamInfo(); - upstream_info_->setUpstreamSslConnection(connection_info); - } - - Ssl::ConnectionInfoConstSharedPtr upstreamSslConnection() const override { - return upstream_info_ ? upstream_info_->upstreamSslConnection() : nullptr; - } - Router::RouteConstSharedPtr route() const override { return route_; } envoy::config::core::v3::Metadata& dynamicMetadata() override { return metadata_; }; @@ -342,29 +237,6 @@ struct StreamInfoImpl : public StreamInfo { const FilterStateSharedPtr& filterState() override { return filter_state_; } const FilterState& filterState() const override { return *filter_state_; } - const FilterStateSharedPtr& upstreamFilterState() const override { - if (!upstream_info_) { - return legacy_upstream_filter_state_; - } - return upstream_info_->upstreamFilterState(); - } - void setUpstreamFilterState(const FilterStateSharedPtr& filter_state) override { - maybeCreateUpstreamInfo(); - return upstream_info_->setUpstreamFilterState(filter_state); - } - - void setUpstreamTransportFailureReason(absl::string_view failure_reason) override { - maybeCreateUpstreamInfo(); - upstream_info_->setUpstreamTransportFailureReason(failure_reason); - } - - const std::string& upstreamTransportFailureReason() const override { - if (!upstream_info_) { - return legacy_upstream_transport_failure_reason_; - } - return upstream_info_->upstreamTransportFailureReason(); - } - void setRequestHeaders(const Http::RequestHeaderMap& headers) override { request_headers_ = &headers; } @@ -448,7 +320,6 @@ struct StreamInfoImpl : public StreamInfo { Router::RouteConstSharedPtr route_; envoy::config::core::v3::Metadata metadata_{}; FilterStateSharedPtr filter_state_; - FilterStateSharedPtr legacy_upstream_filter_state_; std::string route_name_; absl::optional attempt_count_; // TODO(agrawroh): Check if the owner of this storage outlives the StreamInfo. We should only copy @@ -477,12 +348,10 @@ struct StreamInfoImpl : public StreamInfo { std::shared_ptr upstream_info_; uint64_t bytes_received_{}; uint64_t bytes_sent_{}; - Network::Address::InstanceConstSharedPtr legacy_upstream_local_address_; const Network::ConnectionInfoProviderSharedPtr downstream_connection_info_provider_; const Http::RequestHeaderMap* request_headers_{}; Http::RequestIdStreamInfoProviderSharedPtr request_id_provider_; absl::optional downstream_timing_; - std::string legacy_upstream_transport_failure_reason_; absl::optional upstream_cluster_info_; std::string filter_chain_name_; Tracing::Reason trace_reason_; diff --git a/source/common/stream_info/utility.cc b/source/common/stream_info/utility.cc index bda0687672900..00c84c6bbe39f 100644 --- a/source/common/stream_info/utility.cc +++ b/source/common/stream_info/utility.cc @@ -43,6 +43,79 @@ absl::optional ResponseFlagUtils::toResponseFlag(absl::string_view return absl::nullopt; } +OptRef getUpstreamTiming(const StreamInfo& stream_info) { + OptRef info = stream_info.upstreamInfo(); + if (!info.has_value()) { + return {}; + } + return info.value().get().upstreamTiming(); +} + +absl::optional duration(const absl::optional& time, + const StreamInfo& stream_info) { + if (!time.has_value()) { + return absl::nullopt; + } + return std::chrono::duration_cast(time.value() - + stream_info.startTimeMonotonic()); +} + +absl::optional TimingUtility::firstUpstreamTxByteSent() { + OptRef timing = getUpstreamTiming(stream_info_); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().first_upstream_tx_byte_sent_, stream_info_); +} + +absl::optional TimingUtility::lastUpstreamTxByteSent() { + OptRef timing = getUpstreamTiming(stream_info_); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().last_upstream_tx_byte_sent_, stream_info_); +} + +absl::optional TimingUtility::firstUpstreamRxByteReceived() { + OptRef timing = getUpstreamTiming(stream_info_); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().first_upstream_rx_byte_received_, stream_info_); +} + +absl::optional TimingUtility::lastUpstreamRxByteReceived() { + OptRef timing = getUpstreamTiming(stream_info_); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().last_upstream_rx_byte_received_, stream_info_); +} + +absl::optional TimingUtility::firstDownstreamTxByteSent() { + OptRef timing = stream_info_.downstreamTiming(); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().firstDownstreamTxByteSent(), stream_info_); +} + +absl::optional TimingUtility::lastDownstreamTxByteSent() { + OptRef timing = stream_info_.downstreamTiming(); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().lastDownstreamTxByteSent(), stream_info_); +} + +absl::optional TimingUtility::lastDownstreamRxByteReceived() { + OptRef timing = stream_info_.downstreamTiming(); + if (!timing) { + return absl::nullopt; + } + return duration(timing.value().get().lastDownstreamRxByteReceived(), stream_info_); +} + const std::string& Utility::formatDownstreamAddressNoPort(const Network::Address::Instance& address) { if (address.type() == Network::Address::Type::Ip) { diff --git a/source/common/stream_info/utility.h b/source/common/stream_info/utility.h index f6c39b8bd25a5..4c38b01f5414a 100644 --- a/source/common/stream_info/utility.h +++ b/source/common/stream_info/utility.h @@ -83,6 +83,22 @@ class ResponseFlagUtils { static absl::flat_hash_map getFlagMap(); }; +class TimingUtility { +public: + TimingUtility(const StreamInfo& info) : stream_info_(info) {} + + absl::optional firstUpstreamTxByteSent(); + absl::optional lastUpstreamTxByteSent(); + absl::optional firstUpstreamRxByteReceived(); + absl::optional lastUpstreamRxByteReceived(); + absl::optional firstDownstreamTxByteSent(); + absl::optional lastDownstreamTxByteSent(); + absl::optional lastDownstreamRxByteReceived(); + +private: + const StreamInfo& stream_info_; +}; + /** * Utility class for StreamInfo. */ diff --git a/source/common/tcp_proxy/tcp_proxy.cc b/source/common/tcp_proxy/tcp_proxy.cc index 4dd925c34cdc0..7f0e231fa1829 100644 --- a/source/common/tcp_proxy/tcp_proxy.cc +++ b/source/common/tcp_proxy/tcp_proxy.cc @@ -88,7 +88,6 @@ Config::Config(const envoy::extensions::filters::network::tcp_proxy::v3::TcpProx upstream_drain_manager_slot_(context.threadLocal().allocateSlot()), shared_config_(std::make_shared(config, context)), random_generator_(context.api().randomGenerator()) { - upstream_drain_manager_slot_->set([](Event::Dispatcher&) { ThreadLocal::ThreadLocalObjectSharedPtr drain_manager = std::make_shared(); @@ -196,7 +195,7 @@ void Filter::initialize(Network::ReadFilterCallbacks& callbacks, bool set_connec // in onData(). This will get re-enabled when the upstream connection is // established. read_callbacks_->connection().readDisable(true); - + getStreamInfo().setUpstreamInfo(std::make_shared()); config_->stats().downstream_cx_total_.inc(); if (set_connection_stats) { read_callbacks_->connection().setConnectionStats( @@ -439,7 +438,7 @@ void Filter::onGenericPoolFailure(ConnectionPool::PoolFailureReason reason, Upstream::HostDescriptionConstSharedPtr host) { generic_conn_pool_.reset(); read_callbacks_->upstreamHost(host); - getStreamInfo().onUpstreamHostSelected(host); + getStreamInfo().upstreamInfo()->setUpstreamHost(host); switch (reason) { case ConnectionPool::PoolFailureReason::Overflow: @@ -468,13 +467,14 @@ void Filter::onGenericPoolReady(StreamInfo::StreamInfo* info, upstream_ = std::move(upstream); generic_conn_pool_.reset(); read_callbacks_->upstreamHost(host); - getStreamInfo().onUpstreamHostSelected(host); - getStreamInfo().setUpstreamLocalAddress(local_address); - getStreamInfo().setUpstreamSslConnection(ssl_info); + StreamInfo::UpstreamInfo& upstream_info = *getStreamInfo().upstreamInfo(); + upstream_info.setUpstreamHost(host); + upstream_info.setUpstreamLocalAddress(local_address); + upstream_info.setUpstreamSslConnection(ssl_info); onUpstreamConnection(); read_callbacks_->continueReading(); if (info) { - read_callbacks_->connection().streamInfo().setUpstreamFilterState(info->filterState()); + upstream_info.setUpstreamFilterState(info->filterState()); } } diff --git a/source/common/tracing/http_tracer_impl.cc b/source/common/tracing/http_tracer_impl.cc index 84e7168a68e92..d9ed9a86d18a6 100644 --- a/source/common/tracing/http_tracer_impl.cc +++ b/source/common/tracing/http_tracer_impl.cc @@ -95,39 +95,40 @@ template static void addGrpcResponseTags(Span& span, const T& headers) static void annotateVerbose(Span& span, const StreamInfo::StreamInfo& stream_info) { const auto start_time = stream_info.startTime(); - if (stream_info.lastDownstreamRxByteReceived()) { + StreamInfo::TimingUtility timing(stream_info); + if (timing.lastDownstreamRxByteReceived()) { span.log(start_time + std::chrono::duration_cast( - *stream_info.lastDownstreamRxByteReceived()), + *timing.lastDownstreamRxByteReceived()), Tracing::Logs::get().LastDownstreamRxByteReceived); } - if (stream_info.firstUpstreamTxByteSent()) { + if (timing.firstUpstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast( - *stream_info.firstUpstreamTxByteSent()), + *timing.firstUpstreamTxByteSent()), Tracing::Logs::get().FirstUpstreamTxByteSent); } - if (stream_info.lastUpstreamTxByteSent()) { - span.log(start_time + std::chrono::duration_cast( - *stream_info.lastUpstreamTxByteSent()), + if (timing.lastUpstreamTxByteSent()) { + span.log(start_time + + std::chrono::duration_cast(*timing.lastUpstreamTxByteSent()), Tracing::Logs::get().LastUpstreamTxByteSent); } - if (stream_info.firstUpstreamRxByteReceived()) { + if (timing.firstUpstreamRxByteReceived()) { span.log(start_time + std::chrono::duration_cast( - *stream_info.firstUpstreamRxByteReceived()), + *timing.firstUpstreamRxByteReceived()), Tracing::Logs::get().FirstUpstreamRxByteReceived); } - if (stream_info.lastUpstreamRxByteReceived()) { + if (timing.lastUpstreamRxByteReceived()) { span.log(start_time + std::chrono::duration_cast( - *stream_info.lastUpstreamRxByteReceived()), + *timing.lastUpstreamRxByteReceived()), Tracing::Logs::get().LastUpstreamRxByteReceived); } - if (stream_info.firstDownstreamTxByteSent()) { + if (timing.firstDownstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast( - *stream_info.firstDownstreamTxByteSent()), + *timing.firstDownstreamTxByteSent()), Tracing::Logs::get().FirstDownstreamTxByteSent); } - if (stream_info.lastDownstreamTxByteSent()) { + if (timing.lastDownstreamTxByteSent()) { span.log(start_time + std::chrono::duration_cast( - *stream_info.lastDownstreamTxByteSent()), + *timing.lastDownstreamTxByteSent()), Tracing::Logs::get().LastDownstreamTxByteSent); } } @@ -197,9 +198,9 @@ void HttpTracerUtility::finalizeUpstreamSpan(Span& span, Tracing::Tags::get().HttpProtocol, Formatter::SubstitutionFormatUtils::protocolToStringOrDefault(stream_info.protocol())); - if (stream_info.upstreamHost()) { + if (stream_info.upstreamInfo() && stream_info.upstreamInfo()->upstreamHost()) { span.setTag(Tracing::Tags::get().UpstreamAddress, - stream_info.upstreamHost()->address()->asStringView()); + stream_info.upstreamInfo()->upstreamHost()->address()->asStringView()); } setCommonTags(span, response_headers, response_trailers, stream_info, tracing_config); @@ -214,10 +215,11 @@ void HttpTracerUtility::setCommonTags(Span& span, const Http::ResponseHeaderMap* span.setTag(Tracing::Tags::get().Component, Tracing::Tags::get().Proxy); - if (nullptr != stream_info.upstreamHost()) { - span.setTag(Tracing::Tags::get().UpstreamCluster, stream_info.upstreamHost()->cluster().name()); + if (stream_info.upstreamInfo() && stream_info.upstreamInfo()->upstreamHost()) { + span.setTag(Tracing::Tags::get().UpstreamCluster, + stream_info.upstreamInfo()->upstreamHost()->cluster().name()); span.setTag(Tracing::Tags::get().UpstreamClusterName, - stream_info.upstreamHost()->cluster().observabilityName()); + stream_info.upstreamInfo()->upstreamHost()->cluster().observabilityName()); } // Post response data. @@ -350,21 +352,27 @@ void MetadataCustomTag::apply(Span& span, const CustomTagContext& ctx) const { const envoy::config::core::v3::Metadata* MetadataCustomTag::metadata(const CustomTagContext& ctx) const { - const StreamInfo::StreamInfo& info = ctx.stream_info; + const StreamInfo::StreamInfo& stream_info = ctx.stream_info; switch (kind_) { case envoy::type::metadata::v3::MetadataKind::KindCase::kRequest: - return &info.dynamicMetadata(); + return &stream_info.dynamicMetadata(); case envoy::type::metadata::v3::MetadataKind::KindCase::kRoute: { - Router::RouteConstSharedPtr route = info.route(); + Router::RouteConstSharedPtr route = stream_info.route(); return route ? &route->metadata() : nullptr; } case envoy::type::metadata::v3::MetadataKind::KindCase::kCluster: { - const auto& hostPtr = info.upstreamHost(); - return hostPtr ? &hostPtr->cluster().metadata() : nullptr; + if (stream_info.upstreamInfo().has_value() && + stream_info.upstreamInfo().value().get().upstreamHost()) { + return &stream_info.upstreamInfo().value().get().upstreamHost()->cluster().metadata(); + } + return nullptr; } case envoy::type::metadata::v3::MetadataKind::KindCase::kHost: { - const auto& hostPtr = info.upstreamHost(); - return hostPtr ? hostPtr->metadata().get() : nullptr; + if (stream_info.upstreamInfo().has_value() && + stream_info.upstreamInfo().value().get().upstreamHost()) { + return stream_info.upstreamInfo().value().get().upstreamHost()->metadata().get(); + } + return nullptr; } default: NOT_REACHED_GCOVR_EXCL_LINE; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index 6bb52b6b90ca0..ebd9b4c6e4c7d 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -298,7 +298,8 @@ void HttpHealthCheckerImpl::HttpActiveHealthCheckSession::onInterval() { host_->transportSocketFactory().implementsSecureTransport()); StreamInfo::StreamInfoImpl stream_info(protocol_, parent_.dispatcher_.timeSource(), local_connection_info_provider_); - stream_info.onUpstreamHostSelected(host_); + stream_info.setUpstreamInfo(std::make_shared()); + stream_info.upstreamInfo()->setUpstreamHost(host_); parent_.request_headers_parser_->evaluateHeaders(*request_headers, stream_info); auto status = request_encoder->encodeHeaders(*request_headers, true); // Encoding will only fail if required request headers are missing. diff --git a/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc b/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc index 01ccb77d85fc6..408173a16ebbf 100644 --- a/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc +++ b/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc @@ -5,6 +5,7 @@ #include "envoy/upstream/upstream.h" #include "source/common/network/utility.h" +#include "source/common/stream_info/utility.h" namespace Envoy { namespace Extensions { @@ -201,68 +202,72 @@ void Utility::extractCommonAccessLogProperties( stream_info.startTime().time_since_epoch()) .count())); - absl::optional dur = stream_info.lastDownstreamRxByteReceived(); + StreamInfo::TimingUtility timing(stream_info); + absl::optional dur = timing.lastDownstreamRxByteReceived(); if (dur) { common_access_log.mutable_time_to_last_rx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - dur = stream_info.firstUpstreamTxByteSent(); + dur = timing.firstUpstreamTxByteSent(); if (dur) { common_access_log.mutable_time_to_first_upstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - dur = stream_info.lastUpstreamTxByteSent(); + dur = timing.lastUpstreamTxByteSent(); if (dur) { common_access_log.mutable_time_to_last_upstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - dur = stream_info.firstUpstreamRxByteReceived(); + dur = timing.firstUpstreamRxByteReceived(); if (dur) { common_access_log.mutable_time_to_first_upstream_rx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - dur = stream_info.lastUpstreamRxByteReceived(); + dur = timing.lastUpstreamRxByteReceived(); if (dur) { common_access_log.mutable_time_to_last_upstream_rx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - dur = stream_info.firstDownstreamTxByteSent(); + dur = timing.firstDownstreamTxByteSent(); if (dur) { common_access_log.mutable_time_to_first_downstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - dur = stream_info.lastDownstreamTxByteSent(); + dur = timing.lastDownstreamTxByteSent(); if (dur) { common_access_log.mutable_time_to_last_downstream_tx_byte()->MergeFrom( Protobuf::util::TimeUtil::NanosecondsToDuration(dur.value().count())); } - if (stream_info.upstreamHost() != nullptr) { - Network::Utility::addressToProtobufAddress( - *stream_info.upstreamHost()->address(), - *common_access_log.mutable_upstream_remote_address()); - common_access_log.set_upstream_cluster(stream_info.upstreamHost()->cluster().name()); + if (stream_info.upstreamInfo().has_value()) { + const auto& upstream_info = stream_info.upstreamInfo().value().get(); + if (upstream_info.upstreamHost() != nullptr) { + Network::Utility::addressToProtobufAddress( + *upstream_info.upstreamHost()->address(), + *common_access_log.mutable_upstream_remote_address()); + common_access_log.set_upstream_cluster(upstream_info.upstreamHost()->cluster().name()); + } + if (upstream_info.upstreamLocalAddress() != nullptr) { + Network::Utility::addressToProtobufAddress( + *upstream_info.upstreamLocalAddress(), + *common_access_log.mutable_upstream_local_address()); + } + if (!upstream_info.upstreamTransportFailureReason().empty()) { + common_access_log.set_upstream_transport_failure_reason( + upstream_info.upstreamTransportFailureReason()); + } } - if (!stream_info.getRouteName().empty()) { common_access_log.set_route_name(stream_info.getRouteName()); } - if (stream_info.upstreamLocalAddress() != nullptr) { - Network::Utility::addressToProtobufAddress(*stream_info.upstreamLocalAddress(), - *common_access_log.mutable_upstream_local_address()); - } responseFlagsToAccessLogResponseFlags(common_access_log, stream_info); - if (!stream_info.upstreamTransportFailureReason().empty()) { - common_access_log.set_upstream_transport_failure_reason( - stream_info.upstreamTransportFailureReason()); - } if (stream_info.dynamicMetadata().filter_metadata_size() > 0) { common_access_log.mutable_metadata()->MergeFrom(stream_info.dynamicMetadata()); } diff --git a/source/extensions/common/wasm/context.cc b/source/extensions/common/wasm/context.cc index d3db5864dd47b..28b962fdd5638 100644 --- a/source/extensions/common/wasm/context.cc +++ b/source/extensions/common/wasm/context.cc @@ -88,6 +88,13 @@ Http::RequestHeaderMapPtr buildRequestHeaderMapFromPairs(const Pairs& pairs) { template static uint32_t headerSize(const P& p) { return p ? p->size() : 0; } +Upstream::HostDescriptionConstSharedPtr getHost(const StreamInfo::StreamInfo* info) { + if (info && info->upstreamInfo() && info->upstreamInfo().value().get().upstreamHost()) { + return info->upstreamInfo().value().get().upstreamHost(); + } + return nullptr; +} + } // namespace // Test support. @@ -443,9 +450,12 @@ Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) co const CelState* state; if (info->filterState().hasData(key)) { state = &info->filterState().getDataReadOnly(key); - } else if (info->upstreamFilterState() && - info->upstreamFilterState()->hasData(key)) { - state = &info->upstreamFilterState()->getDataReadOnly(key); + } else if (info->upstreamInfo().has_value() && + info->upstreamInfo().value().get().upstreamFilterState() && + info->upstreamInfo().value().get().upstreamFilterState()->hasData(key)) { + state = + &info->upstreamInfo().value().get().upstreamFilterState()->getDataReadOnly( + key); } else { return {}; } @@ -522,8 +532,8 @@ Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) co } break; case PropertyToken::CLUSTER_NAME: - if (info && info->upstreamHost()) { - return CelValue::CreateString(&info->upstreamHost()->cluster().name()); + if (getHost(info)) { + return CelValue::CreateString(&getHost(info)->cluster().name()); } else if (info && info->route() && info->route()->routeEntry()) { return CelValue::CreateString(&info->route()->routeEntry()->clusterName()); } else if (info && info->upstreamClusterInfo().has_value() && @@ -532,8 +542,8 @@ Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) co } break; case PropertyToken::CLUSTER_METADATA: - if (info && info->upstreamHost()) { - return CelProtoWrapper::CreateMessage(&info->upstreamHost()->cluster().metadata(), arena); + if (getHost(info)) { + return CelProtoWrapper::CreateMessage(&getHost(info)->cluster().metadata(), arena); } else if (info && info->upstreamClusterInfo().has_value() && info->upstreamClusterInfo().value()) { return CelProtoWrapper::CreateMessage(&info->upstreamClusterInfo().value()->metadata(), @@ -541,8 +551,8 @@ Context::findValue(absl::string_view name, Protobuf::Arena* arena, bool last) co } break; case PropertyToken::UPSTREAM_HOST_METADATA: - if (info && info->upstreamHost() && info->upstreamHost()->metadata()) { - return CelProtoWrapper::CreateMessage(info->upstreamHost()->metadata().get(), arena); + if (getHost(info)) { + return CelProtoWrapper::CreateMessage(getHost(info)->metadata().get(), arena); } break; case PropertyToken::ROUTE_NAME: diff --git a/source/extensions/filters/common/expr/context.cc b/source/extensions/filters/common/expr/context.cc index ac0a47bd98d33..b2c4ed14eae3d 100644 --- a/source/extensions/filters/common/expr/context.cc +++ b/source/extensions/filters/common/expr/context.cc @@ -208,31 +208,32 @@ absl::optional ConnectionWrapper::operator[](CelValue key) const { } absl::optional UpstreamWrapper::operator[](CelValue key) const { - if (!key.IsString()) { + if (!key.IsString() || !info_.upstreamInfo().has_value()) { return {}; } auto value = key.StringOrDie().value(); if (value == Address) { - auto upstream_host = info_.upstreamHost(); + auto upstream_host = info_.upstreamInfo().value().get().upstreamHost(); if (upstream_host != nullptr && upstream_host->address() != nullptr) { return CelValue::CreateStringView(upstream_host->address()->asStringView()); } } else if (value == Port) { - auto upstream_host = info_.upstreamHost(); + auto upstream_host = info_.upstreamInfo().value().get().upstreamHost(); if (upstream_host != nullptr && upstream_host->address() != nullptr && upstream_host->address()->ip() != nullptr) { return CelValue::CreateInt64(upstream_host->address()->ip()->port()); } } else if (value == UpstreamLocalAddress) { - auto upstream_local_address = info_.upstreamLocalAddress(); + auto upstream_local_address = info_.upstreamInfo().value().get().upstreamLocalAddress(); if (upstream_local_address != nullptr) { return CelValue::CreateStringView(upstream_local_address->asStringView()); } } else if (value == UpstreamTransportFailureReason) { - return CelValue::CreateStringView(info_.upstreamTransportFailureReason()); + return CelValue::CreateStringView( + info_.upstreamInfo().value().get().upstreamTransportFailureReason()); } - auto ssl_info = info_.upstreamSslConnection(); + auto ssl_info = info_.upstreamInfo().value().get().upstreamSslConnection(); if (ssl_info != nullptr) { return extractSslInfo(*ssl_info, value); } diff --git a/source/extensions/filters/http/alternate_protocols_cache/filter.cc b/source/extensions/filters/http/alternate_protocols_cache/filter.cc index 2d87b6fbef7a1..663b79b3d3fd5 100644 --- a/source/extensions/filters/http/alternate_protocols_cache/filter.cc +++ b/source/extensions/filters/http/alternate_protocols_cache/filter.cc @@ -64,7 +64,8 @@ Http::FilterHeadersStatus Filter::encodeHeaders(Http::ResponseHeaderMap& headers // Envoy routes request to upstream hosts not to origin servers directly. This choice would // allow HTTP/3 to be used on a per-upstream host basis, even for origins which are load // balanced across them. - Upstream::HostDescriptionConstSharedPtr host = encoder_callbacks_->streamInfo().upstreamHost(); + Upstream::HostDescriptionConstSharedPtr host = + encoder_callbacks_->streamInfo().upstreamInfo()->upstreamHost(); const uint32_t port = host->address()->ip()->port(); const std::string& hostname = host->hostname(); Http::AlternateProtocolsCache::Origin origin(Http::Headers::get().SchemeValues.Https, hostname, diff --git a/source/extensions/filters/http/grpc_stats/BUILD b/source/extensions/filters/http/grpc_stats/BUILD index d3727239b7106..d2836eea5524a 100644 --- a/source/extensions/filters/http/grpc_stats/BUILD +++ b/source/extensions/filters/http/grpc_stats/BUILD @@ -22,6 +22,7 @@ envoy_cc_extension( "//source/common/grpc:common_lib", "//source/common/grpc:context_lib", "//source/common/runtime:runtime_lib", + "//source/common/stream_info:utility_lib", "//source/extensions/filters/http/common:factory_base_lib", "//source/extensions/filters/http/common:pass_through_filter_lib", "@envoy_api//envoy/extensions/filters/http/grpc_stats/v3:pkg_cc_proto", diff --git a/source/extensions/filters/http/grpc_stats/grpc_stats_filter.cc b/source/extensions/filters/http/grpc_stats/grpc_stats_filter.cc index 7280a419d21da..3e604ddf1f4f4 100644 --- a/source/extensions/filters/http/grpc_stats/grpc_stats_filter.cc +++ b/source/extensions/filters/http/grpc_stats/grpc_stats_filter.cc @@ -9,6 +9,7 @@ #include "source/common/grpc/context_impl.h" #include "source/common/runtime/runtime_impl.h" #include "source/common/stats/symbol_table_impl.h" +#include "source/common/stream_info/utility.h" #include "source/extensions/filters/http/common/pass_through_filter.h" namespace Envoy { @@ -254,13 +255,16 @@ class GrpcStatsFilter : public Http::PassThroughFilter { } void maybeChargeUpstreamStat() { - if (config_->enable_upstream_stats_ && - decoder_callbacks_->streamInfo().lastUpstreamTxByteSent().has_value() && - decoder_callbacks_->streamInfo().lastUpstreamRxByteReceived().has_value()) { + if (!config_->enable_upstream_stats_) { + return; + } + StreamInfo::TimingUtility timing(decoder_callbacks_->streamInfo()); + if (config_->enable_upstream_stats_ && timing.lastUpstreamTxByteSent().has_value() && + timing.lastUpstreamRxByteReceived().has_value()) { std::chrono::milliseconds chrono_duration = std::chrono::duration_cast( - decoder_callbacks_->streamInfo().lastUpstreamRxByteReceived().value() - - decoder_callbacks_->streamInfo().lastUpstreamTxByteSent().value()); + timing.lastUpstreamRxByteReceived().value() - + timing.lastUpstreamTxByteSent().value()); config_->context_.chargeUpstreamStat(*cluster_, request_names_, chrono_duration); } } diff --git a/source/extensions/transport_sockets/tls/ssl_socket.cc b/source/extensions/transport_sockets/tls/ssl_socket.cc index c94634a4c675c..d1c1229814e7d 100644 --- a/source/extensions/transport_sockets/tls/ssl_socket.cc +++ b/source/extensions/transport_sockets/tls/ssl_socket.cc @@ -180,8 +180,13 @@ Network::Connection& SslSocket::connection() const { return callbacks_->connecti void SslSocket::onSuccess(SSL* ssl) { ctx_->logHandshake(ssl); - callbacks_->connection().streamInfo().upstreamTiming().onUpstreamHandshakeComplete( - callbacks_->connection().dispatcher().timeSource()); + if (callbacks_->connection().streamInfo().upstreamInfo()) { + callbacks_->connection() + .streamInfo() + .upstreamInfo() + ->upstreamTiming() + .onUpstreamHandshakeComplete(callbacks_->connection().dispatcher().timeSource()); + } callbacks_->raiseEvent(Network::ConnectionEvent::Connected); } diff --git a/test/common/access_log/access_log_impl_test.cc b/test/common/access_log/access_log_impl_test.cc index c5b24903996df..48f8dcf72aba1 100644 --- a/test/common/access_log/access_log_impl_test.cc +++ b/test/common/access_log/access_log_impl_test.cc @@ -106,7 +106,7 @@ name: accesslog EXPECT_CALL(*file_, write(_)); auto cluster = std::make_shared>(); - stream_info_.onUpstreamHostSelected( + stream_info_.upstreamInfo()->setUpstreamHost( Upstream::makeTestHostDescription(cluster, "tcp://10.0.0.5:1234", simTime())); stream_info_.setResponseFlag(StreamInfo::ResponseFlag::DownstreamConnectionTermination); @@ -217,7 +217,7 @@ name: accesslog TEST_F(AccessLogImplTest, UpstreamHost) { auto cluster = std::make_shared>(); - stream_info_.onUpstreamHostSelected( + stream_info_.upstreamInfo()->setUpstreamHost( Upstream::makeTestHostDescription(cluster, "tcp://10.0.0.5:1234", simTime())); const std::string yaml = R"EOF( diff --git a/test/common/formatter/substitution_formatter_test.cc b/test/common/formatter/substitution_formatter_test.cc index b732fec40c261..fb0e627534e72 100644 --- a/test/common/formatter/substitution_formatter_test.cc +++ b/test/common/formatter/substitution_formatter_test.cc @@ -253,102 +253,95 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { Http::TestResponseHeaderMapImpl response_headers; Http::TestResponseTrailerMapImpl response_trailers; std::string body; + MockTimeSystem time_system; + auto& upstream_timing = stream_info.upstream_info_->upstreamTiming(); { StreamInfoFormatter request_duration_format("REQUEST_DURATION"); - absl::optional dur = std::chrono::nanoseconds(5000000); - EXPECT_CALL(stream_info, lastDownstreamRxByteReceived()).WillRepeatedly(Return(dur)); - EXPECT_EQ("5", request_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_EQ(absl::nullopt, request_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(request_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::numberValue(5.0))); + ProtoEq(ValueUtil::nullValue())); } { StreamInfoFormatter request_duration_format("REQUEST_DURATION"); - absl::optional dur; - EXPECT_CALL(stream_info, lastDownstreamRxByteReceived()).WillRepeatedly(Return(dur)); - EXPECT_EQ(absl::nullopt, request_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(5000000)))); + stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); + EXPECT_EQ("5", request_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(request_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::nullValue())); + ProtoEq(ValueUtil::numberValue(5.0))); } { StreamInfoFormatter request_tx_duration_format("REQUEST_TX_DURATION"); - absl::optional dur = std::chrono::nanoseconds(15000000); - EXPECT_CALL(stream_info, lastUpstreamTxByteSent()).WillRepeatedly(Return(dur)); - EXPECT_EQ("15", request_tx_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_EQ(absl::nullopt, + request_tx_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(request_tx_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::numberValue(15.0))); + ProtoEq(ValueUtil::nullValue())); } { StreamInfoFormatter request_tx_duration_format("REQUEST_TX_DURATION"); - absl::optional dur; - EXPECT_CALL(stream_info, lastUpstreamTxByteSent()).WillRepeatedly(Return(dur)); - EXPECT_EQ(absl::nullopt, - request_tx_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(15000000)))); + upstream_timing.onLastUpstreamTxByteSent(time_system); + EXPECT_EQ("15", request_tx_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(request_tx_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::nullValue())); + ProtoEq(ValueUtil::numberValue(15.0))); } { StreamInfoFormatter response_duration_format("RESPONSE_DURATION"); - absl::optional dur = std::chrono::nanoseconds(10000000); - EXPECT_CALL(stream_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(dur)); - EXPECT_EQ("10", response_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_EQ(absl::nullopt, response_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(response_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::numberValue(10.0))); + ProtoEq(ValueUtil::nullValue())); } { StreamInfoFormatter response_duration_format("RESPONSE_DURATION"); - absl::optional dur; - EXPECT_CALL(stream_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(dur)); - EXPECT_EQ(absl::nullopt, response_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(10000000)))); + upstream_timing.onFirstUpstreamRxByteReceived(time_system); + EXPECT_EQ("10", response_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(response_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::nullValue())); + ProtoEq(ValueUtil::numberValue(10.0))); } { StreamInfoFormatter ttlb_duration_format("RESPONSE_TX_DURATION"); - absl::optional dur_upstream = std::chrono::nanoseconds(10000000); - EXPECT_CALL(stream_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(dur_upstream)); - absl::optional dur_downstream = std::chrono::nanoseconds(25000000); - EXPECT_CALL(stream_info, lastDownstreamTxByteSent()).WillRepeatedly(Return(dur_downstream)); - - EXPECT_EQ("15", ttlb_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_EQ(absl::nullopt, ttlb_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(ttlb_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::numberValue(15.0))); + ProtoEq(ValueUtil::nullValue())); } { StreamInfoFormatter ttlb_duration_format("RESPONSE_TX_DURATION"); - absl::optional dur_upstream; - EXPECT_CALL(stream_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(dur_upstream)); - absl::optional dur_downstream; - EXPECT_CALL(stream_info, lastDownstreamTxByteSent()).WillRepeatedly(Return(dur_downstream)); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(25000000)))); + stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); - EXPECT_EQ(absl::nullopt, ttlb_duration_format.format(request_headers, response_headers, - response_trailers, stream_info, body)); + EXPECT_EQ("15", ttlb_duration_format.format(request_headers, response_headers, + response_trailers, stream_info, body)); EXPECT_THAT(ttlb_duration_format.formatValue(request_headers, response_headers, response_trailers, stream_info, body), - ProtoEq(ValueUtil::nullValue())); + ProtoEq(ValueUtil::numberValue(15.0))); } { @@ -536,8 +529,6 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { const std::string observable_cluster_name = "observability_name"; auto cluster_info_mock = std::make_shared(); absl::optional cluster_info = cluster_info_mock; - // Make sure that cluster info is obtained without calling upstreamHost. - EXPECT_CALL(stream_info, upstreamHost()).Times(0); EXPECT_CALL(stream_info, upstreamClusterInfo()).WillRepeatedly(Return(cluster_info)); EXPECT_CALL(*cluster_info_mock, observabilityName()) .WillRepeatedly(ReturnRef(observable_cluster_name)); @@ -556,8 +547,6 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { const std::string upstream_cluster_name = "cluster_name"; auto cluster_info_mock = std::make_shared(); absl::optional cluster_info = cluster_info_mock; - // Make sure that cluster info is obtained without calling upstreamHost. - EXPECT_CALL(stream_info, upstreamHost()).Times(0); EXPECT_CALL(stream_info, upstreamClusterInfo()).WillRepeatedly(Return(cluster_info)); EXPECT_CALL(*cluster_info_mock, name()).WillRepeatedly(ReturnRef(upstream_cluster_name)); EXPECT_EQ("cluster_name", upstream_format.format(request_headers, response_headers, @@ -570,8 +559,6 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { { StreamInfoFormatter upstream_format("UPSTREAM_CLUSTER"); absl::optional cluster_info = nullptr; - // Make sure that cluster info is obtained without calling upstreamHost. - EXPECT_CALL(stream_info, upstreamHost()).Times(0); EXPECT_CALL(stream_info, upstreamClusterInfo()).WillRepeatedly(Return(cluster_info)); EXPECT_EQ(absl::nullopt, upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); @@ -582,7 +569,7 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { { StreamInfoFormatter upstream_format("UPSTREAM_HOST"); - EXPECT_CALL(stream_info, upstreamHost()).WillRepeatedly(Return(nullptr)); + stream_info.upstreamInfo()->setUpstreamHost(nullptr); EXPECT_EQ(absl::nullopt, upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); EXPECT_THAT(upstream_format.formatValue(request_headers, response_headers, response_trailers, @@ -745,8 +732,8 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { { StreamInfoFormatter upstream_format("UPSTREAM_TRANSPORT_FAILURE_REASON"); std::string upstream_transport_failure_reason = "SSL error"; - EXPECT_CALL(stream_info, upstreamTransportFailureReason()) - .WillRepeatedly(ReturnRef(upstream_transport_failure_reason)); + stream_info.upstreamInfo()->setUpstreamTransportFailureReason( + upstream_transport_failure_reason); EXPECT_EQ("SSL error", upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); EXPECT_THAT(upstream_format.formatValue(request_headers, response_headers, response_trailers, @@ -756,8 +743,8 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { { StreamInfoFormatter upstream_format("UPSTREAM_TRANSPORT_FAILURE_REASON"); std::string upstream_transport_failure_reason; - EXPECT_CALL(stream_info, upstreamTransportFailureReason()) - .WillRepeatedly(ReturnRef(upstream_transport_failure_reason)); + stream_info.upstreamInfo()->setUpstreamTransportFailureReason( + upstream_transport_failure_reason); EXPECT_EQ(absl::nullopt, upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); EXPECT_THAT(upstream_format.formatValue(request_headers, response_headers, response_trailers, @@ -2658,10 +2645,12 @@ TEST(SubstitutionFormatterTest, StructFormatterTypedTest) { Http::TestRequestHeaderMapImpl request_headers; Http::TestResponseHeaderMapImpl response_headers; Http::TestResponseTrailerMapImpl response_trailers; - StreamInfo::MockStreamInfo stream_info; + NiceMock stream_info; std::string body; - EXPECT_CALL(Const(stream_info), lastDownstreamRxByteReceived()) - .WillRepeatedly(Return(std::chrono::nanoseconds(5000000))); + MockTimeSystem time_system; + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(5000000)))); + stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); ProtobufWkt::Value list; list.mutable_list_value()->add_values()->set_bool_value(true); @@ -2697,7 +2686,7 @@ TEST(SubstitutionFormatterTest, StructFormatterTypedTest) { } TEST(SubstitutionFormatterTest, JsonFormatterTest) { - StreamInfo::MockStreamInfo stream_info; + NiceMock stream_info; Http::TestRequestHeaderMapImpl request_header; Http::TestResponseHeaderMapImpl response_header; Http::TestResponseTrailerMapImpl response_trailer; @@ -2707,8 +2696,10 @@ TEST(SubstitutionFormatterTest, JsonFormatterTest) { populateMetadataTestData(metadata); absl::optional protocol = Http::Protocol::Http11; EXPECT_CALL(stream_info, protocol()).WillRepeatedly(Return(protocol)); - EXPECT_CALL(Const(stream_info), lastDownstreamRxByteReceived()) - .WillRepeatedly(Return(std::chrono::nanoseconds(5000000))); + MockTimeSystem time_system; + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(5000000)))); + stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); ProtobufWkt::Struct key_mapping; TestUtility::loadFromYaml(R"EOF( diff --git a/test/common/router/header_formatter_test.cc b/test/common/router/header_formatter_test.cc index 1970b16b2a4e3..4abe2626fcc97 100644 --- a/test/common/router/header_formatter_test.cc +++ b/test/common/router/header_formatter_test.cc @@ -106,7 +106,7 @@ TEST_F(StreamInfoHeaderFormatterTest, TestformatWithUpstreamRemoteAddressVariabl testFormatting("UPSTREAM_REMOTE_ADDRESS", "10.0.0.1:443"); NiceMock stream_info; - stream_info.host_.reset(); + stream_info.upstreamInfo()->setUpstreamHost(nullptr); testFormatting(stream_info, "UPSTREAM_REMOTE_ADDRESS", ""); } @@ -592,7 +592,7 @@ TEST_F(StreamInfoHeaderFormatterTest, TestFormatWithUpstreamMetadataVariable) { EXPECT_EQ(nested_struct.fields().at("list_key").kind_case(), ProtobufWkt::Value::kListValue); EXPECT_EQ(nested_struct.fields().at("struct_key").kind_case(), ProtobufWkt::Value::kStructValue); - ON_CALL(stream_info, upstreamHost()).WillByDefault(Return(host)); + stream_info.upstreamInfo()->setUpstreamHost(host); ON_CALL(*host, metadata()).WillByDefault(Return(metadata)); // Top-level value. @@ -666,7 +666,7 @@ TEST_F(StreamInfoHeaderFormatterTest, ValidateLimitsOnUserDefinedHeaders) { TEST_F(StreamInfoHeaderFormatterTest, TestFormatWithUpstreamMetadataVariableMissingHost) { NiceMock stream_info; std::shared_ptr> host; - ON_CALL(stream_info, upstreamHost()).WillByDefault(Return(host)); + stream_info.upstreamInfo()->setUpstreamHost(host); testFormatting(stream_info, "UPSTREAM_METADATA([\"namespace\", \"key\"])", ""); } @@ -951,7 +951,7 @@ TEST(HeaderParserTest, TestParseInternal) { std::shared_ptr> host( new NiceMock()); - ON_CALL(stream_info, upstreamHost()).WillByDefault(Return(host)); + stream_info.upstreamInfo()->setUpstreamHost(host); Http::TestRequestHeaderMapImpl request_headers; request_headers.addCopy(Http::LowerCaseString(std::string("x-request-id")), 123); @@ -1127,7 +1127,7 @@ match: { prefix: "/new_endpoint" } new NiceMock()); NiceMock stream_info; auto metadata = std::make_shared(); - ON_CALL(stream_info, upstreamHost()).WillByDefault(Return(host)); + stream_info.upstreamInfo()->setUpstreamHost(host); ON_CALL(*host, metadata()).WillByDefault(Return(metadata)); req_header_parser->evaluateHeaders(header_map, stream_info); EXPECT_FALSE(header_map.has("x-key")); @@ -1202,7 +1202,7 @@ request_headers_to_remove: ["x-nope"] std::shared_ptr> host( new NiceMock()); - ON_CALL(stream_info, upstreamHost()).WillByDefault(Return(host)); + stream_info.upstreamInfo()->setUpstreamHost(host); // Metadata with percent signs in the key. auto metadata = std::make_shared( diff --git a/test/common/router/router_2_test.cc b/test/common/router/router_2_test.cc index 4d37b31004f29..5b0d6a22634b8 100644 --- a/test/common/router/router_2_test.cc +++ b/test/common/router/router_2_test.cc @@ -280,10 +280,6 @@ TEST_F(WatermarkTest, RetryRequestNotComplete) { })); EXPECT_CALL(callbacks_.stream_info_, setResponseFlag(StreamInfo::ResponseFlag::UpstreamRemoteReset)); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillRepeatedly(Invoke([&](const Upstream::HostDescriptionConstSharedPtr& host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); Http::TestRequestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}}; HttpTestUtility::addDefaultHeaders(headers); @@ -728,10 +724,6 @@ TEST_F(RouterTestSupressGRPCStatsEnabled, ExcludeTimeoutHttpStats) { upstream_stream_info_, Http::Protocol::Http10); return nullptr; })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); expectResponseTimerCreate(); @@ -793,10 +785,6 @@ TEST_F(RouterTestSupressGRPCStatsDisabled, IncludeHttpTimeoutStats) { upstream_stream_info_, Http::Protocol::Http10); return nullptr; })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); expectResponseTimerCreate(); diff --git a/test/common/router/router_test.cc b/test/common/router/router_test.cc index ae008d6228ee5..6e247b665f651 100644 --- a/test/common/router/router_test.cc +++ b/test/common/router/router_test.cc @@ -27,6 +27,7 @@ #include "source/common/router/debug_config.h" #include "source/common/router/router.h" #include "source/common/stream_info/uint32_accessor_impl.h" +#include "source/common/stream_info/utility.h" #include "source/common/tracing/http_tracer_impl.h" #include "source/common/upstream/upstream_impl.h" @@ -361,10 +362,6 @@ TEST_F(RouterTest, PoolFailureWithPriority) { EXPECT_CALL(callbacks_, encodeData(_, true)); EXPECT_CALL(callbacks_.stream_info_, setResponseFlag(StreamInfo::ResponseFlag::UpstreamConnectionFailure)); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); Http::TestRequestHeaderMapImpl headers; HttpTestUtility::addDefaultHeaders(headers); @@ -396,10 +393,6 @@ TEST_F(RouterTest, PoolFailureDueToConnectTimeout) { EXPECT_CALL(callbacks_, encodeData(_, true)); EXPECT_CALL(callbacks_.stream_info_, setResponseFlag(StreamInfo::ResponseFlag::UpstreamConnectionFailure)); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); Http::TestRequestHeaderMapImpl headers; HttpTestUtility::addDefaultHeaders(headers); @@ -1006,10 +999,6 @@ TEST_F(RouterTest, EnvoyAttemptCountInResponsePresentWithLocalReply) { EXPECT_CALL(callbacks_, encodeData(_, true)); EXPECT_CALL(callbacks_.stream_info_, setResponseFlag(StreamInfo::ResponseFlag::UpstreamConnectionFailure)); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); Http::TestRequestHeaderMapImpl headers; HttpTestUtility::addDefaultHeaders(headers); @@ -1265,10 +1254,6 @@ TEST_F(RouterTest, UpstreamTimeout) { upstream_stream_info_, Http::Protocol::Http10); return nullptr; })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); expectResponseTimerCreate(); @@ -1902,10 +1887,6 @@ TEST_F(RouterTest, UpstreamTimeoutWithAltResponse) { upstream_stream_info_, Http::Protocol::Http10); return nullptr; })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); expectResponseTimerCreate(); @@ -1974,11 +1955,6 @@ TEST_F(RouterTest, UpstreamPerTryIdleTimeout) { Buffer::OwnedImpl data; router_.decodeData(data, true); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); - per_try_idle_timeout_ = new Event::MockTimer(&callbacks_.dispatcher_); EXPECT_CALL(*per_try_idle_timeout_, enableTimer(std::chrono::milliseconds(3000), _)); EXPECT_EQ(0U, @@ -2041,11 +2017,6 @@ TEST_F(RouterTest, UpstreamPerTryIdleTimeoutSuccess) { Buffer::OwnedImpl data; router_.decodeData(data, true); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); - per_try_idle_timeout_ = new Event::MockTimer(&callbacks_.dispatcher_); EXPECT_CALL(*per_try_idle_timeout_, enableTimer(std::chrono::milliseconds(3000), _)); EXPECT_EQ(0U, @@ -2083,11 +2054,6 @@ TEST_F(RouterTest, UpstreamPerTryTimeout) { upstream_stream_info_, Http::Protocol::Http10); return nullptr; })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); - Http::TestRequestHeaderMapImpl headers{{"x-envoy-internal", "true"}, {"x-envoy-upstream-rq-per-try-timeout-ms", "5"}}; HttpTestUtility::addDefaultHeaders(headers); @@ -2149,11 +2115,6 @@ TEST_F(RouterTest, UpstreamPerTryTimeoutDelayedPoolReady) { // Per try timeout starts when onPoolReady is called. expectPerTryTimerCreate(); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); - EXPECT_EQ(0U, callbacks_.route_->route_entry_.virtual_cluster_.stats().upstream_rq_total_.value()); pool_callbacks->onPoolReady(encoder, cm_.thread_local_cluster_.conn_pool_.host_, @@ -2198,11 +2159,6 @@ TEST_F(RouterTest, UpstreamPerTryTimeoutExcludesNewStream) { response_timeout_ = new Event::MockTimer(&callbacks_.dispatcher_); EXPECT_CALL(*response_timeout_, enableTimer(_, _)); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); - Http::TestRequestHeaderMapImpl headers{{"x-envoy-internal", "true"}, {"x-envoy-upstream-rq-per-try-timeout-ms", "5"}}; HttpTestUtility::addDefaultHeaders(headers); @@ -2548,7 +2504,7 @@ TEST_F(RouterTest, HedgedPerTryTimeoutThirdRequestSucceeds) { response_decoder3->decodeHeaders(std::move(response_headers2), true); EXPECT_TRUE(verifyHostUpstreamStats(1, 1)); - EXPECT_EQ(333U, callbacks_.stream_info_.upstream_connection_id_); + EXPECT_EQ(333U, callbacks_.stream_info_.upstreamInfo()->upstreamConnectionId()); // TODO: Verify hedge stats here once they are implemented. } @@ -3430,10 +3386,6 @@ TEST_F(RouterTest, RetryNoneHealthy) { })); expectResponseTimerCreate(); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); Http::TestRequestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}}; HttpTestUtility::addDefaultHeaders(headers); @@ -5057,7 +5009,8 @@ TEST_F(RouterTest, PropagatesUpstreamFilterState) { bool filter_state_verified = false; router_.config().upstream_logs_.push_back( std::make_shared([&](const auto& stream_info) { - filter_state_verified = stream_info.upstreamFilterState()->hasDataWithName("upstream data"); + filter_state_verified = + stream_info.upstreamInfo()->upstreamFilterState()->hasDataWithName("upstream data"); })); upstream_stream_info_.filterState()->setData( @@ -5085,7 +5038,8 @@ TEST_F(RouterTest, PropagatesUpstreamFilterState) { EXPECT_TRUE(verifyHostUpstreamStats(1, 0)); EXPECT_TRUE(filter_state_verified); - EXPECT_TRUE(callbacks_.streamInfo().upstreamFilterState()->hasDataWithName("upstream data")); + EXPECT_TRUE(callbacks_.streamInfo().upstreamInfo()->upstreamFilterState()->hasDataWithName( + "upstream data")); } TEST_F(RouterTest, UpstreamSSLConnection) { @@ -5116,12 +5070,14 @@ TEST_F(RouterTest, UpstreamSSLConnection) { Http::ResponseHeaderMapPtr response_headers( new Http::TestResponseHeaderMapImpl{{":status", "200"}}); + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) response_decoder->decodeHeaders(std::move(response_headers), true); EXPECT_TRUE(verifyHostUpstreamStats(1, 0)); - ASSERT_NE(nullptr, callbacks_.streamInfo().upstreamSslConnection()); - EXPECT_EQ(session_id, callbacks_.streamInfo().upstreamSslConnection()->sessionId()); - EXPECT_FALSE(callbacks_.streamInfo().upstreamConnectionId().has_value()); + ASSERT_NE(nullptr, callbacks_.streamInfo().upstreamInfo()->upstreamSslConnection()); + EXPECT_EQ(session_id, + callbacks_.streamInfo().upstreamInfo()->upstreamSslConnection()->sessionId()); + EXPECT_FALSE(callbacks_.streamInfo().upstreamInfo()->upstreamConnectionId().has_value()); } // Verify that upstream timing information is set into the StreamInfo after the upstream @@ -5142,10 +5098,7 @@ TEST_F(RouterTest, UpstreamTimingSingleRequest) { StreamInfo::StreamInfoImpl stream_info(test_time_.timeSystem(), nullptr); ON_CALL(callbacks_, streamInfo()).WillByDefault(ReturnRef(stream_info)); - EXPECT_FALSE(stream_info.firstUpstreamTxByteSent().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamTxByteSent().has_value()); - EXPECT_FALSE(stream_info.firstUpstreamRxByteReceived().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamRxByteReceived().has_value()); + EXPECT_EQ(nullptr, stream_info.upstreamInfo()); Http::TestRequestHeaderMapImpl headers{}; HttpTestUtility::addDefaultHeaders(headers); @@ -5159,30 +5112,32 @@ TEST_F(RouterTest, UpstreamTimingSingleRequest) { Http::ResponseHeaderMapPtr response_headers( new Http::TestResponseHeaderMapImpl{{":status", "503"}}); + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) response_decoder->decodeHeaders(std::move(response_headers), false); test_time_.advanceTimeWait(std::chrono::milliseconds(43)); - // Confirm we still have no upstream timing data. It won't be set until after the - // stream has ended. - EXPECT_FALSE(stream_info.firstUpstreamTxByteSent().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamTxByteSent().has_value()); - EXPECT_FALSE(stream_info.firstUpstreamRxByteReceived().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamRxByteReceived().has_value()); + // Upstream timing data is now available live. + ASSERT_NE(nullptr, stream_info.upstreamInfo()); + auto& upstream_timing = stream_info.upstreamInfo()->upstreamTiming(); + EXPECT_TRUE(upstream_timing.first_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.last_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.first_upstream_rx_byte_received_.has_value()); + EXPECT_FALSE(upstream_timing.last_upstream_rx_byte_received_.has_value()); response_decoder->decodeData(data, true); - // Now these should be set. - EXPECT_TRUE(stream_info.firstUpstreamTxByteSent().has_value()); - EXPECT_TRUE(stream_info.lastUpstreamTxByteSent().has_value()); - EXPECT_TRUE(stream_info.firstUpstreamRxByteReceived().has_value()); - EXPECT_TRUE(stream_info.lastUpstreamRxByteReceived().has_value()); + // Now all these should be set. + EXPECT_TRUE(upstream_timing.first_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.last_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.first_upstream_rx_byte_received_.has_value()); + EXPECT_TRUE(upstream_timing.last_upstream_rx_byte_received_.has_value()); // Timings should match our sleep() calls. - EXPECT_EQ(stream_info.lastUpstreamRxByteReceived().value() - - stream_info.firstUpstreamRxByteReceived().value(), + EXPECT_EQ(upstream_timing.last_upstream_rx_byte_received_.value() - + upstream_timing.first_upstream_rx_byte_received_.value(), std::chrono::milliseconds(43)); - EXPECT_EQ(stream_info.lastUpstreamTxByteSent().value() - - stream_info.firstUpstreamTxByteSent().value(), + EXPECT_EQ(upstream_timing.last_upstream_tx_byte_sent_.value() - + upstream_timing.first_upstream_tx_byte_sent_.value(), std::chrono::milliseconds(32)); } @@ -5230,14 +5185,10 @@ TEST_F(RouterTest, UpstreamTimingRetry) { return nullptr; })); - // Check that upstream timing is not set when a retry will occur. Http::ResponseHeaderMapPtr bad_response_headers( new Http::TestResponseHeaderMapImpl{{":status", "503"}}); + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) response_decoder->decodeHeaders(std::move(bad_response_headers), true); - EXPECT_FALSE(stream_info.firstUpstreamTxByteSent().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamTxByteSent().has_value()); - EXPECT_FALSE(stream_info.firstUpstreamRxByteReceived().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamRxByteReceived().has_value()); router_.retry_state_->callback_(); EXPECT_CALL(*router_.retry_state_, shouldRetryHeaders(_, _)).WillOnce(Return(RetryStatus::No)); @@ -5251,25 +5202,26 @@ TEST_F(RouterTest, UpstreamTimingRetry) { response_decoder->decodeData(data, true); - EXPECT_TRUE(stream_info.firstUpstreamTxByteSent().has_value()); - EXPECT_TRUE(stream_info.lastUpstreamTxByteSent().has_value()); - EXPECT_TRUE(stream_info.firstUpstreamRxByteReceived().has_value()); - EXPECT_TRUE(stream_info.lastUpstreamRxByteReceived().has_value()); + auto& upstream_timing = stream_info.upstreamInfo()->upstreamTiming(); + EXPECT_TRUE(upstream_timing.first_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.last_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.first_upstream_rx_byte_received_.has_value()); + EXPECT_TRUE(upstream_timing.last_upstream_rx_byte_received_.has_value()); - EXPECT_EQ(stream_info.lastUpstreamRxByteReceived().value() - - stream_info.firstUpstreamRxByteReceived().value(), + EXPECT_EQ(upstream_timing.last_upstream_rx_byte_received_.value() - + upstream_timing.first_upstream_rx_byte_received_.value(), std::chrono::milliseconds(153)); // Time spent in upstream tx is 0 because we're using simulated time and // don't have a good way to insert a "sleep" there, but values being present // and equal to the time the retry was sent is good enough of a test. - EXPECT_EQ(stream_info.lastUpstreamTxByteSent().value() - - stream_info.firstUpstreamTxByteSent().value(), + StreamInfo::TimingUtility timing(stream_info); + EXPECT_EQ(timing.lastUpstreamTxByteSent().value() - timing.firstUpstreamTxByteSent().value(), std::chrono::milliseconds(0)); - EXPECT_EQ(stream_info.lastUpstreamTxByteSent().value() + + EXPECT_EQ(timing.lastUpstreamTxByteSent().value() + stream_info.startTimeMonotonic().time_since_epoch(), retry_time.time_since_epoch()); - EXPECT_EQ(stream_info.firstUpstreamTxByteSent().value() + + EXPECT_EQ(timing.firstUpstreamTxByteSent().value() + stream_info.startTimeMonotonic().time_since_epoch(), retry_time.time_since_epoch()); } @@ -5299,7 +5251,8 @@ TEST_F(RouterTest, UpstreamTimingTimeout) { Http::TestRequestHeaderMapImpl headers{{"x-envoy-upstream-rq-timeout-ms", "50"}}; HttpTestUtility::addDefaultHeaders(headers); router_.decodeHeaders(headers, false); - EXPECT_FALSE(stream_info.lastUpstreamRxByteReceived().has_value()); + auto& upstream_timing = stream_info.upstreamInfo()->upstreamTiming(); + EXPECT_FALSE(upstream_timing.last_upstream_rx_byte_received_.has_value()); test_time_.advanceTimeWait(std::chrono::milliseconds(13)); Buffer::OwnedImpl data; @@ -5311,19 +5264,21 @@ TEST_F(RouterTest, UpstreamTimingTimeout) { Http::ResponseHeaderMapPtr response_headers( new Http::TestResponseHeaderMapImpl{{":status", "200"}}); + // NOLINTNEXTLINE(clang-analyzer-core.CallAndMessage) response_decoder->decodeHeaders(std::move(response_headers), false); test_time_.advanceTimeWait(std::chrono::milliseconds(99)); response_timeout_->invokeCallback(); - EXPECT_TRUE(stream_info.firstUpstreamTxByteSent().has_value()); - EXPECT_TRUE(stream_info.lastUpstreamTxByteSent().has_value()); - EXPECT_TRUE(stream_info.firstUpstreamRxByteReceived().has_value()); - EXPECT_FALSE(stream_info.lastUpstreamRxByteReceived() - .has_value()); // False because no end_stream was seen. - EXPECT_EQ(stream_info.firstUpstreamTxByteSent().value(), std::chrono::milliseconds(10)); - EXPECT_EQ(stream_info.lastUpstreamTxByteSent().value(), std::chrono::milliseconds(23)); - EXPECT_EQ(stream_info.firstUpstreamRxByteReceived().value(), std::chrono::milliseconds(56)); + EXPECT_TRUE(upstream_timing.first_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.last_upstream_tx_byte_sent_.has_value()); + EXPECT_TRUE(upstream_timing.first_upstream_rx_byte_received_.has_value()); + // False because no end_stream was seen. + EXPECT_FALSE(upstream_timing.last_upstream_rx_byte_received_.has_value()); + StreamInfo::TimingUtility timing(stream_info); + EXPECT_EQ(timing.firstUpstreamTxByteSent().value(), std::chrono::milliseconds(10)); + EXPECT_EQ(timing.lastUpstreamTxByteSent().value(), std::chrono::milliseconds(23)); + EXPECT_EQ(timing.firstUpstreamRxByteReceived().value(), std::chrono::milliseconds(56)); } TEST(RouterFilterUtilityTest, FinalHedgingParamsHedgeOnPerTryTimeout) { @@ -6004,10 +5959,6 @@ TEST_F(RouterTest, AutoHostRewriteEnabled) { return Http::okStatus(); })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); EXPECT_CALL(callbacks_.route_->route_entry_, autoHostRewrite()).WillOnce(Return(true)); EXPECT_CALL(callbacks_.route_->route_entry_, appendXfh()).WillOnce(Return(true)); router_.decodeHeaders(incoming_headers, true); @@ -6044,10 +5995,6 @@ TEST_F(RouterTest, AutoHostRewriteDisabled) { return Http::okStatus(); })); - EXPECT_CALL(callbacks_.stream_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { - EXPECT_EQ(host_address_, host->address()); - })); EXPECT_CALL(callbacks_.route_->route_entry_, autoHostRewrite()).WillOnce(Return(false)); router_.decodeHeaders(incoming_headers, true); EXPECT_EQ(1U, diff --git a/test/common/stream_info/stream_info_impl_test.cc b/test/common/stream_info/stream_info_impl_test.cc index 74ad2c1dcbabe..ec27d05615833 100644 --- a/test/common/stream_info/stream_info_impl_test.cc +++ b/test/common/stream_info/stream_info_impl_test.cc @@ -8,6 +8,7 @@ #include "source/common/common/fmt.h" #include "source/common/protobuf/utility.h" #include "source/common/stream_info/stream_info_impl.h" +#include "source/common/stream_info/utility.h" #include "test/common/stream_info/test_int_accessor.h" #include "test/mocks/router/mocks.h" @@ -39,7 +40,8 @@ class StreamInfoImplTest : public testing::Test { TEST_F(StreamInfoImplTest, TimingTest) { MonotonicTime pre_start = test_time_.timeSystem().monotonicTime(); StreamInfoImpl info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); - Envoy::StreamInfo::UpstreamTiming upstream_timing; + info.setUpstreamInfo(std::make_shared()); + UpstreamTiming& upstream_timing = info.upstreamInfo()->upstreamTiming(); MonotonicTime post_start = test_time_.timeSystem().monotonicTime(); const MonotonicTime& start = info.startTimeMonotonic(); @@ -47,38 +49,35 @@ TEST_F(StreamInfoImplTest, TimingTest) { EXPECT_LE(pre_start, start) << "Start time was lower than expected"; EXPECT_GE(post_start, start) << "Start time was higher than expected"; - EXPECT_FALSE(info.lastDownstreamRxByteReceived()); + TimingUtility timing(info); + EXPECT_FALSE(timing.lastDownstreamRxByteReceived()); info.downstreamTiming().onLastDownstreamRxByteReceived(test_time_.timeSystem()); std::chrono::nanoseconds dur = - checkDuration(std::chrono::nanoseconds{0}, info.lastDownstreamRxByteReceived()); + checkDuration(std::chrono::nanoseconds{0}, timing.lastDownstreamRxByteReceived()); - EXPECT_FALSE(info.firstUpstreamTxByteSent()); + EXPECT_FALSE(timing.firstUpstreamTxByteSent()); upstream_timing.onFirstUpstreamTxByteSent(test_time_.timeSystem()); - info.setUpstreamTiming(upstream_timing); - dur = checkDuration(dur, info.firstUpstreamTxByteSent()); + dur = checkDuration(dur, timing.firstUpstreamTxByteSent()); - EXPECT_FALSE(info.lastUpstreamTxByteSent()); + EXPECT_FALSE(timing.lastUpstreamTxByteSent()); upstream_timing.onLastUpstreamTxByteSent(test_time_.timeSystem()); - info.setUpstreamTiming(upstream_timing); - dur = checkDuration(dur, info.lastUpstreamTxByteSent()); + dur = checkDuration(dur, timing.lastUpstreamTxByteSent()); - EXPECT_FALSE(info.firstUpstreamRxByteReceived()); + EXPECT_FALSE(timing.firstUpstreamRxByteReceived()); upstream_timing.onFirstUpstreamRxByteReceived(test_time_.timeSystem()); - info.setUpstreamTiming(upstream_timing); - dur = checkDuration(dur, info.firstUpstreamRxByteReceived()); + dur = checkDuration(dur, timing.firstUpstreamRxByteReceived()); - EXPECT_FALSE(info.lastUpstreamRxByteReceived()); + EXPECT_FALSE(timing.lastUpstreamRxByteReceived()); upstream_timing.onLastUpstreamRxByteReceived(test_time_.timeSystem()); - info.setUpstreamTiming(upstream_timing); - dur = checkDuration(dur, info.lastUpstreamRxByteReceived()); + dur = checkDuration(dur, timing.lastUpstreamRxByteReceived()); - EXPECT_FALSE(info.downstreamTiming().firstDownstreamTxByteSent()); + EXPECT_FALSE(timing.firstDownstreamTxByteSent()); info.downstreamTiming().onFirstDownstreamTxByteSent(test_time_.timeSystem()); - dur = checkDuration(dur, info.firstDownstreamTxByteSent()); + dur = checkDuration(dur, timing.firstDownstreamTxByteSent()); - EXPECT_FALSE(info.lastDownstreamTxByteSent()); + EXPECT_FALSE(timing.lastDownstreamTxByteSent()); info.downstreamTiming().onLastDownstreamTxByteSent(test_time_.timeSystem()); - dur = checkDuration(dur, info.lastDownstreamTxByteSent()); + dur = checkDuration(dur, timing.lastDownstreamTxByteSent()); EXPECT_FALSE(info.requestComplete()); info.onRequestComplete(); @@ -139,7 +138,7 @@ TEST_F(StreamInfoImplTest, MiscSettersAndGetters) { EXPECT_EQ(nullptr, stream_info.upstreamInfo()); EXPECT_EQ(Http::Protocol::Http2, stream_info.protocol().value()); - EXPECT_FALSE(stream_info.upstreamConnectionId().has_value()); + stream_info.setUpstreamInfo(std::make_shared()); stream_info.protocol(Http::Protocol::Http10); EXPECT_EQ(Http::Protocol::Http10, stream_info.protocol().value()); @@ -164,10 +163,10 @@ TEST_F(StreamInfoImplTest, MiscSettersAndGetters) { ASSERT_TRUE(stream_info.connectionTerminationDetails().has_value()); EXPECT_EQ("access_denied", stream_info.connectionTerminationDetails().value()); - EXPECT_EQ(nullptr, stream_info.upstreamHost()); + EXPECT_EQ(nullptr, stream_info.upstreamInfo()->upstreamHost()); Upstream::HostDescriptionConstSharedPtr host(new NiceMock()); - stream_info.onUpstreamHostSelected(host); - EXPECT_EQ(host, stream_info.upstreamHost()); + stream_info.upstreamInfo()->setUpstreamHost(host); + EXPECT_EQ(host, stream_info.upstreamInfo()->upstreamHost()); EXPECT_FALSE(stream_info.healthCheck()); stream_info.healthCheck(true); @@ -184,10 +183,11 @@ TEST_F(StreamInfoImplTest, MiscSettersAndGetters) { FilterState::LifeSpan::FilterChain); EXPECT_EQ(1, stream_info.filterState()->getDataReadOnly("test").access()); - EXPECT_EQ(nullptr, stream_info.upstreamFilterState()); - stream_info.setUpstreamFilterState(stream_info.filterState()); - EXPECT_EQ(1, - stream_info.upstreamFilterState()->getDataReadOnly("test").access()); + stream_info.upstreamInfo()->setUpstreamFilterState(stream_info.filterState()); + EXPECT_EQ(1, stream_info.upstreamInfo() + ->upstreamFilterState() + ->getDataReadOnly("test") + .access()); EXPECT_EQ(absl::nullopt, stream_info.upstreamClusterInfo()); Upstream::ClusterInfoConstSharedPtr cluster_info(new NiceMock()); @@ -199,13 +199,13 @@ TEST_F(StreamInfoImplTest, MiscSettersAndGetters) { "D62A523A65695219D46FE1FFE285A4C371425ACE421B110B5B8D11D3EB4D5F0B"; auto ssl_info = std::make_shared(); EXPECT_CALL(*ssl_info, sessionId()).WillRepeatedly(testing::ReturnRef(session_id)); - stream_info.setUpstreamSslConnection(ssl_info); - EXPECT_EQ(session_id, stream_info.upstreamSslConnection()->sessionId()); + stream_info.upstreamInfo()->setUpstreamSslConnection(ssl_info); + EXPECT_EQ(session_id, stream_info.upstreamInfo()->upstreamSslConnection()->sessionId()); - EXPECT_FALSE(stream_info.upstreamConnectionId().has_value()); - stream_info.setUpstreamConnectionId(12345); - ASSERT_TRUE(stream_info.upstreamConnectionId().has_value()); - EXPECT_EQ(12345, stream_info.upstreamConnectionId().value()); + EXPECT_FALSE(stream_info.upstreamInfo()->upstreamConnectionId().has_value()); + stream_info.upstreamInfo()->setUpstreamConnectionId(12345); + ASSERT_TRUE(stream_info.upstreamInfo()->upstreamConnectionId().has_value()); + EXPECT_EQ(12345, stream_info.upstreamInfo()->upstreamConnectionId().value()); std::shared_ptr new_info = std::make_shared(); EXPECT_NE(stream_info.upstreamInfo(), new_info); diff --git a/test/common/stream_info/test_util.h b/test/common/stream_info/test_util.h index 903bf7221b91f..35302d154bb33 100644 --- a/test/common/stream_info/test_util.h +++ b/test/common/stream_info/test_util.h @@ -25,6 +25,7 @@ class TestStreamInfo : public StreamInfo::StreamInfoImpl { MonotonicTime now = timeSystem().monotonicTime(); start_time_monotonic_ = now; end_time_ = now + std::chrono::milliseconds(3); + setUpstreamInfo(std::make_shared()); } SystemTime startTime() const override { return start_time_; } diff --git a/test/common/tcp_proxy/tcp_proxy_test.cc b/test/common/tcp_proxy/tcp_proxy_test.cc index 8ca0a1e0ae956..f7b5549bf6fdb 100644 --- a/test/common/tcp_proxy/tcp_proxy_test.cc +++ b/test/common/tcp_proxy/tcp_proxy_test.cc @@ -935,8 +935,9 @@ TEST_F(TcpProxyTest, AccessLogUpstreamSSLConnection) { EXPECT_CALL(*upstream_connections_.at(0), streamInfo()).WillRepeatedly(ReturnRef(stream_info)); raiseEventUpstreamConnected(0); - ASSERT_NE(nullptr, filter_->getStreamInfo().upstreamSslConnection()); - EXPECT_EQ(session_id, filter_->getStreamInfo().upstreamSslConnection()->sessionId()); + ASSERT_NE(nullptr, filter_->getStreamInfo().upstreamInfo()->upstreamSslConnection()); + EXPECT_EQ(session_id, + filter_->getStreamInfo().upstreamInfo()->upstreamSslConnection()->sessionId()); } // Tests that upstream flush works properly with no idle timeout configured. @@ -1081,7 +1082,8 @@ TEST_F(TcpProxyTest, ShareFilterState) { raiseEventUpstreamConnected(0); EXPECT_EQ("filter_state_cluster", filter_callbacks_.connection_.streamInfo() - .upstreamFilterState() + .upstreamInfo() + ->upstreamFilterState() ->getDataReadOnly("envoy.tcp_proxy.cluster") .value()); } @@ -1093,9 +1095,10 @@ TEST_F(TcpProxyTest, AccessDownstreamAndUpstreamProperties) { raiseEventUpstreamConnected(0); EXPECT_EQ(filter_callbacks_.connection().streamInfo().downstreamAddressProvider().sslConnection(), filter_callbacks_.connection().ssl()); - EXPECT_EQ(filter_callbacks_.connection().streamInfo().upstreamLocalAddress(), - upstream_connections_.at(0)->streamInfo().downstreamAddressProvider().localAddress()); - EXPECT_EQ(filter_callbacks_.connection().streamInfo().upstreamSslConnection(), + EXPECT_EQ( + filter_callbacks_.connection().streamInfo().upstreamInfo()->upstreamLocalAddress().get(), + upstream_connections_.at(0)->streamInfo().downstreamAddressProvider().localAddress().get()); + EXPECT_EQ(filter_callbacks_.connection().streamInfo().upstreamInfo()->upstreamSslConnection(), upstream_connections_.at(0)->streamInfo().downstreamAddressProvider().sslConnection()); } } // namespace diff --git a/test/common/tcp_proxy/tcp_proxy_test_base.h b/test/common/tcp_proxy/tcp_proxy_test_base.h index b6b437b2f38ee..7464ce7738bb1 100644 --- a/test/common/tcp_proxy/tcp_proxy_test_base.h +++ b/test/common/tcp_proxy/tcp_proxy_test_base.h @@ -62,11 +62,6 @@ class TcpProxyTestBase : public testing::Test { TcpProxyTestBase() { ON_CALL(*factory_context_.access_log_manager_.file_, write(_)) .WillByDefault(SaveArg<0>(&access_log_data_)); - ON_CALL(filter_callbacks_.connection_.stream_info_, onUpstreamHostSelected(_)) - .WillByDefault(Invoke( - [this](Upstream::HostDescriptionConstSharedPtr host) { upstream_host_ = host; })); - ON_CALL(filter_callbacks_.connection_.stream_info_, upstreamHost()) - .WillByDefault(ReturnPointee(&upstream_host_)); ON_CALL(filter_callbacks_.connection_.stream_info_, setUpstreamClusterInfo(_)) .WillByDefault(Invoke([this](const Upstream::ClusterInfoConstSharedPtr& cluster_info) { upstream_cluster_ = cluster_info; diff --git a/test/common/tracing/http_tracer_impl_test.cc b/test/common/tracing/http_tracer_impl_test.cc index 1b263c8dfe661..35476c421f22f 100644 --- a/test/common/tracing/http_tracer_impl_test.cc +++ b/test/common/tracing/http_tracer_impl_test.cc @@ -95,6 +95,10 @@ TEST(HttpTracerUtilityTest, IsTracing) { class HttpConnManFinalizerImplTest : public testing::Test { protected: + HttpConnManFinalizerImplTest() { + Upstream::HostDescriptionConstSharedPtr shared_host(host_); + stream_info.upstreamInfo()->setUpstreamHost(shared_host); + } struct CustomTagCase { std::string custom_tag; bool set; @@ -117,6 +121,7 @@ class HttpConnManFinalizerImplTest : public testing::Test { NiceMock span; NiceMock config; NiceMock stream_info; + Upstream::MockHostDescription* host_{new NiceMock()}; }; TEST_F(HttpConnManFinalizerImplTest, OriginalAndLongPath) { @@ -219,7 +224,7 @@ TEST_F(HttpConnManFinalizerImplTest, NullRequestHeadersAndNullRouteEntry) { EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(11)); absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); - EXPECT_CALL(stream_info, upstreamHost()).WillRepeatedly(Return(nullptr)); + stream_info.upstreamInfo()->setUpstreamHost(nullptr); EXPECT_CALL(stream_info, route()).WillRepeatedly(Return(nullptr)); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().HttpStatusCode), Eq("0"))); @@ -257,25 +262,30 @@ tag: d } TEST_F(HttpConnManFinalizerImplTest, StreamInfoLogs) { - stream_info.host_->cluster_.name_ = "my_upstream_cluster"; + host_->hostname_ = "my_upstream_cluster"; EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(11)); absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); - EXPECT_CALL(stream_info, upstreamHost()).Times(3); const auto start_timestamp = SystemTime{std::chrono::duration_cast(std::chrono::hours{123})}; EXPECT_CALL(stream_info, startTime()).WillRepeatedly(Return(start_timestamp)); const absl::optional nanoseconds = std::chrono::nanoseconds{10}; - EXPECT_CALL(stream_info, lastDownstreamRxByteReceived()).WillRepeatedly(Return(nanoseconds)); - EXPECT_CALL(stream_info, firstUpstreamTxByteSent()).WillRepeatedly(Return(nanoseconds)); - EXPECT_CALL(stream_info, lastUpstreamTxByteSent()).WillRepeatedly(Return(nanoseconds)); - EXPECT_CALL(stream_info, firstUpstreamRxByteReceived()).WillRepeatedly(Return(nanoseconds)); - EXPECT_CALL(stream_info, lastUpstreamRxByteReceived()).WillRepeatedly(Return(nanoseconds)); - EXPECT_CALL(stream_info, firstDownstreamTxByteSent()).WillRepeatedly(Return(nanoseconds)); - EXPECT_CALL(stream_info, lastDownstreamTxByteSent()).WillRepeatedly(Return(nanoseconds)); + const MonotonicTime time = MonotonicTime(nanoseconds.value()); + MockTimeSystem time_system; + EXPECT_CALL(time_system, monotonicTime) + .Times(AnyNumber()) + .WillRepeatedly(Return(MonotonicTime(std::chrono::nanoseconds(10)))); + auto& timing = stream_info.upstream_info_->upstreamTiming(); + timing.first_upstream_tx_byte_sent_ = time; + timing.last_upstream_tx_byte_sent_ = time; + timing.first_upstream_rx_byte_received_ = time; + timing.last_upstream_rx_byte_received_ = time; + stream_info.downstream_timing_.onFirstDownstreamTxByteSent(time_system); + stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); + stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); const auto log_timestamp = start_timestamp + std::chrono::duration_cast(*nanoseconds); @@ -292,14 +302,13 @@ TEST_F(HttpConnManFinalizerImplTest, StreamInfoLogs) { } TEST_F(HttpConnManFinalizerImplTest, UpstreamClusterTagSet) { - stream_info.host_->cluster_.name_ = "my_upstream_cluster"; - stream_info.host_->cluster_.observability_name_ = "my_upstream_cluster_observable"; + host_->cluster_.name_ = "my_upstream_cluster"; + host_->cluster_.observability_name_ = "my_upstream_cluster_observable"; EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(11)); absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); - EXPECT_CALL(stream_info, upstreamHost()).Times(3); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().Component), Eq(Tracing::Tags::get().Proxy))); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().UpstreamCluster), Eq("my_upstream_cluster"))); @@ -341,7 +350,7 @@ TEST_F(HttpConnManFinalizerImplTest, SpanOptionalHeaders) { absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(100)); - EXPECT_CALL(stream_info, upstreamHost()).WillOnce(Return(nullptr)); + stream_info.upstreamInfo()->setUpstreamHost(nullptr); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().HttpStatusCode), Eq("0"))); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().Error), Eq(Tracing::Tags::get().True))); @@ -402,8 +411,7 @@ TEST_F(HttpConnManFinalizerImplTest, SpanCustomTags) { std::shared_ptr host_metadata = std::make_shared(); (*host_metadata->mutable_filter_metadata())["m.host"].MergeFrom(fake_struct); - (*stream_info.host_->cluster_.metadata_.mutable_filter_metadata())["m.cluster"].MergeFrom( - fake_struct); + (*host_->cluster_.metadata_.mutable_filter_metadata())["m.cluster"].MergeFrom(fake_struct); absl::optional protocol = Http::Protocol::Http10; EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); @@ -411,7 +419,7 @@ TEST_F(HttpConnManFinalizerImplTest, SpanCustomTags) { absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(100)); - EXPECT_CALL(*stream_info.host_, metadata()).WillRepeatedly(Return(host_metadata)); + EXPECT_CALL(*host_, metadata()).WillRepeatedly(Return(host_metadata)); EXPECT_CALL(config, customTags()); EXPECT_CALL(span, setTag(_, _)).Times(testing::AnyNumber()); @@ -532,7 +540,7 @@ TEST_F(HttpConnManFinalizerImplTest, SpanPopulatedFailureResponse) { EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(100)); ON_CALL(stream_info, hasResponseFlag(StreamInfo::ResponseFlag::UpstreamRequestTimeout)) .WillByDefault(Return(true)); - EXPECT_CALL(stream_info, upstreamHost()).WillOnce(Return(nullptr)); + stream_info.upstreamInfo()->setUpstreamHost(nullptr); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().Error), Eq(Tracing::Tags::get().True))); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().HttpStatusCode), Eq("503"))); @@ -728,6 +736,8 @@ class HttpTracerImplTest : public testing::Test { driver_ = new NiceMock(); DriverPtr driver_ptr(driver_); tracer_ = std::make_shared(std::move(driver_ptr), local_info_); + Upstream::HostDescriptionConstSharedPtr shared_host(host_); + stream_info_.upstreamInfo()->setUpstreamHost(shared_host); } Http::TestRequestHeaderMapImpl request_headers_{ @@ -742,6 +752,7 @@ class HttpTracerImplTest : public testing::Test { NiceMock config_; NiceMock* driver_; HttpTracerSharedPtr tracer_; + Upstream::MockHostDescription* host_{new NiceMock()}; }; TEST_F(HttpTracerImplTest, BasicFunctionalityNullSpan) { @@ -799,10 +810,9 @@ TEST_F(HttpTracerImplTest, ChildUpstreamSpanTest) { const std::string ob_cluster_name = "ob fake cluster"; EXPECT_CALL(stream_info_, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); EXPECT_CALL(stream_info_, protocol()).WillRepeatedly(ReturnPointee(&protocol)); - EXPECT_CALL(*(stream_info_.host_), address()).WillOnce(Return(remote_address)); - EXPECT_CALL(stream_info_.host_->cluster_, name()).WillOnce(ReturnRef(cluster_name)); - EXPECT_CALL(stream_info_.host_->cluster_, observabilityName()) - .WillOnce(ReturnRef(ob_cluster_name)); + EXPECT_CALL(*host_, address()).WillOnce(Return(remote_address)); + EXPECT_CALL(host_->cluster_, name()).WillOnce(ReturnRef(cluster_name)); + EXPECT_CALL(host_->cluster_, observabilityName()).WillOnce(ReturnRef(ob_cluster_name)); EXPECT_CALL(*second_span, setTag(_, _)).Times(testing::AnyNumber()); EXPECT_CALL(*second_span, setTag(Eq(Tracing::Tags::get().HttpProtocol), Eq("HTTP/2"))); diff --git a/test/extensions/access_loggers/file/config_test.cc b/test/extensions/access_loggers/file/config_test.cc index 4126b865e7ef5..ca8448f7ad9f9 100644 --- a/test/extensions/access_loggers/file/config_test.cc +++ b/test/extensions/access_loggers/file/config_test.cc @@ -62,7 +62,7 @@ class FileAccessLogTest : public testing::Test { absl::Time abslStartTime = TestUtility::parseTime("Dec 18 01:50:34 2018 GMT", "%b %e %H:%M:%S %Y GMT"); stream_info_.start_time_ = absl::ToChronoTime(abslStartTime); - EXPECT_CALL(stream_info_, upstreamHost()).WillRepeatedly(Return(nullptr)); + stream_info_.upstreamInfo()->setUpstreamHost(nullptr); stream_info_.response_code_ = 200; EXPECT_CALL(*file, write(_)).WillOnce(Invoke([expected, is_json](absl::string_view got) { diff --git a/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc b/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc index 481c249c779c2..d90a47af545e5 100644 --- a/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc +++ b/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc @@ -7,9 +7,11 @@ #include "source/common/network/address_impl.h" #include "source/common/router/string_accessor_impl.h" #include "source/common/stream_info/uint32_accessor_impl.h" +#include "source/common/stream_info/utility.h" #include "source/extensions/access_loggers/grpc/http_grpc_access_log_impl.h" #include "test/mocks/access_log/mocks.h" +#include "test/mocks/common.h" #include "test/mocks/grpc/mocks.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/ssl/mocks.h" @@ -117,8 +119,8 @@ class HttpGrpcAccessLogTest : public testing::Test { void expectLogRequestMethod(const std::string& request_method) { NiceMock stream_info; - stream_info.host_ = nullptr; stream_info.start_time_ = SystemTime(1h); + stream_info.upstreamInfo()->setUpstreamHost(nullptr); Http::TestRequestHeaderMapImpl request_headers{ {":method", request_method}, @@ -172,13 +174,18 @@ class TestSerializedFilterState : public StreamInfo::FilterState::Object { // Test HTTP log marshaling. TEST_F(HttpGrpcAccessLogTest, Marshalling) { InSequence s; + NiceMock time_system; { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); stream_info.start_time_monotonic_ = MonotonicTime(1h); - stream_info.last_downstream_tx_byte_sent_ = 2ms; + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::hours(1) + std::chrono::milliseconds(2)))); + stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); + StreamInfo::TimingUtility timing(stream_info); + ASSERT(timing.lastDownstreamTxByteSent().has_value()); stream_info.downstream_connection_info_provider_->setLocalAddress( std::make_shared("/foo")); (*stream_info.metadata_.mutable_filter_metadata())["foo"] = ProtobufWkt::Struct(); @@ -231,9 +238,11 @@ response: {} { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); - stream_info.last_downstream_tx_byte_sent_ = std::chrono::nanoseconds(2000000); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::nanoseconds(2000000)))); + stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); expectLog(R"EOF( common_properties: @@ -263,15 +272,26 @@ response: {} NiceMock stream_info; stream_info.start_time_ = SystemTime(1h); - stream_info.last_downstream_rx_byte_received_ = 2ms; - stream_info.first_upstream_tx_byte_sent_ = 4ms; - stream_info.last_upstream_tx_byte_sent_ = 6ms; - stream_info.first_upstream_rx_byte_received_ = 8ms; - stream_info.last_upstream_rx_byte_received_ = 10ms; - stream_info.first_downstream_tx_byte_sent_ = 12ms; - stream_info.last_downstream_tx_byte_sent_ = 14ms; - - stream_info.setUpstreamLocalAddress( + MockTimeSystem time_system; + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(2)))); + stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); + stream_info.upstream_info_->upstreamTiming().first_upstream_tx_byte_sent_ = + MonotonicTime(std::chrono::milliseconds(4)); + stream_info.upstream_info_->upstreamTiming().last_upstream_tx_byte_sent_ = + MonotonicTime(std::chrono::milliseconds(6)); + stream_info.upstream_info_->upstreamTiming().first_upstream_rx_byte_received_ = + MonotonicTime(std::chrono::milliseconds(8)); + stream_info.upstream_info_->upstreamTiming().last_upstream_rx_byte_received_ = + MonotonicTime(std::chrono::milliseconds(10)); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(12)))); + stream_info.downstream_timing_.onFirstDownstreamTxByteSent(time_system); + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(14)))); + stream_info.downstream_timing_.onLastDownstreamTxByteSent(time_system); + + stream_info.upstream_info_->setUpstreamLocalAddress( std::make_shared("10.0.0.2")); stream_info.protocol_ = Http::Protocol::Http10; stream_info.addBytesReceived(10); @@ -363,9 +383,9 @@ protocol_version: HTTP10 { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); - stream_info.upstream_transport_failure_reason_ = "TLS error"; + stream_info.upstream_info_->setUpstreamTransportFailureReason("TLS error"); Http::TestRequestHeaderMapImpl request_headers{ {":method", "WHACKADOO"}, @@ -398,7 +418,7 @@ response: {} { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared>(); @@ -465,7 +485,7 @@ response: {} // TLSv1.2 { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared>(); @@ -515,7 +535,7 @@ response: {} // TLSv1.1 { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared>(); @@ -565,7 +585,7 @@ response: {} // TLSv1 { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared>(); @@ -615,7 +635,7 @@ response: {} // Unknown TLS version (TLSv1.4) { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); auto connection_info = std::make_shared>(); @@ -685,7 +705,7 @@ TEST_F(HttpGrpcAccessLogTest, MarshallingAdditionalHeaders) { { NiceMock stream_info; - stream_info.host_ = nullptr; + stream_info.upstreamInfo()->setUpstreamHost(nullptr); stream_info.start_time_ = SystemTime(1h); Http::TestRequestHeaderMapImpl request_headers{ diff --git a/test/extensions/access_loggers/open_telemetry/access_log_impl_test.cc b/test/extensions/access_loggers/open_telemetry/access_log_impl_test.cc index c5ec330a9db52..0be99aac72e64 100644 --- a/test/extensions/access_loggers/open_telemetry/access_log_impl_test.cc +++ b/test/extensions/access_loggers/open_telemetry/access_log_impl_test.cc @@ -12,6 +12,7 @@ #include "source/extensions/access_loggers/open_telemetry/access_log_impl.h" #include "test/mocks/access_log/mocks.h" +#include "test/mocks/common.h" #include "test/mocks/grpc/mocks.h" #include "test/mocks/local_info/mocks.h" #include "test/mocks/ssl/mocks.h" @@ -100,7 +101,10 @@ TEST_F(AccessLogTest, Marshalling) { InSequence s; NiceMock stream_info; stream_info.start_time_ = SystemTime(1h); - stream_info.last_downstream_rx_byte_received_ = 2ms; + MockTimeSystem time_system; + EXPECT_CALL(time_system, monotonicTime) + .WillOnce(Return(MonotonicTime(std::chrono::milliseconds(2)))); + stream_info.downstream_timing_.onLastDownstreamRxByteReceived(time_system); stream_info.protocol_ = Http::Protocol::Http10; stream_info.addBytesReceived(10); stream_info.response_code_ = 200; diff --git a/test/extensions/access_loggers/stream/stream_test_base.h b/test/extensions/access_loggers/stream/stream_test_base.h index 6a55c3c81f034..021c26766f3d0 100644 --- a/test/extensions/access_loggers/stream/stream_test_base.h +++ b/test/extensions/access_loggers/stream/stream_test_base.h @@ -42,7 +42,7 @@ class StreamAccessLogTest : public testing::Test { absl::Time abslStartTime = TestUtility::parseTime("Dec 18 01:50:34 2018 GMT", "%b %e %H:%M:%S %Y GMT"); stream_info_.start_time_ = absl::ToChronoTime(abslStartTime); - EXPECT_CALL(stream_info_, upstreamHost()).WillRepeatedly(Return(nullptr)); + stream_info_.upstreamInfo()->setUpstreamHost(nullptr); stream_info_.response_code_ = 200; EXPECT_CALL(*file, write(_)).WillOnce(Invoke([expected, is_json](absl::string_view got) { diff --git a/test/extensions/filters/common/expr/context_test.cc b/test/extensions/filters/common/expr/context_test.cc index 2f7fe9d0f95ce..914c1338d4904 100644 --- a/test/extensions/filters/common/expr/context_test.cc +++ b/test/extensions/filters/common/expr/context_test.cc @@ -442,12 +442,11 @@ TEST(Context, ConnectionAttributes) { info.downstream_connection_info_provider_->setRemoteAddress(remote); info.downstream_connection_info_provider_->setRequestedServerName(sni_name); info.downstream_connection_info_provider_->setSslConnection(downstream_ssl_info); - EXPECT_CALL(info, upstreamSslConnection()).WillRepeatedly(Return(upstream_ssl_info)); - EXPECT_CALL(info, upstreamHost()).WillRepeatedly(Return(upstream_host)); - EXPECT_CALL(info, upstreamLocalAddress()).WillRepeatedly(ReturnRef(upstream_local_address)); const std::string upstream_transport_failure_reason = "ConnectionTermination"; - EXPECT_CALL(info, upstreamTransportFailureReason()) - .WillRepeatedly(ReturnRef(upstream_transport_failure_reason)); + info.upstreamInfo()->setUpstreamSslConnection(upstream_ssl_info); + info.upstreamInfo()->setUpstreamHost(upstream_host); + info.upstreamInfo()->setUpstreamLocalAddress(upstream_local_address); + info.upstreamInfo()->setUpstreamTransportFailureReason(upstream_transport_failure_reason); EXPECT_CALL(info, connectionID()).WillRepeatedly(Return(123)); info.downstream_connection_info_provider_->setConnectionID(123); const absl::optional connection_termination_details = "unauthorized"; diff --git a/test/extensions/filters/http/alternate_protocols_cache/filter_test.cc b/test/extensions/filters/http/alternate_protocols_cache/filter_test.cc index 51e0c85161509..dd11f5717fe88 100644 --- a/test/extensions/filters/http/alternate_protocols_cache/filter_test.cc +++ b/test/extensions/filters/http/alternate_protocols_cache/filter_test.cc @@ -104,9 +104,9 @@ TEST_F(FilterTest, ValidAltSvc) { std::string hostname = "host1"; std::shared_ptr hd = std::make_shared(); - StreamInfo::MockStreamInfo stream_info; + testing::NiceMock stream_info; EXPECT_CALL(callbacks_, streamInfo()).WillOnce(ReturnRef(stream_info)); - EXPECT_CALL(stream_info, upstreamHost()).WillOnce(testing::Return(hd)); + stream_info.upstreamInfo()->setUpstreamHost(hd); EXPECT_CALL(*hd, hostname()).WillOnce(ReturnRef(hostname)); EXPECT_CALL(*hd, address()).WillOnce(Return(address)); EXPECT_CALL(*address, ip()).WillOnce(Return(&ip)); diff --git a/test/extensions/filters/http/grpc_stats/config_test.cc b/test/extensions/filters/http/grpc_stats/config_test.cc index c8b15739736bb..959a05c076cbf 100644 --- a/test/extensions/filters/http/grpc_stats/config_test.cc +++ b/test/extensions/filters/http/grpc_stats/config_test.cc @@ -422,12 +422,10 @@ TEST_F(GrpcStatsFilterConfigTest, UpstreamStats) { {"content-type", "application/grpc+proto"}, {":path", "/lyft.users.BadCompanions/GetBadCompanions"}}; - ON_CALL(stream_info_, lastUpstreamRxByteReceived()) - .WillByDefault(testing::Return( - absl::optional(std::chrono::nanoseconds(30000000)))); - ON_CALL(stream_info_, lastUpstreamTxByteSent()) - .WillByDefault(testing::Return( - absl::optional(std::chrono::nanoseconds(20000000)))); + stream_info_.upstream_info_->upstreamTiming().last_upstream_tx_byte_sent_ = + MonotonicTime(std::chrono::nanoseconds(20000000)); + stream_info_.upstream_info_->upstreamTiming().last_upstream_rx_byte_received_ = + MonotonicTime(std::chrono::nanoseconds(30000000)); EXPECT_CALL(stats_store_, deliverHistogramToSinks( @@ -444,12 +442,10 @@ TEST_F(GrpcStatsFilterConfigTest, UpstreamStatsWithTrailersOnly) { config_.set_enable_upstream_stats(true); initialize(); - ON_CALL(stream_info_, lastUpstreamRxByteReceived()) - .WillByDefault(testing::Return( - absl::optional(std::chrono::nanoseconds(30000000)))); - ON_CALL(stream_info_, lastUpstreamTxByteSent()) - .WillByDefault(testing::Return( - absl::optional(std::chrono::nanoseconds(20000000)))); + stream_info_.upstream_info_->upstreamTiming().last_upstream_tx_byte_sent_ = + MonotonicTime(std::chrono::nanoseconds(20000000)); + stream_info_.upstream_info_->upstreamTiming().last_upstream_rx_byte_received_ = + MonotonicTime(std::chrono::nanoseconds(30000000)); EXPECT_CALL(stats_store_, deliverHistogramToSinks( diff --git a/test/extensions/filters/http/wasm/wasm_filter_test.cc b/test/extensions/filters/http/wasm/wasm_filter_test.cc index 000e65353f051..c5227d88a369b 100644 --- a/test/extensions/filters/http/wasm/wasm_filter_test.cc +++ b/test/extensions/filters/http/wasm/wasm_filter_test.cc @@ -1796,7 +1796,7 @@ TEST_P(WasmHttpFilterTest, Property) { key: endpoint )EOF")); EXPECT_CALL(*host_description, metadata()).WillRepeatedly(Return(metadata)); - EXPECT_CALL(request_stream_info_, upstreamHost()).WillRepeatedly(Return(host_description)); + request_stream_info_.upstreamInfo()->setUpstreamHost(host_description); filter().log(&request_headers, nullptr, nullptr, log_stream_info); } @@ -1826,11 +1826,11 @@ TEST_P(WasmHttpFilterTest, ClusterMetadata) { EXPECT_CALL(encoder_callbacks_, streamInfo()).WillRepeatedly(ReturnRef(request_stream_info_)); EXPECT_CALL(*cluster, metadata()).WillRepeatedly(ReturnRef(*cluster_metadata)); EXPECT_CALL(*host_description, cluster()).WillRepeatedly(ReturnRef(*cluster)); - EXPECT_CALL(request_stream_info_, upstreamHost()).WillRepeatedly(Return(host_description)); + request_stream_info_.upstreamInfo()->setUpstreamHost(host_description); filter().log(&request_headers, nullptr, nullptr, log_stream_info); // If upstream host is empty, fallback to upstream cluster info for cluster metadata. - EXPECT_CALL(request_stream_info_, upstreamHost()).WillRepeatedly(Return(nullptr)); + request_stream_info_.upstreamInfo()->setUpstreamHost(nullptr); EXPECT_CALL(request_stream_info_, upstreamClusterInfo()).WillRepeatedly(Return(cluster)); EXPECT_CALL(filter(), log_(spdlog::level::warn, Eq(absl::string_view("cluster metadata: cluster")))); diff --git a/test/fuzz/utility.h b/test/fuzz/utility.h index 6647c6cf4d591..55b4772e15639 100644 --- a/test/fuzz/utility.h +++ b/test/fuzz/utility.h @@ -157,7 +157,8 @@ inline std::unique_ptr fromStreamInfo(const test::fuzz::StreamIn auto upstream_metadata = std::make_shared( replaceInvalidStringValues(stream_info.upstream_metadata())); ON_CALL(*upstream_host, metadata()).WillByDefault(testing::Return(upstream_metadata)); - test_stream_info->onUpstreamHostSelected(upstream_host); + test_stream_info->setUpstreamInfo(std::make_shared()); + test_stream_info->upstreamInfo()->setUpstreamHost(upstream_host); auto address = stream_info.has_address() ? Envoy::Network::Address::resolveProtoAddress(stream_info.address()) : Network::Utility::resolveUrl("tcp://10.0.0.1:443"); @@ -165,7 +166,7 @@ inline std::unique_ptr fromStreamInfo(const test::fuzz::StreamIn stream_info.has_upstream_local_address() ? Envoy::Network::Address::resolveProtoAddress(stream_info.upstream_local_address()) : Network::Utility::resolveUrl("tcp://10.0.0.1:10000"); - test_stream_info->setUpstreamLocalAddress(upstream_local_address); + test_stream_info->upstreamInfo()->setUpstreamLocalAddress(upstream_local_address); test_stream_info->downstream_connection_info_provider_ = std::make_shared(address, address); test_stream_info->downstream_connection_info_provider_->setRequestedServerName( diff --git a/test/integration/filters/stream_info_to_headers_filter.cc b/test/integration/filters/stream_info_to_headers_filter.cc index 8914454b4e0f4..01c8d7b44b3ab 100644 --- a/test/integration/filters/stream_info_to_headers_filter.cc +++ b/test/integration/filters/stream_info_to_headers_filter.cc @@ -40,15 +40,19 @@ class StreamInfoToHeadersFilter : public Http::PassThroughFilter { headers.addCopy(Http::LowerCaseString("dns_end"), absl::StrCat(toMs(stream_info.downstreamTiming().getValue(dns_end).value()))); } - if (decoder_callbacks_->streamInfo().upstreamSslConnection()) { - headers.addCopy(Http::LowerCaseString("alpn"), - decoder_callbacks_->streamInfo().upstreamSslConnection()->alpn()); + if (decoder_callbacks_->streamInfo().upstreamInfo() && + decoder_callbacks_->streamInfo().upstreamInfo()->upstreamSslConnection()) { + headers.addCopy( + Http::LowerCaseString("alpn"), + decoder_callbacks_->streamInfo().upstreamInfo()->upstreamSslConnection()->alpn()); } return Http::FilterHeadersStatus::Continue; } Http::FilterTrailersStatus encodeTrailers(Http::ResponseTrailerMap& trailers) override { - StreamInfo::UpstreamTiming& upstream_timing = decoder_callbacks_->streamInfo().upstreamTiming(); + ASSERT(decoder_callbacks_->streamInfo().upstreamInfo()); + StreamInfo::UpstreamTiming& upstream_timing = + decoder_callbacks_->streamInfo().upstreamInfo()->upstreamTiming(); // Upstream metrics aren't available until the response is complete. if (upstream_timing.upstream_connect_start_.has_value()) { trailers.addCopy( diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index fa37db802b260..528ec13a3c898 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -21,6 +21,10 @@ MockStreamInfo::MockStreamInfo() downstream_connection_info_provider_(std::make_shared( std::make_shared("127.0.0.2"), std::make_shared("127.0.0.1"))) { + upstream_info_ = std::make_unique(); + Upstream::HostDescriptionConstSharedPtr host{ + new testing::NiceMock()}; + upstream_info_->setUpstreamHost(host); ON_CALL(*this, setResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag response_flag) { response_flags_ |= response_flag; })); @@ -36,41 +40,24 @@ MockStreamInfo::MockStreamInfo() })); ON_CALL(*this, startTime()).WillByDefault(ReturnPointee(&start_time_)); ON_CALL(*this, startTimeMonotonic()).WillByDefault(ReturnPointee(&start_time_monotonic_)); - ON_CALL(*this, lastDownstreamRxByteReceived()) - .WillByDefault(ReturnPointee(&last_downstream_rx_byte_received_)); - ON_CALL(*this, firstUpstreamTxByteSent()) - .WillByDefault(ReturnPointee(&first_upstream_tx_byte_sent_)); - ON_CALL(*this, lastUpstreamTxByteSent()) - .WillByDefault(ReturnPointee(&last_upstream_tx_byte_sent_)); - ON_CALL(*this, firstUpstreamRxByteReceived()) - .WillByDefault(ReturnPointee(&first_upstream_rx_byte_received_)); - ON_CALL(*this, lastUpstreamRxByteReceived()) - .WillByDefault(ReturnPointee(&last_upstream_rx_byte_received_)); - ON_CALL(*this, firstDownstreamTxByteSent()) - .WillByDefault(ReturnPointee(&first_downstream_tx_byte_sent_)); - ON_CALL(*this, lastDownstreamTxByteSent()) - .WillByDefault(ReturnPointee(&last_downstream_tx_byte_sent_)); ON_CALL(*this, requestComplete()).WillByDefault(ReturnPointee(&end_time_)); ON_CALL(*this, onRequestComplete()).WillByDefault(Invoke([this]() { end_time_ = absl::make_optional( std::chrono::duration_cast(ts_.systemTime() - start_time_) .count()); })); - ON_CALL(*this, downstreamTiming()).WillByDefault(ReturnRef(downstream_timing_)); - ON_CALL(*this, setUpstreamLocalAddress(_)) + ON_CALL(*this, downstreamTiming()).WillByDefault(Invoke([this]() -> DownstreamTiming& { + return downstream_timing_; + })); + ON_CALL(Const(*this), downstreamTiming()) .WillByDefault( - Invoke([this](const Network::Address::InstanceConstSharedPtr& upstream_local_address) { - upstream_local_address_ = upstream_local_address; - })); - ON_CALL(*this, upstreamLocalAddress()).WillByDefault(ReturnRef(upstream_local_address_)); + Invoke([this]() -> OptRef { return downstream_timing_; })); + ON_CALL(*this, upstreamInfo()).WillByDefault(Invoke([this]() { return upstream_info_; })); + ON_CALL(testing::Const(*this), upstreamInfo()).WillByDefault(Invoke([this]() { + return OptRef(*upstream_info_); + })); ON_CALL(*this, downstreamAddressProvider()) .WillByDefault(ReturnPointee(downstream_connection_info_provider_)); - ON_CALL(*this, setUpstreamSslConnection(_)) - .WillByDefault(Invoke( - [this](const auto& connection_info) { upstream_connection_info_ = connection_info; })); - ON_CALL(*this, upstreamSslConnection()).WillByDefault(Invoke([this]() { - return upstream_connection_info_; - })); ON_CALL(*this, protocol()).WillByDefault(ReturnPointee(&protocol_)); ON_CALL(*this, responseCode()).WillByDefault(ReturnPointee(&response_code_)); ON_CALL(*this, responseCodeDetails()).WillByDefault(ReturnPointee(&response_code_details_)); @@ -94,19 +81,12 @@ MockStreamInfo::MockStreamInfo() return response_flags_ != 0; })); ON_CALL(*this, responseFlags()).WillByDefault(Return(response_flags_)); - ON_CALL(*this, upstreamHost()).WillByDefault(ReturnPointee(&host_)); - ON_CALL(*this, dynamicMetadata()).WillByDefault(ReturnRef(metadata_)); ON_CALL(Const(*this), dynamicMetadata()).WillByDefault(ReturnRef(metadata_)); ON_CALL(*this, filterState()).WillByDefault(ReturnRef(filter_state_)); ON_CALL(Const(*this), filterState()).WillByDefault(Invoke([this]() -> const FilterState& { return *filter_state_; })); - ON_CALL(*this, upstreamFilterState()).WillByDefault(ReturnRef(upstream_filter_state_)); - ON_CALL(*this, setUpstreamFilterState(_)) - .WillByDefault(Invoke([this](const FilterStateSharedPtr& filter_state) { - upstream_filter_state_ = filter_state; - })); ON_CALL(*this, setRouteName(_)).WillByDefault(Invoke([this](const absl::string_view route_name) { route_name_ = std::string(route_name); })); @@ -115,23 +95,14 @@ MockStreamInfo::MockStreamInfo() virtual_cluster_name_ = virtual_cluster_name; })); ON_CALL(*this, getRouteName()).WillByDefault(ReturnRef(route_name_)); + ON_CALL(*this, setUpstreamInfo(_)) + .WillByDefault(Invoke([this](std::shared_ptr info) { upstream_info_ = info; })); ON_CALL(*this, virtualClusterName()).WillByDefault(ReturnRef(virtual_cluster_name_)); - ON_CALL(*this, upstreamTransportFailureReason()) - .WillByDefault(ReturnRef(upstream_transport_failure_reason_)); - ON_CALL(*this, setConnectionID(_)).WillByDefault(Invoke([this](uint64_t id) { - connection_id_ = id; - })); ON_CALL(*this, setFilterChainName(_)) .WillByDefault(Invoke([this](const absl::string_view filter_chain_name) { filter_chain_name_ = std::string(filter_chain_name); })); ON_CALL(*this, filterChainName()).WillByDefault(ReturnRef(filter_chain_name_)); - ON_CALL(*this, setUpstreamConnectionId(_)).WillByDefault(Invoke([this](uint64_t id) { - upstream_connection_id_ = id; - })); - ON_CALL(*this, upstreamConnectionId()).WillByDefault(Invoke([this]() { - return upstream_connection_id_; - })); ON_CALL(*this, setAttemptCount(_)).WillByDefault(Invoke([this](uint32_t attempt_count) { attempt_count_ = attempt_count; })); @@ -146,8 +117,6 @@ MockStreamInfo::MockStreamInfo() .WillByDefault(Invoke([this](const BytesMeterSharedPtr& downstream_bytes_meter) { downstream_bytes_meter_ = downstream_bytes_meter; })); - ON_CALL(*this, upstreamTiming()).WillByDefault(ReturnRef(upstream_timing_)); - ON_CALL(Const(*this), upstreamTiming()).WillByDefault(Return(upstream_timing_)); } MockStreamInfo::~MockStreamInfo() = default; diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index 485a4c7244df5..bd3603ea25647 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -6,6 +6,7 @@ #include "source/common/network/socket_impl.h" #include "source/common/stream_info/filter_state_impl.h" +#include "source/common/stream_info/stream_info_impl.h" #include "test/mocks/upstream/host.h" #include "test/test_common/simulated_time_system.h" @@ -29,26 +30,13 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(void, onUpstreamHostSelected, (Upstream::HostDescriptionConstSharedPtr host)); MOCK_METHOD(SystemTime, startTime, (), (const)); MOCK_METHOD(MonotonicTime, startTimeMonotonic, (), (const)); - MOCK_METHOD(absl::optional, lastDownstreamRxByteReceived, (), (const)); - MOCK_METHOD(void, setUpstreamTiming, (const UpstreamTiming&)); MOCK_METHOD(void, setUpstreamInfo, (std::shared_ptr)); MOCK_METHOD(std::shared_ptr, upstreamInfo, ()); MOCK_METHOD(OptRef, upstreamInfo, (), (const)); - MOCK_METHOD(UpstreamTiming&, upstreamTiming, ()); - MOCK_METHOD(OptRef, upstreamTiming, (), (const)); - MOCK_METHOD(absl::optional, firstUpstreamTxByteSent, (), (const)); - MOCK_METHOD(void, onFirstUpstreamTxByteSent, ()); - MOCK_METHOD(absl::optional, lastUpstreamTxByteSent, (), (const)); - MOCK_METHOD(void, onLastUpstreamTxByteSent, ()); - MOCK_METHOD(absl::optional, firstUpstreamRxByteReceived, (), (const)); - MOCK_METHOD(void, onFirstUpstreamRxByteReceived, ()); - MOCK_METHOD(absl::optional, lastUpstreamRxByteReceived, (), (const)); - MOCK_METHOD(void, onLastUpstreamRxByteReceived, ()); - MOCK_METHOD(absl::optional, firstDownstreamTxByteSent, (), (const)); - MOCK_METHOD(absl::optional, lastDownstreamTxByteSent, (), (const)); MOCK_METHOD(void, onRequestComplete, ()); MOCK_METHOD(absl::optional, requestComplete, (), (const)); MOCK_METHOD(DownstreamTiming&, downstreamTiming, ()); + MOCK_METHOD(OptRef, downstreamTiming, (), (const)); MOCK_METHOD(void, addBytesReceived, (uint64_t)); MOCK_METHOD(uint64_t, bytesReceived, (), (const)); MOCK_METHOD(void, addWireBytesReceived, (uint64_t)); @@ -70,14 +58,9 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(bool, hasResponseFlag, (ResponseFlag), (const)); MOCK_METHOD(bool, hasAnyResponseFlag, (), (const)); MOCK_METHOD(uint64_t, responseFlags, (), (const)); - MOCK_METHOD(Upstream::HostDescriptionConstSharedPtr, upstreamHost, (), (const)); - MOCK_METHOD(void, setUpstreamLocalAddress, (const Network::Address::InstanceConstSharedPtr&)); - MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, upstreamLocalAddress, (), (const)); MOCK_METHOD(bool, healthCheck, (), (const)); MOCK_METHOD(void, healthCheck, (bool is_health_check)); MOCK_METHOD(const Network::ConnectionInfoProvider&, downstreamAddressProvider, (), (const)); - MOCK_METHOD(void, setUpstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); - MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, upstreamSslConnection, (), (const)); MOCK_METHOD(Router::RouteConstSharedPtr, route, (), (const)); MOCK_METHOD(envoy::config::core::v3::Metadata&, dynamicMetadata, ()); MOCK_METHOD(const envoy::config::core::v3::Metadata&, dynamicMetadata, (), (const)); @@ -86,10 +69,6 @@ class MockStreamInfo : public StreamInfo { (const std::string&, const std::string&, const std::string&)); MOCK_METHOD(const FilterStateSharedPtr&, filterState, ()); MOCK_METHOD(const FilterState&, filterState, (), (const)); - MOCK_METHOD(const FilterStateSharedPtr&, upstreamFilterState, (), (const)); - MOCK_METHOD(void, setUpstreamFilterState, (const FilterStateSharedPtr&)); - MOCK_METHOD(void, setUpstreamTransportFailureReason, (absl::string_view)); - MOCK_METHOD(const std::string&, upstreamTransportFailureReason, (), (const)); MOCK_METHOD(void, setRequestHeaders, (const Http::RequestHeaderMap&)); MOCK_METHOD(const Http::RequestHeaderMap*, getRequestHeaders, (), (const)); MOCK_METHOD(void, setUpstreamClusterInfo, (const Upstream::ClusterInfoConstSharedPtr&)); @@ -104,49 +83,32 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(void, setConnectionID, (uint64_t)); MOCK_METHOD(void, setFilterChainName, (const absl::string_view)); MOCK_METHOD(const std::string&, filterChainName, (), (const)); - MOCK_METHOD(void, setUpstreamConnectionId, (uint64_t)); - MOCK_METHOD(absl::optional, upstreamConnectionId, (), (const)); MOCK_METHOD(void, setAttemptCount, (uint32_t), ()); MOCK_METHOD(absl::optional, attemptCount, (), (const)); MOCK_METHOD(const BytesMeterSharedPtr&, getUpstreamBytesMeter, (), (const)); MOCK_METHOD(const BytesMeterSharedPtr&, getDownstreamBytesMeter, (), (const)); MOCK_METHOD(void, setUpstreamBytesMeter, (const BytesMeterSharedPtr&)); MOCK_METHOD(void, setDownstreamBytesMeter, (const BytesMeterSharedPtr&)); - std::shared_ptr> host_{ - new testing::NiceMock()}; Envoy::Event::SimulatedTimeSystem ts_; SystemTime start_time_; MonotonicTime start_time_monotonic_; - absl::optional last_downstream_rx_byte_received_; - absl::optional first_upstream_tx_byte_sent_; - absl::optional last_upstream_tx_byte_sent_; - absl::optional first_upstream_rx_byte_received_; - absl::optional connection_id_; - absl::optional last_upstream_rx_byte_received_; - absl::optional first_downstream_tx_byte_sent_; - absl::optional last_downstream_tx_byte_sent_; absl::optional end_time_; absl::optional protocol_; absl::optional response_code_; absl::optional response_code_details_; absl::optional connection_termination_details_; - UpstreamTiming upstream_timing_; + std::shared_ptr upstream_info_; uint64_t response_flags_{}; envoy::config::core::v3::Metadata metadata_; - FilterStateSharedPtr upstream_filter_state_; FilterStateSharedPtr filter_state_; uint64_t bytes_received_{}; uint64_t bytes_sent_{}; - Network::Address::InstanceConstSharedPtr upstream_local_address_; std::shared_ptr downstream_connection_info_provider_; BytesMeterSharedPtr upstream_bytes_meter_; BytesMeterSharedPtr downstream_bytes_meter_; Ssl::ConnectionInfoConstSharedPtr downstream_connection_info_; - Ssl::ConnectionInfoConstSharedPtr upstream_connection_info_; std::string route_name_; - std::string upstream_transport_failure_reason_; std::string filter_chain_name_; - absl::optional upstream_connection_id_; absl::optional attempt_count_; absl::optional virtual_cluster_name_; DownstreamTiming downstream_timing_;