Skip to content

Commit 7532fca

Browse files
authored
[BUG] Stop OTLP ForceFlush returning on the first notification and overrunning its deadline (#4357)
1 parent 44b4540 commit 7532fca

5 files changed

Lines changed: 270 additions & 13 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ Increment the:
5757

5858
* [BUG] Stop reading past a `nostd::string_view` that is not NUL terminated
5959
[#4346](https://github.com/open-telemetry/opentelemetry-cpp/pull/4346)
60+
* [BUG] Stop OTLP `ForceFlush` returning on the first notification and
61+
overrunning the caller's deadline
62+
[#4357](https://github.com/open-telemetry/opentelemetry-cpp/pull/4357)
6063

6164
* [OTLP EXPORTERS] add otlp_common target for shared otlp utils
6265
[#4333](https://github.com/open-telemetry/opentelemetry-cpp/pull/4333)

‎exporters/otlp/src/otlp_grpc_client.cc‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -757,20 +757,20 @@ bool OtlpGrpcClient::ForceFlush(
757757
while (timeout_steady > std::chrono::steady_clock::duration::zero() &&
758758
request_counter > async_data_->finished_request_counter.load(std::memory_order_acquire))
759759
{
760-
// When changes of running_sessions_ and notify_one/notify_all happen between predicate
761-
// checking and waiting, we should not wait forever.We should cleanup gc sessions here as soon
762-
// as possible to call FinishSession() and cleanup resources.
760+
// A completion can land between the loop condition and the wait, so the wait is bounded and the
761+
// condition re-read on every wakeup. Never wait past the caller's deadline.
762+
const std::chrono::steady_clock::duration wait_interval =
763+
(std::min)(std::chrono::duration_cast<std::chrono::steady_clock::duration>(
764+
async_data_->export_timeout),
765+
timeout_steady);
766+
763767
std::chrono::steady_clock::time_point start_timepoint = std::chrono::steady_clock::now();
764-
if (std::cv_status::timeout !=
765-
async_data_->session_waker.wait_for(lock, async_data_->export_timeout))
766-
{
767-
break;
768-
}
768+
async_data_->session_waker.wait_for(lock, wait_interval);
769769

770770
timeout_steady -= std::chrono::steady_clock::now() - start_timepoint;
771771
}
772772

773-
return timeout_steady > std::chrono::steady_clock::duration::zero();
773+
return request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire);
774774
#else
775775
return true;
776776
#endif

‎exporters/otlp/src/otlp_http_client.cc‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
#include <algorithm>
45
#include <atomic>
56
#include <chrono>
67
#include <condition_variable>
@@ -857,8 +858,12 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept
857858
// When changes of running_sessions_ and notify_one/notify_all happen between predicate
858859
// checking and waiting, we should not wait forever.We should cleanup gc sessions here as soon
859860
// as possible to call FinishSession() and cleanup resources.
861+
const std::chrono::steady_clock::duration wait_interval = (std::min)(
862+
std::chrono::duration_cast<std::chrono::steady_clock::duration>(options_.timeout),
863+
timeout_steady);
864+
860865
std::chrono::steady_clock::time_point start_timepoint = std::chrono::steady_clock::now();
861-
if (std::cv_status::timeout == session_waker_.wait_for(lock, options_.timeout))
866+
if (std::cv_status::timeout == session_waker_.wait_for(lock, wait_interval))
862867
{
863868
cleanupGCSessions();
864869
}
@@ -870,7 +875,10 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept
870875
timeout_steady -= std::chrono::steady_clock::now() - start_timepoint;
871876
}
872877

873-
return timeout_steady > std::chrono::steady_clock::duration::zero();
878+
// What the wait was for, rather than what is left of the deadline. A session that finishes
879+
// between the last check and the last wait takes its notification with it, and the flush it was
880+
// holding up has happened.
881+
return finished_session_counter_.load(std::memory_order_acquire) >= wait_counter;
874882
}
875883

876884
bool OtlpHttpClient::Shutdown(std::chrono::microseconds timeout) noexcept

‎exporters/otlp/test/otlp_grpc_exporter_test.cc‎

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,13 @@
4040
# include <grpcpp/grpcpp.h>
4141
# include <gtest/gtest.h>
4242
# include <algorithm>
43+
# include <chrono>
44+
# include <cstddef>
45+
# include <functional>
4346
# include <future>
47+
# include <memory>
48+
# include <mutex>
49+
# include <thread>
4450
# include <utility>
4551
# include <vector>
4652

@@ -86,6 +92,13 @@ class OtlpMockTraceServiceStub : public proto::collector::trace::v1::MockTraceSe
8692
::opentelemetry::proto::collector::trace::v1::ExportTraceServiceResponse *response,
8793
std::function<void(::grpc::Status)> callback) override
8894
{
95+
if (stub_->defer_completions_)
96+
{
97+
std::lock_guard<std::mutex> guard(stub_->deferred_lock_);
98+
stub_->deferred_.push_back(std::move(callback));
99+
return;
100+
}
101+
89102
stub_->last_async_status_ = stub_->Export(context, *request, response);
90103
callback(stub_->last_async_status_);
91104
}
@@ -118,11 +131,68 @@ class OtlpMockTraceServiceStub : public proto::collector::trace::v1::MockTraceSe
118131

119132
::grpc::Status GetLastAsyncStatus() const noexcept { return last_async_status_; }
120133

134+
// Keep the completion callbacks instead of running them inline, so a test can call ForceFlush()
135+
// with requests still in flight. Call before the first export.
136+
void DeferCompletions() noexcept { defer_completions_ = true; }
137+
138+
std::size_t DeferredCount()
139+
{
140+
std::lock_guard<std::mutex> guard(deferred_lock_);
141+
return deferred_.size();
142+
}
143+
144+
// Completes whichever deferred request has been waiting longest, false when there is none.
145+
bool CompleteOneDeferred()
146+
{
147+
std::function<void(::grpc::Status)> callback;
148+
{
149+
std::lock_guard<std::mutex> guard(deferred_lock_);
150+
if (deferred_.empty())
151+
{
152+
return false;
153+
}
154+
callback = std::move(deferred_.front());
155+
deferred_.erase(deferred_.begin());
156+
}
157+
158+
callback(::grpc::Status::OK);
159+
return true;
160+
}
161+
162+
void CompleteAllDeferred()
163+
{
164+
while (CompleteOneDeferred())
165+
{
166+
}
167+
}
168+
121169
private:
122170
::grpc::Status last_async_status_;
171+
bool defer_completions_{false};
172+
std::mutex deferred_lock_;
173+
std::vector<std::function<void(::grpc::Status)>> deferred_;
123174
async_interface async_interface_;
124175
};
125176

