Skip to content

Commit 8e61017

Browse files
authored
[SDK] Fix MetricReader post shutdown handling (#4548)
1 parent e0e0458 commit 8e61017

4 files changed

Lines changed: 218 additions & 8 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,14 @@ Increment the:
2020
`CURLE_SEND_FAIL_REWIND` and dropping the batch
2121
([#4549](https://github.com/open-telemetry/opentelemetry-cpp/issues/4549))
2222

23+
* [SDK] Fix `MetricReader::ForceFlush()` invoking `OnForceFlush()` on a
24+
shutdown reader.
25+
[#4548](https://github.com/open-telemetry/opentelemetry-cpp/pull/4548)
26+
27+
* [SDK] Fix `MetricReader::Shutdown()` invoking `OnShutDown()` multiple times.
28+
Concurrent calls now block until the first call's shutdown has completed.
29+
[#4536](https://github.com/open-telemetry/opentelemetry-cpp/issues/4536)
30+
2331
* [DOC] Fix and clarify the `StartSpanOptions` documentation
2432
[#4526](https://github.com/open-telemetry/opentelemetry-cpp/pull/4526)
2533

‎sdk/include/opentelemetry/sdk/metrics/metric_reader.h‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include <atomic>
77
#include <chrono>
88
#include <cstddef>
9+
#include <mutex>
910

1011
#include "opentelemetry/nostd/function_ref.h"
1112
#include "opentelemetry/sdk/metrics/cardinality_limits.h"
@@ -71,11 +72,19 @@ class MetricReader
7172

7273
/**
7374
* Shutdown the metric reader.
75+
*
76+
* Idempotent and a completion barrier: only the first call runs OnShutDown(), and a
77+
* concurrent call blocks until the first call has finished before returning.
78+
*
79+
* @return the result of OnShutDown() for the first call, true for any subsequent call.
7480
*/
7581
bool Shutdown(std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept;
7682

7783
/**
7884
* Force flush the metric read by the reader.
85+
*
86+
* @return false without invoking OnForceFlush() if the reader is already shut down, otherwise
87+
* the result of OnForceFlush().
7988
*/
8089
bool ForceFlush(std::chrono::microseconds timeout = (std::chrono::microseconds::max)()) noexcept;
8190

@@ -96,6 +105,7 @@ class MetricReader
96105
protected:
97106
private:
98107
MetricProducer *metric_producer_{nullptr};
108+
std::mutex shutdown_m_;
99109
std::atomic<bool> shutdown_{false};
100110
CardinalityLimits cardinality_limits_;
101111
};

‎sdk/src/metrics/metric_reader.cc‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
#include "opentelemetry/sdk/metrics/metric_reader.h"
5+
#include <mutex>
56
#include "opentelemetry/sdk/common/global_log_handler.h"
67
#include "opentelemetry/sdk/metrics/cardinality_limits.h"
78
#include "opentelemetry/sdk/metrics/export/metric_producer.h"
@@ -48,13 +49,14 @@ bool MetricReader::Collect(
4849

4950
bool MetricReader::Shutdown(std::chrono::microseconds timeout) noexcept
5051
{
51-
bool status = true;
52-
if (IsShutdown())
52+
// Serialize so concurrent calls block until the first call's shutdown has completed.
53+
std::lock_guard<std::mutex> shutdown_guard{shutdown_m_};
54+
if (shutdown_.exchange(true, std::memory_order_release))
5355
{
54-
OTEL_INTERNAL_LOG_WARN("MetricReader::Shutdown - Cannot invoke shutdown twice!");
56+
OTEL_INTERNAL_LOG_WARN("MetricReader::Shutdown - Already shutdown!");
57+
return true;
5558
}
56-
57-
shutdown_.store(true, std::memory_order_release);
59+
bool status = true;
5860

5961
if (!OnShutDown(timeout))
6062
{
@@ -67,11 +69,14 @@ bool MetricReader::Shutdown(std::chrono::microseconds timeout) noexcept
6769
/** Flush metric read by this reader **/
6870
bool MetricReader::ForceFlush(std::chrono::microseconds timeout) noexcept
6971
{
70-
bool status = true;
7172
if (IsShutdown())
7273
{
73-
OTEL_INTERNAL_LOG_WARN("MetricReader::Shutdown Cannot invoke Force flush on shutdown reader!");
74+
OTEL_INTERNAL_LOG_WARN(
75+
"MetricReader::ForceFlush Cannot invoke Force flush on shutdown reader!");
76+
return false;
7477
}
78+
79+
bool status = true;
7580
if (!OnForceFlush(timeout))
7681
{
7782
status = false;

‎sdk/test/metrics/metric_reader_test.cc‎

Lines changed: 188 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,17 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
#include <gtest/gtest.h>
5-
#include <memory>
5+
#include <atomic>
6+
#include <chrono>
7+
#include <future>
68
#include <string>
9+
#include <thread>
710
#include <utility>
11+
#include <vector>
812
#include "common.h"
913

14+
#include "opentelemetry/nostd/shared_ptr.h"
15+
#include "opentelemetry/sdk/common/global_log_handler.h"
1016
#include "opentelemetry/sdk/instrumentationscope/instrumentation_scope.h"
1117
#include "opentelemetry/sdk/metrics/cardinality_limits.h"
1218
#include "opentelemetry/sdk/metrics/export/metric_producer.h"
@@ -147,3 +153,184 @@ TEST(MetricReaderTest, CardinalityLimitsExplicitSdkDefaultIsHonoured)
147153
EXPECT_EQ(metric_reader->GetCardinalityLimit(InstrumentType::kHistogram), 1500);
148154
EXPECT_EQ(metric_reader->GetCardinalityLimit(InstrumentType::kUpDownCounter), 1500);
149155
}
156+
157+
namespace
158+
{
159+
160+
class CountingMetricReader : public MetricReader
161+
{
162+
public:
163+
// hook_result is what both OnForceFlush() and OnShutDown() report back.
164+
explicit CountingMetricReader(bool hook_result = true) : hook_result_(hook_result) {}
165+
166+
AggregationTemporality GetAggregationTemporality(InstrumentType) const noexcept override
167+
{
168+
return AggregationTemporality::kCumulative;
169+
}
170+
171+
std::atomic<int> shutdown_count{0};
172+
std::atomic<int> force_flush_count{0};
173+
174+
private:
175+
bool OnForceFlush(std::chrono::microseconds) noexcept override
176+
{
177+
++force_flush_count;
178+
return hook_result_;
179+
}
180+
181+
bool OnShutDown(std::chrono::microseconds) noexcept override
182+
{
183+
++shutdown_count;
184+
return hook_result_;
185+
}
186+
187+
const bool hook_result_;
188+
};
189+
190+
} // namespace
191+
192+
TEST(MetricReaderTest, ShutdownIsInvokedOnce)
193+
{
194+
CountingMetricReader reader;
195+
196+
EXPECT_TRUE(reader.Shutdown());
197+
EXPECT_TRUE(reader.IsShutdown());
198+
EXPECT_EQ(reader.shutdown_count.load(), 1);
199+
200+
EXPECT_TRUE(reader.Shutdown());
201+
EXPECT_TRUE(reader.Shutdown());
202+
EXPECT_EQ(reader.shutdown_count.load(), 1);
203+
}
204+
205+
TEST(MetricReaderTest, ConcurrentShutdownIsInvokedOnce)
206+
{
207+
namespace internal_log = opentelemetry::sdk::common::internal_log;
208+
CountingMetricReader reader;
209+
210+
// default logger is not thread-safe
211+
auto previous_handler = internal_log::GlobalLogHandler::GetLogHandler();
212+
internal_log::GlobalLogHandler::SetLogHandler(
213+
nostd::shared_ptr<internal_log::LogHandler>(new internal_log::NoopLogHandler()));
214+
215+
std::vector<std::thread> threads;
216+
threads.reserve(8);
217+
for (int i = 0; i < 8; i++)
218+
{
219+
threads.emplace_back([&reader]() { reader.Shutdown(); });
220+
}
221+
for (auto &thread : threads)
222+
{
223+
thread.join();
224+
}
225+
226+
internal_log::GlobalLogHandler::SetLogHandler(previous_handler);
227+
228+
EXPECT_EQ(reader.shutdown_count.load(), 1);
229+
}
230+
231+
TEST(MetricReaderTest, ForceFlushAfterShutdownIsNoOp)
232+
{
233+
CountingMetricReader reader;
234+
235+
EXPECT_TRUE(reader.ForceFlush());
236+
EXPECT_EQ(reader.force_flush_count.load(), 1);
237+
238+
EXPECT_TRUE(reader.Shutdown());
239+
240+
EXPECT_FALSE(reader.ForceFlush());
241+
EXPECT_EQ(reader.force_flush_count.load(), 1);
242+
}
243+
244+
TEST(MetricReaderTest, FailedShutdownIsReportedAndNotRetried)
245+
{
246+
CountingMetricReader reader{/* hook_result= */ false};
247+
248+
EXPECT_FALSE(reader.ForceFlush());
249+
EXPECT_EQ(reader.force_flush_count.load(), 1);
250+
251+
// The first call reports the hook's failure.
252+
EXPECT_FALSE(reader.Shutdown());
253+
EXPECT_TRUE(reader.IsShutdown());
254+
EXPECT_EQ(reader.shutdown_count.load(), 1);
255+
256+
// A later call is a no-op that succeeds, without re-entering the failed hook.
257+
EXPECT_TRUE(reader.Shutdown());
258+
EXPECT_EQ(reader.shutdown_count.load(), 1);
259+
260+
// Flush stays rejected even after a failed shutdown, without re-entering the hook.
261+
EXPECT_FALSE(reader.ForceFlush());
262+
EXPECT_EQ(reader.force_flush_count.load(), 1);
263+
}
264+
265+
namespace
266+
{
267+
268+
// Parks inside OnShutDown() until released, to observe what a concurrent caller sees.
269+
class BlockingMetricReader : public MetricReader
270+
{
271+
public:
272+
AggregationTemporality GetAggregationTemporality(InstrumentType) const noexcept override
273+
{
274+
return AggregationTemporality::kCumulative;
275+
}
276+
277+
std::promise<void> entered_shutdown;
278+
std::promise<void> release_shutdown;
279+
std::atomic<bool> shutdown_finished{false};
280+
281+
private:
282+
bool OnForceFlush(std::chrono::microseconds) noexcept override { return true; }
283+
284+
bool OnShutDown(std::chrono::microseconds) noexcept override
285+
{
286+
entered_shutdown.set_value();
287+
release_shutdown.get_future().wait();
288+
shutdown_finished.store(true, std::memory_order_release);
289+
return true;
290+
}
291+
};
292+
293+
} // namespace
294+
295+
TEST(MetricReaderTest, ConcurrentShutdownWaitsForCleanupToComplete)
296+
{
297+
namespace internal_log = opentelemetry::sdk::common::internal_log;
298+
BlockingMetricReader reader;
299+
300+
// default logger is not thread-safe
301+
auto previous_handler = internal_log::GlobalLogHandler::GetLogHandler();
302+
internal_log::GlobalLogHandler::SetLogHandler(
303+
nostd::shared_ptr<internal_log::LogHandler>(new internal_log::NoopLogHandler()));
304+
305+
auto entered = reader.entered_shutdown.get_future();
306+
std::thread first([&reader]() { EXPECT_TRUE(reader.Shutdown()); });
307+
308+
// The first caller owns the shutdown and is now parked inside OnShutDown().
309+
entered.wait();
310+
EXPECT_TRUE(reader.IsShutdown());
311+
EXPECT_FALSE(reader.shutdown_finished.load(std::memory_order_acquire));
312+
313+
std::atomic<bool> second_returned{false};
314+
std::promise<void> second_started;
315+
auto started = second_started.get_future();
316+
std::thread second([&]() {
317+
second_started.set_value();
318+
// Block until first caller releases the shutdown, then return true.
319+
EXPECT_TRUE(reader.Shutdown());
320+
EXPECT_TRUE(reader.shutdown_finished.load(std::memory_order_acquire));
321+
second_returned.store(true, std::memory_order_release);
322+
});
323+
324+
started.wait();
325+
// Arbitrary sleep to ensure second is still blocked and not just we were too fast to check.
326+
std::this_thread::sleep_for(std::chrono::milliseconds(50));
327+
EXPECT_FALSE(second_returned.load(std::memory_order_acquire));
328+
329+
reader.release_shutdown.set_value();
330+
second.join();
331+
first.join();
332+
333+
internal_log::GlobalLogHandler::SetLogHandler(previous_handler);
334+
335+
EXPECT_TRUE(second_returned.load(std::memory_order_acquire));
336+
}

0 commit comments

Comments
 (0)