Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup of context from Runtime storage #885

Merged
merged 7 commits into from
Jul 9, 2021
Merged
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
12 changes: 8 additions & 4 deletions api/include/opentelemetry/context/runtime_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -223,15 +223,19 @@ class ThreadLocalContextStorage : public RuntimeContextStorage

Stack() noexcept : size_(0), capacity_(0), base_(nullptr){};

// Pops the top Context off the stack and returns it.
Context Pop() noexcept
// Pops the top Context off the stack.
void Pop() noexcept
{
if (size_ == 0)
{
return Context();
return;
}
// Store empty Context before decrementing `size`, to ensure
// the shared_ptr object (if stored in prev context object ) are released.
// The stack is not resized, and the unused memory would be reutilised
// for subsequent context storage.
base_[size_ - 1] = Context();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How could someone get a shared_ptr of the Context stored in ThreadLocalContextStorage?

Copy link
Member Author

@lalitb lalitb Jul 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Line 237 is actually resetting the base[size - 1] with empty Context() object. This is to ensure that previously-stored shared_ptr<Span> gets released. The new empty Context() is not supposed to be used again.

size_ -= 1;
return base_[size_];
}

bool Contains(const Token &token) const noexcept
Expand Down
20 changes: 20 additions & 0 deletions sdk/test/trace/tracer_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -632,3 +632,23 @@ TEST(Tracer, ValidTraceIdToSampler)
EXPECT_TRUE(span->IsRecording());
EXPECT_TRUE(span->GetContext().IsValid());
}

TEST(Tracer, SpanCleanupWithScope)
{
std::unique_ptr<InMemorySpanExporter> exporter(new InMemorySpanExporter());
std::shared_ptr<InMemorySpanData> span_data = exporter->GetData();
auto tracer = initTracer(std::move(exporter));
{
auto span0 = tracer->StartSpan("Span0");
auto span1 = tracer->StartSpan("span1");
{
trace_api::Scope scope(span1);
auto span2 = tracer->StartSpan("span2");
{
trace_api::Scope scope(span2);
auto span3 = tracer->StartSpan("span3");
}
}
}
EXPECT_EQ(4, span_data->GetSpans().size());
}