diff --git a/CHANGELOG.md b/CHANGELOG.md index b05b5b6d66..e9e6379d93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,6 +57,9 @@ Increment the: * [BUG] Stop reading past a `nostd::string_view` that is not NUL terminated [#4346](https://github.com/open-telemetry/opentelemetry-cpp/pull/4346) +* [BUG] Stop OTLP `ForceFlush` returning on the first notification and + overrunning the caller's deadline + [#4357](https://github.com/open-telemetry/opentelemetry-cpp/pull/4357) * [OTLP EXPORTERS] add otlp_common target for shared otlp utils [#4333](https://github.com/open-telemetry/opentelemetry-cpp/pull/4333) diff --git a/exporters/otlp/src/otlp_grpc_client.cc b/exporters/otlp/src/otlp_grpc_client.cc index 2b800bfd4b..bbaa4387f8 100644 --- a/exporters/otlp/src/otlp_grpc_client.cc +++ b/exporters/otlp/src/otlp_grpc_client.cc @@ -757,20 +757,20 @@ bool OtlpGrpcClient::ForceFlush( while (timeout_steady > std::chrono::steady_clock::duration::zero() && request_counter > async_data_->finished_request_counter.load(std::memory_order_acquire)) { - // When changes of running_sessions_ and notify_one/notify_all happen between predicate - // checking and waiting, we should not wait forever.We should cleanup gc sessions here as soon - // as possible to call FinishSession() and cleanup resources. + // A completion can land between the loop condition and the wait, so the wait is bounded and the + // condition re-read on every wakeup. Never wait past the caller's deadline. + const std::chrono::steady_clock::duration wait_interval = + (std::min)(std::chrono::duration_cast( + async_data_->export_timeout), + timeout_steady); + std::chrono::steady_clock::time_point start_timepoint = std::chrono::steady_clock::now(); - if (std::cv_status::timeout != - async_data_->session_waker.wait_for(lock, async_data_->export_timeout)) - { - break; - } + async_data_->session_waker.wait_for(lock, wait_interval); timeout_steady -= std::chrono::steady_clock::now() - start_timepoint; } - return timeout_steady > std::chrono::steady_clock::duration::zero(); + return request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire); #else return true; #endif diff --git a/exporters/otlp/src/otlp_http_client.cc b/exporters/otlp/src/otlp_http_client.cc index bb0e0a21e4..1f2bf98071 100644 --- a/exporters/otlp/src/otlp_http_client.cc +++ b/exporters/otlp/src/otlp_http_client.cc @@ -1,6 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#include #include #include #include @@ -857,8 +858,12 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept // When changes of running_sessions_ and notify_one/notify_all happen between predicate // checking and waiting, we should not wait forever.We should cleanup gc sessions here as soon // as possible to call FinishSession() and cleanup resources. + const std::chrono::steady_clock::duration wait_interval = (std::min)( + std::chrono::duration_cast(options_.timeout), + timeout_steady); + std::chrono::steady_clock::time_point start_timepoint = std::chrono::steady_clock::now(); - if (std::cv_status::timeout == session_waker_.wait_for(lock, options_.timeout)) + if (std::cv_status::timeout == session_waker_.wait_for(lock, wait_interval)) { cleanupGCSessions(); } @@ -870,7 +875,10 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept timeout_steady -= std::chrono::steady_clock::now() - start_timepoint; } - return timeout_steady > std::chrono::steady_clock::duration::zero(); + // What the wait was for, rather than what is left of the deadline. A session that finishes + // between the last check and the last wait takes its notification with it, and the flush it was + // holding up has happened. + return finished_session_counter_.load(std::memory_order_acquire) >= wait_counter; } bool OtlpHttpClient::Shutdown(std::chrono::microseconds timeout) noexcept diff --git a/exporters/otlp/test/otlp_grpc_exporter_test.cc b/exporters/otlp/test/otlp_grpc_exporter_test.cc index 239f788c49..754e58dd26 100644 --- a/exporters/otlp/test/otlp_grpc_exporter_test.cc +++ b/exporters/otlp/test/otlp_grpc_exporter_test.cc @@ -40,7 +40,13 @@ # include # include # include +# include +# include +# include # include +# include +# include +# include # include # include @@ -86,6 +92,13 @@ class OtlpMockTraceServiceStub : public proto::collector::trace::v1::MockTraceSe ::opentelemetry::proto::collector::trace::v1::ExportTraceServiceResponse *response, std::function callback) override { + if (stub_->defer_completions_) + { + std::lock_guard guard(stub_->deferred_lock_); + stub_->deferred_.push_back(std::move(callback)); + return; + } + stub_->last_async_status_ = stub_->Export(context, *request, response); callback(stub_->last_async_status_); } @@ -118,11 +131,68 @@ class OtlpMockTraceServiceStub : public proto::collector::trace::v1::MockTraceSe ::grpc::Status GetLastAsyncStatus() const noexcept { return last_async_status_; } + // Keep the completion callbacks instead of running them inline, so a test can call ForceFlush() + // with requests still in flight. Call before the first export. + void DeferCompletions() noexcept { defer_completions_ = true; } + + std::size_t DeferredCount() + { + std::lock_guard guard(deferred_lock_); + return deferred_.size(); + } + + // Completes whichever deferred request has been waiting longest, false when there is none. + bool CompleteOneDeferred() + { + std::function callback; + { + std::lock_guard guard(deferred_lock_); + if (deferred_.empty()) + { + return false; + } + callback = std::move(deferred_.front()); + deferred_.erase(deferred_.begin()); + } + + callback(::grpc::Status::OK); + return true; + } + + void CompleteAllDeferred() + { + while (CompleteOneDeferred()) + { + } + } + private: ::grpc::Status last_async_status_; + bool defer_completions_{false}; + std::mutex deferred_lock_; + std::vector> deferred_; async_interface async_interface_; }; +// Completes whatever is still deferred on the way out. ~OtlpGrpcClient waits for +// running_requests to reach zero with no deadline, and TryCancel() cannot move it for a request +// the stub is holding, so an assertion that ends a case early would hang the binary instead of +// failing it. Declare after the exporter, so this runs first. +class DrainDeferredCompletions +{ +public: + explicit DrainDeferredCompletions(OtlpMockTraceServiceStub *stub) noexcept : stub_(stub) {} + ~DrainDeferredCompletions() { stub_->CompleteAllDeferred(); } + + DrainDeferredCompletions(const DrainDeferredCompletions &) = delete; + DrainDeferredCompletions &operator=(const DrainDeferredCompletions &) = delete; + DrainDeferredCompletions(DrainDeferredCompletions &&) = delete; + DrainDeferredCompletions &operator=(DrainDeferredCompletions &&) = delete; + +private: + OtlpMockTraceServiceStub *stub_; +}; + using opentelemetry::test_common::ScopedTestLogHandler; } // namespace @@ -244,6 +314,92 @@ TEST_F(OtlpGrpcExporterTestPeer, ExportPartialSuccess) EXPECT_TRUE(contains("too many spans!!")); } +namespace +{ +// ForceFlush() only has requests to wait for when the client tracks them, which it does under +// ENABLE_ASYNC_EXPORT. gtest_add_tests registers by source text, so the cases below have to exist +// in every build and opt out here rather than be compiled away. +class OtlpGrpcExporterFlushTestPeer : public OtlpGrpcExporterTestPeer +{ +protected: + void SetUp() override + { +# if !defined(ENABLE_ASYNC_EXPORT) + GTEST_SKIP() << "ForceFlush has no in-flight requests to wait for without async export"; +# endif + } +}; + +// The wait is bounded by the exporter's timeout, so a caller asking for less than that used to +// wait for the larger of the two. +TEST_F(OtlpGrpcExporterFlushTestPeer, ForceFlushReturnsWithinTheCallerDeadline) +{ + auto *mock_stub = new OtlpMockTraceServiceStub(); + mock_stub->DeferCompletions(); + std::unique_ptr stub_interface( + mock_stub); + auto exporter = GetExporter(stub_interface); + DrainDeferredCompletions drain{mock_stub}; + + auto recordable = exporter->MakeRecordable(); + recordable->SetName("Test span"); + nostd::span> batch(&recordable, 1); + exporter->Export(batch); + ASSERT_EQ(1u, mock_stub->DeferredCount()); + + const auto started = std::chrono::steady_clock::now(); + const bool flushed = exporter->ForceFlush(std::chrono::milliseconds{50}); + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started); + + EXPECT_FALSE(flushed); + EXPECT_LT(elapsed.count(), 1000) + << "waited on the export timeout rather than the one it was given"; +} + +// A completion for one request used to end the wait for every other request, and the leftover +// deadline was then reported as success. +TEST_F(OtlpGrpcExporterFlushTestPeer, ForceFlushKeepsWaitingWhenAnotherRequestCompletes) +{ + auto *mock_stub = new OtlpMockTraceServiceStub(); + mock_stub->DeferCompletions(); + std::unique_ptr stub_interface( + mock_stub); + auto exporter = GetExporter(stub_interface); + DrainDeferredCompletions drain{mock_stub}; + + auto first = exporter->MakeRecordable(); + first->SetName("Test span 1"); + nostd::span> first_batch(&first, 1); + exporter->Export(first_batch); + + auto second = exporter->MakeRecordable(); + second->SetName("Test span 2"); + nostd::span> second_batch(&second, 1); + exporter->Export(second_batch); + + ASSERT_EQ(2u, mock_stub->DeferredCount()); + + // Completed once the flush below is parked, so it arrives as a notification rather than as a + // counter the loop condition reads on its way in. + std::thread completer([mock_stub] { + std::this_thread::sleep_for(std::chrono::milliseconds{100}); + mock_stub->CompleteOneDeferred(); + }); + + const auto started = std::chrono::steady_clock::now(); + const bool flushed = exporter->ForceFlush(std::chrono::milliseconds{1000}); + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started); + completer.join(); + + EXPECT_FALSE(flushed); + // Ran its own deadline down rather than returning on the notification. + EXPECT_GE(elapsed.count(), 500); + EXPECT_EQ(1u, mock_stub->DeferredCount()); +} +} // namespace + // Create spans, let processor call Export() TEST_F(OtlpGrpcExporterTestPeer, ExportIntegrationTest) { diff --git a/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc b/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc index e49ad776a7..d9767c5cf9 100644 --- a/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc +++ b/exporters/otlp/test/otlp_http_exporter_custom_client_test.cc @@ -4,13 +4,25 @@ #ifndef OPENTELEMETRY_STL_VERSION # include +# include +# include # include "opentelemetry/exporters/otlp/otlp_http_client.h" # include "opentelemetry/exporters/otlp/otlp_http_exporter.h" # include "opentelemetry/exporters/otlp/otlp_http_exporter_factory.h" # include "opentelemetry/exporters/otlp/otlp_http_exporter_options.h" # include "opentelemetry/exporters/otlp/otlp_http_exporter_runtime_options.h" + +# include "opentelemetry/exporters/otlp/protobuf_include_prefix.h" + +# include +# include "opentelemetry/proto/collector/trace/v1/trace_service.pb.h" + +# include "opentelemetry/exporters/otlp/protobuf_include_suffix.h" + +# include "opentelemetry/ext/http/client/http_client.h" # include "opentelemetry/ext/http/client/http_client_factory.h" +# include "opentelemetry/sdk/common/exporter_utils.h" # include "opentelemetry/sdk/trace/batch_span_processor.h" # include "opentelemetry/sdk/trace/batch_span_processor_options.h" # include "opentelemetry/sdk/trace/tracer_provider.h" @@ -33,12 +45,13 @@ namespace http_client = opentelemetry::ext::http::client; using NosendHttpClientFactory = opentelemetry::test_common::ext::http::client::nosend::HttpClientFactoryNosend; -static OtlpHttpClientOptions MakeOtlpHttpClientOptions() +static OtlpHttpClientOptions MakeOtlpHttpClientOptions( + std::chrono::system_clock::duration timeout = std::chrono::system_clock::duration::zero()) { std::shared_ptr not_instrumented; OtlpHttpExporterOptions options; options.console_debug = true; - options.timeout = std::chrono::system_clock::duration::zero(); + options.timeout = timeout; options.retry_policy_max_attempts = 0U; options.retry_policy_initial_backoff = std::chrono::duration::zero(); options.retry_policy_max_backoff = std::chrono::duration::zero(); @@ -77,6 +90,23 @@ class OtlpHttpExporterCustomClientTestPeer : public ::testing::Test auto http_client = http_client::HttpClientTestFactory::Create(); return {new OtlpHttpClient(MakeOtlpHttpClientOptions(), http_client), http_client}; } + + // A non-zero request budget keeps the export asynchronous, so it returns while the session runs. + static void ExportOneRequest(OtlpHttpClient &otlp_client) + { + auto arena = std::make_unique(); + auto *request = + google::protobuf::Arena::Create( + arena.get()); + auto *response = + google::protobuf::Arena::Create( + arena.get()); + + otlp_client.Export( + *request, std::move(arena), response, + [](opentelemetry::sdk::common::ExportResult, google::protobuf::Message *) { return true; }, + 1); + } }; TEST_F(OtlpHttpExporterCustomClientTestPeer, FactoryInjectionCreatesExporter) @@ -145,6 +175,66 @@ TEST_F(OtlpHttpExporterCustomClientTestPeer, ExportCallsSendRequest) provider->ForceFlush(); } +TEST_F(OtlpHttpExporterCustomClientTestPeer, ForceFlushReturnsWithinTheCallerDeadline) +{ + auto client = http_client::HttpClientTestFactory::Create(); + auto no_send_client = std::static_pointer_cast(client); + auto session = std::static_pointer_cast(no_send_client->session_); + + // Hold the request open, so ForceFlush has something to wait for. + std::shared_ptr pending; + EXPECT_CALL(*session, SendRequest) + .WillRepeatedly( + [&pending](std::shared_ptr callback) { + pending = std::move(callback); + }); + + // A client timeout far longer than the deadline ForceFlush is given below. + OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::seconds{30}), client); + + ExportOneRequest(otlp_client); + ASSERT_NE(pending, nullptr); + + const auto started = std::chrono::steady_clock::now(); + const bool flushed = otlp_client.ForceFlush(std::chrono::milliseconds{50}); + const auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started) + .count(); + + EXPECT_FALSE(flushed); + EXPECT_LT(elapsed, 1000) << "waited on the client timeout rather than the one it was given"; + + // Complete the export, or the client destructor waits on it. + http_client::nosend::Response sent; + sent.Finish(*pending); +} + +// The result is the finished counter alone, so a flush with nothing left to wait for has to say +// so. Guards the counter against the session bookkeeping it is derived from. +TEST_F(OtlpHttpExporterCustomClientTestPeer, ForceFlushReportsSuccessOnceTheSessionIsDone) +{ + auto client = http_client::HttpClientTestFactory::Create(); + auto no_send_client = std::static_pointer_cast(client); + auto session = std::static_pointer_cast(no_send_client->session_); + + std::shared_ptr pending; + EXPECT_CALL(*session, SendRequest) + .WillRepeatedly( + [&pending](std::shared_ptr callback) { + pending = std::move(callback); + }); + + OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::seconds{30}), client); + + ExportOneRequest(otlp_client); + ASSERT_NE(pending, nullptr); + + http_client::nosend::Response sent; + sent.Finish(*pending); + + EXPECT_TRUE(otlp_client.ForceFlush(std::chrono::milliseconds{50})); +} + } // namespace otlp } // namespace exporter OPENTELEMETRY_END_NAMESPACE