177+
// Completes whatever is still deferred on the way out. ~OtlpGrpcClient waits for
178+
// running_requests to reach zero with no deadline, and TryCancel() cannot move it for a request
179+
// the stub is holding, so an assertion that ends a case early would hang the binary instead of
180+
// failing it. Declare after the exporter, so this runs first.
181+
class DrainDeferredCompletions
182+
{
183+
public:
184+
explicit DrainDeferredCompletions(OtlpMockTraceServiceStub *stub) noexcept : stub_(stub) {}
185+
~DrainDeferredCompletions() { stub_->CompleteAllDeferred(); }
186+
187+
DrainDeferredCompletions(const DrainDeferredCompletions &) = delete;
188+
DrainDeferredCompletions &operator=(const DrainDeferredCompletions &) = delete;
189+
DrainDeferredCompletions(DrainDeferredCompletions &&) = delete;
190+
DrainDeferredCompletions &operator=(DrainDeferredCompletions &&) = delete;
191+
192+
private:
193+
OtlpMockTraceServiceStub *stub_;
194+
};
195+
126196
using opentelemetry::test_common::ScopedTestLogHandler;
127197
} // namespace
128198

@@ -244,6 +314,92 @@ TEST_F(OtlpGrpcExporterTestPeer, ExportPartialSuccess)
244314
EXPECT_TRUE(contains("too many spans!!"));
245315
}
246316

