Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ Increment the:

## [Unreleased]

* [EXPORTER] `OtlpHttpClient::ForceFlush`, and `OtlpGrpcClient::ForceFlush`
under the async export preview, now wait for the requests that were pending
when they were called, instead of for as many completions as there were
requests started. A request begun after the call could supply one of those
completions, so the flush reported success with an earlier request still in
flight
[#4339](https://github.com/open-telemetry/opentelemetry-cpp/issues/4339)

* [SDK] Restore the check in `DoubleHistogram::Record` that drops NaN and +Inf
measurements, so they no longer reach the histogram aggregations

Expand Down
4 changes: 3 additions & 1 deletion exporters/otlp/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ if(OTELCPP_WITH_OTLP_HTTP)
opentelemetry_exporter_otlp_http_client
PUBLIC opentelemetry_http_client
PRIVATE opentelemetry_common)
otel_link_libatomic(opentelemetry_exporter_otlp_http_client)

target_include_directories(
opentelemetry_exporter_otlp_http_client
Expand Down Expand Up @@ -529,7 +530,8 @@ if(OTELCPP_WITH_OTLP_HTTP)
endif()
opentelemetry_add_pkgconfig(
exporter_otlp_http_client "OpenTelemetry OTLP - HTTP Client"
"HTTP client for OTLP protocol." "${_otlp_http_client_pc_requires}")
"HTTP client for OTLP protocol." "${_otlp_http_client_pc_requires}"
EXTRA_LIBS ${OPENTELEMETRY_ATOMIC_LIB})

opentelemetry_add_pkgconfig(
exporter_otlp_http
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <list>
#include <memory>
Expand Down Expand Up @@ -244,6 +245,12 @@ class OtlpHttpClient
std::unique_ptr<google::protobuf::Arena> arena;
google::protobuf::Message *response = nullptr;

// Where this session falls in the order sessions were started, taken from
// start_session_counter_ before it is incremented. ForceFlush waits for the sessions below
// the sequence it was entered with, rather than for a number of completions that a session
// started after the call could supply.
std::uint64_t sequence = 0;

HttpSessionData() noexcept;
HttpSessionData(std::shared_ptr<opentelemetry::ext::http::client::Session> &&input_session,
std::shared_ptr<opentelemetry::ext::http::client::EventHandler> &&input_handle,
Expand Down Expand Up @@ -286,6 +293,15 @@ class OtlpHttpClient
*/
bool cleanupGCSessions() noexcept;

/**
* @brief Whether every session started before the given sequence has finished.
*
* Reads running_sessions_ under session_manager_lock_, so it answers for the moment it is
* called. A session started after the call has a sequence at or above the given one, so it
* does not hold the answer back.
*/
bool allSessionsBeforeFinished(std::uint64_t sequence) noexcept;

// Stores if this HTTP client had its Shutdown() method called
std::atomic<bool> is_shutdown_;

Expand All @@ -308,8 +324,11 @@ class OtlpHttpClient
// Condition variable and mutex to control the concurrency count of running sessions
std::mutex session_waker_lock_;
std::condition_variable session_waker_;
std::atomic<size_t> start_session_counter_;
std::atomic<size_t> finished_session_counter_;
std::atomic<std::uint64_t> start_session_counter_;

// For testing. Reaches start_session_counter_ and allSessionsBeforeFinished, so that the
// sequence a flush would take as its cutoff can be asked about without racing a real flush.
friend class OtlpHttpExporterCustomClientTestPeer;
};
} // namespace otlp
} // namespace exporter
Expand Down
77 changes: 67 additions & 10 deletions exporters/otlp/src/otlp_grpc_client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,11 @@ class OPENTELEMETRY_LOCAL_SYMBOL OtlpGrpcAsyncCallDataBase
opentelemetry::sdk::common::ExportResult::kFailure;
GrpcAsyncCallback grpc_async_callback = nullptr;

// Where this call falls in the order calls were started, taken from start_request_counter
// before it is incremented. ForceFlush waits for the calls below the sequence it was entered
// with, rather than for a number of completions that a call started after it could supply.
std::uint64_t sequence = 0;

OtlpGrpcAsyncCallDataBase() = default;
virtual ~OtlpGrpcAsyncCallDataBase() = default;
OtlpGrpcAsyncCallDataBase(const OtlpGrpcAsyncCallDataBase &) = delete;
Expand Down Expand Up @@ -114,8 +119,7 @@ struct OtlpGrpcClientAsyncData
// Running requests, this is used to limit the number of concurrent requests.
std::atomic<std::size_t> running_requests{0};
// Request counter is used to record ForceFlush.
std::atomic<std::size_t> start_request_counter{0};
std::atomic<std::size_t> finished_request_counter{0};
std::atomic<std::uint64_t> start_request_counter{0};
std::size_t max_concurrent_requests = 64;

