Skip to content
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
196 changes: 179 additions & 17 deletions api/include/opentelemetry/context/runtime_context.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class Token
bool operator==(const Context &other) noexcept { return context_ == other; }

private:
friend class RuntimeContext;
friend class RuntimeContextStorage;

// The ContextDetacher object automatically attempts to detach
// the Token when all copies of the Token are out of scope.
Expand Down Expand Up @@ -45,28 +45,64 @@ class Token
nostd::shared_ptr<ContextDetacher> detacher_;
};

// Provides a wrapper for propagating the context object globally. In order
// to use either the threadlocal_context.h file must be included or another
// implementation which must be derived from the RuntimeContext can be
// provided.
/**
* RuntimeContextStorage is used by RuntimeContext to store Context frames.
*
* Custom context management strategies can be implemented by deriving from
* this class and passing an initialized RuntimeContextStorage object to
* RuntimeContext::SetRuntimeContextStorage.
*/
class RuntimeContextStorage
{
public:
/**
* Return the current context.
* @return the current context
*/
virtual Context GetCurrent() noexcept = 0;

/**
* Set the current context.
* @param the new current context
*/
virtual Token Attach(Context context) noexcept = 0;

/**
* Detach the context related to the given token.
* @param token a token related to a context
* @return true if the context could be detached
*/
virtual bool Detach(Token &token) noexcept = 0;

protected:
Token CreateToken(Context context) noexcept { return Token(context); }
};

/**
* Construct and return the default RuntimeContextStorage
* @return a ThreadLocalContextStorage
*/
static RuntimeContextStorage *GetDefaultStorage() noexcept;

// Provides a wrapper for propagating the context object globally.
//
// By default, a thread-local runtime context storage is used.
class RuntimeContext
{
public:
// Return the current context.
static Context GetCurrent() noexcept { return context_handler_->InternalGetCurrent(); }
static Context GetCurrent() noexcept { return GetRuntimeContextStorage()->GetCurrent(); }

// Sets the current 'Context' object. Returns a token
// that can be used to reset to the previous Context.
static Token Attach(Context context) noexcept
{
return context_handler_->InternalAttach(context);
return GetRuntimeContextStorage()->Attach(context);
}

// Resets the context to a previous value stored in the
// passed in token. Returns true if successful, false otherwise
static bool Detach(Token &token) noexcept { return context_handler_->InternalDetach(token); }

static RuntimeContext *context_handler_;
static bool Detach(Token &token) noexcept { return GetRuntimeContextStorage()->Detach(token); }

// Sets the Key and Value into the passed in context or if a context is not
// passed in, the RuntimeContext.
Expand Down Expand Up @@ -108,15 +144,31 @@ class RuntimeContext
return temp_context.GetValue(key);
}

protected:
// Provides a token with the passed in context
Token CreateToken(Context context) noexcept { return Token(context); }

virtual Context InternalGetCurrent() noexcept = 0;
/**
* Provide a custom runtime context storage.
*
* This provides a possibility to override the default thread-local runtime
* context storage. This has to be set before any spans are created by the
* application, otherwise the behavior is undefined.
*
* @param storage a custom runtime context storage
*/
static void SetRuntimeContextStorage(nostd::shared_ptr<RuntimeContextStorage> storage) noexcept
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this method typically gonna be the very first method called before any telemetry is emitted by the process?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hard to say. I think it is, but I'm not sure about all the different scenarios.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is this method typically gonna be the very first method called before any telemetry is emitted by the process?

I documented that this method has to be called before any spans are created.

{
GetStorage() = storage;
}

virtual Token InternalAttach(Context context) noexcept = 0;
private:
static nostd::shared_ptr<RuntimeContextStorage> GetRuntimeContextStorage() noexcept
{
return GetStorage();
}

virtual bool InternalDetach(Token &token) noexcept = 0;
static nostd::shared_ptr<RuntimeContextStorage> &GetStorage() noexcept
{
static nostd::shared_ptr<RuntimeContextStorage> context(GetDefaultStorage());
return context;
}
};

inline Token::ContextDetacher::~ContextDetacher()
Expand All @@ -125,5 +177,115 @@ inline Token::ContextDetacher::~ContextDetacher()
token.context_ = context_;
context::RuntimeContext::Detach(token);
}