317+
namespace
318+
{
319+
// ForceFlush() only has requests to wait for when the client tracks them, which it does under
320+
// ENABLE_ASYNC_EXPORT. gtest_add_tests registers by source text, so the cases below have to exist
321+
// in every build and opt out here rather than be compiled away.
322+
class OtlpGrpcExporterFlushTestPeer : public OtlpGrpcExporterTestPeer
323+
{
324+
protected:
325+
void SetUp() override
326+
{
327+
# if !defined(ENABLE_ASYNC_EXPORT)
328+
GTEST_SKIP() << "ForceFlush has no in-flight requests to wait for without async export";
329+
# endif
330+
}
331+
};
332+
333+
// The wait is bounded by the exporter's timeout, so a caller asking for less than that used to
334+
// wait for the larger of the two.
335+
TEST_F(OtlpGrpcExporterFlushTestPeer, ForceFlushReturnsWithinTheCallerDeadline)
336+
{
337+
auto *mock_stub = new OtlpMockTraceServiceStub();
338+
mock_stub->DeferCompletions();
339+
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> stub_interface(
340+
mock_stub);
341+
auto exporter = GetExporter(stub_interface);
342+
DrainDeferredCompletions drain{mock_stub};
343+
344+
auto recordable = exporter->MakeRecordable();
345+
recordable->SetName("Test span");
346+
nostd::span<std::unique_ptr<sdk::trace::Recordable>> batch(&recordable, 1);
347+
exporter->Export(batch);
348+
ASSERT_EQ(1u, mock_stub->DeferredCount());
349+
350+
const auto started = std::chrono::steady_clock::now();
351+
const bool flushed = exporter->ForceFlush(std::chrono::milliseconds{50});
352+
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
353+
std::chrono::steady_clock::now() - started);
354+
355+
EXPECT_FALSE(flushed);
356+
EXPECT_LT(elapsed.count(), 1000)
357+
<< "waited on the export timeout rather than the one it was given";
358+
}
359+
360+
// A completion for one request used to end the wait for every other request, and the leftover
361+
// deadline was then reported as success.
362+
TEST_F(OtlpGrpcExporterFlushTestPeer, ForceFlushKeepsWaitingWhenAnotherRequestCompletes)
363+
{
364+
auto *mock_stub = new OtlpMockTraceServiceStub();
365+
mock_stub->DeferCompletions();
366+
std::unique_ptr<proto::collector::trace::v1::TraceService::StubInterface> stub_interface(
367+
mock_stub);
368+
auto exporter = GetExporter(stub_interface);
369+
DrainDeferredCompletions drain{mock_stub};
370+
371+
auto first = exporter->MakeRecordable();
372+
first->SetName("Test span 1");
373+
nostd::span<std::unique_ptr<sdk::trace::Recordable>> first_batch(&first, 1);
374+
exporter->Export(first_batch);
375+
376+
auto second = exporter->MakeRecordable();
377+
second->SetName("Test span 2");
378+
nostd::span<std::unique_ptr<sdk::trace::Recordable>> second_batch(&second, 1);
379+
exporter->Export(second_batch);
380+
381+
ASSERT_EQ(2u, mock_stub->DeferredCount());
382+
383+
// Completed once the flush below is parked, so it arrives as a notification rather than as a
384+
// counter the loop condition reads on its way in.
385+
std::thread completer([mock_stub] {
386+
std::this_thread::sleep_for(std::chrono::milliseconds{100});
387+
mock_stub->CompleteOneDeferred();
388+
});
389+
390+
const auto started = std::chrono::steady_clock::now();
391+
const bool flushed = exporter->ForceFlush(std::chrono::milliseconds{1000});
392+
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
393+
std::chrono::steady_clock::now() - started);
394+
completer.join();
395+
396+
EXPECT_FALSE(flushed);
397+
// Ran its own deadline down rather than returning on the notification.
398+
EXPECT_GE(elapsed.count(), 500);
399+
EXPECT_EQ(1u, mock_stub->DeferredCount());
400+
}
401+
} // namespace
402+
247403
// Create spans, let processor call Export()
248404
TEST_F(OtlpGrpcExporterTestPeer, ExportIntegrationTest)
249405
{

‎exporters/otlp/test/otlp_http_exporter_custom_client_test.cc‎

Lines changed: 92 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,25 @@
44
#ifndef OPENTELEMETRY_STL_VERSION
55

66
# include <chrono>
7+
# include <memory>
8+
# include <utility>
79

810
# include "opentelemetry/exporters/otlp/otlp_http_client.h"
911
# include "opentelemetry/exporters/otlp/otlp_http_exporter.h"
1012
# include "opentelemetry/exporters/otlp/otlp_http_exporter_factory.h"
1113
# include "opentelemetry/exporters/otlp/otlp_http_exporter_options.h"
1214
# include "opentelemetry/exporters/otlp/otlp_http_exporter_runtime_options.h"
15+
16+
# include "opentelemetry/exporters/otlp/protobuf_include_prefix.h"
17+
18+
# include <google/protobuf/arena.h>
19+
# include "opentelemetry/proto/collector/trace/v1/trace_service.pb.h"
20+
21+
# include "opentelemetry/exporters/otlp/protobuf_include_suffix.h"
22+
23+
# include "opentelemetry/ext/http/client/http_client.h"
1324
# include "opentelemetry/ext/http/client/http_client_factory.h"
25+
# include "opentelemetry/sdk/common/exporter_utils.h"
1426
# include "opentelemetry/sdk/trace/batch_span_processor.h"
1527
# include "opentelemetry/sdk/trace/batch_span_processor_options.h"
1628
# include "opentelemetry/sdk/trace/tracer_provider.h"
@@ -33,12 +45,13 @@ namespace http_client = opentelemetry::ext::http::client;
3345
using NosendHttpClientFactory =
3446
opentelemetry::test_common::ext::http::client::nosend::HttpClientFactoryNosend;
3547

36-
static OtlpHttpClientOptions MakeOtlpHttpClientOptions()
48+
static OtlpHttpClientOptions MakeOtlpHttpClientOptions(
49+
std::chrono::system_clock::duration timeout = std::chrono::system_clock::duration::zero())
3750
{
3851
std::shared_ptr<opentelemetry::sdk::common::ThreadInstrumentation> not_instrumented;
3952
OtlpHttpExporterOptions options;
4053
options.console_debug = true;
41-
options.timeout = std::chrono::system_clock::duration::zero();
54+
options.timeout = timeout;
4255
options.retry_policy_max_attempts = 0U;
4356
options.retry_policy_initial_backoff = std::chrono::duration<float>::zero();
4457
options.retry_policy_max_backoff = std::chrono::duration<float>::zero();
@@ -77,6 +90,23 @@ class OtlpHttpExporterCustomClientTestPeer : public ::testing::Test
7790
auto http_client = http_client::HttpClientTestFactory::Create();
7891
return {new OtlpHttpClient(MakeOtlpHttpClientOptions(), http_client), http_client};
7992
}
93+
94+
// A non-zero request budget keeps the export asynchronous, so it returns while the session runs.
95+
static void ExportOneRequest(OtlpHttpClient &otlp_client)
96+
{
97+
auto arena = std::make_unique<google::protobuf::Arena>();
98+
auto *request =
99+
google::protobuf::Arena::Create<proto::collector::trace::v1::ExportTraceServiceRequest>(
100+
arena.get());
101+
auto *response =
102+
google::protobuf::Arena::Create<proto::collector::trace::v1::ExportTraceServiceResponse>(
103+
arena.get());
104+
105+
otlp_client.Export(
106+
*request, std::move(arena), response,
107+
[](opentelemetry::sdk::common::ExportResult, google::protobuf::Message *) { return true; },
108+
1);
109+
}
80110
};
81111