// Condition variable and mutex to control the concurrency count of running requests.
Expand Down Expand Up @@ -205,10 +209,12 @@ static sdk::common::ExportResult InternalDelegateAsyncExport(
return true;
};

++async_data->start_request_counter;
++async_data->running_requests;
{
std::lock_guard<std::mutex> lock{async_data->running_calls_lock};
// Counted inside the lock the flush predicate takes, so a ForceFlush cannot read a sequence
// that includes this call and then fail to find the call itself.
call_data->sequence = async_data->start_request_counter.fetch_add(1, std::memory_order_release);
async_data->running_calls.insert(
std::static_pointer_cast<OtlpGrpcAsyncCallDataBase>(call_data));
}
Expand All @@ -225,11 +231,12 @@ static sdk::common::ExportResult InternalDelegateAsyncExport(
std::lock_guard<std::mutex> lock{async_data->running_calls_lock};
async_data->running_calls.erase(
std::static_pointer_cast<OtlpGrpcAsyncCallDataBase>(call_data));
// Dropped under the same lock as the erase. ForceFlush answers from the
// registry now, so releasing the lock first would leave a window where a
// flush reports success and the next Export is still refused for capacity.
--async_data->running_requests;
}

--async_data->running_requests;
++async_data->finished_request_counter;

call_data->grpc_status = grpc_status;
if (call_data->grpc_status.ok())
{
Expand Down Expand Up @@ -719,6 +726,52 @@ bool OtlpGrpcClient::IsShutdown() const noexcept
return is_shutdown_.load(std::memory_order_acquire);
}

#ifdef ENABLE_ASYNC_EXPORT
namespace
{
/// Whether \p sequence was handed out before \p cutoff, across a wrap of the counter.
///
/// The counter is finite, so this is a distance and not a comparison. cutoff - sequence is
/// evaluated in unsigned arithmetic: it is small for a request that started before the cutoff,
/// including when the counter has since wrapped past zero, and close to the whole range for one
/// that started after it. Half the range is the dividing line, so the answer holds while fewer
/// than 2^63 sequences are handed out during the lifetime of the request being asked about.
/// Nothing bounds that from the number of requests in flight at once, which is why the sequence
/// is 64 bits wide rather than size_t: at a thousand registrations a second the boundary is a few
/// hundred million years away, and at 32 bits it was twenty five days.
bool StartedBefore(std::uint64_t sequence, std::uint64_t cutoff) noexcept
{
const std::uint64_t distance = cutoff - sequence;
return distance != 0U && distance <= ((~static_cast<std::uint64_t>(0)) >> 1);
}
} // namespace

namespace
{
/// Whether every call started before the given sequence has finished.
///
/// A call started after the flush has a sequence at or above the given one, so it does not hold
/// the answer back. Takes running_calls_lock. The check on the way into ForceFlush holds nothing
/// else; the loop condition and the result hold session_waker_lock too, and that nesting, waker
/// then calls, is the only one in this file. Nothing takes the two the other way round.
bool AllCallsBeforeFinished(const std::shared_ptr<OtlpGrpcClientAsyncData> &async_data,
std::uint64_t sequence) noexcept
{
std::lock_guard<std::mutex> lock{async_data->running_calls_lock};

for (const auto &call_data : async_data->running_calls)
{
if (call_data && StartedBefore(call_data->sequence, sequence))
{
return false;
}
}

return true;
}
} // namespace
#endif

bool OtlpGrpcClient::ForceFlush(
OPENTELEMETRY_MAYBE_UNUSED std::chrono::microseconds timeout) noexcept
{
Expand All @@ -728,8 +781,12 @@ bool OtlpGrpcClient::ForceFlush(
}

#ifdef ENABLE_ASYNC_EXPORT
std::size_t request_counter = async_data_->start_request_counter.load(std::memory_order_acquire);
if (request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire))
// The calls to wait for are the ones already started, so the sequence is read once and the
// predicate is about those. A request that starts after this point cannot satisfy the flush and
// cannot hold it back either.
const std::uint64_t wait_sequence =
async_data_->start_request_counter.load(std::memory_order_acquire);
if (AllCallsBeforeFinished(async_data_, wait_sequence))
{
return true;
}
Expand All @@ -750,7 +807,7 @@ bool OtlpGrpcClient::ForceFlush(
}