// The ThreadLocalContextStorage class is a derived class from
// RuntimeContextStorage and provides a wrapper for propogating context through
// cpp thread locally. This file must be included to use the RuntimeContext
// class if another implementation has not been registered.
class ThreadLocalContextStorage : public RuntimeContextStorage
Comment thread
reyang marked this conversation as resolved.
{
public:
ThreadLocalContextStorage() noexcept = default;

// Return the current context.
Context GetCurrent() noexcept override { return GetStack().Top(); }

// Resets the context to a previous value stored in the
// passed in token. Returns true if successful, false otherwise
bool Detach(Token &token) noexcept override
{
if (!(token == GetStack().Top()))
{
return false;
}
GetStack().Pop();
return true;
}

// Sets the current 'Context' object. Returns a token
// that can be used to reset to the previous Context.
Token Attach(Context context) noexcept override
{
GetStack().Push(context);
Token old_context = CreateToken(context);
return old_context;
}

private:
// A nested class to store the attached contexts in a stack.
class Stack
{
friend class ThreadLocalContextStorage;

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

// Pops the top Context off the stack and returns it.
Context Pop() noexcept
{
if (size_ == 0)
{
return Context();
}
size_ -= 1;
return base_[size_];
}

// Returns the Context at the top of the stack.
Context Top() const noexcept
{
if (size_ == 0)
{
return Context();
}
return base_[size_ - 1];
}

// Pushes the passed in context pointer to the top of the stack
// and resizes if necessary.
void Push(Context context) noexcept
{
size_++;
if (size_ > capacity_)
{
Resize(size_ * 2);
}
base_[size_ - 1] = context;
}

// Reallocates the storage array to the pass in new capacity size.
void Resize(int new_capacity) noexcept
{
int old_size = size_ - 1;
if (new_capacity == 0)
{
new_capacity = 2;
}
Context *temp = new Context[new_capacity];
if (base_ != nullptr)
{
std::copy(base_, base_ + old_size, temp);
delete[] base_;
}
base_ = temp;
}

~Stack() noexcept { delete[] base_; }

size_t size_;
size_t capacity_;
Context *base_;
};

Stack &GetStack()
{
static thread_local Stack stack_ = Stack();
return stack_;
}
};

static RuntimeContextStorage *GetDefaultStorage() noexcept
{
return new ThreadLocalContextStorage();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Wondering whether it is necessary to new ThreadLocalContextStorage() at every call, or just keep one global instance?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That call is used to initialize the one global instance. It's only called once to initialize a static variable.

}
} // namespace context
OPENTELEMETRY_END_NAMESPACE
116 changes: 0 additions & 116 deletions api/include/opentelemetry/context/threadlocal_context.h

This file was deleted.

2 changes: 1 addition & 1 deletion api/test/context/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
include(GoogleTest)

foreach(testname context_test)
foreach(testname context_test runtime_context_test)
add_executable(${testname} "${testname}.cc")
target_link_libraries(${testname} ${GTEST_BOTH_LIBRARIES}
${CMAKE_THREAD_LIBS_INIT} opentelemetry_api)
Expand Down
2 changes: 1 addition & 1 deletion api/test/context/runtime_context_test.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#include "opentelemetry/context/runtime_context.h"
#include "opentelemetry/context/context.h"
#include "opentelemetry/context/threadlocal_context.h"

#include <gtest/gtest.h>

Expand Down
1 change: 0 additions & 1 deletion api/test/plugin/dynamic_load_test.cc
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#include "opentelemetry/plugin/dynamic_load.h"
#include "opentelemetry/context/threadlocal_context.h"

#include <gtest/gtest.h>

Expand Down
1 change: 0 additions & 1 deletion api/test/trace/scope_test.cc
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#include "opentelemetry/trace/scope.h"
#include "opentelemetry/context/context.h"
#include "opentelemetry/context/threadlocal_context.h"
#include "opentelemetry/nostd/shared_ptr.h"
#include "opentelemetry/trace/noop.h"

Expand Down
2 changes: 1 addition & 1 deletion ci/do_ci.sh
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ elif [[ "$1" == "bazel.tsan" ]]; then
exit 0
elif [[ "$1" == "bazel.valgrind" ]]; then
bazel build $BAZEL_OPTIONS //...
bazel test --run_under="/usr/bin/valgrind --leak-check=full --error-exitcode=1" $BAZEL_TEST_OPTIONS //...
bazel test --run_under="/usr/bin/valgrind --leak-check=full --error-exitcode=1 --suppressions=\"${SRC_DIR}/ci/valgrind-suppressions\"" $BAZEL_TEST_OPTIONS //...
exit 0
elif [[ "$1" == "benchmark" ]]; then
[ -z "${BENCHMARK_DIR}" ] && export BENCHMARK_DIR=$HOME/benchmark
Expand Down
Loading