82112
TEST_F(OtlpHttpExporterCustomClientTestPeer, FactoryInjectionCreatesExporter)
@@ -145,6 +175,66 @@ TEST_F(OtlpHttpExporterCustomClientTestPeer, ExportCallsSendRequest)
145175
provider->ForceFlush();
146176
}
147177

178+
TEST_F(OtlpHttpExporterCustomClientTestPeer, ForceFlushReturnsWithinTheCallerDeadline)
179+
{
180+
auto client = http_client::HttpClientTestFactory::Create();
181+
auto no_send_client = std::static_pointer_cast<http_client::nosend::HttpClient>(client);
182+
auto session = std::static_pointer_cast<http_client::nosend::Session>(no_send_client->session_);
183+
184+
// Hold the request open, so ForceFlush has something to wait for.
185+
std::shared_ptr<opentelemetry::ext::http::client::EventHandler> pending;
186+
EXPECT_CALL(*session, SendRequest)
187+
.WillRepeatedly(
188+
[&pending](std::shared_ptr<opentelemetry::ext::http::client::EventHandler> callback) {
189+
pending = std::move(callback);
190+
});
191+
192+
// A client timeout far longer than the deadline ForceFlush is given below.
193+
OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::seconds{30}), client);
194+
195+
ExportOneRequest(otlp_client);
196+
ASSERT_NE(pending, nullptr);
197+
198+
const auto started = std::chrono::steady_clock::now();
199+
const bool flushed = otlp_client.ForceFlush(std::chrono::milliseconds{50});
200+
const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
201+
std::chrono::steady_clock::now() - started)
202+
.count();
203+
204+
EXPECT_FALSE(flushed);
205+
EXPECT_LT(elapsed, 1000) << "waited on the client timeout rather than the one it was given";
206+
207+
// Complete the export, or the client destructor waits on it.
208+
http_client::nosend::Response sent;
209+
sent.Finish(*pending);
210+
}
211+
212+
// The result is the finished counter alone, so a flush with nothing left to wait for has to say
213+
// so. Guards the counter against the session bookkeeping it is derived from.
214+
TEST_F(OtlpHttpExporterCustomClientTestPeer, ForceFlushReportsSuccessOnceTheSessionIsDone)
215+
{
216+
auto client = http_client::HttpClientTestFactory::Create();
217+
auto no_send_client = std::static_pointer_cast<http_client::nosend::HttpClient>(client);
218+
auto session = std::static_pointer_cast<http_client::nosend::Session>(no_send_client->session_);
219+
220+
std::shared_ptr<opentelemetry::ext::http::client::EventHandler> pending;
221+
EXPECT_CALL(*session, SendRequest)
222+
.WillRepeatedly(
223+
[&pending](std::shared_ptr<opentelemetry::ext::http::client::EventHandler> callback) {
224+
pending = std::move(callback);
225+
});
226+
227+
OtlpHttpClient otlp_client(MakeOtlpHttpClientOptions(std::chrono::seconds{30}), client);
228+
229+
ExportOneRequest(otlp_client);
230+
ASSERT_NE(pending, nullptr);
231+
232+
http_client::nosend::Response sent;
233+
sent.Finish(*pending);
234+
235+
EXPECT_TRUE(otlp_client.ForceFlush(std::chrono::milliseconds{50}));
236+
}
237+
148238
} // namespace otlp
149239
} // namespace exporter
150240
OPENTELEMETRY_END_NAMESPACE

0 commit comments

Comments
 (0)