while (timeout_steady > std::chrono::steady_clock::duration::zero() &&
request_counter > async_data_->finished_request_counter.load(std::memory_order_acquire))
!AllCallsBeforeFinished(async_data_, wait_sequence))
{
// 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.
Expand All @@ -765,7 +822,7 @@ bool OtlpGrpcClient::ForceFlush(
timeout_steady -= std::chrono::steady_clock::now() - start_timepoint;
}

return request_counter <= async_data_->finished_request_counter.load(std::memory_order_acquire);
return AllCallsBeforeFinished(async_data_, wait_sequence);
#else
return true;
#endif
Expand Down
67 changes: 49 additions & 18 deletions exporters/otlp/src/otlp_http_client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <list>
Expand Down Expand Up @@ -709,8 +710,7 @@ OtlpHttpClient::OtlpHttpClient(OtlpHttpClientOptions &&options,
: is_shutdown_(false),
options_(std::move(options)),
http_client_(std::move(http_client)),
start_session_counter_(0),
finished_session_counter_(0)
start_session_counter_(0)
{
http_client_->SetMaxSessionsPerConnection(options_.max_requests_per_connection);
}
Expand Down Expand Up @@ -829,16 +829,16 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept
timeout_steady = (std::chrono::steady_clock::duration::max)();
}

size_t wait_counter = start_session_counter_.load(std::memory_order_acquire);
// The sessions to wait for are the ones already started, so the sequence is read once and the
// predicate is about those. A request that starts after this point cannot satisfy the flush and
// cannot hold it back either.
const std::uint64_t wait_sequence = start_session_counter_.load(std::memory_order_acquire);

while (timeout_steady > std::chrono::steady_clock::duration::zero())
{
if (allSessionsBeforeFinished(wait_sequence))
{
std::lock_guard<std::recursive_mutex> guard{session_manager_lock_};
if (running_sessions_.empty())
{
break;
}
break;
}
// 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
Expand All @@ -852,18 +852,14 @@ bool OtlpHttpClient::ForceFlush(std::chrono::microseconds timeout) noexcept
{
cleanupGCSessions();
}
else if (finished_session_counter_.load(std::memory_order_acquire) >= wait_counter)
{
break;
}

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

// 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;
// The same question the loop asked, so the result and the reason the wait ended agree. 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 allSessionsBeforeFinished(wait_sequence);
}

bool OtlpHttpClient::Shutdown(std::chrono::microseconds timeout) noexcept
Expand Down Expand Up @@ -902,7 +898,6 @@ void OtlpHttpClient::ReleaseSession(
gc_sessions_.emplace_back(std::move(session_iter->second));
running_sessions_.erase(session_iter);

finished_session_counter_.fetch_add(1, std::memory_order_release);
has_session = true;
}

Expand Down Expand Up @@ -1076,13 +1071,49 @@ void OtlpHttpClient::addSession(HttpSessionData &&session_data) noexcept

HttpSessionData &store_session_data = running_sessions_[session.get()];
store_session_data = std::move(session_data);
// Assigned after the move, which would otherwise overwrite it, and inside the lock the
// predicate takes, so a concurrent ForceFlush never reads an entry without a sequence.
store_session_data.sequence = start_session_counter_.fetch_add(1, std::memory_order_release);
}

start_session_counter_.fetch_add(1, std::memory_order_release);
// Send request after the session is added
session->SendRequest(handle);
}

namespace
{
/// Whether \p sequence was handed out before \p cutoff, across a wrap of the counter.
///
/// The counter is finite, so this is a distance and not a comparison. cutoff - sequence is
/// evaluated in unsigned arithmetic: it is small for a request that started before the cutoff,
/// including when the counter has since wrapped past zero, and close to the whole range for one
/// that started after it. Half the range is the dividing line, so the answer holds while fewer
/// than 2^63 sequences are handed out during the lifetime of the request being asked about.
/// Nothing bounds that from the number of requests in flight at once, which is why the sequence
/// is 64 bits wide rather than size_t: at a thousand registrations a second the boundary is a few
/// hundred million years away, and at 32 bits it was twenty five days.
bool StartedBefore(std::uint64_t sequence, std::uint64_t cutoff) noexcept
{
const std::uint64_t distance = cutoff - sequence;
return distance != 0U && distance <= ((~static_cast<std::uint64_t>(0)) >> 1);
}
} // namespace

bool OtlpHttpClient::allSessionsBeforeFinished(std::uint64_t sequence) noexcept
{
std::lock_guard<std::recursive_mutex> guard{session_manager_lock_};

for (const auto &running_session : running_sessions_)
{
if (StartedBefore(running_session.second.sequence, sequence))
{
return false;
}
}

return true;
}

bool OtlpHttpClient::cleanupGCSessions() noexcept
{
std::lock_guard<std::recursive_mutex> guard{session_manager_lock_};
Expand Down
Loading
Loading