From 45e0c4b4f55d7e848aa48ea120816459afd3aaf6 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sat, 31 Dec 2022 22:58:27 -0500 Subject: [PATCH 01/46] First attempt --- .gitmodules | 5 + CMakeLists.txt | 7 + opentracing-shim/CMakeLists.txt | 40 +++ opentracing-shim/include/shim_utils.h | 134 +++++++++ opentracing-shim/include/span_context_shim.h | 51 ++++ opentracing-shim/include/span_shim.h | 56 ++++ opentracing-shim/include/tracer_shim.h | 103 +++++++ opentracing-shim/src/CMakeLists.txt | 34 +++ opentracing-shim/src/span_context_shim.cc | 37 +++ opentracing-shim/src/span_shim.cc | 133 +++++++++ opentracing-shim/src/tracer_shim.cc | 273 +++++++++++++++++++ opentracing-shim/test/CMakeLists.txt | 9 + opentracing-shim/test/shim_test.cc | 47 ++++ opentracing-shim/test/tracer_test.cpp | 43 +++ 14 files changed, 972 insertions(+) create mode 100644 opentracing-shim/CMakeLists.txt create mode 100644 opentracing-shim/include/shim_utils.h create mode 100644 opentracing-shim/include/span_context_shim.h create mode 100644 opentracing-shim/include/span_shim.h create mode 100644 opentracing-shim/include/tracer_shim.h create mode 100644 opentracing-shim/src/CMakeLists.txt create mode 100644 opentracing-shim/src/span_context_shim.cc create mode 100644 opentracing-shim/src/span_shim.cc create mode 100644 opentracing-shim/src/tracer_shim.cc create mode 100644 opentracing-shim/test/CMakeLists.txt create mode 100644 opentracing-shim/test/shim_test.cc create mode 100644 opentracing-shim/test/tracer_test.cpp diff --git a/.gitmodules b/.gitmodules index c422e39e27..88a78e5f94 100644 --- a/.gitmodules +++ b/.gitmodules @@ -32,3 +32,8 @@ branch = main path = third_party/nlohmann-json url = https://github.com/nlohmann/json branch = master + +[submodule "third_party/opentracing-cpp"] +path = third_party/opentracing-cpp +url = https://github.com/opentracing/opentracing-cpp.git +branch = master diff --git a/CMakeLists.txt b/CMakeLists.txt index f1a6d1cd17..b0db1cbfe7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -170,6 +170,8 @@ option(BUILD_W3CTRACECONTEXT_TEST "Whether to build w3c trace context" OFF) option(OTELCPP_MAINTAINER_MODE "Build in maintainer mode (-Wall -Werror)" OFF) +option(WITH_OPENTRACING "Whether to include the Opentracing shim" ON) + set(OTELCPP_PROTO_PATH "" CACHE PATH "Path to opentelemetry-proto") @@ -492,6 +494,10 @@ include_directories(api/include) add_subdirectory(api) +if(WITH_OPENTRACING) + add_subdirectory(opentracing-shim) +endif() + if(NOT WITH_API_ONLY) set(BUILD_TESTING ${BUILD_TESTING}) include_directories(sdk/include) @@ -501,6 +507,7 @@ if(NOT WITH_API_ONLY) add_subdirectory(sdk) add_subdirectory(ext) add_subdirectory(exporters) + if(BUILD_TESTING) add_subdirectory(test_common) endif() diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt new file mode 100644 index 0000000000..4b6daf8619 --- /dev/null +++ b/opentracing-shim/CMakeLists.txt @@ -0,0 +1,40 @@ +#set(this_target opentelemetry_opentracing_shim) + +#message("CMAKE_CURRENT_LIST_DIR " ${CMAKE_CURRENT_LIST_DIR}) +#message("CMAKE_CURRENT_SOURCE_DIR " ${CMAKE_CURRENT_SOURCE_DIR}) +#message("CMAKE_SOURCE_DIR " ${CMAKE_SOURCE_DIR}) +#message("PROJECT_SOURCE_DIR " ${PROJECT_SOURCE_DIR}) + +#add_library(${this_target} INTERFACE) +#target_include_directories( +# ${this_target} +# PUBLIC "$" +# "$" +# "$") +# +#set_target_properties(${this_target} PROPERTIES EXPORT_NAME "opentracing-shim") +#target_link_libraries(${this_target} INTERFACE ${this_target} opentracing-cpp) +# +#get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES) +#foreach(dir ${dirs}) +# message(STATUS "dir='${dir}'") +#endforeach() +# +#install( +# TARGETS ${this_target} +# EXPORT "${PROJECT_NAME}-target" +# RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} +# LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} +# ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) +# +#install( +# DIRECTORY include/opentelemetry/opentracing-shim +# DESTINATION include/opentelemetry/ +# FILES_MATCHING +# PATTERN "*.h") + +add_subdirectory(src) + +if(BUILD_TESTING) + add_subdirectory(test) +endif() # BUILD_TESTING \ No newline at end of file diff --git a/opentracing-shim/include/shim_utils.h b/opentracing-shim/include/shim_utils.h new file mode 100644 index 0000000000..3c7fce0fcc --- /dev/null +++ b/opentracing-shim/include/shim_utils.h @@ -0,0 +1,134 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim::shimutils +{ + +using opentelemetry::common::AttributeValue; + +static inline AttributeValue attributeFromValue(const opentracing::Value& value) +{ + static struct + { + AttributeValue operator()(bool v) { return v; } + AttributeValue operator()(double v) { return v; } + AttributeValue operator()(int64_t v) { return v; } + AttributeValue operator()(uint64_t v) { return v; } + AttributeValue operator()(std::string v) { return v.c_str(); } + AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } + AttributeValue operator()(std::nullptr_t) { return std::string{}; } + AttributeValue operator()(const char* v) { return v; } + AttributeValue operator()(opentracing::util::recursive_wrapper) { return std::string{}; } + AttributeValue operator()(opentracing::util::recursive_wrapper) { return std::string{}; } + } AttributeMapper; + + return opentracing::Value::visit(value, AttributeMapper); +} + +static inline std::string stringFromValue(const opentracing::Value& value) +{ + static struct + { + std::string operator()(bool v) { return v ? "true" : "false"; } + std::string operator()(double v) { return std::to_string(v); } + std::string operator()(int64_t v) { return std::to_string(v); } + std::string operator()(uint64_t v) { return std::to_string(v); } + std::string operator()(std::string v) { return v; } + std::string operator()(opentracing::string_view v) { return std::string{v.data()}; } + std::string operator()(std::nullptr_t) { return std::string{}; } + std::string operator()(const char* v) { return std::string{v}; } + std::string operator()(opentracing::util::recursive_wrapper) { return std::string{}; } + std::string operator()(opentracing::util::recursive_wrapper) { return std::string{}; } + } StringMapper; + + return opentracing::Value::visit(value, StringMapper); +} + +template::value, bool> = true> +class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCarrier +{ +public: + + CarrierWriterShim(const T& writer) : writer_(writer) {} + + // returns the value associated with the passed key. + virtual nostd::string_view Get(nostd::string_view key) const noexcept override + { + return ""; + } + + // stores the key-value pair. + virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override + { + writer_.Set(key.data(), value.data()); + } + +private: + + const T& writer_; + +}; + +template::value, bool> = true> +class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCarrier +{ +public: + + CarrierReaderShim(const T& reader) : reader_(reader) {} + + // returns the value associated with the passed key. + virtual nostd::string_view Get(nostd::string_view key) const noexcept override + { + // First try carrier.LookupKey since that can potentially be the fastest approach. + auto result = reader_.LookupKey(key.data()); + + if (!result.has_value() || + opentracing::are_errors_equal(result.error(), opentracing::lookup_key_not_supported_error)) + { + // Fall back to iterating through all of the keys. + reader_.ForeachKey([key, &result] + (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { + if (key == k) + { + result = opentracing::make_expected(v); + // Found key, so bail out of the loop with a success error code. + return opentracing::make_unexpected(std::error_code{}); + } + return opentracing::make_expected(); + }); + } + + return nostd::string_view{ result.has_value() ? result.value().data() : "" }; + } + + // stores the key-value pair. + virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override + { + // Not required for Opentracing reader + } + +private: + + const T& reader_; + +}; + +static inline bool isBaggageEmpty(const BaggagePtr& baggage) +{ + if (baggage) + { + return baggage->GetAllEntries([](nostd::string_view, nostd::string_view){ + return false; + }); + } + + return true; +} + +} // namespace opentracingshim::shimutils +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/span_context_shim.h b/opentracing-shim/include/span_context_shim.h new file mode 100644 index 0000000000..b2db5ed6c8 --- /dev/null +++ b/opentracing-shim/include/span_context_shim.h @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "opentelemetry/baggage/baggage.h" +#include "opentelemetry/trace/span_context.h" +#include "opentracing/span.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +using BaggagePtr = nostd::shared_ptr; + +class SpanContextShim final : public opentracing::SpanContext +{ +public: + + explicit SpanContextShim(const opentelemetry::trace::SpanContext& context, const BaggagePtr& baggage) : + context_(context), baggage_(baggage) {} + + inline SpanContextShim operator=(const SpanContextShim& other) + { + return SpanContextShim(other.context_, other.baggage_); + } + + inline const opentelemetry::trace::SpanContext& context() const { return context_; } + + inline const BaggagePtr& baggage() const { return baggage_; } + + SpanContextShim newWithKeyValue(const nostd::string_view &key, const nostd::string_view &value) const noexcept; + + bool BaggageItem(nostd::string_view key, std::string& value) const noexcept; + + using VisitBaggageItem = std::function; + void ForeachBaggageItem(VisitBaggageItem f) const override; + + std::unique_ptr Clone() const noexcept override; + +private: + + const opentelemetry::trace::SpanContext context_; + const BaggagePtr baggage_; + +}; + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/include/span_shim.h b/opentracing-shim/include/span_shim.h new file mode 100644 index 0000000000..a90b7499dd --- /dev/null +++ b/opentracing-shim/include/span_shim.h @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "tracer_shim.h" +#include "span_context_shim.h" + +#include "opentelemetry/baggage/baggage.h" +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/spin_lock_mutex.h" +#include "opentelemetry/trace/span.h" +#include "opentracing/span.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +using SpanPtr = nostd::shared_ptr; +using EventEntry = std::pair; + +class SpanShim : public opentracing::Span +{ +public: + + explicit SpanShim(const TracerShim& tracer, const SpanPtr& span, const BaggagePtr& baggage) : + tracer_(tracer), span_(span), context_(span->GetContext(), baggage) {} + + void handleError(const opentracing::Value& value) noexcept; + + void FinishWithOptions(const opentracing::FinishSpanOptions& finish_span_options) noexcept override; + void SetOperationName(opentracing::string_view name) noexcept override; + void SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept override; + void SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept override; + std::string BaggageItem(opentracing::string_view restricted_key) const noexcept override; + void Log(std::initializer_list fields) noexcept override; + void Log(opentracing::SystemTime timestamp, std::initializer_list fields) noexcept override; + void Log(opentracing::SystemTime timestamp, const std::vector& fields) noexcept override; + inline const opentracing::SpanContext& context() const noexcept override { return context_; }; + inline const opentracing::Tracer& tracer() const noexcept override { return tracer_; }; + +private: + + void logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept; + + TracerShim tracer_; + SpanPtr span_; + SpanContextShim context_; + mutable opentelemetry::common::SpinLockMutex context_lock_; + +}; + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/include/tracer_shim.h b/opentracing-shim/include/tracer_shim.h new file mode 100644 index 0000000000..df98b2647d --- /dev/null +++ b/opentracing-shim/include/tracer_shim.h @@ -0,0 +1,103 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "opentelemetry/trace/tracer.h" +#include "opentelemetry/trace/provider.h" +#include "opentelemetry/context/propagation/text_map_propagator.h" +#include "opentracing/tracer.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +using TracerPtr = nostd::shared_ptr; +using TracerProviderPtr = nostd::shared_ptr; +using PropagatorPtr = nostd::shared_ptr; + +struct OpenTracingPropagators { + PropagatorPtr textMap; + PropagatorPtr httpHeaders; +}; + +class TracerShim : public opentracing::Tracer +{ +public: + + /** + * Creates a {@code opentracing::Tracer} shim out of + * {@code Provider::GetTracerProvider()} and + * {@code GlobalTextMapPropagator::GetGlobalPropagator()}. + * + * @returns a {@code opentracing::Tracer}. + */ + static inline TracerShim createTracerShim() + { + return createTracerShim(opentelemetry::trace::Provider::GetTracerProvider()); + } + + /** + * Creates a {@code opentracing::Tracer} shim using the provided + * {@code TracerProvider} and + * {@code TextMapPropagator} instance. + * + * @param provider the {@code TracerProvider} instance used to create this shim. + * @param propagators the {@code OpenTracingPropagators} instance used to create this shim. + * @returns a {@code opentracing::Tracer}. + */ + static inline TracerShim createTracerShim(const TracerProviderPtr& provider, + const OpenTracingPropagators& propagators = {}) + { + return createTracerShim(provider->GetTracer("opentracing-shim"), propagators); + } + + /** + * Creates a {@code opentracing::Tracer} shim using provided + * {@code Tracer} instance and + * {@code GlobalTextMapPropagator::GetGlobalPropagator()}. + * + * @returns a {@code opentracing::Tracer}. + */ + static inline TracerShim createTracerShim(const TracerPtr& tracer, + const OpenTracingPropagators& propagators = {}) + { + return TracerShim(tracer, propagators); + } + + std::unique_ptr StartSpanWithOptions(opentracing::string_view operation_name, + const opentracing::StartSpanOptions& options) const noexcept override; + opentracing::expected Inject(const opentracing::SpanContext& sc, + std::ostream& writer) const override; + opentracing::expected Inject(const opentracing::SpanContext& sc, + const opentracing::TextMapWriter& writer) const override; + opentracing::expected Inject(const opentracing::SpanContext& sc, + const opentracing::HTTPHeadersWriter& writer) const override; + opentracing::expected> Extract(std::istream& reader) const override; + opentracing::expected> Extract(const opentracing::TextMapReader& reader) const override; + opentracing::expected> Extract(const opentracing::HTTPHeadersReader& reader) const override; + inline void Close() noexcept override { is_closed_ = true; }; + +private: + + explicit TracerShim(const TracerPtr& tracer, const OpenTracingPropagators& propagators) + : tracer_(tracer), propagators_(propagators) {} + + template + opentracing::expected injectImpl(const opentracing::SpanContext& sc, + const T& writer, + const PropagatorPtr& propagator) const; + + template + opentracing::expected> extractImpl(const T& reader, + const PropagatorPtr& propagator) const; + + TracerPtr tracer_; + OpenTracingPropagators propagators_; + bool is_closed_ = false; +}; + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/src/CMakeLists.txt b/opentracing-shim/src/CMakeLists.txt new file mode 100644 index 0000000000..10e840a377 --- /dev/null +++ b/opentracing-shim/src/CMakeLists.txt @@ -0,0 +1,34 @@ +set(THIS_TARGET opentelemetry_opentracing_shim) +set(TARGET_NAME opentracing_shim) + +include_directories( + ${CMAKE_CURRENT_LIST_DIR}/../include + ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/include + ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/build/include + ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/3rd_party/include) + +file(GLOB_RECURSE SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/*.cc) +file(GLOB_RECURSE HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/../include/*.h) + +add_library(${THIS_TARGET} SHARED ${SOURCE_FILES} ${HEADER_FILES}) + +set_target_properties(${THIS_TARGET} PROPERTIES EXPORT_NAME ${TARGET_NAME}) + +target_include_directories( + ${THIS_TARGET} + PUBLIC "$" + "$") + +target_link_libraries(${THIS_TARGET} PUBLIC opentelemetry_api) + +install( + TARGETS ${THIS_TARGET} + EXPORT "${PROJECT_NAME}-target" + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES) +foreach(dir ${dirs}) + message(STATUS "dir='${dir}'") +endforeach() \ No newline at end of file diff --git a/opentracing-shim/src/span_context_shim.cc b/opentracing-shim/src/span_context_shim.cc new file mode 100644 index 0000000000..d220634701 --- /dev/null +++ b/opentracing-shim/src/span_context_shim.cc @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "span_context_shim.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +SpanContextShim SpanContextShim::newWithKeyValue(const nostd::string_view &key, const nostd::string_view &value) const noexcept +{ + return SpanContextShim{context_, baggage_->Set(key, value)}; +} + +bool SpanContextShim::BaggageItem(nostd::string_view key, std::string& value) const noexcept +{ + return baggage_->GetValue(key, value); +} + +void SpanContextShim::ForeachBaggageItem(VisitBaggageItem f) const +{ + baggage_->GetAllEntries([&f](nostd::string_view key, nostd::string_view value) + { + return f(key.data(), value.data()); + } + ); +} + +std::unique_ptr SpanContextShim::Clone() const noexcept +{ + return std::unique_ptr(new (std::nothrow) SpanContextShim(context_, baggage_)); +} + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc new file mode 100644 index 0000000000..6600872494 --- /dev/null +++ b/opentracing-shim/src/span_shim.cc @@ -0,0 +1,133 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "span_shim.h" +#include "span_context_shim.h" +#include "tracer_shim.h" +#include "shim_utils.h" + +#include "opentelemetry/trace/semantic_conventions.h" +#include "opentelemetry/trace/span_metadata.h" +#include + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +void SpanShim::handleError(const opentracing::Value& value) noexcept +{ + using opentelemetry::trace::StatusCode; + + auto code = StatusCode::kUnset; + const auto& str_value = shimutils::stringFromValue(value); + if (str_value == "true") + { + code = StatusCode::kError; + } + else if (str_value == "false") + { + code = StatusCode::kOk; + } + + span_->SetStatus(code); +} + +void SpanShim::FinishWithOptions(const opentracing::FinishSpanOptions& finish_span_options) noexcept +{ + span_->End({{ finish_span_options.finish_steady_timestamp }}); +} + +void SpanShim::SetOperationName(opentracing::string_view name) noexcept +{ + span_->UpdateName(name.data()); +} + +void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept +{ + if (key == opentracing::ext::error) + { + handleError(value); + } + else + { + span_->SetAttribute(key.data(), shimutils::attributeFromValue(value)); + } +} + +void SpanShim::SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept +{ + const std::lock_guard guard(context_lock_); + context_ = context_.newWithKeyValue(restricted_key.data(), value.data()); +} + +std::string SpanShim::BaggageItem(opentracing::string_view restricted_key) const noexcept +{ + const std::lock_guard guard(context_lock_); + std::string value; + return context_.BaggageItem(restricted_key.data(), value) ? value : ""; +} + +void SpanShim::Log(std::initializer_list fields) noexcept +{ + logImpl(opentracing::SystemTime::min(), fields); +} + +void SpanShim::Log(opentracing::SystemTime timestamp, std::initializer_list fields) noexcept +{ + logImpl(timestamp, fields); +} + +void SpanShim::Log(opentracing::SystemTime timestamp, const std::vector& fields) noexcept +{ + logImpl(timestamp, fields); +} + +void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept +{ + const auto event = std::find_if(fields.begin(), fields.end(), [](EventEntry item){ return item.first == "event"; }); + auto name = (event != fields.end()) ? shimutils::stringFromValue(event->second) : std::string{"log"}; + + bool is_error = (name == opentracing::ext::error); + if (is_error) name = "exception"; + + std::vector> attributes; + attributes.reserve(fields.size()); + + for (const auto& entry : fields) + { + auto key = entry.first; + const auto& value = shimutils::attributeFromValue(entry.second); + + if (is_error) + { + if (key == "error.kind") + { + key = opentelemetry::trace::SemanticConventions::kExceptionType; + } + else if (key == "message") + { + key = opentelemetry::trace::SemanticConventions::kExceptionMessage; + } + else if (key == "stack") + { + key = opentelemetry::trace::SemanticConventions::kExceptionStacktrace; + } + } + + attributes.emplace_back(key, value); + } + + if (timestamp != opentracing::SystemTime::min()) + { + span_->AddEvent(name, timestamp, attributes); + } + else + { + span_->AddEvent(name, attributes); + } +} + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc new file mode 100644 index 0000000000..ac5cd31ef9 --- /dev/null +++ b/opentracing-shim/src/tracer_shim.cc @@ -0,0 +1,273 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "tracer_shim.h" +#include "span_shim.h" +#include "shim_utils.h" + +#include +#include +#include +#include +#include + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +namespace detail +{ + +using RefsList = std::initializer_list>; +using LinksList = std::vector>; + +static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing::StartSpanOptions& options) noexcept +{ + using opentracing::SpanReferenceType; + + opentelemetry::trace::StartSpanOptions options_shim; + // If an explicit start timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. + options_shim.start_system_time = opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; + options_shim.start_steady_time = opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; + + const auto& refs = options.references; + + // If a list of Span references is specified... + if (!refs.empty()) + { + auto first_child_of = std::find_if(refs.cbegin(), refs.cend(), + [](const std::pair& entry){ + return entry.first == SpanReferenceType::ChildOfRef; + }); + // The first SpanContext with Child Of type in the entire list is used as parent, + // else the first SpanContext is used as parent + auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; + + if (auto context_shim = dynamic_cast(context)) + { + options_shim.parent = context_shim->context(); + } + } + + return options_shim; +} + +static LinksList makeReferenceLinks(const opentracing::StartSpanOptions& options) noexcept +{ + using opentracing::SpanReferenceType; + using namespace opentelemetry::trace::SemanticConventions; + + LinksList links; + links.reserve(options.references.size()); + + // All values in the list MUST be added as Links with the reference type value + // as a Link attribute, i.e. opentracing.ref_type set to follows_from or child_of + for (const auto& entry : options.references) + { + auto context_shim = dynamic_cast(entry.second); + nostd::string_view span_kind; + + if (entry.first == SpanReferenceType::ChildOfRef) + { + span_kind = OpentracingRefTypeValues::kChildOf; + } + else if (entry.first == SpanReferenceType::FollowsFromRef) + { + span_kind = OpentracingRefTypeValues::kFollowsFrom; + } + + if (context_shim && !span_kind.empty()) + { + // links.push_back({ context_shim->context(), {{ opentracing::ext::span_kind.data(), span_kind }} }); + links.emplace_back(std::piecewise_construct, + std::forward_as_tuple(context_shim->context()), + std::forward_as_tuple(std::forward({{ opentracing::ext::span_kind.data(), span_kind }}))); + } + } + + return links; +} + +static BaggagePtr makeBaggage(const opentracing::StartSpanOptions& options) noexcept +{ + using namespace opentelemetry::baggage; + + std::unordered_map baggage_items; + + // If a list of Span references is specified... + for (const auto& entry : options.references) + { + if (auto context_shim = dynamic_cast(entry.second)) + { + // The union of their Baggage values MUST be used as the initial Baggage of the newly created Span. + context_shim->ForeachBaggageItem([&baggage_items](const std::string& key, const std::string& value){ + // It is unspecified which Baggage value is used in the case of repeated keys. + if (baggage_items.find(key) == baggage_items.end()) + { + baggage_items.emplace(key, value); // Here, only insert if key not already present + } + return true; + }); + } + } + + // If no such lisf of references is specified, the current Baggage + // MUST be used as the initial value of the newly created Span. + return baggage_items.empty() + ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) + : nostd::shared_ptr(new Baggage(baggage_items)); +} + +static std::vector> makeTags(const opentracing::StartSpanOptions& options) noexcept +{ + std::vector> tags; + tags.reserve(options.tags.size()); + + // If an initial set of tags is specified, the values MUST + // be set at the creation time of the OpenTelemetry Span. + for (const auto& entry : options.tags) + { + tags.emplace_back(entry.first, shimutils::attributeFromValue(entry.second)); + } + + return tags; +} + +} // namespace opentracingshim::detail + +std::unique_ptr TracerShim::StartSpanWithOptions(opentracing::string_view operation_name, + const opentracing::StartSpanOptions& options) const noexcept +{ + if (is_closed_) return nullptr; + + const auto& opts = detail::makeOptionsShim(options); + const auto& links = detail::makeReferenceLinks(options); + const auto& baggage = detail::makeBaggage(options); + const auto& attributes = detail::makeTags(options); + + auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); + auto span_shim = new SpanShim(*this, span, baggage); + + // If an initial set of tags is specified and the OpenTracing error tag + // is included after the OpenTelemetry Span was created. + const auto& error_entry = std::find_if(options.tags.begin(), options.tags.end(), + [](const std::pair& entry){ + return entry.first == opentracing::ext::error; + }); + + // The Shim layer MUST perform the same error handling as described in the Set Tag operation + if (error_entry != options.tags.end()) { + span_shim->handleError(error_entry->second); + } + + return std::unique_ptr(span_shim); +} + +opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, + std::ostream& writer) const +{ + // Errors MAY be raised if the specified Format is not recognized, + // depending on the specific OpenTracing Language API. + return opentracing::make_unexpected(opentracing::invalid_carrier_error); +} + +opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, + const opentracing::TextMapWriter& writer) const +{ + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // if any, or else use the global TextMapPropagator. + const auto& propagator = propagators_.textMap + ? propagators_.textMap + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + + return injectImpl(sc, writer, propagator); +} + +opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, + const opentracing::HTTPHeadersWriter& writer) const +{ + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // if any, or else use the global TextMapPropagator. + const auto& propagator = propagators_.httpHeaders + ? propagators_.httpHeaders + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + + return injectImpl(sc, writer, propagator); +} + +opentracing::expected> TracerShim::Extract(std::istream& reader) const +{ + // Errors MAY be raised if either the Format is not recognized or no value + // could be extracted, depending on the specific OpenTracing Language API. + return opentracing::make_unexpected(opentracing::invalid_carrier_error); +} + +opentracing::expected> TracerShim::Extract(const opentracing::TextMapReader& reader) const +{ + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // if any, or else use the global TextMapPropagator. + const auto& propagator = propagators_.textMap + ? propagators_.textMap + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + + return extractImpl(reader, propagator); +} + +opentracing::expected> TracerShim::Extract(const opentracing::HTTPHeadersReader& reader) const +{ + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // if any, or else use the global TextMapPropagator. + const auto& propagator = propagators_.httpHeaders + ? propagators_.httpHeaders + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + + return extractImpl(reader, propagator); +} + +template +opentracing::expected TracerShim::injectImpl(const opentracing::SpanContext& sc, + const T& writer, + const PropagatorPtr& propagator) const +{ + // Inject the underlying OpenTelemetry Span and Baggage using either the explicitly registered + // or the global OpenTelemetry Propagators, as configured at construction time. + if (auto context_shim = dynamic_cast(&sc)) + { + auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); + // It MUST inject any non-empty Baggage even amidst no valid SpanContext. + const auto& context = opentelemetry::baggage::SetBaggage(current_context, context_shim->baggage()); + + shimutils::CarrierWriterShim carrier{writer}; + propagator->Inject(carrier, context); + } + + return opentracing::make_expected(); +} + +template +opentracing::expected> TracerShim::extractImpl(const T& reader, + const PropagatorPtr& propagator) const +{ + // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered + // or the global OpenTelemetry Propagators, as configured at construction time. + shimutils::CarrierReaderShim carrier{reader}; + auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); + auto context = propagator->Extract(carrier, current_context); + auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); + auto baggage = opentelemetry::baggage::GetBaggage(context); + + // If the extracted SpanContext is invalid AND the extracted Baggage is empty, + // this operation MUST return a null value, and otherwise it MUST return a + // SpanContext Shim instance with the extracted values. + SpanContextShim* context_shim = (!span_context.IsValid() && shimutils::isBaggageEmpty(baggage)) + ? nullptr + : new SpanContextShim(span_context, baggage); + + return opentracing::make_expected(std::unique_ptr(context_shim)); +} + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/test/CMakeLists.txt b/opentracing-shim/test/CMakeLists.txt new file mode 100644 index 0000000000..016f938785 --- /dev/null +++ b/opentracing-shim/test/CMakeLists.txt @@ -0,0 +1,9 @@ +set(this_target shim_test) + +add_executable(${this_target} "${this_target}.cc") +target_link_libraries(${this_target} ${GTEST_BOTH_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} opentelemetry_api) +gtest_add_tests( + TARGET ${this_target} + TEST_PREFIX ${this_target}. + TEST_LIST ${this_target}) diff --git a/opentracing-shim/test/shim_test.cc b/opentracing-shim/test/shim_test.cc new file mode 100644 index 0000000000..6d9020b1bb --- /dev/null +++ b/opentracing-shim/test/shim_test.cc @@ -0,0 +1,47 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include "opentelemetry/nostd/shared_ptr.h" +#include "opentelemetry/trace/noop.h" +#include "opentelemetry/trace/scope.h" + +#include + +namespace trace_api = opentelemetry::trace; +namespace nostd = opentelemetry::nostd; +namespace context = opentelemetry::context; + +TEST(ShimTest, SpanReferenceToCreatingTracer) +{ + // auto tracer = MakeNoopTracer(); + + // auto span1 = tracer->StartSpan("a"); + // CHECK(span1); + + // CHECK(&span1->tracer() == tracer.get()); + + // std::unique_ptr tracer(new trace_api::NoopTracer()); + // nostd::shared_ptr span_first(new trace_api::NoopSpan(nullptr)); + // nostd::shared_ptr span_second(new trace_api::NoopSpan(nullptr)); + + // auto current = tracer->GetCurrentSpan(); + // ASSERT_FALSE(current->GetContext().IsValid()); + + // { + // auto scope_first = tracer->WithActiveSpan(span_first); + // current = tracer->GetCurrentSpan(); + // ASSERT_EQ(current, span_first); + + // { + // auto scope_second = tracer->WithActiveSpan(span_second); + // current = tracer->GetCurrentSpan(); + // ASSERT_EQ(current, span_second); + // } + // current = tracer->GetCurrentSpan(); + // ASSERT_EQ(current, span_first); + // } + + // current = tracer->GetCurrentSpan(); + // ASSERT_FALSE(current->GetContext().IsValid()); + ASSERT_TRUE(true); +} diff --git a/opentracing-shim/test/tracer_test.cpp b/opentracing-shim/test/tracer_test.cpp new file mode 100644 index 0000000000..eca3a367fb --- /dev/null +++ b/opentracing-shim/test/tracer_test.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace opentracing; + +#define CATCH_CONFIG_MAIN +#include + +TEST_CASE("tracer") { + auto tracer = MakeNoopTracer(); + + auto span1 = tracer->StartSpan("a"); + CHECK(span1); + + SECTION("Spans provide references to the tracer that created them.") { + CHECK(&span1->tracer() == tracer.get()); + } + + SECTION("Ensure basic operations compile.") { + auto span2 = tracer->StartSpan("b", {ChildOf(&span1->context())}); + CHECK(span2); + span2->SetOperationName("b1"); + span2->SetTag("x", true); + span2->SetTag(opentracing::ext::span_kind, + opentracing::ext::span_kind_rpc_client); + CHECK(span2->BaggageItem("y").empty()); + span2->Log({{"event", "xyz"}, {"abc", 123}}); + span2->Finish(); + } + + SECTION("A reference to a null SpanContext is ignored.") { + StartSpanOptions options; + ChildOf(nullptr).Apply(options); + CHECK(options.references.size() == 0); + } +} + +TEST_CASE("A tracer can be globally registered") { + CHECK(!Tracer::IsGlobalTracerRegistered()); + auto tracer = MakeNoopTracer(); + CHECK(Tracer::InitGlobal(tracer) != nullptr); + CHECK(Tracer::IsGlobalTracerRegistered()); +} From 321a80151dce675733cdfe08c5513765b984fc5d Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 1 Jan 2023 22:49:50 -0500 Subject: [PATCH 02/46] Tracer unit tests wip --- opentracing-shim/CMakeLists.txt | 8 +- opentracing-shim/include/span_shim.h | 2 +- opentracing-shim/include/tracer_shim.h | 12 +- opentracing-shim/src/CMakeLists.txt | 20 ++-- opentracing-shim/test/CMakeLists.txt | 22 ++-- opentracing-shim/test/shim_test.cc | 47 -------- opentracing-shim/test/tracer_shim_test.cc | 133 ++++++++++++++++++++++ opentracing-shim/test/tracer_test.cpp | 43 ------- 8 files changed, 169 insertions(+), 118 deletions(-) delete mode 100644 opentracing-shim/test/shim_test.cc create mode 100644 opentracing-shim/test/tracer_shim_test.cc delete mode 100644 opentracing-shim/test/tracer_test.cpp diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt index 4b6daf8619..7800cbdc91 100644 --- a/opentracing-shim/CMakeLists.txt +++ b/opentracing-shim/CMakeLists.txt @@ -1,4 +1,4 @@ -#set(this_target opentelemetry_opentracing_shim) +set(this_target opentelemetry_opentracing_shim) #message("CMAKE_CURRENT_LIST_DIR " ${CMAKE_CURRENT_LIST_DIR}) #message("CMAKE_CURRENT_SOURCE_DIR " ${CMAKE_CURRENT_SOURCE_DIR}) @@ -33,6 +33,12 @@ # FILES_MATCHING # PATTERN "*.h") +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/include + ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/build/include + ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/3rd_party/include) + add_subdirectory(src) if(BUILD_TESTING) diff --git a/opentracing-shim/include/span_shim.h b/opentracing-shim/include/span_shim.h index a90b7499dd..a6bbf67c12 100644 --- a/opentracing-shim/include/span_shim.h +++ b/opentracing-shim/include/span_shim.h @@ -45,7 +45,7 @@ class SpanShim : public opentracing::Span void logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept; - TracerShim tracer_; + const TracerShim& tracer_; SpanPtr span_; SpanContextShim context_; mutable opentelemetry::common::SpinLockMutex context_lock_; diff --git a/opentracing-shim/include/tracer_shim.h b/opentracing-shim/include/tracer_shim.h index df98b2647d..aada00980e 100644 --- a/opentracing-shim/include/tracer_shim.h +++ b/opentracing-shim/include/tracer_shim.h @@ -34,7 +34,7 @@ class TracerShim : public opentracing::Tracer * * @returns a {@code opentracing::Tracer}. */ - static inline TracerShim createTracerShim() + static inline std::shared_ptr createTracerShim() noexcept { return createTracerShim(opentelemetry::trace::Provider::GetTracerProvider()); } @@ -48,8 +48,8 @@ class TracerShim : public opentracing::Tracer * @param propagators the {@code OpenTracingPropagators} instance used to create this shim. * @returns a {@code opentracing::Tracer}. */ - static inline TracerShim createTracerShim(const TracerProviderPtr& provider, - const OpenTracingPropagators& propagators = {}) + static inline std::shared_ptr createTracerShim(const TracerProviderPtr& provider, + const OpenTracingPropagators& propagators = {}) noexcept { return createTracerShim(provider->GetTracer("opentracing-shim"), propagators); } @@ -61,10 +61,10 @@ class TracerShim : public opentracing::Tracer * * @returns a {@code opentracing::Tracer}. */ - static inline TracerShim createTracerShim(const TracerPtr& tracer, - const OpenTracingPropagators& propagators = {}) + static inline std::shared_ptr createTracerShim(const TracerPtr& tracer, + const OpenTracingPropagators& propagators = {}) noexcept { - return TracerShim(tracer, propagators); + return std::shared_ptr(new (std::nothrow) TracerShim(tracer, propagators)); } std::unique_ptr StartSpanWithOptions(opentracing::string_view operation_name, diff --git a/opentracing-shim/src/CMakeLists.txt b/opentracing-shim/src/CMakeLists.txt index 10e840a377..037e171773 100644 --- a/opentracing-shim/src/CMakeLists.txt +++ b/opentracing-shim/src/CMakeLists.txt @@ -1,28 +1,22 @@ -set(THIS_TARGET opentelemetry_opentracing_shim) -set(TARGET_NAME opentracing_shim) - -include_directories( - ${CMAKE_CURRENT_LIST_DIR}/../include - ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/include - ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/build/include - ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/3rd_party/include) +set(this_target opentelemetry_opentracing_shim) +set(target_name opentracing_shim) file(GLOB_RECURSE SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/*.cc) file(GLOB_RECURSE HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/../include/*.h) -add_library(${THIS_TARGET} SHARED ${SOURCE_FILES} ${HEADER_FILES}) +add_library(${this_target} SHARED ${SOURCE_FILES} ${HEADER_FILES}) -set_target_properties(${THIS_TARGET} PROPERTIES EXPORT_NAME ${TARGET_NAME}) +set_target_properties(${this_target} PROPERTIES EXPORT_NAME ${target_name}) target_include_directories( - ${THIS_TARGET} + ${this_target} PUBLIC "$" "$") -target_link_libraries(${THIS_TARGET} PUBLIC opentelemetry_api) +target_link_libraries(${this_target} PUBLIC opentelemetry_api opentracing) install( - TARGETS ${THIS_TARGET} + TARGETS ${this_target} EXPORT "${PROJECT_NAME}-target" RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} diff --git a/opentracing-shim/test/CMakeLists.txt b/opentracing-shim/test/CMakeLists.txt index 016f938785..19b5cbf44a 100644 --- a/opentracing-shim/test/CMakeLists.txt +++ b/opentracing-shim/test/CMakeLists.txt @@ -1,9 +1,17 @@ set(this_target shim_test) -add_executable(${this_target} "${this_target}.cc") -target_link_libraries(${this_target} ${GTEST_BOTH_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} opentelemetry_api) -gtest_add_tests( - TARGET ${this_target} - TEST_PREFIX ${this_target}. - TEST_LIST ${this_target}) +file(GLOB source_files ${CMAKE_CURRENT_LIST_DIR}/*.*) + +add_executable(${this_target} ${source_files}) + +target_link_libraries(${this_target} + ${GTEST_BOTH_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + opentelemetry_api + opentelemetry_opentracing_shim + opentracing) + +#gtest_add_tests( +# TARGET ${this_target} +# TEST_PREFIX ${this_target}. +# TEST_LIST ${this_target}) diff --git a/opentracing-shim/test/shim_test.cc b/opentracing-shim/test/shim_test.cc deleted file mode 100644 index 6d9020b1bb..0000000000 --- a/opentracing-shim/test/shim_test.cc +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -#include "opentelemetry/nostd/shared_ptr.h" -#include "opentelemetry/trace/noop.h" -#include "opentelemetry/trace/scope.h" - -#include - -namespace trace_api = opentelemetry::trace; -namespace nostd = opentelemetry::nostd; -namespace context = opentelemetry::context; - -TEST(ShimTest, SpanReferenceToCreatingTracer) -{ - // auto tracer = MakeNoopTracer(); - - // auto span1 = tracer->StartSpan("a"); - // CHECK(span1); - - // CHECK(&span1->tracer() == tracer.get()); - - // std::unique_ptr tracer(new trace_api::NoopTracer()); - // nostd::shared_ptr span_first(new trace_api::NoopSpan(nullptr)); - // nostd::shared_ptr span_second(new trace_api::NoopSpan(nullptr)); - - // auto current = tracer->GetCurrentSpan(); - // ASSERT_FALSE(current->GetContext().IsValid()); - - // { - // auto scope_first = tracer->WithActiveSpan(span_first); - // current = tracer->GetCurrentSpan(); - // ASSERT_EQ(current, span_first); - - // { - // auto scope_second = tracer->WithActiveSpan(span_second); - // current = tracer->GetCurrentSpan(); - // ASSERT_EQ(current, span_second); - // } - // current = tracer->GetCurrentSpan(); - // ASSERT_EQ(current, span_first); - // } - - // current = tracer->GetCurrentSpan(); - // ASSERT_FALSE(current->GetContext().IsValid()); - ASSERT_TRUE(true); -} diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc new file mode 100644 index 0000000000..d0273c4b84 --- /dev/null +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -0,0 +1,133 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include "tracer_shim.h" + +#include + +#include + +namespace trace_api = opentelemetry::trace; +namespace nostd = opentelemetry::nostd; +namespace context = opentelemetry::context; +namespace shim = opentelemetry::opentracingshim; + +struct TextMapCarrier : opentracing::TextMapReader, opentracing::TextMapWriter { + TextMapCarrier(std::unordered_map& text_map_) + : text_map(text_map_) {} + + opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { + text_map[key] = value; + return {}; + } + + opentracing::expected LookupKey(opentracing::string_view key) const override { + if (!supports_lookup) { + return opentracing::make_unexpected(opentracing::lookup_key_not_supported_error); + } + auto iter = text_map.find(key); + if (iter != text_map.end()) { + return opentracing::string_view{iter->second}; + } else { + return opentracing::make_unexpected(opentracing::key_not_found_error); + } + } + + opentracing::expected ForeachKey( + std::function(opentracing::string_view key, opentracing::string_view value)> f) + const override { + ++foreach_key_call_count; + for (const auto& key_value : text_map) { + auto result = f(key_value.first, key_value.second); + if (!result) return result; + } + return {}; + } + + bool supports_lookup = false; + mutable int foreach_key_call_count = 0; + std::unordered_map& text_map; +}; + +struct HTTPHeadersCarrier : opentracing::HTTPHeadersReader, opentracing::HTTPHeadersWriter { + HTTPHeadersCarrier(std::unordered_map& text_map_) + : text_map(text_map_) {} + + opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { + text_map[key] = value; + return {}; + } + + opentracing::expected ForeachKey( + std::function(opentracing::string_view key, opentracing::string_view value)> f) + const override { + for (const auto& key_value : text_map) { + auto result = f(key_value.first, key_value.second); + if (!result) return result; + } + return {}; + } + + std::unordered_map& text_map; +}; + +class TracerShimTest : public testing::Test +{ +public: + std::shared_ptr tracer_shim; + +protected: + virtual void SetUp() + { + tracer_shim = shim::TracerShim::createTracerShim(); + } + + virtual void TearDown() + { + tracer_shim.reset(); + } +}; + +TEST_F(TracerShimTest, SpanReferenceToCreatingTracer) +{ + auto span_shim = tracer_shim->StartSpan("a"); + ASSERT_NE(span_shim, nullptr); + ASSERT_EQ(&span_shim->tracer(), tracer_shim.get()); +} + +TEST_F(TracerShimTest, TracerGloballyRegistered) +{ + ASSERT_FALSE(opentracing::Tracer::IsGlobalTracerRegistered()); + ASSERT_NE(opentracing::Tracer::InitGlobal(tracer_shim), nullptr); + ASSERT_TRUE(opentracing::Tracer::IsGlobalTracerRegistered()); +} + +TEST_F(TracerShimTest, InjectInvalidCarrier) +{ + auto span_shim = tracer_shim->StartSpan("a"); + auto result = tracer_shim->Inject(span_shim->context(), std::cout); + ASSERT_TRUE(opentracing::are_errors_equal(result.error(), opentracing::invalid_carrier_error)); +} + +TEST_F(TracerShimTest, InjectNullContext) +{ + std::unordered_map text_map; + auto noop_tracer = opentracing::MakeNoopTracer(); + auto span = noop_tracer->StartSpan("a"); + auto result = tracer_shim->Inject(span->context(), TextMapCarrier{text_map}); + ASSERT_TRUE(result.has_value()); + ASSERT_TRUE(text_map.empty()); +} + +TEST_F(TracerShimTest, ExtractInvalidCarrier) +{ + auto result = tracer_shim->Extract(std::cin); + ASSERT_TRUE(opentracing::are_errors_equal(result.error(), opentracing::invalid_carrier_error)); +} + +TEST_F(TracerShimTest, ExtractNullContext) +{ + std::unordered_map text_map; + auto result = tracer_shim->Extract(TextMapCarrier{text_map}); + ASSERT_EQ(result.value(), nullptr); +} diff --git a/opentracing-shim/test/tracer_test.cpp b/opentracing-shim/test/tracer_test.cpp deleted file mode 100644 index eca3a367fb..0000000000 --- a/opentracing-shim/test/tracer_test.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include -using namespace opentracing; - -#define CATCH_CONFIG_MAIN -#include - -TEST_CASE("tracer") { - auto tracer = MakeNoopTracer(); - - auto span1 = tracer->StartSpan("a"); - CHECK(span1); - - SECTION("Spans provide references to the tracer that created them.") { - CHECK(&span1->tracer() == tracer.get()); - } - - SECTION("Ensure basic operations compile.") { - auto span2 = tracer->StartSpan("b", {ChildOf(&span1->context())}); - CHECK(span2); - span2->SetOperationName("b1"); - span2->SetTag("x", true); - span2->SetTag(opentracing::ext::span_kind, - opentracing::ext::span_kind_rpc_client); - CHECK(span2->BaggageItem("y").empty()); - span2->Log({{"event", "xyz"}, {"abc", 123}}); - span2->Finish(); - } - - SECTION("A reference to a null SpanContext is ignored.") { - StartSpanOptions options; - ChildOf(nullptr).Apply(options); - CHECK(options.references.size() == 0); - } -} - -TEST_CASE("A tracer can be globally registered") { - CHECK(!Tracer::IsGlobalTracerRegistered()); - auto tracer = MakeNoopTracer(); - CHECK(Tracer::InitGlobal(tracer) != nullptr); - CHECK(Tracer::IsGlobalTracerRegistered()); -} From 36cca420802f5ea9c2f5e9b44fb46a6db0075de9 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 2 Jan 2023 18:34:44 -0500 Subject: [PATCH 03/46] Add more comments from compatibility section --- opentracing-shim/include/span_context_shim.h | 25 ++---- opentracing-shim/include/span_shim.h | 10 +-- opentracing-shim/include/tracer_shim.h | 12 +-- opentracing-shim/src/span_context_shim.cc | 8 +- opentracing-shim/src/span_shim.cc | 74 ++++++++++------ opentracing-shim/src/tracer_shim.cc | 89 ++++++++++---------- 6 files changed, 110 insertions(+), 108 deletions(-) diff --git a/opentracing-shim/include/span_context_shim.h b/opentracing-shim/include/span_context_shim.h index b2db5ed6c8..12d2f57acc 100644 --- a/opentracing-shim/include/span_context_shim.h +++ b/opentracing-shim/include/span_context_shim.h @@ -18,33 +18,20 @@ using BaggagePtr = nostd::shared_ptr; class SpanContextShim final : public opentracing::SpanContext { public: - - explicit SpanContextShim(const opentelemetry::trace::SpanContext& context, const BaggagePtr& baggage) : - context_(context), baggage_(baggage) {} - - inline SpanContextShim operator=(const SpanContextShim& other) - { - return SpanContextShim(other.context_, other.baggage_); - } - + explicit SpanContextShim(const opentelemetry::trace::SpanContext& context, const BaggagePtr& baggage) + : context_(context), baggage_(baggage) {} inline const opentelemetry::trace::SpanContext& context() const { return context_; } - inline const BaggagePtr& baggage() const { return baggage_; } - - SpanContextShim newWithKeyValue(const nostd::string_view &key, const nostd::string_view &value) const noexcept; - + SpanContextShim newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept; bool BaggageItem(nostd::string_view key, std::string& value) const noexcept; - + // Overrides using VisitBaggageItem = std::function; void ForeachBaggageItem(VisitBaggageItem f) const override; - std::unique_ptr Clone() const noexcept override; private: - - const opentelemetry::trace::SpanContext context_; - const BaggagePtr baggage_; - + opentelemetry::trace::SpanContext context_; + BaggagePtr baggage_; }; } // namespace opentracingshim diff --git a/opentracing-shim/include/span_shim.h b/opentracing-shim/include/span_shim.h index a6bbf67c12..fe341debbf 100644 --- a/opentracing-shim/include/span_shim.h +++ b/opentracing-shim/include/span_shim.h @@ -24,12 +24,10 @@ using EventEntry = std::pair; class SpanShim : public opentracing::Span { public: - - explicit SpanShim(const TracerShim& tracer, const SpanPtr& span, const BaggagePtr& baggage) : - tracer_(tracer), span_(span), context_(span->GetContext(), baggage) {} - + explicit SpanShim(const TracerShim& tracer, const SpanPtr& span, const BaggagePtr& baggage) + : tracer_(tracer), span_(span), context_(span->GetContext(), baggage) {} void handleError(const opentracing::Value& value) noexcept; - + // Overrides void FinishWithOptions(const opentracing::FinishSpanOptions& finish_span_options) noexcept override; void SetOperationName(opentracing::string_view name) noexcept override; void SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept override; @@ -42,14 +40,12 @@ class SpanShim : public opentracing::Span inline const opentracing::Tracer& tracer() const noexcept override { return tracer_; }; private: - void logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept; const TracerShim& tracer_; SpanPtr span_; SpanContextShim context_; mutable opentelemetry::common::SpinLockMutex context_lock_; - }; } // namespace opentracingshim diff --git a/opentracing-shim/include/tracer_shim.h b/opentracing-shim/include/tracer_shim.h index aada00980e..e91b8a2b03 100644 --- a/opentracing-shim/include/tracer_shim.h +++ b/opentracing-shim/include/tracer_shim.h @@ -19,14 +19,13 @@ using TracerProviderPtr = nostd::shared_ptr; struct OpenTracingPropagators { - PropagatorPtr textMap; - PropagatorPtr httpHeaders; + PropagatorPtr text_map; + PropagatorPtr http_headers; }; class TracerShim : public opentracing::Tracer { public: - /** * Creates a {@code opentracing::Tracer} shim out of * {@code Provider::GetTracerProvider()} and @@ -66,7 +65,7 @@ class TracerShim : public opentracing::Tracer { return std::shared_ptr(new (std::nothrow) TracerShim(tracer, propagators)); } - + // Overrides std::unique_ptr StartSpanWithOptions(opentracing::string_view operation_name, const opentracing::StartSpanOptions& options) const noexcept override; opentracing::expected Inject(const opentracing::SpanContext& sc, @@ -81,19 +80,16 @@ class TracerShim : public opentracing::Tracer inline void Close() noexcept override { is_closed_ = true; }; private: - explicit TracerShim(const TracerPtr& tracer, const OpenTracingPropagators& propagators) : tracer_(tracer), propagators_(propagators) {} - template opentracing::expected injectImpl(const opentracing::SpanContext& sc, const T& writer, const PropagatorPtr& propagator) const; - template opentracing::expected> extractImpl(const T& reader, const PropagatorPtr& propagator) const; - + TracerPtr tracer_; OpenTracingPropagators propagators_; bool is_closed_ = false; diff --git a/opentracing-shim/src/span_context_shim.cc b/opentracing-shim/src/span_context_shim.cc index d220634701..9d1c60618c 100644 --- a/opentracing-shim/src/span_context_shim.cc +++ b/opentracing-shim/src/span_context_shim.cc @@ -6,10 +6,10 @@ #include "span_context_shim.h" OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim +namespace opentracingshim { -SpanContextShim SpanContextShim::newWithKeyValue(const nostd::string_view &key, const nostd::string_view &value) const noexcept +SpanContextShim SpanContextShim::newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept { return SpanContextShim{context_, baggage_->Set(key, value)}; } @@ -22,8 +22,8 @@ bool SpanContextShim::BaggageItem(nostd::string_view key, std::string& value) co void SpanContextShim::ForeachBaggageItem(VisitBaggageItem f) const { baggage_->GetAllEntries([&f](nostd::string_view key, nostd::string_view value) - { - return f(key.data(), value.data()); + { + return f(key.data(), value.data()); } ); } diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 6600872494..7ba644215b 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -13,29 +13,35 @@ #include OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim +namespace opentracingshim { void SpanShim::handleError(const opentracing::Value& value) noexcept { using opentelemetry::trace::StatusCode; - + // The error tag MUST be mapped to StatusCode: + // - true maps to Error. + // - false maps to Ok + // - no value being set maps to Unset. auto code = StatusCode::kUnset; const auto& str_value = shimutils::stringFromValue(value); - if (str_value == "true") + + if (str_value == "true") { code = StatusCode::kError; } - else if (str_value == "false") + else if (str_value == "false") { code = StatusCode::kOk; } span_->SetStatus(code); -} +} void SpanShim::FinishWithOptions(const opentracing::FinishSpanOptions& finish_span_options) noexcept { + // If an explicit timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. span_->End({{ finish_span_options.finish_steady_timestamp }}); } @@ -46,6 +52,7 @@ void SpanShim::SetOperationName(opentracing::string_view name) noexcept void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept { + // Calls Set Attribute on the underlying OpenTelemetry Span with the specified key/value pair. if (key == opentracing::ext::error) { handleError(value); @@ -58,12 +65,16 @@ void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value& va void SpanShim::SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept { + // Creates a new SpanContext Shim with a new OpenTelemetry Baggage containing the specified + // Baggage key/value pair, and sets it as the current instance for this Span Shim. const std::lock_guard guard(context_lock_); - context_ = context_.newWithKeyValue(restricted_key.data(), value.data()); + context_ = context_.newWithKeyValue(restricted_key.data(), value.data());; } std::string SpanShim::BaggageItem(opentracing::string_view restricted_key) const noexcept { + // Returns the value for the specified key in the OpenTelemetry Baggage + // of the current SpanContext Shim, or null if none exists. const std::lock_guard guard(context_lock_); std::string value; return context_.BaggageItem(restricted_key.data(), value) ? value : ""; @@ -71,59 +82,72 @@ std::string SpanShim::BaggageItem(opentracing::string_view restricted_key) const void SpanShim::Log(std::initializer_list fields) noexcept { + // If an explicit timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. logImpl(opentracing::SystemTime::min(), fields); } void SpanShim::Log(opentracing::SystemTime timestamp, std::initializer_list fields) noexcept { + // If an explicit timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. logImpl(timestamp, fields); } void SpanShim::Log(opentracing::SystemTime timestamp, const std::vector& fields) noexcept { + // If an explicit timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. logImpl(timestamp, fields); } -void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept +void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept { - const auto event = std::find_if(fields.begin(), fields.end(), [](EventEntry item){ return item.first == "event"; }); + // The Add Event’s name parameter MUST be the value with the event key + // in the pair set, or else fallback to use the log literal string. + const auto event = std::find_if(fields.begin(), fields.end(), [](EventEntry item){ return item.first == "event"; }); auto name = (event != fields.end()) ? shimutils::stringFromValue(event->second) : std::string{"log"}; - + // If pair set contains an event=error entry, the values MUST be mapped to an Event + // with the conventions outlined in the Exception semantic conventions document: bool is_error = (name == opentracing::ext::error); + // A call to AddEvent is performed with name being set to exception if (is_error) name = "exception"; - - std::vector> attributes; + // Along the specified key/value pair set as additional event attributes... + std::vector> attributes; attributes.reserve(fields.size()); - - for (const auto& entry : fields) + + for (const auto& entry : fields) { auto key = entry.first; const auto& value = shimutils::attributeFromValue(entry.second); - - if (is_error) + // ... including mapping of the following key/value pairs: + // - error.kind maps to exception.type. + // - message maps to exception.message. + // - stack maps to exception.stacktrace. + if (is_error) { - if (key == "error.kind") + if (key == "error.kind") { key = opentelemetry::trace::SemanticConventions::kExceptionType; - } - else if (key == "message") + } + else if (key == "message") { key = opentelemetry::trace::SemanticConventions::kExceptionMessage; - } - else if (key == "stack") + } + else if (key == "stack") { key = opentelemetry::trace::SemanticConventions::kExceptionStacktrace; } } - + attributes.emplace_back(key, value); } - - if (timestamp != opentracing::SystemTime::min()) + // Calls Add Events on the underlying OpenTelemetry Span with the specified key/value pair set. + if (timestamp != opentracing::SystemTime::min()) { span_->AddEvent(name, timestamp, attributes); - } - else + } + else { span_->AddEvent(name, attributes); } diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index ac5cd31ef9..2b8ff88b8d 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -14,7 +14,7 @@ #include OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim +namespace opentracingshim { namespace detail @@ -28,30 +28,30 @@ static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing: using opentracing::SpanReferenceType; opentelemetry::trace::StartSpanOptions options_shim; - // If an explicit start timestamp is specified, a conversion MUST + // If an explicit start timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. options_shim.start_system_time = opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; options_shim.start_steady_time = opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; - + const auto& refs = options.references; // If a list of Span references is specified... if (!refs.empty()) { - auto first_child_of = std::find_if(refs.cbegin(), refs.cend(), - [](const std::pair& entry){ - return entry.first == SpanReferenceType::ChildOfRef; + auto first_child_of = std::find_if(refs.cbegin(), refs.cend(), + [](const std::pair& entry){ + return entry.first == SpanReferenceType::ChildOfRef; }); - // The first SpanContext with Child Of type in the entire list is used as parent, + // The first SpanContext with Child Of type in the entire list is used as parent, // else the first SpanContext is used as parent auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; - - if (auto context_shim = dynamic_cast(context)) + + if (auto context_shim = dynamic_cast(context)) { options_shim.parent = context_shim->context(); } } - + return options_shim; } @@ -59,17 +59,17 @@ static LinksList makeReferenceLinks(const opentracing::StartSpanOptions& options { using opentracing::SpanReferenceType; using namespace opentelemetry::trace::SemanticConventions; - + LinksList links; links.reserve(options.references.size()); // All values in the list MUST be added as Links with the reference type value // as a Link attribute, i.e. opentracing.ref_type set to follows_from or child_of - for (const auto& entry : options.references) + for (const auto& entry : options.references) { auto context_shim = dynamic_cast(entry.second); nostd::string_view span_kind; - + if (entry.first == SpanReferenceType::ChildOfRef) { span_kind = OpentracingRefTypeValues::kChildOf; @@ -79,7 +79,7 @@ static LinksList makeReferenceLinks(const opentracing::StartSpanOptions& options span_kind = OpentracingRefTypeValues::kFollowsFrom; } - if (context_shim && !span_kind.empty()) + if (context_shim && !span_kind.empty()) { // links.push_back({ context_shim->context(), {{ opentracing::ext::span_kind.data(), span_kind }} }); links.emplace_back(std::piecewise_construct, @@ -98,7 +98,7 @@ static BaggagePtr makeBaggage(const opentracing::StartSpanOptions& options) noex std::unordered_map baggage_items; // If a list of Span references is specified... - for (const auto& entry : options.references) + for (const auto& entry : options.references) { if (auto context_shim = dynamic_cast(entry.second)) { @@ -114,7 +114,7 @@ static BaggagePtr makeBaggage(const opentracing::StartSpanOptions& options) noex } } - // If no such lisf of references is specified, the current Baggage + // If no such lisf of references is specified, the current Baggage // MUST be used as the initial value of the newly created Span. return baggage_items.empty() ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) @@ -126,7 +126,7 @@ static std::vector> makeTags(cons std::vector> tags; tags.reserve(options.tags.size()); - // If an initial set of tags is specified, the values MUST + // If an initial set of tags is specified, the values MUST // be set at the creation time of the OpenTelemetry Span. for (const auto& entry : options.tags) { @@ -138,26 +138,25 @@ static std::vector> makeTags(cons } // namespace opentracingshim::detail -std::unique_ptr TracerShim::StartSpanWithOptions(opentracing::string_view operation_name, +std::unique_ptr TracerShim::StartSpanWithOptions(opentracing::string_view operation_name, const opentracing::StartSpanOptions& options) const noexcept { if (is_closed_) return nullptr; - + const auto& opts = detail::makeOptionsShim(options); const auto& links = detail::makeReferenceLinks(options); const auto& baggage = detail::makeBaggage(options); const auto& attributes = detail::makeTags(options); - + auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); auto span_shim = new SpanShim(*this, span, baggage); // If an initial set of tags is specified and the OpenTracing error tag // is included after the OpenTelemetry Span was created. - const auto& error_entry = std::find_if(options.tags.begin(), options.tags.end(), + const auto& error_entry = std::find_if(options.tags.begin(), options.tags.end(), [](const std::pair& entry){ return entry.first == opentracing::ext::error; }); - // The Shim layer MUST perform the same error handling as described in the Set Tag operation if (error_entry != options.tags.end()) { span_shim->handleError(error_entry->second); @@ -169,7 +168,7 @@ std::unique_ptr TracerShim::StartSpanWithOptions(opentracing: opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, std::ostream& writer) const { - // Errors MAY be raised if the specified Format is not recognized, + // Errors MAY be raised if the specified Format is not recognized, // depending on the specific OpenTracing Language API. return opentracing::make_unexpected(opentracing::invalid_carrier_error); } @@ -177,10 +176,10 @@ opentracing::expected TracerShim::Inject(const opentracing::SpanContext& s opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, const opentracing::TextMapWriter& writer) const { - // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.textMap - ? propagators_.textMap + const auto& propagator = propagators_.text_map + ? propagators_.text_map : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); return injectImpl(sc, writer, propagator); @@ -189,10 +188,10 @@ opentracing::expected TracerShim::Inject(const opentracing::SpanContext& s opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, const opentracing::HTTPHeadersWriter& writer) const { - // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.httpHeaders - ? propagators_.httpHeaders + const auto& propagator = propagators_.http_headers + ? propagators_.http_headers : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); return injectImpl(sc, writer, propagator); @@ -200,39 +199,39 @@ opentracing::expected TracerShim::Inject(const opentracing::SpanContext& s opentracing::expected> TracerShim::Extract(std::istream& reader) const { - // Errors MAY be raised if either the Format is not recognized or no value + // Errors MAY be raised if either the Format is not recognized or no value // could be extracted, depending on the specific OpenTracing Language API. return opentracing::make_unexpected(opentracing::invalid_carrier_error); } opentracing::expected> TracerShim::Extract(const opentracing::TextMapReader& reader) const { - // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.textMap - ? propagators_.textMap + const auto& propagator = propagators_.text_map + ? propagators_.text_map : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); - + return extractImpl(reader, propagator); } opentracing::expected> TracerShim::Extract(const opentracing::HTTPHeadersReader& reader) const { - // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, + // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.httpHeaders - ? propagators_.httpHeaders + const auto& propagator = propagators_.http_headers + ? propagators_.http_headers : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); - + return extractImpl(reader, propagator); } template -opentracing::expected TracerShim::injectImpl(const opentracing::SpanContext& sc, - const T& writer, +opentracing::expected TracerShim::injectImpl(const opentracing::SpanContext& sc, + const T& writer, const PropagatorPtr& propagator) const { - // Inject the underlying OpenTelemetry Span and Baggage using either the explicitly registered + // Inject the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. if (auto context_shim = dynamic_cast(&sc)) { @@ -248,10 +247,10 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex } template -opentracing::expected> TracerShim::extractImpl(const T& reader, +opentracing::expected> TracerShim::extractImpl(const T& reader, const PropagatorPtr& propagator) const { - // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered + // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. shimutils::CarrierReaderShim carrier{reader}; auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); @@ -259,8 +258,8 @@ opentracing::expected> TracerShim::ext auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); auto baggage = opentelemetry::baggage::GetBaggage(context); - // If the extracted SpanContext is invalid AND the extracted Baggage is empty, - // this operation MUST return a null value, and otherwise it MUST return a + // If the extracted SpanContext is invalid AND the extracted Baggage is empty, + // this operation MUST return a null value, and otherwise it MUST return a // SpanContext Shim instance with the extracted values. SpanContextShim* context_shim = (!span_context.IsValid() && shimutils::isBaggageEmpty(baggage)) ? nullptr From 81b8557716eb755a3ac725ff40b19dc66b788d47 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 2 Jan 2023 20:56:15 -0500 Subject: [PATCH 04/46] More tracer unit tests --- opentracing-shim/include/shim_utils.h | 17 +-- opentracing-shim/src/tracer_shim.cc | 4 +- opentracing-shim/test/tracer_shim_test.cc | 122 +++++++++++++++++++++- 3 files changed, 133 insertions(+), 10 deletions(-) diff --git a/opentracing-shim/include/shim_utils.h b/opentracing-shim/include/shim_utils.h index 3c7fce0fcc..9fbd71dbc9 100644 --- a/opentracing-shim/include/shim_utils.h +++ b/opentracing-shim/include/shim_utils.h @@ -53,7 +53,6 @@ template::value, bool> = true> class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCarrier { public: - CarrierReaderShim(const T& reader) : reader_(reader) {} // returns the value associated with the passed key. @@ -112,10 +108,19 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar // Not required for Opentracing reader } -private: + // list of all the keys in the carrier. + virtual bool Keys(nostd::function_ref callback) const noexcept override + { + reader_.ForeachKey([&callback] + (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { + callback(k.data()); + return opentracing::make_expected(); + }); + return true; + } +private: const T& reader_; - }; static inline bool isBaggageEmpty(const BaggagePtr& baggage) diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index 2b8ff88b8d..3f6df5119c 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -26,15 +26,13 @@ using LinksList = std::vector #include #include @@ -10,8 +12,46 @@ namespace trace_api = opentelemetry::trace; namespace nostd = opentelemetry::nostd; namespace context = opentelemetry::context; +namespace baggage = opentelemetry::baggage; namespace shim = opentelemetry::opentracingshim; +struct MockPropagator : public context::propagation::TextMapPropagator +{ + // Returns the context that is stored in the carrier with the TextMapCarrier as extractor. + context::Context Extract(const context::propagation::TextMapCarrier &carrier, + context::Context &context) noexcept override + { + std::vector> kvs; + carrier.Keys([&carrier,&kvs](nostd::string_view k){ + kvs.emplace_back(k, carrier.Get(k)); + return true; + }); + is_extracted = true; + return baggage::SetBaggage(context, nostd::shared_ptr(new baggage::Baggage(kvs))); + } + + // Sets the context for carrier with self defined rules. + void Inject(context::propagation::TextMapCarrier &carrier, + const context::Context &context) noexcept override + { + auto baggage = baggage::GetBaggage(context); + baggage->GetAllEntries([&carrier](nostd::string_view k, nostd::string_view v){ + carrier.Set(k, v); + return true; + }); + is_injected = true; + } + + // Gets the fields set in the carrier by the `inject` method + bool Fields(nostd::function_ref callback) const noexcept override + { + return true; + } + + bool is_extracted = false; + bool is_injected = false; +}; + struct TextMapCarrier : opentracing::TextMapReader, opentracing::TextMapWriter { TextMapCarrier(std::unordered_map& text_map_) : text_map(text_map_) {} @@ -75,11 +115,20 @@ class TracerShimTest : public testing::Test { public: std::shared_ptr tracer_shim; + MockPropagator* text_map_format; + MockPropagator* http_headers_format; protected: virtual void SetUp() { - tracer_shim = shim::TracerShim::createTracerShim(); + using context::propagation::TextMapPropagator; + + text_map_format = new MockPropagator(); + http_headers_format = new MockPropagator(); + + tracer_shim = shim::TracerShim::createTracerShim(trace_api::Provider::GetTracerProvider(), + { .text_map = nostd::shared_ptr(text_map_format), + .http_headers = nostd::shared_ptr(http_headers_format) }); } virtual void TearDown() @@ -119,6 +168,30 @@ TEST_F(TracerShimTest, InjectNullContext) ASSERT_TRUE(text_map.empty()); } +TEST_F(TracerShimTest, InjectTextMap) +{ + ASSERT_FALSE(text_map_format->is_injected); + ASSERT_FALSE(http_headers_format->is_injected); + + std::unordered_map text_map; + auto span_shim = tracer_shim->StartSpan("a"); + tracer_shim->Inject(span_shim->context(), TextMapCarrier{text_map}); + ASSERT_TRUE(text_map_format->is_injected); + ASSERT_FALSE(http_headers_format->is_injected); +} + +TEST_F(TracerShimTest, InjectHttpsHeaders) +{ + ASSERT_FALSE(text_map_format->is_injected); + ASSERT_FALSE(http_headers_format->is_injected); + + std::unordered_map text_map; + auto span_shim = tracer_shim->StartSpan("a"); + tracer_shim->Inject(span_shim->context(), HTTPHeadersCarrier{text_map}); + ASSERT_FALSE(text_map_format->is_injected); + ASSERT_TRUE(http_headers_format->is_injected); +} + TEST_F(TracerShimTest, ExtractInvalidCarrier) { auto result = tracer_shim->Extract(std::cin); @@ -131,3 +204,50 @@ TEST_F(TracerShimTest, ExtractNullContext) auto result = tracer_shim->Extract(TextMapCarrier{text_map}); ASSERT_EQ(result.value(), nullptr); } + +TEST_F(TracerShimTest, ExtractTextMap) +{ + ASSERT_FALSE(text_map_format->is_extracted); + ASSERT_FALSE(http_headers_format->is_extracted); + + std::unordered_map text_map; + auto result = tracer_shim->Extract(TextMapCarrier{text_map}); + ASSERT_EQ(result.value(), nullptr); + ASSERT_TRUE(text_map_format->is_extracted); + ASSERT_FALSE(http_headers_format->is_extracted); +} + +TEST_F(TracerShimTest, ExtractHttpsHeaders) +{ + ASSERT_FALSE(text_map_format->is_extracted); + ASSERT_FALSE(http_headers_format->is_extracted); + + std::unordered_map text_map; + auto result = tracer_shim->Extract(HTTPHeadersCarrier{text_map}); + ASSERT_EQ(result.value(), nullptr); + ASSERT_FALSE(text_map_format->is_extracted); + ASSERT_TRUE(http_headers_format->is_extracted); +} + +TEST_F(TracerShimTest, ExtractOnlyBaggage) +{ + std::unordered_map text_map; + auto span_shim = tracer_shim->StartSpan("a"); + span_shim->SetBaggageItem("foo", "bar"); + + ASSERT_EQ(span_shim->BaggageItem("foo"), "bar"); + + TextMapCarrier carrier{text_map}; + tracer_shim->Inject(span_shim->context(), carrier); + + auto span_context = tracer_shim->Extract(carrier); + ASSERT_TRUE(span_context.value() != nullptr); + + // auto span_context_shim = dynamic_cast(span_context.value().get()); + // ASSERT_TRUE(span_context_shim != nullptr); + // ASSERT_TRUE(span_context_shim->context().IsValid()); + + // std::string value; + // ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); + // ASSERT_EQ(value, "bar"); +} From 1fc7f33f9511ab8f822aafbbeafaaf76d2c0e638 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Tue, 3 Jan 2023 19:39:07 -0500 Subject: [PATCH 05/46] Unit tests for shim utils --- opentracing-shim/include/shim_utils.h | 65 +++--- opentracing-shim/include/span_context_shim.h | 4 +- opentracing-shim/include/span_shim.h | 4 +- opentracing-shim/include/tracer_shim.h | 65 ++---- opentracing-shim/src/span_shim.cc | 8 +- opentracing-shim/src/tracer_shim.cc | 12 +- opentracing-shim/test/shim_mocks.h | 111 +++++++++++ opentracing-shim/test/shim_utils_test.cc | 196 +++++++++++++++++++ opentracing-shim/test/tracer_shim_test.cc | 140 +++---------- 9 files changed, 403 insertions(+), 202 deletions(-) create mode 100644 opentracing-shim/test/shim_mocks.h create mode 100644 opentracing-shim/test/shim_utils_test.cc diff --git a/opentracing-shim/include/shim_utils.h b/opentracing-shim/include/shim_utils.h index 9fbd71dbc9..87e1951140 100644 --- a/opentracing-shim/include/shim_utils.h +++ b/opentracing-shim/include/shim_utils.h @@ -5,14 +5,21 @@ #pragma once +#include +#include +#include +#include +#include +#include + OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim::shimutils +namespace opentracingshim::utils { - -using opentelemetry::common::AttributeValue; -static inline AttributeValue attributeFromValue(const opentracing::Value& value) +static inline opentelemetry::common::AttributeValue attributeFromValue(const opentracing::Value& value) { + using opentelemetry::common::AttributeValue; + static struct { AttributeValue operator()(bool v) { return v; } @@ -21,12 +28,12 @@ static inline AttributeValue attributeFromValue(const opentracing::Value& value) AttributeValue operator()(uint64_t v) { return v; } AttributeValue operator()(std::string v) { return v.c_str(); } AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } - AttributeValue operator()(std::nullptr_t) { return std::string{}; } + AttributeValue operator()(std::nullptr_t) { return nostd::string_view{}; } AttributeValue operator()(const char* v) { return v; } - AttributeValue operator()(opentracing::util::recursive_wrapper) { return std::string{}; } - AttributeValue operator()(opentracing::util::recursive_wrapper) { return std::string{}; } + AttributeValue operator()(opentracing::util::recursive_wrapper) { return nostd::string_view{}; } + AttributeValue operator()(opentracing::util::recursive_wrapper) { return nostd::string_view{}; } } AttributeMapper; - + return opentracing::Value::visit(value, AttributeMapper); } @@ -54,7 +61,7 @@ class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCar { public: CarrierWriterShim(const T& writer) : writer_(writer) {} - + // returns the value associated with the passed key. virtual nostd::string_view Get(nostd::string_view key) const noexcept override { @@ -76,22 +83,24 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar { public: CarrierReaderShim(const T& reader) : reader_(reader) {} - + // returns the value associated with the passed key. virtual nostd::string_view Get(nostd::string_view key) const noexcept override { - // First try carrier.LookupKey since that can potentially be the fastest approach. - auto result = reader_.LookupKey(key.data()); + nostd::string_view value; - if (!result.has_value() || - opentracing::are_errors_equal(result.error(), opentracing::lookup_key_not_supported_error)) + // First try carrier.LookupKey since that can potentially be the fastest approach. + if (auto result = reader_.LookupKey(key.data())) + { + value = result.value().data(); + } + else // Fall back to iterating through all of the keys. { - // Fall back to iterating through all of the keys. - reader_.ForeachKey([key, &result] + reader_.ForeachKey([key, &value] (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { - if (key == k) + if (k == key.data()) { - result = opentracing::make_expected(v); + value = v.data(); // Found key, so bail out of the loop with a success error code. return opentracing::make_unexpected(std::error_code{}); } @@ -99,7 +108,7 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar }); } - return nostd::string_view{ result.has_value() ? result.value().data() : "" }; + return value; } // stores the key-value pair. @@ -111,29 +120,29 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar // list of all the keys in the carrier. virtual bool Keys(nostd::function_ref callback) const noexcept override { - reader_.ForeachKey([&callback] - (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { - callback(k.data()); - return opentracing::make_expected(); - }); - return true; + return reader_.ForeachKey([&callback] + (opentracing::string_view key, opentracing::string_view) -> opentracing::expected { + return callback(key.data()) + ? opentracing::make_expected() + : opentracing::make_unexpected(std::error_code{}); + }).has_value(); } private: const T& reader_; }; -static inline bool isBaggageEmpty(const BaggagePtr& baggage) +static inline bool isBaggageEmpty(const nostd::shared_ptr& baggage) { if (baggage) { return baggage->GetAllEntries([](nostd::string_view, nostd::string_view){ return false; - }); + }); } return true; } -} // namespace opentracingshim::shimutils +} // namespace opentracingshim::utils OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/span_context_shim.h b/opentracing-shim/include/span_context_shim.h index 12d2f57acc..d615d56d0b 100644 --- a/opentracing-shim/include/span_context_shim.h +++ b/opentracing-shim/include/span_context_shim.h @@ -10,7 +10,7 @@ #include "opentracing/span.h" OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim +namespace opentracingshim { using BaggagePtr = nostd::shared_ptr; @@ -35,4 +35,4 @@ class SpanContextShim final : public opentracing::SpanContext }; } // namespace opentracingshim -OPENTELEMETRY_END_NAMESPACE \ No newline at end of file +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/span_shim.h b/opentracing-shim/include/span_shim.h index fe341debbf..72b7349c89 100644 --- a/opentracing-shim/include/span_shim.h +++ b/opentracing-shim/include/span_shim.h @@ -15,7 +15,7 @@ #include "opentracing/span.h" OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim +namespace opentracingshim { using SpanPtr = nostd::shared_ptr; @@ -49,4 +49,4 @@ class SpanShim : public opentracing::Span }; } // namespace opentracingshim -OPENTELEMETRY_END_NAMESPACE \ No newline at end of file +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/tracer_shim.h b/opentracing-shim/include/tracer_shim.h index e91b8a2b03..0726b12f5a 100644 --- a/opentracing-shim/include/tracer_shim.h +++ b/opentracing-shim/include/tracer_shim.h @@ -11,7 +11,7 @@ #include "opentracing/tracer.h" OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim +namespace opentracingshim { using TracerPtr = nostd::shared_ptr; @@ -19,54 +19,29 @@ using TracerProviderPtr = nostd::shared_ptr; struct OpenTracingPropagators { - PropagatorPtr text_map; - PropagatorPtr http_headers; + PropagatorPtr text_map; + PropagatorPtr http_headers; }; class TracerShim : public opentracing::Tracer { public: - /** - * Creates a {@code opentracing::Tracer} shim out of - * {@code Provider::GetTracerProvider()} and - * {@code GlobalTextMapPropagator::GetGlobalPropagator()}. - * - * @returns a {@code opentracing::Tracer}. - */ - static inline std::shared_ptr createTracerShim() noexcept + // This operation MUST accept the following parameters: + // - An OpenTelemetry TracerProvider. This operation MUST use this TracerProvider to obtain a + // Tracer with the name opentracing-shim along with the current shim library version. + // - OpenTelemetry Propagators to be used to perform injection and extraction for the the + // OpenTracing TextMap and HTTPHeaders formats. If not specified, no Propagator values will + // be stored in the Shim, and the global OpenTelemetry TextMap propagator will be used for + // both OpenTracing TextMap and HTTPHeaders formats. + static inline std::shared_ptr createTracerShim( + const TracerProviderPtr& provider = opentelemetry::trace::Provider::GetTracerProvider(), + const OpenTracingPropagators& propagators = {}) noexcept { - return createTracerShim(opentelemetry::trace::Provider::GetTracerProvider()); - } - - /** - * Creates a {@code opentracing::Tracer} shim using the provided - * {@code TracerProvider} and - * {@code TextMapPropagator} instance. - * - * @param provider the {@code TracerProvider} instance used to create this shim. - * @param propagators the {@code OpenTracingPropagators} instance used to create this shim. - * @returns a {@code opentracing::Tracer}. - */ - static inline std::shared_ptr createTracerShim(const TracerProviderPtr& provider, - const OpenTracingPropagators& propagators = {}) noexcept - { - return createTracerShim(provider->GetTracer("opentracing-shim"), propagators); - } - - /** - * Creates a {@code opentracing::Tracer} shim using provided - * {@code Tracer} instance and - * {@code GlobalTextMapPropagator::GetGlobalPropagator()}. - * - * @returns a {@code opentracing::Tracer}. - */ - static inline std::shared_ptr createTracerShim(const TracerPtr& tracer, - const OpenTracingPropagators& propagators = {}) noexcept - { - return std::shared_ptr(new (std::nothrow) TracerShim(tracer, propagators)); + return std::shared_ptr( + new (std::nothrow) TracerShim(provider->GetTracer("opentracing-shim"), propagators)); } // Overrides - std::unique_ptr StartSpanWithOptions(opentracing::string_view operation_name, + std::unique_ptr StartSpanWithOptions(opentracing::string_view operation_name, const opentracing::StartSpanOptions& options) const noexcept override; opentracing::expected Inject(const opentracing::SpanContext& sc, std::ostream& writer) const override; @@ -83,11 +58,11 @@ class TracerShim : public opentracing::Tracer explicit TracerShim(const TracerPtr& tracer, const OpenTracingPropagators& propagators) : tracer_(tracer), propagators_(propagators) {} template - opentracing::expected injectImpl(const opentracing::SpanContext& sc, - const T& writer, + opentracing::expected injectImpl(const opentracing::SpanContext& sc, + const T& writer, const PropagatorPtr& propagator) const; template - opentracing::expected> extractImpl(const T& reader, + opentracing::expected> extractImpl(const T& reader, const PropagatorPtr& propagator) const; TracerPtr tracer_; @@ -96,4 +71,4 @@ class TracerShim : public opentracing::Tracer }; } // namespace opentracingshim -OPENTELEMETRY_END_NAMESPACE \ No newline at end of file +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 7ba644215b..fedd3575cf 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -24,7 +24,7 @@ void SpanShim::handleError(const opentracing::Value& value) noexcept // - false maps to Ok // - no value being set maps to Unset. auto code = StatusCode::kUnset; - const auto& str_value = shimutils::stringFromValue(value); + const auto& str_value = utils::stringFromValue(value); if (str_value == "true") { @@ -59,7 +59,7 @@ void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value& va } else { - span_->SetAttribute(key.data(), shimutils::attributeFromValue(value)); + span_->SetAttribute(key.data(), utils::attributeFromValue(value)); } } @@ -106,7 +106,7 @@ void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::spansecond) : std::string{"log"}; + auto name = (event != fields.end()) ? utils::stringFromValue(event->second) : std::string{"log"}; // If pair set contains an event=error entry, the values MUST be mapped to an Event // with the conventions outlined in the Exception semantic conventions document: bool is_error = (name == opentracing::ext::error); @@ -119,7 +119,7 @@ void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::span baggage_items; - // If a list of Span references is specified... for (const auto& entry : options.references) { @@ -111,7 +109,6 @@ static BaggagePtr makeBaggage(const opentracing::StartSpanOptions& options) noex }); } } - // If no such lisf of references is specified, the current Baggage // MUST be used as the initial value of the newly created Span. return baggage_items.empty() @@ -128,7 +125,7 @@ static std::vector> makeTags(cons // be set at the creation time of the OpenTelemetry Span. for (const auto& entry : options.tags) { - tags.emplace_back(entry.first, shimutils::attributeFromValue(entry.second)); + tags.emplace_back(entry.first, utils::attributeFromValue(entry.second)); } return tags; @@ -145,7 +142,6 @@ std::unique_ptr TracerShim::StartSpanWithOptions(opentracing: const auto& links = detail::makeReferenceLinks(options); const auto& baggage = detail::makeBaggage(options); const auto& attributes = detail::makeTags(options); - auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); auto span_shim = new SpanShim(*this, span, baggage); @@ -237,7 +233,7 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex // It MUST inject any non-empty Baggage even amidst no valid SpanContext. const auto& context = opentelemetry::baggage::SetBaggage(current_context, context_shim->baggage()); - shimutils::CarrierWriterShim carrier{writer}; + utils::CarrierWriterShim carrier{writer}; propagator->Inject(carrier, context); } @@ -250,7 +246,7 @@ opentracing::expected> TracerShim::ext { // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. - shimutils::CarrierReaderShim carrier{reader}; + utils::CarrierReaderShim carrier{reader}; auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); auto context = propagator->Extract(carrier, current_context); auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); @@ -259,7 +255,7 @@ opentracing::expected> TracerShim::ext // If the extracted SpanContext is invalid AND the extracted Baggage is empty, // this operation MUST return a null value, and otherwise it MUST return a // SpanContext Shim instance with the extracted values. - SpanContextShim* context_shim = (!span_context.IsValid() && shimutils::isBaggageEmpty(baggage)) + SpanContextShim* context_shim = (!span_context.IsValid() && utils::isBaggageEmpty(baggage)) ? nullptr : new SpanContextShim(span_context, baggage); diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h new file mode 100644 index 0000000000..2842c35db0 --- /dev/null +++ b/opentracing-shim/test/shim_mocks.h @@ -0,0 +1,111 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include + +#include + +namespace baggage = opentelemetry::baggage; +namespace context = opentelemetry::context; +namespace nostd = opentelemetry::nostd; + +struct MockPropagator : public context::propagation::TextMapPropagator +{ + // Returns the context that is stored in the carrier with the TextMapCarrier as extractor. + context::Context Extract(const context::propagation::TextMapCarrier &carrier, + context::Context &context) noexcept override + { + std::vector> kvs; + carrier.Keys([&carrier,&kvs](nostd::string_view k){ + kvs.emplace_back(k, carrier.Get(k)); + return true; + }); + is_extracted = true; + return baggage::SetBaggage(context, nostd::shared_ptr(new baggage::Baggage(kvs))); + } + + // Sets the context for carrier with self defined rules. + void Inject(context::propagation::TextMapCarrier &carrier, + const context::Context &context) noexcept override + { + auto baggage = baggage::GetBaggage(context); + baggage->GetAllEntries([&carrier](nostd::string_view k, nostd::string_view v){ + carrier.Set(k, v); + return true; + }); + is_injected = true; + } + + // Gets the fields set in the carrier by the `inject` method + bool Fields(nostd::function_ref callback) const noexcept override + { + return true; + } + + bool is_extracted = false; + bool is_injected = false; +}; + +struct TextMapCarrier : opentracing::TextMapReader, opentracing::TextMapWriter { + TextMapCarrier(std::unordered_map& text_map_) + : text_map(text_map_) {} + + opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { + text_map[key] = value; + return {}; + } + + opentracing::expected LookupKey(opentracing::string_view key) const override { + if (!supports_lookup) { + return opentracing::make_unexpected(opentracing::lookup_key_not_supported_error); + } + auto iter = text_map.find(key); + if (iter != text_map.end()) { + return opentracing::string_view{iter->second}; + } else { + return opentracing::make_unexpected(opentracing::key_not_found_error); + } + } + + opentracing::expected ForeachKey( + std::function(opentracing::string_view key, opentracing::string_view value)> f) + const override { + ++foreach_key_call_count; + for (const auto& key_value : text_map) { + auto result = f(key_value.first, key_value.second); + if (!result) return result; + } + return {}; + } + + bool supports_lookup = false; + mutable int foreach_key_call_count = 0; + std::unordered_map& text_map; +}; + +struct HTTPHeadersCarrier : opentracing::HTTPHeadersReader, opentracing::HTTPHeadersWriter { + HTTPHeadersCarrier(std::unordered_map& text_map_) + : text_map(text_map_) {} + + opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { + text_map[key] = value; + return {}; + } + + opentracing::expected ForeachKey( + std::function(opentracing::string_view key, opentracing::string_view value)> f) + const override { + for (const auto& key_value : text_map) { + auto result = f(key_value.first, key_value.second); + if (!result) return result; + } + return {}; + } + + std::unordered_map& text_map; +}; diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc new file mode 100644 index 0000000000..665f070b9c --- /dev/null +++ b/opentracing-shim/test/shim_utils_test.cc @@ -0,0 +1,196 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "shim_utils.h" +#include "shim_mocks.h" + +#include + +namespace baggage = opentelemetry::baggage; +namespace common = opentelemetry::common; +namespace nostd = opentelemetry::nostd; +namespace shim = opentelemetry::opentracingshim; + +class ShimUtilsTest : public testing::Test +{ +protected: + virtual void SetUp() + { + } + + virtual void TearDown() + { + } +}; + +TEST_F(ShimUtilsTest, IsBaggageEmpty) +{ + auto none = nostd::shared_ptr(nullptr); + ASSERT_TRUE(shim::utils::isBaggageEmpty(none)); + + auto empty = nostd::shared_ptr(new baggage::Baggage({})); + ASSERT_TRUE(shim::utils::isBaggageEmpty(empty)); + + std::map list{{ "foo", "bar" }}; + auto non_empty = nostd::shared_ptr(new baggage::Baggage(list)); + ASSERT_FALSE(shim::utils::isBaggageEmpty(non_empty)); +} + +TEST_F(ShimUtilsTest, StringFromValue) +{ + ASSERT_EQ(shim::utils::stringFromValue(true), "true"); + ASSERT_EQ(shim::utils::stringFromValue(false), "false"); + ASSERT_EQ(shim::utils::stringFromValue(1234.567890), "1234.567890"); + ASSERT_EQ(shim::utils::stringFromValue(42l), "42"); + ASSERT_EQ(shim::utils::stringFromValue(55ul), "55"); + ASSERT_EQ(shim::utils::stringFromValue(std::string{"a string"}), "a string"); + ASSERT_EQ(shim::utils::stringFromValue(opentracing::string_view{"a string view"}), "a string view"); + ASSERT_EQ(shim::utils::stringFromValue(nullptr), ""); + ASSERT_EQ(shim::utils::stringFromValue("a char ptr"), "a char ptr"); + + opentracing::util::recursive_wrapper values{}; + ASSERT_EQ(shim::utils::stringFromValue(values.get()), ""); + + opentracing::util::recursive_wrapper dict{}; + ASSERT_EQ(shim::utils::stringFromValue(dict.get()), ""); +} + +TEST_F(ShimUtilsTest, AttributeFromValue) +{ + auto value = shim::utils::attributeFromValue(true); + ASSERT_EQ(value.index(), common::AttributeType::kTypeBool); + ASSERT_TRUE(nostd::get(value)); + + value = shim::utils::attributeFromValue(false); + ASSERT_EQ(value.index(), common::AttributeType::kTypeBool); + ASSERT_FALSE(nostd::get(value)); + + value = shim::utils::attributeFromValue(1234.567890); + ASSERT_EQ(value.index(), common::AttributeType::kTypeDouble); + ASSERT_EQ(nostd::get(value), 1234.567890); + + value = shim::utils::attributeFromValue(42l); + ASSERT_EQ(value.index(), common::AttributeType::kTypeInt64); + ASSERT_EQ(nostd::get(value), 42l); + + value = shim::utils::attributeFromValue(55ul); + ASSERT_EQ(value.index(), common::AttributeType::kTypeUInt64); + ASSERT_EQ(nostd::get(value), 55ul); + + value = shim::utils::attributeFromValue(std::string{"a string"}); + ASSERT_EQ(value.index(), common::AttributeType::kTypeCString); + ASSERT_STREQ(nostd::get(value), "a string"); + + value = shim::utils::attributeFromValue(opentracing::string_view{"a string view"}); + ASSERT_EQ(value.index(), common::AttributeType::kTypeString); + ASSERT_EQ(nostd::get(value), nostd::string_view{"a string view"}); + + value = shim::utils::attributeFromValue(nullptr); + ASSERT_EQ(value.index(), common::AttributeType::kTypeString); + ASSERT_EQ(nostd::get(value), nostd::string_view{}); + + value = shim::utils::attributeFromValue("a char ptr"); + ASSERT_EQ(value.index(), common::AttributeType::kTypeCString); + ASSERT_STREQ(nostd::get(value), "a char ptr"); + + opentracing::util::recursive_wrapper values{}; + value = shim::utils::attributeFromValue(values.get()); + ASSERT_EQ(value.index(), common::AttributeType::kTypeString); + ASSERT_EQ(nostd::get(value), nostd::string_view{}); + + opentracing::util::recursive_wrapper dict{}; + value = shim::utils::attributeFromValue(dict.get()); + ASSERT_EQ(value.index(), common::AttributeType::kTypeString); + ASSERT_EQ(nostd::get(value), nostd::string_view{}); +} + +TEST_F(ShimUtilsTest, TextMapReader_Get_LookupKey_Unsupported) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + ASSERT_FALSE(testee.supports_lookup); + ASSERT_EQ(testee.foreach_key_call_count, 0); + + shim::utils::CarrierReaderShim tester{testee}; + auto lookup_unsupported = testee.LookupKey("foo"); + ASSERT_TRUE(text_map.empty()); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); + ASSERT_EQ(testee.foreach_key_call_count, 1); + + text_map["foo"] = "bar"; + auto lookup_found = testee.LookupKey("foo"); + ASSERT_FALSE(text_map.empty()); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); + ASSERT_EQ(testee.foreach_key_call_count, 2); +} + +TEST_F(ShimUtilsTest, TextMapReader_Get_LookupKey_Supported) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + testee.supports_lookup = true; + ASSERT_TRUE(testee.supports_lookup); + ASSERT_EQ(testee.foreach_key_call_count, 0); + + shim::utils::CarrierReaderShim tester{testee}; + auto lookup_not_found = testee.LookupKey("foo"); + ASSERT_TRUE(text_map.empty()); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_not_found.error(), opentracing::key_not_found_error)); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); + ASSERT_EQ(testee.foreach_key_call_count, 1); + + text_map["foo"] = "bar"; + auto lookup_found = testee.LookupKey("foo"); + ASSERT_FALSE(text_map.empty()); + ASSERT_EQ(lookup_found.value(), opentracing::string_view{"bar"}); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); + ASSERT_EQ(testee.foreach_key_call_count, 1); +} + +TEST_F(ShimUtilsTest, TextMapReader_Keys) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + ASSERT_EQ(testee.foreach_key_call_count, 0); + + shim::utils::CarrierReaderShim tester{testee}; + std::vector kvs; + auto callback = [&text_map,&kvs](nostd::string_view k){ + kvs.emplace_back(k); + return !text_map.empty(); + }; + + ASSERT_TRUE(tester.Keys(callback)); + ASSERT_TRUE(text_map.empty()); + ASSERT_TRUE(kvs.empty()); + ASSERT_EQ(testee.foreach_key_call_count, 1); + + text_map["foo"] = "bar"; + text_map["bar"] = "baz"; + text_map["baz"] = "foo"; + ASSERT_TRUE(tester.Keys(callback)); + ASSERT_FALSE(text_map.empty()); + ASSERT_EQ(text_map.size(), kvs.size()); + ASSERT_EQ(testee.foreach_key_call_count, 2); +} + +TEST_F(ShimUtilsTest, TextMapWriter_Set) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + shim::utils::CarrierWriterShim tester{testee}; + ASSERT_TRUE(text_map.empty()); + + tester.Set("foo", "bar"); + tester.Set("bar", "baz"); + tester.Set("baz", "foo"); + ASSERT_FALSE(text_map.empty()); + ASSERT_EQ(text_map.size(), 3); + ASSERT_EQ(text_map["foo"], "bar"); + ASSERT_EQ(text_map["bar"], "baz"); + ASSERT_EQ(text_map["baz"], "foo"); +} \ No newline at end of file diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index c4c2aa7937..3e0abd77f6 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -1,10 +1,14 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ #include "tracer_shim.h" +#include "span_shim.h" #include "span_context_shim.h" +#include "shim_utils.h" +#include "shim_mocks.h" -#include #include #include @@ -15,102 +19,6 @@ namespace context = opentelemetry::context; namespace baggage = opentelemetry::baggage; namespace shim = opentelemetry::opentracingshim; -struct MockPropagator : public context::propagation::TextMapPropagator -{ - // Returns the context that is stored in the carrier with the TextMapCarrier as extractor. - context::Context Extract(const context::propagation::TextMapCarrier &carrier, - context::Context &context) noexcept override - { - std::vector> kvs; - carrier.Keys([&carrier,&kvs](nostd::string_view k){ - kvs.emplace_back(k, carrier.Get(k)); - return true; - }); - is_extracted = true; - return baggage::SetBaggage(context, nostd::shared_ptr(new baggage::Baggage(kvs))); - } - - // Sets the context for carrier with self defined rules. - void Inject(context::propagation::TextMapCarrier &carrier, - const context::Context &context) noexcept override - { - auto baggage = baggage::GetBaggage(context); - baggage->GetAllEntries([&carrier](nostd::string_view k, nostd::string_view v){ - carrier.Set(k, v); - return true; - }); - is_injected = true; - } - - // Gets the fields set in the carrier by the `inject` method - bool Fields(nostd::function_ref callback) const noexcept override - { - return true; - } - - bool is_extracted = false; - bool is_injected = false; -}; - -struct TextMapCarrier : opentracing::TextMapReader, opentracing::TextMapWriter { - TextMapCarrier(std::unordered_map& text_map_) - : text_map(text_map_) {} - - opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { - text_map[key] = value; - return {}; - } - - opentracing::expected LookupKey(opentracing::string_view key) const override { - if (!supports_lookup) { - return opentracing::make_unexpected(opentracing::lookup_key_not_supported_error); - } - auto iter = text_map.find(key); - if (iter != text_map.end()) { - return opentracing::string_view{iter->second}; - } else { - return opentracing::make_unexpected(opentracing::key_not_found_error); - } - } - - opentracing::expected ForeachKey( - std::function(opentracing::string_view key, opentracing::string_view value)> f) - const override { - ++foreach_key_call_count; - for (const auto& key_value : text_map) { - auto result = f(key_value.first, key_value.second); - if (!result) return result; - } - return {}; - } - - bool supports_lookup = false; - mutable int foreach_key_call_count = 0; - std::unordered_map& text_map; -}; - -struct HTTPHeadersCarrier : opentracing::HTTPHeadersReader, opentracing::HTTPHeadersWriter { - HTTPHeadersCarrier(std::unordered_map& text_map_) - : text_map(text_map_) {} - - opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { - text_map[key] = value; - return {}; - } - - opentracing::expected ForeachKey( - std::function(opentracing::string_view key, opentracing::string_view value)> f) - const override { - for (const auto& key_value : text_map) { - auto result = f(key_value.first, key_value.second); - if (!result) return result; - } - return {}; - } - - std::unordered_map& text_map; -}; - class TracerShimTest : public testing::Test { public: @@ -126,9 +34,10 @@ class TracerShimTest : public testing::Test text_map_format = new MockPropagator(); http_headers_format = new MockPropagator(); - tracer_shim = shim::TracerShim::createTracerShim(trace_api::Provider::GetTracerProvider(), - { .text_map = nostd::shared_ptr(text_map_format), - .http_headers = nostd::shared_ptr(http_headers_format) }); + tracer_shim = shim::TracerShim::createTracerShim(trace_api::Provider::GetTracerProvider(), { + .text_map = nostd::shared_ptr(text_map_format), + .http_headers = nostd::shared_ptr(http_headers_format) + }); } virtual void TearDown() @@ -151,6 +60,13 @@ TEST_F(TracerShimTest, TracerGloballyRegistered) ASSERT_TRUE(opentracing::Tracer::IsGlobalTracerRegistered()); } +TEST_F(TracerShimTest, Close) +{ + tracer_shim->Close(); + auto span_shim = tracer_shim->StartSpan("a"); + ASSERT_TRUE(span_shim == nullptr); +} + TEST_F(TracerShimTest, InjectInvalidCarrier) { auto span_shim = tracer_shim->StartSpan("a"); @@ -234,20 +150,18 @@ TEST_F(TracerShimTest, ExtractOnlyBaggage) std::unordered_map text_map; auto span_shim = tracer_shim->StartSpan("a"); span_shim->SetBaggageItem("foo", "bar"); - ASSERT_EQ(span_shim->BaggageItem("foo"), "bar"); - TextMapCarrier carrier{text_map}; - tracer_shim->Inject(span_shim->context(), carrier); - - auto span_context = tracer_shim->Extract(carrier); + tracer_shim->Inject(span_shim->context(), TextMapCarrier{text_map}); + auto span_context = tracer_shim->Extract(TextMapCarrier{text_map}); ASSERT_TRUE(span_context.value() != nullptr); - // auto span_context_shim = dynamic_cast(span_context.value().get()); - // ASSERT_TRUE(span_context_shim != nullptr); - // ASSERT_TRUE(span_context_shim->context().IsValid()); + auto span_context_shim = dynamic_cast(span_context.value().get()); + ASSERT_TRUE(span_context_shim != nullptr); + ASSERT_FALSE(span_context_shim->context().IsValid()); + ASSERT_FALSE(shim::utils::isBaggageEmpty(span_context_shim->baggage())); - // std::string value; - // ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); - // ASSERT_EQ(value, "bar"); + std::string value; + ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); + ASSERT_EQ(value, "bar"); } From 4d99b8565ce9ac95929ffdd82bc4d86dbbc10c8e Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Tue, 3 Jan 2023 21:25:51 -0500 Subject: [PATCH 06/46] Unit tests for span context shim --- .../test/span_context_shim_test.cc | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 opentracing-shim/test/span_context_shim_test.cc diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc new file mode 100644 index 0000000000..0c36b8c3c1 --- /dev/null +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -0,0 +1,91 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "span_context_shim.h" + +#include "opentelemetry/baggage/baggage.h" +#include "opentelemetry/trace/span_context.h" + +#include + +namespace trace_api = opentelemetry::trace; +namespace baggage = opentelemetry::baggage; +namespace nostd = opentelemetry::nostd; +namespace shim = opentelemetry::opentracingshim; + +class SpanContextShimTest : public testing::Test +{ +public: + nostd::unique_ptr span_context_shim; + +protected: + virtual void SetUp() + { + auto span_context = trace_api::SpanContext::GetInvalid(); + auto baggage = baggage::Baggage::GetDefault()->Set("foo", "bar"); + span_context_shim = nostd::unique_ptr( + new shim::SpanContextShim(span_context, baggage)); + } + + virtual void TearDown() + { + span_context_shim.reset(); + } +}; + +TEST_F(SpanContextShimTest, BaggageItem) +{ + std::string value; + ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); + ASSERT_EQ(value, "bar"); + ASSERT_FALSE(span_context_shim->BaggageItem("", value)); +} + +TEST_F(SpanContextShimTest, NewWithKeyValue) +{ + auto new_span_context_shim = span_context_shim->newWithKeyValue("test", "this"); + + std::string value; + ASSERT_TRUE(new_span_context_shim.BaggageItem("foo", value)); + ASSERT_EQ(value, "bar"); + ASSERT_TRUE(new_span_context_shim.BaggageItem("test", value)); + ASSERT_EQ(value, "this"); +} + +TEST_F(SpanContextShimTest, ForeachBaggageItem) +{ + std::initializer_list> list{ + { "foo", "bar" }, { "bar", "baz" }, { "baz", "foo" } + }; + nostd::shared_ptr baggage(new baggage::Baggage(list)); + shim::SpanContextShim new_span_context_shim(span_context_shim->context(), baggage); + + std::vector concatenated; + new_span_context_shim.ForeachBaggageItem([&concatenated] + (const std::string& key, const std::string& value){ + concatenated.emplace_back(key + ":" + value); + return true; + }); + + ASSERT_EQ(concatenated.size(), 3); + ASSERT_EQ(concatenated[0], "foo:bar"); + ASSERT_EQ(concatenated[1], "bar:baz"); + ASSERT_EQ(concatenated[2], "baz:foo"); +} + +TEST_F(SpanContextShimTest, Clone) +{ + auto new_span_context = span_context_shim->Clone(); + auto new_span_context_shim = dynamic_cast(new_span_context.get()); + ASSERT_TRUE(new_span_context_shim != nullptr); + ASSERT_NE(span_context_shim.get(), new_span_context_shim); + ASSERT_EQ(span_context_shim->context().IsValid(), new_span_context_shim->context().IsValid()); + + std::string value; + std::string new_value; + ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); + ASSERT_TRUE(new_span_context_shim->BaggageItem("foo", new_value)); + ASSERT_EQ(value, new_value); +} \ No newline at end of file From 22949e2a7f2d512b4b699c6507174c4f0516769c Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 4 Jan 2023 02:06:18 -0500 Subject: [PATCH 07/46] Unit tests for span shim --- opentracing-shim/include/span_context_shim.h | 2 +- opentracing-shim/include/span_shim.h | 2 +- opentracing-shim/src/span_shim.cc | 18 +- opentracing-shim/test/shim_mocks.h | 65 ++++++- opentracing-shim/test/span_shim_test.cc | 184 +++++++++++++++++++ 5 files changed, 259 insertions(+), 12 deletions(-) create mode 100644 opentracing-shim/test/span_shim_test.cc diff --git a/opentracing-shim/include/span_context_shim.h b/opentracing-shim/include/span_context_shim.h index d615d56d0b..f0493a983f 100644 --- a/opentracing-shim/include/span_context_shim.h +++ b/opentracing-shim/include/span_context_shim.h @@ -21,7 +21,7 @@ class SpanContextShim final : public opentracing::SpanContext explicit SpanContextShim(const opentelemetry::trace::SpanContext& context, const BaggagePtr& baggage) : context_(context), baggage_(baggage) {} inline const opentelemetry::trace::SpanContext& context() const { return context_; } - inline const BaggagePtr& baggage() const { return baggage_; } + inline const BaggagePtr baggage() const { return baggage_; } SpanContextShim newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept; bool BaggageItem(nostd::string_view key, std::string& value) const noexcept; // Overrides diff --git a/opentracing-shim/include/span_shim.h b/opentracing-shim/include/span_shim.h index 72b7349c89..238738228f 100644 --- a/opentracing-shim/include/span_shim.h +++ b/opentracing-shim/include/span_shim.h @@ -40,7 +40,7 @@ class SpanShim : public opentracing::Span inline const opentracing::Tracer& tracer() const noexcept override { return tracer_; }; private: - void logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept; + void logImpl(nostd::span fields, const opentracing::SystemTime* const timestamp) noexcept; const TracerShim& tracer_; SpanPtr span_; diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index fedd3575cf..1f1be112c4 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -67,14 +67,18 @@ void SpanShim::SetBaggageItem(opentracing::string_view restricted_key, opentraci { // Creates a new SpanContext Shim with a new OpenTelemetry Baggage containing the specified // Baggage key/value pair, and sets it as the current instance for this Span Shim. + if (restricted_key.empty() || value.empty()) return; + const std::lock_guard guard(context_lock_); - context_ = context_.newWithKeyValue(restricted_key.data(), value.data());; + context_ = context_.newWithKeyValue(restricted_key.data(), value.data()); } std::string SpanShim::BaggageItem(opentracing::string_view restricted_key) const noexcept { // Returns the value for the specified key in the OpenTelemetry Baggage // of the current SpanContext Shim, or null if none exists. + if (restricted_key.empty()) return ""; + const std::lock_guard guard(context_lock_); std::string value; return context_.BaggageItem(restricted_key.data(), value) ? value : ""; @@ -84,24 +88,24 @@ void SpanShim::Log(std::initializer_list fields) noexcept { // If an explicit timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. - logImpl(opentracing::SystemTime::min(), fields); + logImpl(fields, nullptr); } void SpanShim::Log(opentracing::SystemTime timestamp, std::initializer_list fields) noexcept { // If an explicit timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. - logImpl(timestamp, fields); + logImpl(fields, ×tamp); } void SpanShim::Log(opentracing::SystemTime timestamp, const std::vector& fields) noexcept { // If an explicit timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. - logImpl(timestamp, fields); + logImpl(fields, ×tamp); } -void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::span fields) noexcept +void SpanShim::logImpl(nostd::span fields, const opentracing::SystemTime* const timestamp) noexcept { // The Add Event’s name parameter MUST be the value with the event key // in the pair set, or else fallback to use the log literal string. @@ -143,9 +147,9 @@ void SpanShim::logImpl(opentracing::SystemTime timestamp, nostd::spanAddEvent(name, timestamp, attributes); + span_->AddEvent(name, *timestamp, attributes); } else { diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 2842c35db0..1a74ae1f49 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -6,13 +6,72 @@ #pragma once #include +#include +#include +#include +#include #include #include +#include -namespace baggage = opentelemetry::baggage; -namespace context = opentelemetry::context; -namespace nostd = opentelemetry::nostd; +namespace trace_api = opentelemetry::trace; +namespace baggage = opentelemetry::baggage; +namespace common = opentelemetry::common; +namespace context = opentelemetry::context; +namespace nostd = opentelemetry::nostd; + +struct MockSpan final : public trace_api::Span +{ + void SetAttribute(nostd::string_view key, + const common::AttributeValue& value) noexcept override + { + attribute_ = {key.data(), value}; + } + + void AddEvent(nostd::string_view name, + common::SystemTimestamp timestamp, + const common::KeyValueIterable& attributes) noexcept override + { + std::unordered_map attribute_map; + attribute_map.reserve(attributes.size()); + attributes.ForEachKeyValue([&attribute_map](nostd::string_view key, const common::AttributeValue& value){ + attribute_map.emplace(key.data(), value); + return true; + }); + event_ = {name.data(), timestamp, attribute_map}; + } + + void AddEvent(nostd::string_view name, + const common::KeyValueIterable& attributes) noexcept override + { + AddEvent(name, {}, attributes); + } + + void AddEvent(nostd::string_view name, + common::SystemTimestamp timestamp) noexcept override {} + + void AddEvent(nostd::string_view name) noexcept override {} + + void SetStatus(trace_api::StatusCode code, nostd::string_view description) noexcept override + { + status_ = {code, description.data()}; + } + + void UpdateName(nostd::string_view name) noexcept override { name_ = name.data(); } + + void End(const trace_api::EndSpanOptions& options) noexcept override { options_ = options; } + + bool IsRecording() const noexcept override { return false; } + + trace_api::SpanContext GetContext() const noexcept override { return trace_api::SpanContext(false, false); } + + std::pair attribute_; + std::tuple> event_; + std::pair status_; + std::string name_; + trace_api::EndSpanOptions options_; +}; struct MockPropagator : public context::propagation::TextMapPropagator { diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc new file mode 100644 index 0000000000..4d6cebd80b --- /dev/null +++ b/opentracing-shim/test/span_shim_test.cc @@ -0,0 +1,184 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "span_shim.h" +#include "tracer_shim.h" +#include "shim_mocks.h" + +#include + +namespace trace_api = opentelemetry::trace; +namespace baggage = opentelemetry::baggage; +namespace nostd = opentelemetry::nostd; +namespace shim = opentelemetry::opentracingshim; + +class SpanShimTest : public testing::Test +{ +public: + nostd::unique_ptr span_shim; + MockSpan* mock_span; + +protected: + virtual void SetUp() + { + mock_span = new MockSpan(); + auto span = nostd::shared_ptr(mock_span); + auto tracer = shim::TracerShim::createTracerShim(); + auto tracer_shim = dynamic_cast(tracer.get()); + auto baggage = baggage::Baggage::GetDefault()->Set("baggage", "item"); + span_shim = nostd::unique_ptr( + new shim::SpanShim(*tracer_shim, span, baggage)); + } + + virtual void TearDown() + { + span_shim.reset(); + } +}; + +TEST_F(SpanShimTest, HandleError) +{ + span_shim->handleError(true); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kError); + span_shim->handleError("true"); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kError); + span_shim->handleError(false); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kOk); + span_shim->handleError("false"); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kOk); + span_shim->handleError(nullptr); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kUnset); +} + +TEST_F(SpanShimTest, FinishWithOptions) +{ + opentracing::FinishSpanOptions options; + options.finish_steady_timestamp = opentracing::SteadyTime::clock::now(); + ASSERT_NE(mock_span->options_.end_steady_time, options.finish_steady_timestamp); + span_shim->FinishWithOptions(options); + ASSERT_EQ(mock_span->options_.end_steady_time, options.finish_steady_timestamp); +} + +TEST_F(SpanShimTest, SetOperationName) +{ + ASSERT_NE(mock_span->name_, "foo"); + span_shim->SetOperationName("foo"); + ASSERT_EQ(mock_span->name_, "foo"); +} + +TEST_F(SpanShimTest, SetTag_Normal) +{ + ASSERT_NE(mock_span->attribute_.first, "foo"); + span_shim->SetTag("foo", "bar"); + ASSERT_EQ(mock_span->attribute_.first, "foo"); + ASSERT_STREQ(nostd::get(mock_span->attribute_.second), "bar"); +} + +TEST_F(SpanShimTest, SetTag_Error) +{ + ASSERT_NE(mock_span->attribute_.first, "error"); + span_shim->SetTag("error", true); + ASSERT_NE(mock_span->attribute_.first, "error"); + span_shim->SetTag("error", "false"); + ASSERT_NE(mock_span->attribute_.first, "error"); + span_shim->SetTag("error", nullptr); + ASSERT_NE(mock_span->attribute_.first, "error"); +} + +TEST_F(SpanShimTest, BaggageItem) +{ + ASSERT_EQ(span_shim->BaggageItem({}), ""); + ASSERT_EQ(span_shim->BaggageItem(""), ""); + ASSERT_EQ(span_shim->BaggageItem("invalid"), ""); + ASSERT_EQ(span_shim->BaggageItem("baggage"), "item"); +} + +TEST_F(SpanShimTest, SetBaggageItem) +{ + span_shim->SetBaggageItem("new", "entry"); + ASSERT_EQ(span_shim->BaggageItem("new"), "entry"); + ASSERT_EQ(span_shim->BaggageItem("baggage"), "item"); + span_shim->SetBaggageItem("empty", ""); + ASSERT_EQ(span_shim->BaggageItem("empty"), ""); + span_shim->SetBaggageItem("no value", {}); + ASSERT_EQ(span_shim->BaggageItem("no value"), ""); +} + +TEST_F(SpanShimTest, Log_NoEvent) +{ + std::string name; + common::SystemTimestamp timestamp; + std::unordered_map attributes; + + span_shim->Log({{"test", 42}}); + std::tie(name, timestamp, attributes) = mock_span->event_; + + ASSERT_EQ(name, "log"); + ASSERT_EQ(timestamp, common::SystemTimestamp{}); + ASSERT_EQ(attributes.size(), 1); + ASSERT_EQ(nostd::get(attributes["test"]), 42); +} + +TEST_F(SpanShimTest, Log_NoEvent_Timestamp) +{ + std::string name; + common::SystemTimestamp timestamp; + std::unordered_map attributes; + + auto logtime = opentracing::SystemTime::time_point::clock::now(); + span_shim->Log(logtime, {{"foo", "bar"}}); + std::tie(name, timestamp, attributes) = mock_span->event_; + + ASSERT_EQ(name, "log"); + ASSERT_EQ(timestamp, common::SystemTimestamp{logtime}); + ASSERT_EQ(attributes.size(), 1); + ASSERT_STREQ(nostd::get(attributes["foo"]), "bar"); +} + +TEST_F(SpanShimTest, Log_Event) +{ + std::string name; + common::SystemTimestamp timestamp; + std::unordered_map attributes; + + auto logtime = opentracing::SystemTime::time_point::clock::now(); + std::initializer_list> fields{ + {"event", "test!"}, {"foo", opentracing::string_view{"bar"}}, + {"error.kind", 42}, {"message","hello"}, {"stack","overflow"}}; + span_shim->Log(logtime, fields); + std::tie(name, timestamp, attributes) = mock_span->event_; + + ASSERT_EQ(name, "test!"); + ASSERT_EQ(timestamp, common::SystemTimestamp{logtime}); + ASSERT_EQ(attributes.size(), 5); + ASSERT_STREQ(nostd::get(attributes["event"]), "test!"); + ASSERT_EQ(nostd::get(attributes["foo"]), nostd::string_view{"bar"}); + ASSERT_EQ(nostd::get(attributes["error.kind"]), 42); + ASSERT_STREQ(nostd::get(attributes["message"]), "hello"); + ASSERT_STREQ(nostd::get(attributes["stack"]), "overflow"); +} + +TEST_F(SpanShimTest, Log_Error) +{ + std::string name; + common::SystemTimestamp timestamp; + std::unordered_map attributes; + + auto logtime = opentracing::SystemTime::time_point::clock::now(); + std::vector> fields{ + {"event", "error"}, {"foo", opentracing::string_view{"bar"}}, + {"error.kind", 42}, {"message","hello"}, {"stack","overflow"}}; + span_shim->Log(logtime, fields); + std::tie(name, timestamp, attributes) = mock_span->event_; + + ASSERT_EQ(name, "exception"); + ASSERT_EQ(timestamp, common::SystemTimestamp{logtime}); + ASSERT_EQ(attributes.size(), 5); + ASSERT_STREQ(nostd::get(attributes["event"]), "error"); + ASSERT_EQ(nostd::get(attributes["foo"]), nostd::string_view{"bar"}); + ASSERT_EQ(nostd::get(attributes["exception.type"]), 42); + ASSERT_STREQ(nostd::get(attributes["exception.message"]), "hello"); + ASSERT_STREQ(nostd::get(attributes["exception.stacktrace"]), "overflow"); +} From f62eb78b327b050b0c764b2b7e3c7b84aec7ea07 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 4 Jan 2023 11:52:16 -0500 Subject: [PATCH 08/46] Cleanup and more unit tests --- opentracing-shim/include/propagation.h | 96 +++++++ opentracing-shim/include/shim_utils.h | 174 ++++++++----- opentracing-shim/src/span_shim.cc | 2 +- opentracing-shim/src/tracer_shim.cc | 140 +---------- opentracing-shim/test/propagation_test.cc | 115 +++++++++ opentracing-shim/test/shim_mocks.h | 12 +- opentracing-shim/test/shim_utils_test.cc | 238 ++++++++++++------ .../test/span_context_shim_test.cc | 6 + opentracing-shim/test/tracer_shim_test.cc | 4 +- 9 files changed, 505 insertions(+), 282 deletions(-) create mode 100644 opentracing-shim/include/propagation.h create mode 100644 opentracing-shim/test/propagation_test.cc diff --git a/opentracing-shim/include/propagation.h b/opentracing-shim/include/propagation.h new file mode 100644 index 0000000000..19d0da73fb --- /dev/null +++ b/opentracing-shim/include/propagation.h @@ -0,0 +1,96 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include "opentelemetry/baggage/baggage.h" +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/context/propagation/text_map_propagator.h" +#include "opentelemetry/nostd/type_traits.h" +#include "opentracing/propagation.h" +#include "opentracing/value.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ + +template::value, bool> = true> +class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCarrier +{ +public: + CarrierWriterShim(const T& writer) : writer_(writer) {} + + // returns the value associated with the passed key. + virtual nostd::string_view Get(nostd::string_view key) const noexcept override + { + return ""; + } + + // stores the key-value pair. + virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override + { + writer_.Set(key.data(), value.data()); + } + +private: + const T& writer_; +}; + +template::value, bool> = true> +class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCarrier +{ +public: + CarrierReaderShim(const T& reader) : reader_(reader) {} + + // returns the value associated with the passed key. + virtual nostd::string_view Get(nostd::string_view key) const noexcept override + { + nostd::string_view value; + + // First try carrier.LookupKey since that can potentially be the fastest approach. + if (auto result = reader_.LookupKey(key.data())) + { + value = result.value().data(); + } + else // Fall back to iterating through all of the keys. + { + reader_.ForeachKey([key, &value] + (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { + if (k == key.data()) + { + value = v.data(); + // Found key, so bail out of the loop with a success error code. + return opentracing::make_unexpected(std::error_code{}); + } + return opentracing::make_expected(); + }); + } + + return value; + } + + // stores the key-value pair. + virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override + { + // Not required for Opentracing reader + } + + // list of all the keys in the carrier. + virtual bool Keys(nostd::function_ref callback) const noexcept override + { + return reader_.ForeachKey([&callback] + (opentracing::string_view key, opentracing::string_view) -> opentracing::expected { + return callback(key.data()) + ? opentracing::make_expected() + : opentracing::make_unexpected(std::error_code{}); + }).has_value(); + } + +private: + const T& reader_; +}; + +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/shim_utils.h b/opentracing-shim/include/shim_utils.h index 87e1951140..89dad026a6 100644 --- a/opentracing-shim/include/shim_utils.h +++ b/opentracing-shim/include/shim_utils.h @@ -5,12 +5,20 @@ #pragma once -#include -#include -#include -#include -#include -#include +#include "span_context_shim.h" + +#include "opentelemetry/baggage/baggage.h" +#include "opentelemetry/baggage/baggage_context.h" +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/context/propagation/text_map_propagator.h" +#include "opentelemetry/nostd/type_traits.h" +#include "opentelemetry/trace/semantic_conventions.h" +#include "opentelemetry/trace/tracer.h" +#include "opentracing/propagation.h" +#include "opentracing/tracer.h" +#include "opentracing/value.h" + +#include OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim::utils @@ -56,92 +64,126 @@ static inline std::string stringFromValue(const opentracing::Value& value) return opentracing::Value::visit(value, StringMapper); } -template::value, bool> = true> -class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCarrier +static inline bool isBaggageEmpty(const nostd::shared_ptr& baggage) { -public: - CarrierWriterShim(const T& writer) : writer_(writer) {} - - // returns the value associated with the passed key. - virtual nostd::string_view Get(nostd::string_view key) const noexcept override + if (baggage) { - return ""; + return baggage->GetAllEntries([](nostd::string_view, nostd::string_view){ + return false; + }); } - // stores the key-value pair. - virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override + return true; +} + +static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing::StartSpanOptions& options) noexcept +{ + using opentracing::SpanReferenceType; + // If an explicit start timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. + opentelemetry::trace::StartSpanOptions options_shim; + options_shim.start_system_time = opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; + options_shim.start_steady_time = opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; + + const auto& refs = options.references; + // If a list of Span references is specified... + if (!refs.empty()) { - writer_.Set(key.data(), value.data()); + auto first_child_of = std::find_if(refs.cbegin(), refs.cend(), + [](const std::pair& entry){ + return entry.first == SpanReferenceType::ChildOfRef; + }); + // The first SpanContext with Child Of type in the entire list is used as parent, + // else the first SpanContext is used as parent + auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; + + if (auto context_shim = dynamic_cast(context)) + { + options_shim.parent = context_shim->context(); + } } -private: - const T& writer_; -}; + return options_shim; +} -template::value, bool> = true> -class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCarrier -{ -public: - CarrierReaderShim(const T& reader) : reader_(reader) {} +using RefsList = std::vector>; +using LinksList = std::vector>; - // returns the value associated with the passed key. - virtual nostd::string_view Get(nostd::string_view key) const noexcept override +static LinksList makeReferenceLinks(const opentracing::StartSpanOptions& options) noexcept +{ + using opentracing::SpanReferenceType; + using namespace opentelemetry::trace::SemanticConventions; + + LinksList links; + links.reserve(options.references.size()); + // All values in the list MUST be added as Links with the reference type value + // as a Link attribute, i.e. opentracing.ref_type set to follows_from or child_of + for (const auto& entry : options.references) { - nostd::string_view value; + auto context_shim = dynamic_cast(entry.second); + nostd::string_view span_kind; - // First try carrier.LookupKey since that can potentially be the fastest approach. - if (auto result = reader_.LookupKey(key.data())) + if (entry.first == SpanReferenceType::ChildOfRef) { - value = result.value().data(); + span_kind = OpentracingRefTypeValues::kChildOf; } - else // Fall back to iterating through all of the keys. + else if (entry.first == SpanReferenceType::FollowsFromRef) { - reader_.ForeachKey([key, &value] - (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { - if (k == key.data()) - { - value = v.data(); - // Found key, so bail out of the loop with a success error code. - return opentracing::make_unexpected(std::error_code{}); - } - return opentracing::make_expected(); - }); + span_kind = OpentracingRefTypeValues::kFollowsFrom; } - return value; + if (context_shim && !span_kind.empty()) + { + links.emplace_back(std::piecewise_construct, + std::forward_as_tuple(context_shim->context()), + std::forward_as_tuple(std::forward({{ kOpentracingRefType, span_kind }}))); + } } - // stores the key-value pair. - virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override - { - // Not required for Opentracing reader - } + return links; +} - // list of all the keys in the carrier. - virtual bool Keys(nostd::function_ref callback) const noexcept override +static nostd::shared_ptr makeBaggage(const opentracing::StartSpanOptions& options) noexcept +{ + using namespace opentelemetry::baggage; + + std::unordered_map baggage_items; + // If a list of Span references is specified... + for (const auto& entry : options.references) { - return reader_.ForeachKey([&callback] - (opentracing::string_view key, opentracing::string_view) -> opentracing::expected { - return callback(key.data()) - ? opentracing::make_expected() - : opentracing::make_unexpected(std::error_code{}); - }).has_value(); + if (auto context_shim = dynamic_cast(entry.second)) + { + // The union of their Baggage values MUST be used as the initial Baggage of the newly created Span. + context_shim->ForeachBaggageItem([&baggage_items](const std::string& key, const std::string& value){ + // It is unspecified which Baggage value is used in the case of repeated keys. + if (baggage_items.find(key) == baggage_items.end()) + { + baggage_items.emplace(key, value); // Here, only insert if key not already present + } + return true; + }); + } } + // If no such list of references is specified, the current Baggage + // MUST be used as the initial value of the newly created Span. + return baggage_items.empty() + ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) + : nostd::shared_ptr(new Baggage(baggage_items)); +} -private: - const T& reader_; -}; - -static inline bool isBaggageEmpty(const nostd::shared_ptr& baggage) +static std::vector> makeTags(const opentracing::StartSpanOptions& options) noexcept { - if (baggage) + std::vector> tags; + tags.reserve(options.tags.size()); + + // If an initial set of tags is specified, the values MUST + // be set at the creation time of the OpenTelemetry Span. + for (const auto& entry : options.tags) { - return baggage->GetAllEntries([](nostd::string_view, nostd::string_view){ - return false; - }); + tags.emplace_back(entry.first, utils::attributeFromValue(entry.second)); } - return true; + return tags; } } // namespace opentracingshim::utils diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 1f1be112c4..b40b897d0a 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -10,7 +10,7 @@ #include "opentelemetry/trace/semantic_conventions.h" #include "opentelemetry/trace/span_metadata.h" -#include +#include "opentracing/ext/tags.h" OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index e6674e328e..9e402d45c5 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -6,142 +6,25 @@ #include "tracer_shim.h" #include "span_shim.h" #include "shim_utils.h" +#include "propagation.h" -#include -#include -#include -#include -#include +#include "opentelemetry/context/propagation/global_propagator.h" +#include "opentelemetry/trace/context.h" +#include "opentracing/ext/tags.h" OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -namespace detail -{ - -using RefsList = std::initializer_list>; -using LinksList = std::vector>; - -static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing::StartSpanOptions& options) noexcept -{ - using opentracing::SpanReferenceType; - // If an explicit start timestamp is specified, a conversion MUST - // be done to match the OpenTracing and OpenTelemetry units. - opentelemetry::trace::StartSpanOptions options_shim; - options_shim.start_system_time = opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; - options_shim.start_steady_time = opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; - - const auto& refs = options.references; - // If a list of Span references is specified... - if (!refs.empty()) - { - auto first_child_of = std::find_if(refs.cbegin(), refs.cend(), - [](const std::pair& entry){ - return entry.first == SpanReferenceType::ChildOfRef; - }); - // The first SpanContext with Child Of type in the entire list is used as parent, - // else the first SpanContext is used as parent - auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; - - if (auto context_shim = dynamic_cast(context)) - { - options_shim.parent = context_shim->context(); - } - } - - return options_shim; -} - -static LinksList makeReferenceLinks(const opentracing::StartSpanOptions& options) noexcept -{ - using opentracing::SpanReferenceType; - using namespace opentelemetry::trace::SemanticConventions; - - LinksList links; - links.reserve(options.references.size()); - // All values in the list MUST be added as Links with the reference type value - // as a Link attribute, i.e. opentracing.ref_type set to follows_from or child_of - for (const auto& entry : options.references) - { - auto context_shim = dynamic_cast(entry.second); - nostd::string_view span_kind; - - if (entry.first == SpanReferenceType::ChildOfRef) - { - span_kind = OpentracingRefTypeValues::kChildOf; - } - else if (entry.first == SpanReferenceType::FollowsFromRef) - { - span_kind = OpentracingRefTypeValues::kFollowsFrom; - } - - if (context_shim && !span_kind.empty()) - { - // links.push_back({ context_shim->context(), {{ opentracing::ext::span_kind.data(), span_kind }} }); - links.emplace_back(std::piecewise_construct, - std::forward_as_tuple(context_shim->context()), - std::forward_as_tuple(std::forward({{ opentracing::ext::span_kind.data(), span_kind }}))); - } - } - - return links; -} - -static BaggagePtr makeBaggage(const opentracing::StartSpanOptions& options) noexcept -{ - using namespace opentelemetry::baggage; - - std::unordered_map baggage_items; - // If a list of Span references is specified... - for (const auto& entry : options.references) - { - if (auto context_shim = dynamic_cast(entry.second)) - { - // The union of their Baggage values MUST be used as the initial Baggage of the newly created Span. - context_shim->ForeachBaggageItem([&baggage_items](const std::string& key, const std::string& value){ - // It is unspecified which Baggage value is used in the case of repeated keys. - if (baggage_items.find(key) == baggage_items.end()) - { - baggage_items.emplace(key, value); // Here, only insert if key not already present - } - return true; - }); - } - } - // If no such lisf of references is specified, the current Baggage - // MUST be used as the initial value of the newly created Span. - return baggage_items.empty() - ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) - : nostd::shared_ptr(new Baggage(baggage_items)); -} - -static std::vector> makeTags(const opentracing::StartSpanOptions& options) noexcept -{ - std::vector> tags; - tags.reserve(options.tags.size()); - - // If an initial set of tags is specified, the values MUST - // be set at the creation time of the OpenTelemetry Span. - for (const auto& entry : options.tags) - { - tags.emplace_back(entry.first, utils::attributeFromValue(entry.second)); - } - - return tags; -} - -} // namespace opentracingshim::detail - std::unique_ptr TracerShim::StartSpanWithOptions(opentracing::string_view operation_name, const opentracing::StartSpanOptions& options) const noexcept { if (is_closed_) return nullptr; - const auto& opts = detail::makeOptionsShim(options); - const auto& links = detail::makeReferenceLinks(options); - const auto& baggage = detail::makeBaggage(options); - const auto& attributes = detail::makeTags(options); + const auto& opts = utils::makeOptionsShim(options); + const auto& links = utils::makeReferenceLinks(options); + const auto& baggage = utils::makeBaggage(options); + const auto& attributes = utils::makeTags(options); auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); auto span_shim = new SpanShim(*this, span, baggage); @@ -233,11 +116,12 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex // It MUST inject any non-empty Baggage even amidst no valid SpanContext. const auto& context = opentelemetry::baggage::SetBaggage(current_context, context_shim->baggage()); - utils::CarrierWriterShim carrier{writer}; + CarrierWriterShim carrier{writer}; propagator->Inject(carrier, context); + return opentracing::make_expected(); } - return opentracing::make_expected(); + return opentracing::make_unexpected(opentracing::invalid_span_context_error); } template @@ -246,7 +130,7 @@ opentracing::expected> TracerShim::ext { // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. - utils::CarrierReaderShim carrier{reader}; + CarrierReaderShim carrier{reader}; auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); auto context = propagator->Extract(carrier, current_context); auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc new file mode 100644 index 0000000000..717cb99c9a --- /dev/null +++ b/opentracing-shim/test/propagation_test.cc @@ -0,0 +1,115 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "propagation.h" +#include "shim_mocks.h" + +#include + +namespace baggage = opentelemetry::baggage; +namespace common = opentelemetry::common; +namespace nostd = opentelemetry::nostd; +namespace shim = opentelemetry::opentracingshim; + +class PropagationTest : public testing::Test +{ +protected: + virtual void SetUp() + { + } + + virtual void TearDown() + { + } +}; + +TEST_F(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + ASSERT_FALSE(testee.supports_lookup); + ASSERT_EQ(testee.foreach_key_call_count, 0); + + shim::CarrierReaderShim tester{testee}; + auto lookup_unsupported = testee.LookupKey("foo"); + ASSERT_TRUE(text_map.empty()); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); + ASSERT_EQ(testee.foreach_key_call_count, 1); + + text_map["foo"] = "bar"; + auto lookup_found = testee.LookupKey("foo"); + ASSERT_FALSE(text_map.empty()); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); + ASSERT_EQ(testee.foreach_key_call_count, 2); +} + +TEST_F(PropagationTest, TextMapReader_Get_LookupKey_Supported) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + testee.supports_lookup = true; + ASSERT_TRUE(testee.supports_lookup); + ASSERT_EQ(testee.foreach_key_call_count, 0); + + shim::CarrierReaderShim tester{testee}; + auto lookup_not_found = testee.LookupKey("foo"); + ASSERT_TRUE(text_map.empty()); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_not_found.error(), opentracing::key_not_found_error)); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); + ASSERT_EQ(testee.foreach_key_call_count, 1); + + text_map["foo"] = "bar"; + auto lookup_found = testee.LookupKey("foo"); + ASSERT_FALSE(text_map.empty()); + ASSERT_EQ(lookup_found.value(), opentracing::string_view{"bar"}); + ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); + ASSERT_EQ(testee.foreach_key_call_count, 1); +} + +TEST_F(PropagationTest, TextMapReader_Keys) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + ASSERT_EQ(testee.foreach_key_call_count, 0); + + shim::CarrierReaderShim tester{testee}; + std::vector kvs; + auto callback = [&text_map,&kvs](nostd::string_view k){ + kvs.emplace_back(k); + return !text_map.empty(); + }; + + ASSERT_TRUE(tester.Keys(callback)); + ASSERT_TRUE(text_map.empty()); + ASSERT_TRUE(kvs.empty()); + ASSERT_EQ(testee.foreach_key_call_count, 1); + + text_map["foo"] = "bar"; + text_map["bar"] = "baz"; + text_map["baz"] = "foo"; + ASSERT_TRUE(tester.Keys(callback)); + ASSERT_FALSE(text_map.empty()); + ASSERT_EQ(text_map.size(), kvs.size()); + ASSERT_EQ(testee.foreach_key_call_count, 2); +} + +TEST_F(PropagationTest, TextMapWriter_Set) +{ + std::unordered_map text_map; + TextMapCarrier testee{text_map}; + shim::CarrierWriterShim tester{testee}; + ASSERT_TRUE(text_map.empty()); + + tester.Set("foo", "bar"); + tester.Set("bar", "baz"); + tester.Set("baz", "foo"); + ASSERT_FALSE(text_map.empty()); + ASSERT_EQ(text_map.size(), 3); + ASSERT_EQ(text_map["foo"], "bar"); + ASSERT_EQ(text_map["bar"], "baz"); + ASSERT_EQ(text_map["baz"], "foo"); +} \ No newline at end of file diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 1a74ae1f49..7994dcdec9 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -5,12 +5,12 @@ #pragma once -#include -#include -#include -#include -#include -#include +#include "opentelemetry/baggage/baggage_context.h" +#include "opentelemetry/trace/span.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/trace/tracer.h" +#include "opentracing/propagation.h" #include #include diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index 665f070b9c..ca459079f5 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -6,12 +6,15 @@ #include "shim_utils.h" #include "shim_mocks.h" +#include "opentracing/tracer.h" + #include -namespace baggage = opentelemetry::baggage; -namespace common = opentelemetry::common; -namespace nostd = opentelemetry::nostd; -namespace shim = opentelemetry::opentracingshim; +namespace trace_api = opentelemetry::trace; +namespace baggage = opentelemetry::baggage; +namespace common = opentelemetry::common; +namespace nostd = opentelemetry::nostd; +namespace shim = opentelemetry::opentracingshim; class ShimUtilsTest : public testing::Test { @@ -106,91 +109,168 @@ TEST_F(ShimUtilsTest, AttributeFromValue) ASSERT_EQ(nostd::get(value), nostd::string_view{}); } -TEST_F(ShimUtilsTest, TextMapReader_Get_LookupKey_Unsupported) +TEST_F(ShimUtilsTest, MakeOptionsShim_EmptyRefs) +{ + auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context = static_cast(span_context_shim.get()); + + opentracing::StartSpanOptions options; + options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); + options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); + + auto options_shim = shim::utils::makeOptionsShim(options); + ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(nostd::get(options_shim.parent), trace_api::SpanContext::GetInvalid()); +} + +TEST_F(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) +{ + auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context = static_cast(span_context_shim.get()); + + opentracing::StartSpanOptions options; + options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); + options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); + options.references = {{ opentracing::SpanReferenceType::FollowsFromRef, nullptr }}; + + auto options_shim = shim::utils::makeOptionsShim(options); + ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(nostd::get(options_shim.parent), trace_api::SpanContext::GetInvalid()); +} + +TEST_F(ShimUtilsTest, MakeOptionsShim_FirstChildOf) { - std::unordered_map text_map; - TextMapCarrier testee{text_map}; - ASSERT_FALSE(testee.supports_lookup); - ASSERT_EQ(testee.foreach_key_call_count, 0); - - shim::utils::CarrierReaderShim tester{testee}; - auto lookup_unsupported = testee.LookupKey("foo"); - ASSERT_TRUE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); - ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); - ASSERT_EQ(testee.foreach_key_call_count, 1); - - text_map["foo"] = "bar"; - auto lookup_found = testee.LookupKey("foo"); - ASSERT_FALSE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); - ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); - ASSERT_EQ(testee.foreach_key_call_count, 2); + auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context = static_cast(span_context_shim.get()); + + opentracing::StartSpanOptions options; + options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); + options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); + options.references = { + { opentracing::SpanReferenceType::FollowsFromRef, nullptr }, + { opentracing::SpanReferenceType::ChildOfRef, span_context }, + { opentracing::SpanReferenceType::ChildOfRef, nullptr } + }; + + auto options_shim = shim::utils::makeOptionsShim(options); + ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); +} + +TEST_F(ShimUtilsTest, MakeOptionsShim_FirstInList) +{ + auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context = static_cast(span_context_shim.get()); + + opentracing::StartSpanOptions options; + options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); + options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); + options.references = { + { opentracing::SpanReferenceType::FollowsFromRef, span_context }, + { opentracing::SpanReferenceType::FollowsFromRef, nullptr } + }; + + auto options_shim = shim::utils::makeOptionsShim(options); + ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); +} + +TEST_F(ShimUtilsTest, MakeReferenceLinks) +{ + auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context1 = static_cast(span_context_shim1.get()); + auto span_context_shim2 = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context2 = static_cast(span_context_shim2.get()); + + opentracing::StartSpanOptions options; + auto links = shim::utils::makeReferenceLinks(options); + ASSERT_TRUE(links.empty()); + + options.references = { + { opentracing::SpanReferenceType::FollowsFromRef, nullptr }, + { opentracing::SpanReferenceType::FollowsFromRef, span_context1 }, + { opentracing::SpanReferenceType::ChildOfRef, span_context2 } + }; + + links = shim::utils::makeReferenceLinks(options); + ASSERT_EQ(links.size(), 2); + ASSERT_EQ(links[0].first, span_context_shim1->context()); + ASSERT_FALSE(links[0].second.empty()); + ASSERT_EQ(links[0].second[0].first, "opentracing.ref_type"); + ASSERT_EQ(nostd::get(links[0].second[0].second), "follows_from"); + ASSERT_EQ(links[1].first, span_context_shim2->context()); + ASSERT_EQ(links[1].second[0].first, "opentracing.ref_type"); + ASSERT_EQ(nostd::get(links[1].second[0].second), "child_of"); } -TEST_F(ShimUtilsTest, TextMapReader_Get_LookupKey_Supported) +TEST_F(ShimUtilsTest, MakeBaggage_EmptyRefs) { - std::unordered_map text_map; - TextMapCarrier testee{text_map}; - testee.supports_lookup = true; - ASSERT_TRUE(testee.supports_lookup); - ASSERT_EQ(testee.foreach_key_call_count, 0); - - shim::utils::CarrierReaderShim tester{testee}; - auto lookup_not_found = testee.LookupKey("foo"); - ASSERT_TRUE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_not_found.error(), opentracing::key_not_found_error)); - ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); - ASSERT_EQ(testee.foreach_key_call_count, 1); - - text_map["foo"] = "bar"; - auto lookup_found = testee.LookupKey("foo"); - ASSERT_FALSE(text_map.empty()); - ASSERT_EQ(lookup_found.value(), opentracing::string_view{"bar"}); - ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); - ASSERT_EQ(testee.foreach_key_call_count, 1); + auto baggage = baggage::Baggage::GetDefault()->Set("foo", "bar"); + std::string value; + ASSERT_TRUE(baggage->GetValue("foo", value)); + ASSERT_EQ(value, "bar"); + + auto context = context::RuntimeContext::GetCurrent(); + auto new_context = baggage::SetBaggage(context, baggage); + auto token = context::RuntimeContext::Attach(new_context); + ASSERT_EQ(context::RuntimeContext::GetCurrent(), new_context); + + opentracing::StartSpanOptions options; + auto new_baggage = shim::utils::makeBaggage(options); + ASSERT_TRUE(new_baggage->GetValue("foo", value)); + ASSERT_EQ(value, "bar"); } -TEST_F(ShimUtilsTest, TextMapReader_Keys) +TEST_F(ShimUtilsTest, MakeBaggage_NonEmptyRefs) { - std::unordered_map text_map; - TextMapCarrier testee{text_map}; - ASSERT_EQ(testee.foreach_key_call_count, 0); - - shim::utils::CarrierReaderShim tester{testee}; - std::vector kvs; - auto callback = [&text_map,&kvs](nostd::string_view k){ - kvs.emplace_back(k); - return !text_map.empty(); + auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), + baggage::Baggage::GetDefault()->Set("test", "foo")->Set("test1", "hello"))); + auto span_context1 = static_cast(span_context_shim1.get()); + auto span_context_shim2 = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), + baggage::Baggage::GetDefault()->Set("test", "bar")->Set("test2", "world"))); + auto span_context2 = static_cast(span_context_shim2.get()); + + opentracing::StartSpanOptions options; + options.references = { + { opentracing::SpanReferenceType::FollowsFromRef, span_context1 }, + { opentracing::SpanReferenceType::ChildOfRef, span_context2 } }; - ASSERT_TRUE(tester.Keys(callback)); - ASSERT_TRUE(text_map.empty()); - ASSERT_TRUE(kvs.empty()); - ASSERT_EQ(testee.foreach_key_call_count, 1); - - text_map["foo"] = "bar"; - text_map["bar"] = "baz"; - text_map["baz"] = "foo"; - ASSERT_TRUE(tester.Keys(callback)); - ASSERT_FALSE(text_map.empty()); - ASSERT_EQ(text_map.size(), kvs.size()); - ASSERT_EQ(testee.foreach_key_call_count, 2); + auto baggage = shim::utils::makeBaggage(options); + std::string value; + ASSERT_TRUE(baggage->GetValue("test", value)); + ASSERT_EQ(value, "foo"); + ASSERT_TRUE(baggage->GetValue("test1", value)); + ASSERT_EQ(value, "hello"); + ASSERT_TRUE(baggage->GetValue("test2", value)); + ASSERT_EQ(value, "world"); } -TEST_F(ShimUtilsTest, TextMapWriter_Set) +TEST_F(ShimUtilsTest, MakeTags) { - std::unordered_map text_map; - TextMapCarrier testee{text_map}; - shim::utils::CarrierWriterShim tester{testee}; - ASSERT_TRUE(text_map.empty()); - - tester.Set("foo", "bar"); - tester.Set("bar", "baz"); - tester.Set("baz", "foo"); - ASSERT_FALSE(text_map.empty()); - ASSERT_EQ(text_map.size(), 3); - ASSERT_EQ(text_map["foo"], "bar"); - ASSERT_EQ(text_map["bar"], "baz"); - ASSERT_EQ(text_map["baz"], "foo"); + opentracing::StartSpanOptions options; + auto attributes = shim::utils::makeTags(options); + ASSERT_TRUE(attributes.empty()); + + options.tags = {{ "foo", 42.0 }, { "bar", true }, { "baz", "test" }}; + attributes = shim::utils::makeTags(options); + ASSERT_EQ(attributes.size(), 3); + ASSERT_EQ(attributes[0].first, "foo"); + ASSERT_EQ(nostd::get(attributes[0].second), 42.0); + ASSERT_EQ(attributes[1].first, "bar"); + ASSERT_TRUE(nostd::get(attributes[1].second)); + ASSERT_EQ(attributes[2].first, "baz"); + ASSERT_STREQ(nostd::get(attributes[2].second), "test" ); } \ No newline at end of file diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index 0c36b8c3c1..b8aacd66fe 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -46,6 +46,10 @@ TEST_F(SpanContextShimTest, BaggageItem) TEST_F(SpanContextShimTest, NewWithKeyValue) { auto new_span_context_shim = span_context_shim->newWithKeyValue("test", "this"); + ASSERT_NE(span_context_shim.get(), &new_span_context_shim); + ASSERT_EQ(span_context_shim->context(), new_span_context_shim.context()); + ASSERT_EQ(span_context_shim->context().IsValid(), new_span_context_shim.context().IsValid()); + ASSERT_EQ(span_context_shim->context().IsRemote(), new_span_context_shim.context().IsRemote()); std::string value; ASSERT_TRUE(new_span_context_shim.BaggageItem("foo", value)); @@ -81,7 +85,9 @@ TEST_F(SpanContextShimTest, Clone) auto new_span_context_shim = dynamic_cast(new_span_context.get()); ASSERT_TRUE(new_span_context_shim != nullptr); ASSERT_NE(span_context_shim.get(), new_span_context_shim); + ASSERT_EQ(span_context_shim->context(), new_span_context_shim->context()); ASSERT_EQ(span_context_shim->context().IsValid(), new_span_context_shim->context().IsValid()); + ASSERT_EQ(span_context_shim->context().IsRemote(), new_span_context_shim->context().IsRemote()); std::string value; std::string new_value; diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 3e0abd77f6..f675cb4dd3 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -9,7 +9,7 @@ #include "shim_utils.h" #include "shim_mocks.h" -#include +#include "opentracing/noop.h" #include @@ -80,7 +80,7 @@ TEST_F(TracerShimTest, InjectNullContext) auto noop_tracer = opentracing::MakeNoopTracer(); auto span = noop_tracer->StartSpan("a"); auto result = tracer_shim->Inject(span->context(), TextMapCarrier{text_map}); - ASSERT_TRUE(result.has_value()); + ASSERT_TRUE(opentracing::are_errors_equal(result.error(), opentracing::invalid_span_context_error)); ASSERT_TRUE(text_map.empty()); } From 25aeac8ccc0c39bf069e881b4eaa2bb73b4876ce Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 4 Jan 2023 20:23:50 -0500 Subject: [PATCH 09/46] Reduce copying for StartSpan --- opentracing-shim/include/shim_utils.h | 108 ++++++++++++++-------- opentracing-shim/src/tracer_shim.cc | 4 +- opentracing-shim/test/shim_utils_test.cc | 54 +++++++---- opentracing-shim/test/span_shim_test.cc | 2 +- opentracing-shim/test/tracer_shim_test.cc | 17 ++++ 5 files changed, 124 insertions(+), 61 deletions(-) diff --git a/opentracing-shim/include/shim_utils.h b/opentracing-shim/include/shim_utils.h index 89dad026a6..55d38089c0 100644 --- a/opentracing-shim/include/shim_utils.h +++ b/opentracing-shim/include/shim_utils.h @@ -10,9 +10,11 @@ #include "opentelemetry/baggage/baggage.h" #include "opentelemetry/baggage/baggage_context.h" #include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/key_value_iterable.h" #include "opentelemetry/context/propagation/text_map_propagator.h" #include "opentelemetry/nostd/type_traits.h" #include "opentelemetry/trace/semantic_conventions.h" +#include "opentelemetry/trace/span_context_kv_iterable.h" #include "opentelemetry/trace/tracer.h" #include "opentracing/propagation.h" #include "opentracing/tracer.h" @@ -106,41 +108,80 @@ static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing: return options_shim; } -using RefsList = std::vector>; -using LinksList = std::vector>; - -static LinksList makeReferenceLinks(const opentracing::StartSpanOptions& options) noexcept +class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIterable { - using opentracing::SpanReferenceType; - using namespace opentelemetry::trace::SemanticConventions; - - LinksList links; - links.reserve(options.references.size()); - // All values in the list MUST be added as Links with the reference type value - // as a Link attribute, i.e. opentracing.ref_type set to follows_from or child_of - for (const auto& entry : options.references) +public: + using RefsList = std::vector>; + explicit LinksIterable(const RefsList& refs) noexcept : refs_(refs) {} + + bool ForEachKeyValue(nostd::function_ref + callback) const noexcept override { - auto context_shim = dynamic_cast(entry.second); - nostd::string_view span_kind; - - if (entry.first == SpanReferenceType::ChildOfRef) - { - span_kind = OpentracingRefTypeValues::kChildOf; - } - else if (entry.first == SpanReferenceType::FollowsFromRef) + using opentracing::SpanReferenceType; + using namespace opentelemetry::trace::SemanticConventions; + using LinksList = std::initializer_list>; + + for (const auto& entry : refs_) { - span_kind = OpentracingRefTypeValues::kFollowsFrom; + auto context_shim = dynamic_cast(entry.second); + nostd::string_view span_kind; + + if (entry.first == SpanReferenceType::ChildOfRef) + { + span_kind = OpentracingRefTypeValues::kChildOf; + } + else if (entry.first == SpanReferenceType::FollowsFromRef) + { + span_kind = OpentracingRefTypeValues::kFollowsFrom; + } + + if (context_shim && !span_kind.empty()) + { + if (!callback(context_shim->context(), + opentelemetry::common::KeyValueIterableView( + {{ kOpentracingRefType, span_kind }}))) + return false; + } } - if (context_shim && !span_kind.empty()) + return true; + } + + size_t size() const noexcept { return refs_.size(); } + +private: + const RefsList& refs_; +}; + +static const LinksIterable makeIterableLinks(const opentracing::StartSpanOptions& options) noexcept +{ + return LinksIterable(options.references); +} + +class TagsIterable final : public opentelemetry::common::KeyValueIterable +{ +public: + explicit TagsIterable(const std::vector>& tags) noexcept : tags_(tags) {} + + bool ForEachKeyValue(nostd::function_ref callback) const noexcept override + { + for (const auto& entry : tags_) { - links.emplace_back(std::piecewise_construct, - std::forward_as_tuple(context_shim->context()), - std::forward_as_tuple(std::forward({{ kOpentracingRefType, span_kind }}))); + if (!callback(entry.first, utils::attributeFromValue(entry.second))) return false; } + return true; } - return links; + size_t size() const noexcept override { return tags_.size(); } + +private: + const std::vector>& tags_; +}; + +static const TagsIterable makeIterableTags(const opentracing::StartSpanOptions& options) noexcept +{ + return TagsIterable(options.tags); } static nostd::shared_ptr makeBaggage(const opentracing::StartSpanOptions& options) noexcept @@ -171,20 +212,5 @@ static nostd::shared_ptr makeBaggage(const open : nostd::shared_ptr(new Baggage(baggage_items)); } -static std::vector> makeTags(const opentracing::StartSpanOptions& options) noexcept -{ - std::vector> tags; - tags.reserve(options.tags.size()); - - // If an initial set of tags is specified, the values MUST - // be set at the creation time of the OpenTelemetry Span. - for (const auto& entry : options.tags) - { - tags.emplace_back(entry.first, utils::attributeFromValue(entry.second)); - } - - return tags; -} - } // namespace opentracingshim::utils OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index 9e402d45c5..f3c93570f3 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -22,9 +22,9 @@ std::unique_ptr TracerShim::StartSpanWithOptions(opentracing: if (is_closed_) return nullptr; const auto& opts = utils::makeOptionsShim(options); - const auto& links = utils::makeReferenceLinks(options); + const auto& links = utils::makeIterableLinks(options); + const auto& attributes = utils::makeIterableTags(options); const auto& baggage = utils::makeBaggage(options); - const auto& attributes = utils::makeTags(options); auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); auto span_shim = new SpanShim(*this, span, baggage); diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index ca459079f5..c5c37021d6 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -183,7 +183,7 @@ TEST_F(ShimUtilsTest, MakeOptionsShim_FirstInList) ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); } -TEST_F(ShimUtilsTest, MakeReferenceLinks) +TEST_F(ShimUtilsTest, MakeIterableLinks) { auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); @@ -193,24 +193,38 @@ TEST_F(ShimUtilsTest, MakeReferenceLinks) auto span_context2 = static_cast(span_context_shim2.get()); opentracing::StartSpanOptions options; - auto links = shim::utils::makeReferenceLinks(options); - ASSERT_TRUE(links.empty()); + auto empty = shim::utils::makeIterableLinks(options); + ASSERT_EQ(empty.size(), 0); options.references = { { opentracing::SpanReferenceType::FollowsFromRef, nullptr }, { opentracing::SpanReferenceType::FollowsFromRef, span_context1 }, { opentracing::SpanReferenceType::ChildOfRef, span_context2 } }; - - links = shim::utils::makeReferenceLinks(options); + auto full = shim::utils::makeIterableLinks(options); + ASSERT_EQ(full.size(), 3); + + std::vector> links; + full.ForEachKeyValue([&links](trace_api::SpanContext ctx, const common::KeyValueIterable& it){ + it.ForEachKeyValue([&links, &ctx](nostd::string_view key, common::AttributeValue value){ + links.emplace_back(ctx, key, value); + return false; + }); + return true; + }); ASSERT_EQ(links.size(), 2); - ASSERT_EQ(links[0].first, span_context_shim1->context()); - ASSERT_FALSE(links[0].second.empty()); - ASSERT_EQ(links[0].second[0].first, "opentracing.ref_type"); - ASSERT_EQ(nostd::get(links[0].second[0].second), "follows_from"); - ASSERT_EQ(links[1].first, span_context_shim2->context()); - ASSERT_EQ(links[1].second[0].first, "opentracing.ref_type"); - ASSERT_EQ(nostd::get(links[1].second[0].second), "child_of"); + + trace_api::SpanContext ctx = trace_api::SpanContext::GetInvalid(); + nostd::string_view key; + common::AttributeValue value; + std::tie(ctx, key, value) = links[0]; + ASSERT_EQ(ctx, span_context_shim1->context()); + ASSERT_EQ(key, "opentracing.ref_type"); + ASSERT_EQ(nostd::get(value), "follows_from"); + std::tie(ctx, key, value) = links[1]; + ASSERT_EQ(ctx, span_context_shim2->context()); + ASSERT_EQ(key, "opentracing.ref_type"); + ASSERT_EQ(nostd::get(value), "child_of"); } TEST_F(ShimUtilsTest, MakeBaggage_EmptyRefs) @@ -258,15 +272,21 @@ TEST_F(ShimUtilsTest, MakeBaggage_NonEmptyRefs) ASSERT_EQ(value, "world"); } -TEST_F(ShimUtilsTest, MakeTags) +TEST_F(ShimUtilsTest, MakeIterableTags) { opentracing::StartSpanOptions options; - auto attributes = shim::utils::makeTags(options); - ASSERT_TRUE(attributes.empty()); + auto empty = shim::utils::makeIterableTags(options); + ASSERT_EQ(empty.size(), 0); options.tags = {{ "foo", 42.0 }, { "bar", true }, { "baz", "test" }}; - attributes = shim::utils::makeTags(options); - ASSERT_EQ(attributes.size(), 3); + auto full = shim::utils::makeIterableTags(options); + ASSERT_EQ(full.size(), 3); + + std::vector> attributes; + full.ForEachKeyValue([&attributes](nostd::string_view key, common::AttributeValue value){ + attributes.push_back({key, value}); + return true; + }); ASSERT_EQ(attributes[0].first, "foo"); ASSERT_EQ(nostd::get(attributes[0].second), 42.0); ASSERT_EQ(attributes[1].first, "bar"); diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 4d6cebd80b..c002a24fba 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -181,4 +181,4 @@ TEST_F(SpanShimTest, Log_Error) ASSERT_EQ(nostd::get(attributes["exception.type"]), 42); ASSERT_STREQ(nostd::get(attributes["exception.message"]), "hello"); ASSERT_STREQ(nostd::get(attributes["exception.stacktrace"]), "overflow"); -} +} \ No newline at end of file diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index f675cb4dd3..6e96bba571 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -53,6 +53,23 @@ TEST_F(TracerShimTest, SpanReferenceToCreatingTracer) ASSERT_EQ(&span_shim->tracer(), tracer_shim.get()); } +TEST_F(TracerShimTest, SpanParentChildRelationship) +{ + auto span_shim1 = tracer_shim->StartSpan("a"); + auto span_shim2 = tracer_shim->StartSpan("b", { opentracing::ChildOf(&span_shim1->context()) }); + ASSERT_NE(span_shim1, nullptr); + ASSERT_NE(span_shim2, nullptr); + ASSERT_NE(span_shim1, span_shim2); + ASSERT_EQ(span_shim1->context().ToSpanID(), span_shim2->context().ToSpanID()); + ASSERT_EQ(span_shim1->context().ToTraceID(), span_shim2->context().ToTraceID()); + + auto span_context_shim1 = dynamic_cast(&span_shim1->context()); + auto span_context_shim2 = dynamic_cast(&span_shim2->context()); + ASSERT_TRUE(span_context_shim1 != nullptr); + ASSERT_TRUE(span_context_shim2 != nullptr); + ASSERT_EQ(span_context_shim1->context(), span_context_shim2->context()); +} + TEST_F(TracerShimTest, TracerGloballyRegistered) { ASSERT_FALSE(opentracing::Tracer::IsGlobalTracerRegistered()); From 8f10779195c51c3d20cac2b06238e554a8363862 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Thu, 5 Jan 2023 00:38:08 -0500 Subject: [PATCH 10/46] Implement span context shim trace_id and span_id --- opentracing-shim/include/span_context_shim.h | 10 ++++++++++ opentracing-shim/src/span_context_shim.cc | 10 ++++++++++ opentracing-shim/test/tracer_shim_test.cc | 2 +- 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/opentracing-shim/include/span_context_shim.h b/opentracing-shim/include/span_context_shim.h index f0493a983f..a008f1e531 100644 --- a/opentracing-shim/include/span_context_shim.h +++ b/opentracing-shim/include/span_context_shim.h @@ -28,8 +28,18 @@ class SpanContextShim final : public opentracing::SpanContext using VisitBaggageItem = std::function; void ForeachBaggageItem(VisitBaggageItem f) const override; std::unique_ptr Clone() const noexcept override; + std::string ToTraceID() const noexcept override; + std::string ToSpanID() const noexcept override; private: + template + static std::string toHexString(const T &id_item) + { + char buf[T::kSize * 2]; + id_item.ToLowerBase16(buf); + return std::string(buf, sizeof(buf)); + } + opentelemetry::trace::SpanContext context_; BaggagePtr baggage_; }; diff --git a/opentracing-shim/src/span_context_shim.cc b/opentracing-shim/src/span_context_shim.cc index 9d1c60618c..207f7b1be6 100644 --- a/opentracing-shim/src/span_context_shim.cc +++ b/opentracing-shim/src/span_context_shim.cc @@ -33,5 +33,15 @@ std::unique_ptr SpanContextShim::Clone() const noexcep return std::unique_ptr(new (std::nothrow) SpanContextShim(context_, baggage_)); } +std::string SpanContextShim::ToTraceID() const noexcept +{ + return toHexString(context_.trace_id()); +} + +std::string SpanContextShim::ToSpanID() const noexcept +{ + return toHexString(context_.span_id()); +} + } // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 6e96bba571..a69bd0a7a3 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -181,4 +181,4 @@ TEST_F(TracerShimTest, ExtractOnlyBaggage) std::string value; ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); ASSERT_EQ(value, "bar"); -} +} \ No newline at end of file From 697c4022f5b2f305a02c8ce3ff40055a0cd245bf Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Fri, 6 Jan 2023 01:25:13 -0500 Subject: [PATCH 11/46] Update CMakeFile build and install --- CMakeLists.txt | 19 +++ cmake/opentelemetry-cpp-config.cmake.in | 4 +- opentracing-shim/CMakeLists.txt | 109 +++++++++++------- .../opentracingshim}/propagation.h | 0 .../opentracingshim}/shim_utils.h | 2 +- .../opentracingshim}/span_context_shim.h | 0 .../opentracingshim}/span_shim.h | 4 +- .../opentracingshim}/tracer_shim.h | 0 opentracing-shim/src/CMakeLists.txt | 28 ----- opentracing-shim/src/span_context_shim.cc | 2 +- opentracing-shim/src/span_shim.cc | 8 +- opentracing-shim/src/tracer_shim.cc | 8 +- opentracing-shim/test/CMakeLists.txt | 17 --- opentracing-shim/test/propagation_test.cc | 3 +- opentracing-shim/test/shim_mocks.h | 1 + opentracing-shim/test/shim_utils_test.cc | 3 +- .../test/span_context_shim_test.cc | 2 +- opentracing-shim/test/span_shim_test.cc | 5 +- opentracing-shim/test/tracer_shim_test.cc | 9 +- third_party/opentracing-cpp | 1 + 20 files changed, 117 insertions(+), 108 deletions(-) rename opentracing-shim/include/{ => opentelemetry/opentracingshim}/propagation.h (100%) rename opentracing-shim/include/{ => opentelemetry/opentracingshim}/shim_utils.h (99%) rename opentracing-shim/include/{ => opentelemetry/opentracingshim}/span_context_shim.h (100%) rename opentracing-shim/include/{ => opentelemetry/opentracingshim}/span_shim.h (94%) rename opentracing-shim/include/{ => opentelemetry/opentracingshim}/tracer_shim.h (100%) delete mode 100644 opentracing-shim/src/CMakeLists.txt delete mode 100644 opentracing-shim/test/CMakeLists.txt create mode 160000 third_party/opentracing-cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b0db1cbfe7..f637f489ba 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -495,6 +495,25 @@ include_directories(api/include) add_subdirectory(api) if(WITH_OPENTRACING) + find_package(OpenTracing CONFIG QUIET) + if(NOT OpenTracing_FOUND) + set(OPENTRACING_DIR "third_party/opentracing-cpp") + message("Trying to use local ${OPENTRACING_DIR} from submodule") + if(EXISTS "${PROJECT_SOURCE_DIR}/${OPENTRACING_DIR}/.git") + set(SAVED_BUILD_TESTING ${BUILD_TESTING}) + set(BUILD_TESTING OFF) + add_subdirectory(${OPENTRACING_DIR}) + set(BUILD_TESTING ${SAVED_BUILD_TESTING}) + else() + message( + FATAL_ERROR + "\nopentracing-cpp package was not found. Please either provide it manually or clone with submodules. " + "To initialize, fetch and checkout any nested submodules, you can use the following command:\n" + "git submodule update --init --recursive") + endif() + else() + message("Using external opentracing-cpp") + endif() add_subdirectory(opentracing-shim) endif() diff --git a/cmake/opentelemetry-cpp-config.cmake.in b/cmake/opentelemetry-cpp-config.cmake.in index b6dcd5e276..58f36bb5f0 100644 --- a/cmake/opentelemetry-cpp-config.cmake.in +++ b/cmake/opentelemetry-cpp-config.cmake.in @@ -46,6 +46,7 @@ # opentelemetry-cpp::jaeger_trace_exporter - Imported target of opentelemetry-cpp::jaeger_trace_exporter # opentelemetry-cpp::zpages - Imported target of opentelemetry-cpp::zpages # opentelemetry-cpp::http_client_curl - Imported target of opentelemetry-cpp::http_client_curl +# opentelemetry-cpp::opentracing_shim - Imported target of opentelemetry-cpp::opentracing_shim # # ============================================================================= @@ -101,7 +102,8 @@ set(_OPENTELEMETRY_CPP_LIBRARIES_TEST_TARGETS etw_exporter jaeger_trace_exporter zpages - http_client_curl) + http_client_curl + opentracing_shim) foreach(_TEST_TARGET IN LISTS _OPENTELEMETRY_CPP_LIBRARIES_TEST_TARGETS) if(TARGET opentelemetry-cpp::${_TEST_TARGET}) list(APPEND OPENTELEMETRY_CPP_LIBRARIES opentelemetry-cpp::${_TEST_TARGET}) diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt index 7800cbdc91..c484e2bcc4 100644 --- a/opentracing-shim/CMakeLists.txt +++ b/opentracing-shim/CMakeLists.txt @@ -1,46 +1,73 @@ set(this_target opentelemetry_opentracing_shim) -#message("CMAKE_CURRENT_LIST_DIR " ${CMAKE_CURRENT_LIST_DIR}) -#message("CMAKE_CURRENT_SOURCE_DIR " ${CMAKE_CURRENT_SOURCE_DIR}) -#message("CMAKE_SOURCE_DIR " ${CMAKE_SOURCE_DIR}) -#message("PROJECT_SOURCE_DIR " ${PROJECT_SOURCE_DIR}) - -#add_library(${this_target} INTERFACE) -#target_include_directories( -# ${this_target} -# PUBLIC "$" -# "$" -# "$") -# -#set_target_properties(${this_target} PROPERTIES EXPORT_NAME "opentracing-shim") -#target_link_libraries(${this_target} INTERFACE ${this_target} opentracing-cpp) -# -#get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES) -#foreach(dir ${dirs}) -# message(STATUS "dir='${dir}'") -#endforeach() -# -#install( -# TARGETS ${this_target} -# EXPORT "${PROJECT_NAME}-target" -# RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} -# LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} -# ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) -# -#install( -# DIRECTORY include/opentelemetry/opentracing-shim -# DESTINATION include/opentelemetry/ -# FILES_MATCHING -# PATTERN "*.h") - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/include - ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/include - ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/build/include - ${CMAKE_SOURCE_DIR}/third_party/opentracing-cpp/3rd_party/include) - -add_subdirectory(src) +add_library(${this_target} + src/span_shim.cc + src/span_context_shim.cc + src/tracer_shim.cc) + +set_target_properties(${this_target} PROPERTIES EXPORT_NAME opentracing_shim) + +if(OPENTRACING_DIR) + include_directories( + "${CMAKE_BINARY_DIR}/${OPENTRACING_DIR}/include" + "${CMAKE_SOURCE_DIR}/${OPENTRACING_DIR}/include" + "${CMAKE_SOURCE_DIR}/${OPENTRACING_DIR}/3rd_party/include") +endif() + +target_include_directories( + ${this_target} + PUBLIC "$" + "$") + +target_link_libraries( + ${this_target} + PUBLIC opentelemetry_api) + +install( + TARGETS ${this_target} + EXPORT "${PROJECT_NAME}-target" + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +install( + DIRECTORY include/opentelemetry/opentracingshim + DESTINATION include/opentelemetry + FILES_MATCHING + PATTERN "*.h") if(BUILD_TESTING) - add_subdirectory(test) + foreach( + testname + propagation_test + shim_utils_test + span_shim_test + span_context_shim_test + tracer_shim_test) + + add_executable(${testname} "test/${testname}.cc") + + if(OPENTRACING_DIR) + target_link_libraries( + ${testname} + ${GTEST_BOTH_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + opentelemetry_api + opentelemetry_opentracing_shim + opentracing) + else() + target_link_libraries( + ${testname} + ${GTEST_BOTH_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + opentelemetry_api + opentelemetry_opentracing_shim + OpenTracing::opentracing) + endif() + + gtest_add_tests( + TARGET ${testname} + TEST_PREFIX opentracing_shim. + TEST_LIST ${testname}) + endforeach() endif() # BUILD_TESTING \ No newline at end of file diff --git a/opentracing-shim/include/propagation.h b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h similarity index 100% rename from opentracing-shim/include/propagation.h rename to opentracing-shim/include/opentelemetry/opentracingshim/propagation.h diff --git a/opentracing-shim/include/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h similarity index 99% rename from opentracing-shim/include/shim_utils.h rename to opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index 55d38089c0..adca341b89 100644 --- a/opentracing-shim/include/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -5,7 +5,7 @@ #pragma once -#include "span_context_shim.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" #include "opentelemetry/baggage/baggage.h" #include "opentelemetry/baggage/baggage_context.h" diff --git a/opentracing-shim/include/span_context_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h similarity index 100% rename from opentracing-shim/include/span_context_shim.h rename to opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h diff --git a/opentracing-shim/include/span_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h similarity index 94% rename from opentracing-shim/include/span_shim.h rename to opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h index 238738228f..062421447e 100644 --- a/opentracing-shim/include/span_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h @@ -5,8 +5,8 @@ #pragma once -#include "tracer_shim.h" -#include "span_context_shim.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" #include "opentelemetry/baggage/baggage.h" #include "opentelemetry/common/attribute_value.h" diff --git a/opentracing-shim/include/tracer_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h similarity index 100% rename from opentracing-shim/include/tracer_shim.h rename to opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h diff --git a/opentracing-shim/src/CMakeLists.txt b/opentracing-shim/src/CMakeLists.txt deleted file mode 100644 index 037e171773..0000000000 --- a/opentracing-shim/src/CMakeLists.txt +++ /dev/null @@ -1,28 +0,0 @@ -set(this_target opentelemetry_opentracing_shim) -set(target_name opentracing_shim) - -file(GLOB_RECURSE SOURCE_FILES ${CMAKE_CURRENT_LIST_DIR}/*.cc) -file(GLOB_RECURSE HEADER_FILES ${CMAKE_CURRENT_LIST_DIR}/../include/*.h) - -add_library(${this_target} SHARED ${SOURCE_FILES} ${HEADER_FILES}) - -set_target_properties(${this_target} PROPERTIES EXPORT_NAME ${target_name}) - -target_include_directories( - ${this_target} - PUBLIC "$" - "$") - -target_link_libraries(${this_target} PUBLIC opentelemetry_api opentracing) - -install( - TARGETS ${this_target} - EXPORT "${PROJECT_NAME}-target" - RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} - LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} - ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) - -get_property(dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES) -foreach(dir ${dirs}) - message(STATUS "dir='${dir}'") -endforeach() \ No newline at end of file diff --git a/opentracing-shim/src/span_context_shim.cc b/opentracing-shim/src/span_context_shim.cc index 207f7b1be6..d179a3a728 100644 --- a/opentracing-shim/src/span_context_shim.cc +++ b/opentracing-shim/src/span_context_shim.cc @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "span_context_shim.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index b40b897d0a..77f8c3a262 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -3,10 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "span_shim.h" -#include "span_context_shim.h" -#include "tracer_shim.h" -#include "shim_utils.h" +#include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" +#include "opentelemetry/opentracingshim/shim_utils.h" #include "opentelemetry/trace/semantic_conventions.h" #include "opentelemetry/trace/span_metadata.h" diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index f3c93570f3..a3bef986e3 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -3,10 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "tracer_shim.h" -#include "span_shim.h" -#include "shim_utils.h" -#include "propagation.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" +#include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/opentracingshim/shim_utils.h" +#include "opentelemetry/opentracingshim/propagation.h" #include "opentelemetry/context/propagation/global_propagator.h" #include "opentelemetry/trace/context.h" diff --git a/opentracing-shim/test/CMakeLists.txt b/opentracing-shim/test/CMakeLists.txt deleted file mode 100644 index 19b5cbf44a..0000000000 --- a/opentracing-shim/test/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -set(this_target shim_test) - -file(GLOB source_files ${CMAKE_CURRENT_LIST_DIR}/*.*) - -add_executable(${this_target} ${source_files}) - -target_link_libraries(${this_target} - ${GTEST_BOTH_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - opentelemetry_api - opentelemetry_opentracing_shim - opentracing) - -#gtest_add_tests( -# TARGET ${this_target} -# TEST_PREFIX ${this_target}. -# TEST_LIST ${this_target}) diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index 717cb99c9a..1850d9bd73 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -3,9 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "propagation.h" #include "shim_mocks.h" +#include "opentelemetry/opentracingshim/propagation.h" + #include namespace baggage = opentelemetry::baggage; diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 7994dcdec9..8467d15dab 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -6,6 +6,7 @@ #pragma once #include "opentelemetry/baggage/baggage_context.h" +#include "opentelemetry/context/propagation/text_map_propagator.h" #include "opentelemetry/trace/span.h" #include "opentelemetry/trace/span_context.h" #include "opentelemetry/trace/span_metadata.h" diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index c5c37021d6..712d286de2 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -3,9 +3,10 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "shim_utils.h" #include "shim_mocks.h" +#include "opentelemetry/opentracingshim/shim_utils.h" + #include "opentracing/tracer.h" #include diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index b8aacd66fe..195e66c807 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "span_context_shim.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" #include "opentelemetry/baggage/baggage.h" #include "opentelemetry/trace/span_context.h" diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index c002a24fba..48c498e261 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -3,10 +3,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "span_shim.h" -#include "tracer_shim.h" #include "shim_mocks.h" +#include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" + #include namespace trace_api = opentelemetry::trace; diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index a69bd0a7a3..742584d8b0 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -3,12 +3,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -#include "tracer_shim.h" -#include "span_shim.h" -#include "span_context_shim.h" -#include "shim_utils.h" #include "shim_mocks.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" +#include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" +#include "opentelemetry/opentracingshim/shim_utils.h" + #include "opentracing/noop.h" #include diff --git a/third_party/opentracing-cpp b/third_party/opentracing-cpp new file mode 160000 index 0000000000..06b57f48de --- /dev/null +++ b/third_party/opentracing-cpp @@ -0,0 +1 @@ +Subproject commit 06b57f48ded1fa3bdd3d4346f6ef29e40e08eaf5 From 2d2adf3dd2f9f3e36afff7688b519f4d2f5f58cb Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sat, 7 Jan 2023 19:43:46 -0500 Subject: [PATCH 12/46] Add Bazel build, fix failing test --- bazel/repository.bzl | 11 ++ opentracing-shim/BUILD | 102 ++++++++++++++++++ .../opentracingshim/shim_utils.h | 4 +- 3 files changed, 115 insertions(+), 2 deletions(-) create mode 100644 opentracing-shim/BUILD diff --git a/bazel/repository.bzl b/bazel/repository.bzl index 81c9b3f470..7fda79adf6 100644 --- a/bazel/repository.bzl +++ b/bazel/repository.bzl @@ -168,6 +168,17 @@ def opentelemetry_cpp_deps(): ], ) + # Opentracing + maybe( + http_archive, + name = "com_github_opentracing", + sha256 = "5b170042da4d1c4c231df6594da120875429d5231e9baa5179822ee8d1054ac3", + strip_prefix = "opentracing-cpp-1.6.0", + urls = [ + "https://github.com/opentracing/opentracing-cpp/archive/refs/tags/v1.6.0.tar.gz", + ], + ) + # boost headers from vcpkg maybe( native.new_local_repository, diff --git a/opentracing-shim/BUILD b/opentracing-shim/BUILD new file mode 100644 index 0000000000..422edba39b --- /dev/null +++ b/opentracing-shim/BUILD @@ -0,0 +1,102 @@ +package(default_visibility = ["//visibility:public"]) + +cc_library( + name = "opentracing_shim", + srcs = [ + "src/span_context_shim.cc", + "src/span_shim.cc", + "src/tracer_shim.cc", + ], + hdrs = [ + "include/opentelemetry/opentracingshim/propagation.h", + "include/opentelemetry/opentracingshim/shim_utils.h", + "include/opentelemetry/opentracingshim/span_context_shim.h", + "include/opentelemetry/opentracingshim/span_shim.h", + "include/opentelemetry/opentracingshim/tracer_shim.h", + ], + strip_include_prefix = "include", + tags = ["opentracing"], + deps = [ + "//api", + "@com_github_opentracing//:opentracing", + ], +) + +cc_test( + name = "propagation_test", + srcs = [ + "test/propagation_test.cc", + "test/shim_mocks.h", + ], + tags = [ + "opentracing_shim", + "test", + ], + deps = [ + ":opentracing_shim", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "shim_utils_test", + srcs = [ + "test/shim_utils_test.cc", + "test/shim_mocks.h", + ], + tags = [ + "opentracing_shim", + "test", + ], + deps = [ + ":opentracing_shim", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "span_shim_test", + srcs = [ + "test/span_shim_test.cc", + "test/shim_mocks.h", + ], + tags = [ + "opentracing_shim", + "test", + ], + deps = [ + ":opentracing_shim", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "span_context_shim_test", + srcs = [ + "test/span_context_shim_test.cc", + ], + tags = [ + "opentracing_shim", + "test", + ], + deps = [ + ":opentracing_shim", + "@com_google_googletest//:gtest_main", + ], +) + +cc_test( + name = "tracer_shim_test", + srcs = [ + "test/tracer_shim_test.cc", + "test/shim_mocks.h", + ], + tags = [ + "opentracing_shim", + "test", + ], + deps = [ + ":opentracing_shim", + "@com_google_googletest//:gtest_main", + ], +) \ No newline at end of file diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index adca341b89..ed8c5d9890 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -36,7 +36,7 @@ static inline opentelemetry::common::AttributeValue attributeFromValue(const ope AttributeValue operator()(double v) { return v; } AttributeValue operator()(int64_t v) { return v; } AttributeValue operator()(uint64_t v) { return v; } - AttributeValue operator()(std::string v) { return v.c_str(); } + AttributeValue operator()(const std::string& v) { return v.c_str(); } AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } AttributeValue operator()(std::nullptr_t) { return nostd::string_view{}; } AttributeValue operator()(const char* v) { return v; } @@ -55,7 +55,7 @@ static inline std::string stringFromValue(const opentracing::Value& value) std::string operator()(double v) { return std::to_string(v); } std::string operator()(int64_t v) { return std::to_string(v); } std::string operator()(uint64_t v) { return std::to_string(v); } - std::string operator()(std::string v) { return v; } + std::string operator()(const std::string& v) { return v; } std::string operator()(opentracing::string_view v) { return std::string{v.data()}; } std::string operator()(std::nullptr_t) { return std::string{}; } std::string operator()(const char* v) { return std::string{v}; } From 5d15422023a86817a6aefbd6f860ecc36a15d11b Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sat, 7 Jan 2023 22:44:41 -0500 Subject: [PATCH 13/46] Add README --- opentracing-shim/README.md | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 opentracing-shim/README.md diff --git a/opentracing-shim/README.md b/opentracing-shim/README.md new file mode 100644 index 0000000000..2e8c18f4f1 --- /dev/null +++ b/opentracing-shim/README.md @@ -0,0 +1,45 @@ +# OpenTracing Shim + +[![Apache License][license-image]][license-image] + +The OpenTracing shim is a bridge layer from OpenTelemetry to the OpenTracing API. +It takes OpenTelemetry Tracer and exposes it as an implementation of an OpenTracing Tracer. + +## Usage + +Use the TracerShim wherever you initialize your OpenTracing tracers. +There are 2 ways to expose an OpenTracing Tracer: +1. From the global OpenTelemetry configuration: + ```cpp + auto tracer_shim = TracerShim::createTracerShim(); + ``` +1. From a provided OpenTelemetry Tracer instance: + ```cpp + auto tracer_shim = TracerShim::createTracerShim(tracer); + ``` + +Optionally, you can specify propagators to be used for the OpenTracing `TextMap` and `HttpHeaders` formats: + +```cpp +OpenTracingPropagators propagators{ + .text_map = nostd::shared_ptr(new trace::propagation::JaegerPropagator()), + .http_headers = nostd::shared_ptr(new trace::propagation::HttpTraceContext()) +}; + +auto tracer_shim = TracerShim::createTracerShim(tracer, propagators); +``` + +If propagators are not specified, OpenTelemetry's global propagator will be used. + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +## Useful links + +- For more information on OpenTelemetry, visit: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-cpp/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-cpp/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat \ No newline at end of file From 32ba9156511481b4cd9b68f9cf0a7b27f21c0b20 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 8 Jan 2023 19:20:13 -0500 Subject: [PATCH 14/46] Additional tests and cleanup --- opentracing-shim/src/span_shim.cc | 10 +++---- opentracing-shim/test/propagation_test.cc | 20 +++---------- opentracing-shim/test/shim_mocks.h | 14 ++++++++++ opentracing-shim/test/shim_utils_test.cc | 34 ++++++++--------------- opentracing-shim/test/span_shim_test.cc | 31 +++++++++++++++++++++ opentracing-shim/test/tracer_shim_test.cc | 8 ++++++ 6 files changed, 73 insertions(+), 44 deletions(-) diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 77f8c3a262..927b7090ab 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -24,13 +24,13 @@ void SpanShim::handleError(const opentracing::Value& value) noexcept // - false maps to Ok // - no value being set maps to Unset. auto code = StatusCode::kUnset; - const auto& str_value = utils::stringFromValue(value); + const auto& error_tag = utils::stringFromValue(value); - if (str_value == "true") + if (error_tag == "true") { code = StatusCode::kError; } - else if (str_value == "false") + else if (error_tag == "false") { code = StatusCode::kOk; } @@ -68,7 +68,7 @@ void SpanShim::SetBaggageItem(opentracing::string_view restricted_key, opentraci // Creates a new SpanContext Shim with a new OpenTelemetry Baggage containing the specified // Baggage key/value pair, and sets it as the current instance for this Span Shim. if (restricted_key.empty() || value.empty()) return; - + // This operation MUST be safe to be called concurrently. const std::lock_guard guard(context_lock_); context_ = context_.newWithKeyValue(restricted_key.data(), value.data()); } @@ -78,7 +78,7 @@ std::string SpanShim::BaggageItem(opentracing::string_view restricted_key) const // Returns the value for the specified key in the OpenTelemetry Baggage // of the current SpanContext Shim, or null if none exists. if (restricted_key.empty()) return ""; - + // This operation MUST be safe to be called concurrently. const std::lock_guard guard(context_lock_); std::string value; return context_.BaggageItem(restricted_key.data(), value) ? value : ""; diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index 1850d9bd73..e3b1645500 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -14,19 +14,7 @@ namespace common = opentelemetry::common; namespace nostd = opentelemetry::nostd; namespace shim = opentelemetry::opentracingshim; -class PropagationTest : public testing::Test -{ -protected: - virtual void SetUp() - { - } - - virtual void TearDown() - { - } -}; - -TEST_F(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) +TEST(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) { std::unordered_map text_map; TextMapCarrier testee{text_map}; @@ -48,7 +36,7 @@ TEST_F(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) ASSERT_EQ(testee.foreach_key_call_count, 2); } -TEST_F(PropagationTest, TextMapReader_Get_LookupKey_Supported) +TEST(PropagationTest, TextMapReader_Get_LookupKey_Supported) { std::unordered_map text_map; TextMapCarrier testee{text_map}; @@ -71,7 +59,7 @@ TEST_F(PropagationTest, TextMapReader_Get_LookupKey_Supported) ASSERT_EQ(testee.foreach_key_call_count, 1); } -TEST_F(PropagationTest, TextMapReader_Keys) +TEST(PropagationTest, TextMapReader_Keys) { std::unordered_map text_map; TextMapCarrier testee{text_map}; @@ -98,7 +86,7 @@ TEST_F(PropagationTest, TextMapReader_Keys) ASSERT_EQ(testee.foreach_key_call_count, 2); } -TEST_F(PropagationTest, TextMapWriter_Set) +TEST(PropagationTest, TextMapWriter_Set) { std::unordered_map text_map; TextMapCarrier testee{text_map}; diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 8467d15dab..cf60761678 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -11,6 +11,7 @@ #include "opentelemetry/trace/span_context.h" #include "opentelemetry/trace/span_metadata.h" #include "opentelemetry/trace/tracer.h" +#include "opentelemetry/trace/tracer_provider.h" #include "opentracing/propagation.h" #include @@ -22,6 +23,19 @@ namespace common = opentelemetry::common; namespace context = opentelemetry::context; namespace nostd = opentelemetry::nostd; +struct MockTracerProvider : public trace_api::TracerProvider +{ + nostd::shared_ptr GetTracer(nostd::string_view library_name, + nostd::string_view, + nostd::string_view) noexcept override + { + library_name_ = std::string{library_name}; + return nostd::shared_ptr(); + } + + std::string library_name_; +}; + struct MockSpan final : public trace_api::Span { void SetAttribute(nostd::string_view key, diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index 712d286de2..a8006195a6 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -17,19 +17,7 @@ namespace common = opentelemetry::common; namespace nostd = opentelemetry::nostd; namespace shim = opentelemetry::opentracingshim; -class ShimUtilsTest : public testing::Test -{ -protected: - virtual void SetUp() - { - } - - virtual void TearDown() - { - } -}; - -TEST_F(ShimUtilsTest, IsBaggageEmpty) +TEST(ShimUtilsTest, IsBaggageEmpty) { auto none = nostd::shared_ptr(nullptr); ASSERT_TRUE(shim::utils::isBaggageEmpty(none)); @@ -42,7 +30,7 @@ TEST_F(ShimUtilsTest, IsBaggageEmpty) ASSERT_FALSE(shim::utils::isBaggageEmpty(non_empty)); } -TEST_F(ShimUtilsTest, StringFromValue) +TEST(ShimUtilsTest, StringFromValue) { ASSERT_EQ(shim::utils::stringFromValue(true), "true"); ASSERT_EQ(shim::utils::stringFromValue(false), "false"); @@ -61,7 +49,7 @@ TEST_F(ShimUtilsTest, StringFromValue) ASSERT_EQ(shim::utils::stringFromValue(dict.get()), ""); } -TEST_F(ShimUtilsTest, AttributeFromValue) +TEST(ShimUtilsTest, AttributeFromValue) { auto value = shim::utils::attributeFromValue(true); ASSERT_EQ(value.index(), common::AttributeType::kTypeBool); @@ -110,7 +98,7 @@ TEST_F(ShimUtilsTest, AttributeFromValue) ASSERT_EQ(nostd::get(value), nostd::string_view{}); } -TEST_F(ShimUtilsTest, MakeOptionsShim_EmptyRefs) +TEST(ShimUtilsTest, MakeOptionsShim_EmptyRefs) { auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); @@ -126,7 +114,7 @@ TEST_F(ShimUtilsTest, MakeOptionsShim_EmptyRefs) ASSERT_EQ(nostd::get(options_shim.parent), trace_api::SpanContext::GetInvalid()); } -TEST_F(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) +TEST(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) { auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); @@ -143,7 +131,7 @@ TEST_F(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) ASSERT_EQ(nostd::get(options_shim.parent), trace_api::SpanContext::GetInvalid()); } -TEST_F(ShimUtilsTest, MakeOptionsShim_FirstChildOf) +TEST(ShimUtilsTest, MakeOptionsShim_FirstChildOf) { auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); @@ -164,7 +152,7 @@ TEST_F(ShimUtilsTest, MakeOptionsShim_FirstChildOf) ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); } -TEST_F(ShimUtilsTest, MakeOptionsShim_FirstInList) +TEST(ShimUtilsTest, MakeOptionsShim_FirstInList) { auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); @@ -184,7 +172,7 @@ TEST_F(ShimUtilsTest, MakeOptionsShim_FirstInList) ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); } -TEST_F(ShimUtilsTest, MakeIterableLinks) +TEST(ShimUtilsTest, MakeIterableLinks) { auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); @@ -228,7 +216,7 @@ TEST_F(ShimUtilsTest, MakeIterableLinks) ASSERT_EQ(nostd::get(value), "child_of"); } -TEST_F(ShimUtilsTest, MakeBaggage_EmptyRefs) +TEST(ShimUtilsTest, MakeBaggage_EmptyRefs) { auto baggage = baggage::Baggage::GetDefault()->Set("foo", "bar"); std::string value; @@ -246,7 +234,7 @@ TEST_F(ShimUtilsTest, MakeBaggage_EmptyRefs) ASSERT_EQ(value, "bar"); } -TEST_F(ShimUtilsTest, MakeBaggage_NonEmptyRefs) +TEST(ShimUtilsTest, MakeBaggage_NonEmptyRefs) { auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), @@ -273,7 +261,7 @@ TEST_F(ShimUtilsTest, MakeBaggage_NonEmptyRefs) ASSERT_EQ(value, "world"); } -TEST_F(ShimUtilsTest, MakeIterableTags) +TEST(ShimUtilsTest, MakeIterableTags) { opentracing::StartSpanOptions options; auto empty = shim::utils::makeIterableTags(options); diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 48c498e261..3f6c91c80d 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -107,6 +107,37 @@ TEST_F(SpanShimTest, SetBaggageItem) ASSERT_EQ(span_shim->BaggageItem("no value"), ""); } +TEST_F(SpanShimTest, SetBaggageItem_MultiThreaded) +{ + auto span = nostd::shared_ptr(new MockSpan()); + auto tracer = shim::TracerShim::createTracerShim(); + auto tracer_shim = dynamic_cast(tracer.get()); + auto baggage = baggage::Baggage::GetDefault(); + shim::SpanShim span_shim(*tracer_shim, span, baggage); + + std::vector threads; + std::vector keys; + std::vector values; + int thread_count = 100; + + for (int index = 0; index < thread_count; ++index) + { + keys.emplace_back("key-" + std::to_string(index)); + values.emplace_back("value-" + std::to_string(index)); + threads.emplace_back(std::bind(&shim::SpanShim::SetBaggageItem, &span_shim, keys[index], values[index])); + } + + for (auto& thread : threads) + { + thread.join(); + } + + for (int index = 0; index < thread_count; ++index) + { + ASSERT_EQ(span_shim.BaggageItem(keys[index]), values[index]); + } +} + TEST_F(SpanShimTest, Log_NoEvent) { std::string name; diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 742584d8b0..84c27a4368 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -47,6 +47,14 @@ class TracerShimTest : public testing::Test } }; +TEST_F(TracerShimTest, TracerProviderName) +{ + auto mock_provider_ptr = new MockTracerProvider(); + nostd::shared_ptr provider(mock_provider_ptr); + ASSERT_NE(shim::TracerShim::createTracerShim(provider), nullptr); + ASSERT_EQ(mock_provider_ptr->library_name_, "opentracing-shim"); +} + TEST_F(TracerShimTest, SpanReferenceToCreatingTracer) { auto span_shim = tracer_shim->StartSpan("a"); From 4d91681ba5d50cf115094e453ea9641c02c9ab37 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 8 Jan 2023 22:31:54 -0500 Subject: [PATCH 15/46] Disable by default --- CMakeLists.txt | 2 +- .../opentelemetry/opentracingshim/shim_utils.h | 8 ++++---- opentracing-shim/test/shim_mocks.h | 2 +- opentracing-shim/test/shim_utils_test.cc | 12 ++++++------ opentracing-shim/test/span_context_shim_test.cc | 2 +- opentracing-shim/test/span_shim_test.cc | 4 ++-- opentracing-shim/test/tracer_shim_test.cc | 2 +- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5c80932d06..3abd116ec4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -170,7 +170,7 @@ option(BUILD_W3CTRACECONTEXT_TEST "Whether to build w3c trace context" OFF) option(OTELCPP_MAINTAINER_MODE "Build in maintainer mode (-Wall -Werror)" OFF) -option(WITH_OPENTRACING "Whether to include the Opentracing shim" ON) +option(WITH_OPENTRACING "Whether to include the Opentracing shim" OFF) set(OTELCPP_PROTO_PATH "" diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index ed8c5d9890..3590b86ce7 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -113,15 +113,15 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter public: using RefsList = std::vector>; explicit LinksIterable(const RefsList& refs) noexcept : refs_(refs) {} - - bool ForEachKeyValue(nostd::function_ref callback) const noexcept override { using opentracing::SpanReferenceType; using namespace opentelemetry::trace::SemanticConventions; using LinksList = std::initializer_list>; - + for (const auto& entry : refs_) { auto context_shim = dynamic_cast(entry.second); @@ -138,7 +138,7 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter if (context_shim && !span_kind.empty()) { - if (!callback(context_shim->context(), + if (!callback(context_shim->context(), opentelemetry::common::KeyValueIterableView( {{ kOpentracingRefType, span_kind }}))) return false; diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index cf60761678..a3a39ff41d 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -68,7 +68,7 @@ struct MockSpan final : public trace_api::Span void AddEvent(nostd::string_view name) noexcept override {} - void SetStatus(trace_api::StatusCode code, nostd::string_view description) noexcept override + void SetStatus(trace_api::StatusCode code, nostd::string_view description) noexcept override { status_ = {code, description.data()}; } diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index a8006195a6..2540282da5 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -103,7 +103,7 @@ TEST(ShimUtilsTest, MakeOptionsShim_EmptyRefs) auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); auto span_context = static_cast(span_context_shim.get()); - + opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); @@ -119,7 +119,7 @@ TEST(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); auto span_context = static_cast(span_context_shim.get()); - + opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); @@ -136,7 +136,7 @@ TEST(ShimUtilsTest, MakeOptionsShim_FirstChildOf) auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); auto span_context = static_cast(span_context_shim.get()); - + opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); @@ -157,7 +157,7 @@ TEST(ShimUtilsTest, MakeOptionsShim_FirstInList) auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); auto span_context = static_cast(span_context_shim.get()); - + opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); @@ -237,11 +237,11 @@ TEST(ShimUtilsTest, MakeBaggage_EmptyRefs) TEST(ShimUtilsTest, MakeBaggage_NonEmptyRefs) { auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault()->Set("test", "foo")->Set("test1", "hello"))); auto span_context1 = static_cast(span_context_shim1.get()); auto span_context_shim2 = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault()->Set("test", "bar")->Set("test2", "world"))); auto span_context2 = static_cast(span_context_shim2.get()); diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index 195e66c807..0b9e780417 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -76,7 +76,7 @@ TEST_F(SpanContextShimTest, ForeachBaggageItem) ASSERT_EQ(concatenated.size(), 3); ASSERT_EQ(concatenated[0], "foo:bar"); ASSERT_EQ(concatenated[1], "bar:baz"); - ASSERT_EQ(concatenated[2], "baz:foo"); + ASSERT_EQ(concatenated[2], "baz:foo"); } TEST_F(SpanContextShimTest, Clone) diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 3f6c91c80d..8bb874cdd8 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -120,7 +120,7 @@ TEST_F(SpanShimTest, SetBaggageItem_MultiThreaded) std::vector values; int thread_count = 100; - for (int index = 0; index < thread_count; ++index) + for (int index = 0; index < thread_count; ++index) { keys.emplace_back("key-" + std::to_string(index)); values.emplace_back("value-" + std::to_string(index)); @@ -132,7 +132,7 @@ TEST_F(SpanShimTest, SetBaggageItem_MultiThreaded) thread.join(); } - for (int index = 0; index < thread_count; ++index) + for (int index = 0; index < thread_count; ++index) { ASSERT_EQ(span_shim.BaggageItem(keys[index]), values[index]); } diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 84c27a4368..24b5818c12 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -71,7 +71,7 @@ TEST_F(TracerShimTest, SpanParentChildRelationship) ASSERT_NE(span_shim1, span_shim2); ASSERT_EQ(span_shim1->context().ToSpanID(), span_shim2->context().ToSpanID()); ASSERT_EQ(span_shim1->context().ToTraceID(), span_shim2->context().ToTraceID()); - + auto span_context_shim1 = dynamic_cast(&span_shim1->context()); auto span_context_shim2 = dynamic_cast(&span_shim2->context()); ASSERT_TRUE(span_context_shim1 != nullptr); From 0c55471a2829d9be9ec7f65ceac90abc46d4c946 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 9 Jan 2023 17:12:46 -0500 Subject: [PATCH 16/46] Fixes for markdownlint --- opentracing-shim/README.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/opentracing-shim/README.md b/opentracing-shim/README.md index 2e8c18f4f1..826ce483d6 100644 --- a/opentracing-shim/README.md +++ b/opentracing-shim/README.md @@ -3,26 +3,32 @@ [![Apache License][license-image]][license-image] The OpenTracing shim is a bridge layer from OpenTelemetry to the OpenTracing API. -It takes OpenTelemetry Tracer and exposes it as an implementation of an OpenTracing Tracer. +It takes an OpenTelemetry Tracer and exposes it as an implementation compatible with +that of an OpenTracing Tracer. ## Usage Use the TracerShim wherever you initialize your OpenTracing tracers. There are 2 ways to expose an OpenTracing Tracer: + 1. From the global OpenTelemetry configuration: + ```cpp auto tracer_shim = TracerShim::createTracerShim(); ``` + 1. From a provided OpenTelemetry Tracer instance: + ```cpp auto tracer_shim = TracerShim::createTracerShim(tracer); ``` -Optionally, you can specify propagators to be used for the OpenTracing `TextMap` and `HttpHeaders` formats: +Optionally, one can also specify the propagators to be used for the OpenTracing `TextMap` +and `HttpHeaders` formats: ```cpp OpenTracingPropagators propagators{ - .text_map = nostd::shared_ptr(new trace::propagation::JaegerPropagator()), + .text_map = nostd::shared_ptr(new CustomTextMap()), .http_headers = nostd::shared_ptr(new trace::propagation::HttpTraceContext()) }; @@ -42,4 +48,4 @@ Apache 2.0 - See [LICENSE][license-url] for more information. [discussions-url]: https://github.com/open-telemetry/opentelemetry-cpp/discussions [license-url]: https://github.com/open-telemetry/opentelemetry-cpp/blob/main/LICENSE -[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat \ No newline at end of file +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat From 43114f520efdd03cef03fb36b71b45b3572cf4eb Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 9 Jan 2023 23:05:52 -0500 Subject: [PATCH 17/46] Exclude shim from bazel.noexcept and bazel.nortti --- ci/do_ci.sh | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 6c80c0efe6..3b0592d5c0 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -275,14 +275,14 @@ elif [[ "$1" == "bazel.legacy.test" ]]; then elif [[ "$1" == "bazel.noexcept" ]]; then # there are some exceptions and error handling code from the Prometheus and Jaeger Clients # that make this test always fail. ignore Prometheus and Jaeger exporters in the noexcept here. - bazel $BAZEL_STARTUP_OPTIONS build --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test - bazel $BAZEL_STARTUP_OPTIONS test --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test + bazel $BAZEL_STARTUP_OPTIONS build --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test -//opentracing-shim/... + bazel $BAZEL_STARTUP_OPTIONS test --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test -//opentracing-shim/... exit 0 elif [[ "$1" == "bazel.nortti" ]]; then # there are some exceptions and error handling code from the Prometheus and Jaeger Clients # that make this test always fail. ignore Prometheus and Jaeger exporters in the noexcept here. - bazel $BAZEL_STARTUP_OPTIONS build --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... - bazel $BAZEL_STARTUP_OPTIONS test --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... + bazel $BAZEL_STARTUP_OPTIONS build --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//opentracing-shim/... + bazel $BAZEL_STARTUP_OPTIONS test --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//opentracing-shim/... exit 0 elif [[ "$1" == "bazel.asan" ]]; then bazel $BAZEL_STARTUP_OPTIONS test --config=asan $BAZEL_TEST_OPTIONS_ASYNC //... From fd03fcc0075e35187245d5cc5bdf3982311e5760 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 9 Jan 2023 23:07:23 -0500 Subject: [PATCH 18/46] Value string conversion to Attribute is unsupported --- .../opentelemetry/opentracingshim/shim_utils.h | 8 +++----- opentracing-shim/test/shim_utils_test.cc | 14 +++----------- 2 files changed, 6 insertions(+), 16 deletions(-) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index 3590b86ce7..662b3fb933 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -20,8 +20,6 @@ #include "opentracing/tracer.h" #include "opentracing/value.h" -#include - OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim::utils { @@ -36,7 +34,7 @@ static inline opentelemetry::common::AttributeValue attributeFromValue(const ope AttributeValue operator()(double v) { return v; } AttributeValue operator()(int64_t v) { return v; } AttributeValue operator()(uint64_t v) { return v; } - AttributeValue operator()(const std::string& v) { return v.c_str(); } + AttributeValue operator()(const std::string& v) { return nostd::string_view{}; } AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } AttributeValue operator()(std::nullptr_t) { return nostd::string_view{}; } AttributeValue operator()(const char* v) { return v; } @@ -154,7 +152,7 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter const RefsList& refs_; }; -static const LinksIterable makeIterableLinks(const opentracing::StartSpanOptions& options) noexcept +static LinksIterable makeIterableLinks(const opentracing::StartSpanOptions& options) noexcept { return LinksIterable(options.references); } @@ -179,7 +177,7 @@ class TagsIterable final : public opentelemetry::common::KeyValueIterable const std::vector>& tags_; }; -static const TagsIterable makeIterableTags(const opentracing::StartSpanOptions& options) noexcept +static TagsIterable makeIterableTags(const opentracing::StartSpanOptions& options) noexcept { return TagsIterable(options.tags); } diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index 2540282da5..2bf3ba6256 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -72,8 +72,8 @@ TEST(ShimUtilsTest, AttributeFromValue) ASSERT_EQ(nostd::get(value), 55ul); value = shim::utils::attributeFromValue(std::string{"a string"}); - ASSERT_EQ(value.index(), common::AttributeType::kTypeCString); - ASSERT_STREQ(nostd::get(value), "a string"); + ASSERT_EQ(value.index(), common::AttributeType::kTypeString); + ASSERT_EQ(nostd::get(value), nostd::string_view{}); value = shim::utils::attributeFromValue(opentracing::string_view{"a string view"}); ASSERT_EQ(value.index(), common::AttributeType::kTypeString); @@ -85,7 +85,7 @@ TEST(ShimUtilsTest, AttributeFromValue) value = shim::utils::attributeFromValue("a char ptr"); ASSERT_EQ(value.index(), common::AttributeType::kTypeCString); - ASSERT_STREQ(nostd::get(value), "a char ptr"); + ASSERT_EQ(nostd::get(value), "a char ptr"); opentracing::util::recursive_wrapper values{}; value = shim::utils::attributeFromValue(values.get()); @@ -100,10 +100,6 @@ TEST(ShimUtilsTest, AttributeFromValue) TEST(ShimUtilsTest, MakeOptionsShim_EmptyRefs) { - auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); - auto span_context = static_cast(span_context_shim.get()); - opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); @@ -116,10 +112,6 @@ TEST(ShimUtilsTest, MakeOptionsShim_EmptyRefs) TEST(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) { - auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); - auto span_context = static_cast(span_context_shim.get()); - opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); From a0a53665918a62650de4da235d90de843169f264 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 9 Jan 2023 23:15:11 -0500 Subject: [PATCH 19/46] Fix format --- opentracing-shim/BUILD | 8 +- opentracing-shim/CMakeLists.txt | 41 ++---- .../opentracingshim/propagation.h | 53 +++---- .../opentracingshim/shim_utils.h | 139 ++++++++++-------- .../opentracingshim/span_context_shim.h | 14 +- .../opentelemetry/opentracingshim/span_shim.h | 36 +++-- .../opentracingshim/tracer_shim.h | 61 ++++---- opentracing-shim/src/span_context_shim.cc | 15 +- opentracing-shim/src/span_shim.cc | 45 +++--- opentracing-shim/src/tracer_shim.cc | 115 ++++++++------- opentracing-shim/test/propagation_test.cc | 15 +- opentracing-shim/test/shim_mocks.h | 109 ++++++++------ opentracing-shim/test/shim_utils_test.cc | 111 +++++++------- .../test/span_context_shim_test.cc | 30 ++-- opentracing-shim/test/span_shim_test.cc | 47 +++--- opentracing-shim/test/tracer_shim_test.cc | 44 +++--- 16 files changed, 476 insertions(+), 407 deletions(-) diff --git a/opentracing-shim/BUILD b/opentracing-shim/BUILD index 422edba39b..b3ed93f461 100644 --- a/opentracing-shim/BUILD +++ b/opentracing-shim/BUILD @@ -41,8 +41,8 @@ cc_test( cc_test( name = "shim_utils_test", srcs = [ - "test/shim_utils_test.cc", "test/shim_mocks.h", + "test/shim_utils_test.cc", ], tags = [ "opentracing_shim", @@ -57,8 +57,8 @@ cc_test( cc_test( name = "span_shim_test", srcs = [ - "test/span_shim_test.cc", "test/shim_mocks.h", + "test/span_shim_test.cc", ], tags = [ "opentracing_shim", @@ -88,8 +88,8 @@ cc_test( cc_test( name = "tracer_shim_test", srcs = [ - "test/tracer_shim_test.cc", "test/shim_mocks.h", + "test/tracer_shim_test.cc", ], tags = [ "opentracing_shim", @@ -99,4 +99,4 @@ cc_test( ":opentracing_shim", "@com_google_googletest//:gtest_main", ], -) \ No newline at end of file +) diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt index c484e2bcc4..8af1d209ba 100644 --- a/opentracing-shim/CMakeLists.txt +++ b/opentracing-shim/CMakeLists.txt @@ -1,9 +1,7 @@ set(this_target opentelemetry_opentracing_shim) -add_library(${this_target} - src/span_shim.cc - src/span_context_shim.cc - src/tracer_shim.cc) +add_library(${this_target} src/span_shim.cc src/span_context_shim.cc + src/tracer_shim.cc) set_target_properties(${this_target} PROPERTIES EXPORT_NAME opentracing_shim) @@ -15,13 +13,10 @@ if(OPENTRACING_DIR) endif() target_include_directories( - ${this_target} - PUBLIC "$" - "$") + ${this_target} PUBLIC "$" + "$") -target_link_libraries( - ${this_target} - PUBLIC opentelemetry_api) +target_link_libraries(${this_target} PUBLIC opentelemetry_api) install( TARGETS ${this_target} @@ -37,31 +32,19 @@ install( PATTERN "*.h") if(BUILD_TESTING) - foreach( - testname - propagation_test - shim_utils_test - span_shim_test - span_context_shim_test - tracer_shim_test) + foreach(testname propagation_test shim_utils_test span_shim_test + span_context_shim_test tracer_shim_test) add_executable(${testname} "test/${testname}.cc") if(OPENTRACING_DIR) target_link_libraries( - ${testname} - ${GTEST_BOTH_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - opentelemetry_api - opentelemetry_opentracing_shim - opentracing) + ${testname} ${GTEST_BOTH_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} + opentelemetry_api opentelemetry_opentracing_shim opentracing) else() target_link_libraries( - ${testname} - ${GTEST_BOTH_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - opentelemetry_api - opentelemetry_opentracing_shim + ${testname} ${GTEST_BOTH_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT} + opentelemetry_api opentelemetry_opentracing_shim OpenTracing::opentracing) endif() @@ -70,4 +53,4 @@ if(BUILD_TESTING) TEST_PREFIX opentracing_shim. TEST_LIST ${testname}) endforeach() -endif() # BUILD_TESTING \ No newline at end of file +endif() # BUILD_TESTING diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h index 19d0da73fb..b0faeaffd2 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h @@ -16,16 +16,17 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -template::value, bool> = true> +template ::value, bool> = true> class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCarrier { public: - CarrierWriterShim(const T& writer) : writer_(writer) {} + CarrierWriterShim(const T &writer) : writer_(writer) {} // returns the value associated with the passed key. virtual nostd::string_view Get(nostd::string_view key) const noexcept override { - return ""; + return ""; // Not required for Opentracing writer } // stores the key-value pair. @@ -35,14 +36,15 @@ class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCar } private: - const T& writer_; + const T &writer_; }; -template::value, bool> = true> +template ::value, bool> = true> class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCarrier { public: - CarrierReaderShim(const T& reader) : reader_(reader) {} + CarrierReaderShim(const T &reader) : reader_(reader) {} // returns the value associated with the passed key. virtual nostd::string_view Get(nostd::string_view key) const noexcept override @@ -54,18 +56,18 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar { value = result.value().data(); } - else // Fall back to iterating through all of the keys. + else // Fall back to iterating through all of the keys. { - reader_.ForeachKey([key, &value] - (opentracing::string_view k, opentracing::string_view v) -> opentracing::expected { - if (k == key.data()) - { - value = v.data(); - // Found key, so bail out of the loop with a success error code. - return opentracing::make_unexpected(std::error_code{}); - } - return opentracing::make_expected(); - }); + reader_.ForeachKey([key, &value](opentracing::string_view k, + opentracing::string_view v) -> opentracing::expected { + if (k == key.data()) + { + value = v.data(); + // Found key, so bail out of the loop with a success error code. + return opentracing::make_unexpected(std::error_code{}); + } + return opentracing::make_expected(); + }); } return value; @@ -80,17 +82,18 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar // list of all the keys in the carrier. virtual bool Keys(nostd::function_ref callback) const noexcept override { - return reader_.ForeachKey([&callback] - (opentracing::string_view key, opentracing::string_view) -> opentracing::expected { - return callback(key.data()) - ? opentracing::make_expected() - : opentracing::make_unexpected(std::error_code{}); - }).has_value(); + return reader_ + .ForeachKey([&callback](opentracing::string_view key, + opentracing::string_view) -> opentracing::expected { + return callback(key.data()) ? opentracing::make_expected() + : opentracing::make_unexpected(std::error_code{}); + }) + .has_value(); } private: - const T& reader_; + const T &reader_; }; -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index 662b3fb933..8f30cf228a 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -24,7 +24,8 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim::utils { -static inline opentelemetry::common::AttributeValue attributeFromValue(const opentracing::Value& value) +static inline opentelemetry::common::AttributeValue attributeFromValue( + const opentracing::Value &value) { using opentelemetry::common::AttributeValue; @@ -34,18 +35,24 @@ static inline opentelemetry::common::AttributeValue attributeFromValue(const ope AttributeValue operator()(double v) { return v; } AttributeValue operator()(int64_t v) { return v; } AttributeValue operator()(uint64_t v) { return v; } - AttributeValue operator()(const std::string& v) { return nostd::string_view{}; } + AttributeValue operator()(const std::string &v) { return nostd::string_view{}; } AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } AttributeValue operator()(std::nullptr_t) { return nostd::string_view{}; } - AttributeValue operator()(const char* v) { return v; } - AttributeValue operator()(opentracing::util::recursive_wrapper) { return nostd::string_view{}; } - AttributeValue operator()(opentracing::util::recursive_wrapper) { return nostd::string_view{}; } + AttributeValue operator()(const char *v) { return v; } + AttributeValue operator()(opentracing::util::recursive_wrapper) + { + return nostd::string_view{}; + } + AttributeValue operator()(opentracing::util::recursive_wrapper) + { + return nostd::string_view{}; + } } AttributeMapper; return opentracing::Value::visit(value, AttributeMapper); } -static inline std::string stringFromValue(const opentracing::Value& value) +static inline std::string stringFromValue(const opentracing::Value &value) { static struct { @@ -53,51 +60,59 @@ static inline std::string stringFromValue(const opentracing::Value& value) std::string operator()(double v) { return std::to_string(v); } std::string operator()(int64_t v) { return std::to_string(v); } std::string operator()(uint64_t v) { return std::to_string(v); } - std::string operator()(const std::string& v) { return v; } + std::string operator()(const std::string &v) { return v; } std::string operator()(opentracing::string_view v) { return std::string{v.data()}; } std::string operator()(std::nullptr_t) { return std::string{}; } - std::string operator()(const char* v) { return std::string{v}; } - std::string operator()(opentracing::util::recursive_wrapper) { return std::string{}; } - std::string operator()(opentracing::util::recursive_wrapper) { return std::string{}; } + std::string operator()(const char *v) { return std::string{v}; } + std::string operator()(opentracing::util::recursive_wrapper) + { + return std::string{}; + } + std::string operator()(opentracing::util::recursive_wrapper) + { + return std::string{}; + } } StringMapper; return opentracing::Value::visit(value, StringMapper); } -static inline bool isBaggageEmpty(const nostd::shared_ptr& baggage) +static inline bool isBaggageEmpty(const nostd::shared_ptr &baggage) { if (baggage) { - return baggage->GetAllEntries([](nostd::string_view, nostd::string_view){ - return false; - }); + return baggage->GetAllEntries([](nostd::string_view, nostd::string_view) { return false; }); } return true; } -static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing::StartSpanOptions& options) noexcept +static opentelemetry::trace::StartSpanOptions makeOptionsShim( + const opentracing::StartSpanOptions &options) noexcept { using opentracing::SpanReferenceType; // If an explicit start timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. opentelemetry::trace::StartSpanOptions options_shim; - options_shim.start_system_time = opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; - options_shim.start_steady_time = opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; + options_shim.start_system_time = + opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; + options_shim.start_steady_time = + opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; - const auto& refs = options.references; + const auto &refs = options.references; // If a list of Span references is specified... if (!refs.empty()) { - auto first_child_of = std::find_if(refs.cbegin(), refs.cend(), - [](const std::pair& entry){ - return entry.first == SpanReferenceType::ChildOfRef; - }); + const auto &first_child_of = std::find_if( + refs.cbegin(), refs.cend(), + [](const std::pair &entry) { + return entry.first == SpanReferenceType::ChildOfRef; + }); // The first SpanContext with Child Of type in the entire list is used as parent, // else the first SpanContext is used as parent auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; - if (auto context_shim = dynamic_cast(context)) + if (auto context_shim = dynamic_cast(context)) { options_shim.parent = context_shim->context(); } @@ -109,20 +124,22 @@ static opentelemetry::trace::StartSpanOptions makeOptionsShim(const opentracing: class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIterable { public: - using RefsList = std::vector>; - explicit LinksIterable(const RefsList& refs) noexcept : refs_(refs) {} + using RefsList = + std::vector>; + + explicit LinksIterable(const RefsList &refs) noexcept : refs_(refs) {} bool ForEachKeyValue(nostd::function_ref - callback) const noexcept override + const opentelemetry::common::KeyValueIterable &)> + callback) const noexcept override { using opentracing::SpanReferenceType; using namespace opentelemetry::trace::SemanticConventions; using LinksList = std::initializer_list>; - for (const auto& entry : refs_) + for (const auto &entry : refs_) { - auto context_shim = dynamic_cast(entry.second); + auto context_shim = dynamic_cast(entry.second); nostd::string_view span_kind; if (entry.first == SpanReferenceType::ChildOfRef) @@ -134,12 +151,11 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter span_kind = OpentracingRefTypeValues::kFollowsFrom; } - if (context_shim && !span_kind.empty()) + if (context_shim && !span_kind.empty() && + !callback(context_shim->context(), opentelemetry::common::KeyValueIterableView( + {{kOpentracingRefType, span_kind}}))) { - if (!callback(context_shim->context(), - opentelemetry::common::KeyValueIterableView( - {{ kOpentracingRefType, span_kind }}))) - return false; + return false; } } @@ -149,10 +165,10 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter size_t size() const noexcept { return refs_.size(); } private: - const RefsList& refs_; + const RefsList &refs_; }; -static LinksIterable makeIterableLinks(const opentracing::StartSpanOptions& options) noexcept +static LinksIterable makeIterableLinks(const opentracing::StartSpanOptions &options) noexcept { return LinksIterable(options.references); } @@ -160,13 +176,18 @@ static LinksIterable makeIterableLinks(const opentracing::StartSpanOptions& opti class TagsIterable final : public opentelemetry::common::KeyValueIterable { public: - explicit TagsIterable(const std::vector>& tags) noexcept : tags_(tags) {} + explicit TagsIterable( + const std::vector> &tags) noexcept + : tags_(tags) + {} - bool ForEachKeyValue(nostd::function_ref callback) const noexcept override + bool ForEachKeyValue(nostd::function_ref + callback) const noexcept override { - for (const auto& entry : tags_) + for (const auto &entry : tags_) { - if (!callback(entry.first, utils::attributeFromValue(entry.second))) return false; + if (!callback(entry.first, utils::attributeFromValue(entry.second))) + return false; } return true; } @@ -174,41 +195,43 @@ class TagsIterable final : public opentelemetry::common::KeyValueIterable size_t size() const noexcept override { return tags_.size(); } private: - const std::vector>& tags_; + const std::vector> &tags_; }; -static TagsIterable makeIterableTags(const opentracing::StartSpanOptions& options) noexcept +static TagsIterable makeIterableTags(const opentracing::StartSpanOptions &options) noexcept { return TagsIterable(options.tags); } -static nostd::shared_ptr makeBaggage(const opentracing::StartSpanOptions& options) noexcept +static nostd::shared_ptr makeBaggage( + const opentracing::StartSpanOptions &options) noexcept { using namespace opentelemetry::baggage; std::unordered_map baggage_items; // If a list of Span references is specified... - for (const auto& entry : options.references) + for (const auto &entry : options.references) { - if (auto context_shim = dynamic_cast(entry.second)) + if (auto context_shim = dynamic_cast(entry.second)) { - // The union of their Baggage values MUST be used as the initial Baggage of the newly created Span. - context_shim->ForeachBaggageItem([&baggage_items](const std::string& key, const std::string& value){ - // It is unspecified which Baggage value is used in the case of repeated keys. - if (baggage_items.find(key) == baggage_items.end()) - { - baggage_items.emplace(key, value); // Here, only insert if key not already present - } - return true; - }); + // The union of their Baggage values MUST be used as the initial Baggage of the newly created + // Span. + context_shim->ForeachBaggageItem( + [&baggage_items](const std::string &key, const std::string &value) { + // It is unspecified which Baggage value is used in the case of repeated keys. + if (baggage_items.find(key) == baggage_items.end()) + { + baggage_items.emplace(key, value); // Here, only insert if key not already present + } + return true; + }); } } // If no such list of references is specified, the current Baggage // MUST be used as the initial value of the newly created Span. - return baggage_items.empty() - ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) - : nostd::shared_ptr(new Baggage(baggage_items)); + return baggage_items.empty() ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) + : nostd::shared_ptr(new Baggage(baggage_items)); } -} // namespace opentracingshim::utils +} // namespace opentracingshim::utils OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h index a008f1e531..c20f903fb4 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h @@ -18,14 +18,16 @@ using BaggagePtr = nostd::shared_ptr; class SpanContextShim final : public opentracing::SpanContext { public: - explicit SpanContextShim(const opentelemetry::trace::SpanContext& context, const BaggagePtr& baggage) - : context_(context), baggage_(baggage) {} - inline const opentelemetry::trace::SpanContext& context() const { return context_; } + explicit SpanContextShim(const opentelemetry::trace::SpanContext &context, + const BaggagePtr &baggage) + : context_(context), baggage_(baggage) + {} + inline const opentelemetry::trace::SpanContext &context() const { return context_; } inline const BaggagePtr baggage() const { return baggage_; } SpanContextShim newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept; - bool BaggageItem(nostd::string_view key, std::string& value) const noexcept; + bool BaggageItem(nostd::string_view key, std::string &value) const noexcept; // Overrides - using VisitBaggageItem = std::function; + using VisitBaggageItem = std::function; void ForeachBaggageItem(VisitBaggageItem f) const override; std::unique_ptr Clone() const noexcept override; std::string ToTraceID() const noexcept override; @@ -44,5 +46,5 @@ class SpanContextShim final : public opentracing::SpanContext BaggagePtr baggage_; }; -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h index 062421447e..98673c82d2 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h @@ -5,8 +5,8 @@ #pragma once -#include "opentelemetry/opentracingshim/tracer_shim.h" #include "opentelemetry/opentracingshim/span_context_shim.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" #include "opentelemetry/baggage/baggage.h" #include "opentelemetry/common/attribute_value.h" @@ -18,35 +18,41 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -using SpanPtr = nostd::shared_ptr; +using SpanPtr = nostd::shared_ptr; using EventEntry = std::pair; class SpanShim : public opentracing::Span { public: - explicit SpanShim(const TracerShim& tracer, const SpanPtr& span, const BaggagePtr& baggage) - : tracer_(tracer), span_(span), context_(span->GetContext(), baggage) {} - void handleError(const opentracing::Value& value) noexcept; + explicit SpanShim(const TracerShim &tracer, const SpanPtr &span, const BaggagePtr &baggage) + : tracer_(tracer), span_(span), context_(span->GetContext(), baggage) + {} + void handleError(const opentracing::Value &value) noexcept; // Overrides - void FinishWithOptions(const opentracing::FinishSpanOptions& finish_span_options) noexcept override; + void FinishWithOptions( + const opentracing::FinishSpanOptions &finish_span_options) noexcept override; void SetOperationName(opentracing::string_view name) noexcept override; - void SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept override; - void SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept override; + void SetTag(opentracing::string_view key, const opentracing::Value &value) noexcept override; + void SetBaggageItem(opentracing::string_view restricted_key, + opentracing::string_view value) noexcept override; std::string BaggageItem(opentracing::string_view restricted_key) const noexcept override; void Log(std::initializer_list fields) noexcept override; - void Log(opentracing::SystemTime timestamp, std::initializer_list fields) noexcept override; - void Log(opentracing::SystemTime timestamp, const std::vector& fields) noexcept override; - inline const opentracing::SpanContext& context() const noexcept override { return context_; }; - inline const opentracing::Tracer& tracer() const noexcept override { return tracer_; }; + void Log(opentracing::SystemTime timestamp, + std::initializer_list fields) noexcept override; + void Log(opentracing::SystemTime timestamp, + const std::vector &fields) noexcept override; + inline const opentracing::SpanContext &context() const noexcept override { return context_; }; + inline const opentracing::Tracer &tracer() const noexcept override { return tracer_; }; private: - void logImpl(nostd::span fields, const opentracing::SystemTime* const timestamp) noexcept; + void logImpl(nostd::span fields, + const opentracing::SystemTime *const timestamp) noexcept; - const TracerShim& tracer_; + const TracerShim &tracer_; SpanPtr span_; SpanContextShim context_; mutable opentelemetry::common::SpinLockMutex context_lock_; }; -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h index 0726b12f5a..c16bfaa363 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h @@ -5,20 +5,21 @@ #pragma once -#include "opentelemetry/trace/tracer.h" -#include "opentelemetry/trace/provider.h" #include "opentelemetry/context/propagation/text_map_propagator.h" +#include "opentelemetry/trace/provider.h" +#include "opentelemetry/trace/tracer.h" #include "opentracing/tracer.h" OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -using TracerPtr = nostd::shared_ptr; +using TracerPtr = nostd::shared_ptr; using TracerProviderPtr = nostd::shared_ptr; -using PropagatorPtr = nostd::shared_ptr; +using PropagatorPtr = nostd::shared_ptr; -struct OpenTracingPropagators { +struct OpenTracingPropagators +{ PropagatorPtr text_map; PropagatorPtr http_headers; }; @@ -34,41 +35,47 @@ class TracerShim : public opentracing::Tracer // be stored in the Shim, and the global OpenTelemetry TextMap propagator will be used for // both OpenTracing TextMap and HTTPHeaders formats. static inline std::shared_ptr createTracerShim( - const TracerProviderPtr& provider = opentelemetry::trace::Provider::GetTracerProvider(), - const OpenTracingPropagators& propagators = {}) noexcept + const TracerProviderPtr &provider = opentelemetry::trace::Provider::GetTracerProvider(), + const OpenTracingPropagators &propagators = {}) noexcept { return std::shared_ptr( - new (std::nothrow) TracerShim(provider->GetTracer("opentracing-shim"), propagators)); + new (std::nothrow) TracerShim(provider->GetTracer("opentracing-shim"), propagators)); } // Overrides - std::unique_ptr StartSpanWithOptions(opentracing::string_view operation_name, - const opentracing::StartSpanOptions& options) const noexcept override; - opentracing::expected Inject(const opentracing::SpanContext& sc, - std::ostream& writer) const override; - opentracing::expected Inject(const opentracing::SpanContext& sc, - const opentracing::TextMapWriter& writer) const override; - opentracing::expected Inject(const opentracing::SpanContext& sc, - const opentracing::HTTPHeadersWriter& writer) const override; - opentracing::expected> Extract(std::istream& reader) const override; - opentracing::expected> Extract(const opentracing::TextMapReader& reader) const override; - opentracing::expected> Extract(const opentracing::HTTPHeadersReader& reader) const override; + std::unique_ptr StartSpanWithOptions( + opentracing::string_view operation_name, + const opentracing::StartSpanOptions &options) const noexcept override; + opentracing::expected Inject(const opentracing::SpanContext &sc, + std::ostream &writer) const override; + opentracing::expected Inject(const opentracing::SpanContext &sc, + const opentracing::TextMapWriter &writer) const override; + opentracing::expected Inject(const opentracing::SpanContext &sc, + const opentracing::HTTPHeadersWriter &writer) const override; + opentracing::expected> Extract( + std::istream &reader) const override; + opentracing::expected> Extract( + const opentracing::TextMapReader &reader) const override; + opentracing::expected> Extract( + const opentracing::HTTPHeadersReader &reader) const override; inline void Close() noexcept override { is_closed_ = true; }; private: - explicit TracerShim(const TracerPtr& tracer, const OpenTracingPropagators& propagators) - : tracer_(tracer), propagators_(propagators) {} + explicit TracerShim(const TracerPtr &tracer, const OpenTracingPropagators &propagators) + : tracer_(tracer), propagators_(propagators) + {} template - opentracing::expected injectImpl(const opentracing::SpanContext& sc, - const T& writer, - const PropagatorPtr& propagator) const; + opentracing::expected injectImpl(const opentracing::SpanContext &sc, + const T &writer, + const PropagatorPtr &propagator) const; template - opentracing::expected> extractImpl(const T& reader, - const PropagatorPtr& propagator) const; + opentracing::expected> extractImpl( + const T &reader, + const PropagatorPtr &propagator) const; TracerPtr tracer_; OpenTracingPropagators propagators_; bool is_closed_ = false; }; -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/src/span_context_shim.cc b/opentracing-shim/src/span_context_shim.cc index d179a3a728..589eaa359e 100644 --- a/opentracing-shim/src/span_context_shim.cc +++ b/opentracing-shim/src/span_context_shim.cc @@ -9,23 +9,22 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -SpanContextShim SpanContextShim::newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept +SpanContextShim SpanContextShim::newWithKeyValue(nostd::string_view key, + nostd::string_view value) const noexcept { return SpanContextShim{context_, baggage_->Set(key, value)}; } -bool SpanContextShim::BaggageItem(nostd::string_view key, std::string& value) const noexcept +bool SpanContextShim::BaggageItem(nostd::string_view key, std::string &value) const noexcept { return baggage_->GetValue(key, value); } void SpanContextShim::ForeachBaggageItem(VisitBaggageItem f) const { - baggage_->GetAllEntries([&f](nostd::string_view key, nostd::string_view value) - { - return f(key.data(), value.data()); - } - ); + baggage_->GetAllEntries([&f](nostd::string_view key, nostd::string_view value) { + return f(key.data(), value.data()); + }); } std::unique_ptr SpanContextShim::Clone() const noexcept @@ -43,5 +42,5 @@ std::string SpanContextShim::ToSpanID() const noexcept return toHexString(context_.span_id()); } -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 927b7090ab..15029de696 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -4,9 +4,9 @@ */ #include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/opentracingshim/shim_utils.h" #include "opentelemetry/opentracingshim/span_context_shim.h" #include "opentelemetry/opentracingshim/tracer_shim.h" -#include "opentelemetry/opentracingshim/shim_utils.h" #include "opentelemetry/trace/semantic_conventions.h" #include "opentelemetry/trace/span_metadata.h" @@ -16,15 +16,15 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -void SpanShim::handleError(const opentracing::Value& value) noexcept +void SpanShim::handleError(const opentracing::Value &value) noexcept { using opentelemetry::trace::StatusCode; // The error tag MUST be mapped to StatusCode: // - true maps to Error. // - false maps to Ok // - no value being set maps to Unset. - auto code = StatusCode::kUnset; - const auto& error_tag = utils::stringFromValue(value); + auto code = StatusCode::kUnset; + const auto &error_tag = utils::stringFromValue(value); if (error_tag == "true") { @@ -38,11 +38,11 @@ void SpanShim::handleError(const opentracing::Value& value) noexcept span_->SetStatus(code); } -void SpanShim::FinishWithOptions(const opentracing::FinishSpanOptions& finish_span_options) noexcept +void SpanShim::FinishWithOptions(const opentracing::FinishSpanOptions &finish_span_options) noexcept { // If an explicit timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. - span_->End({{ finish_span_options.finish_steady_timestamp }}); + span_->End({{finish_span_options.finish_steady_timestamp}}); } void SpanShim::SetOperationName(opentracing::string_view name) noexcept @@ -50,7 +50,7 @@ void SpanShim::SetOperationName(opentracing::string_view name) noexcept span_->UpdateName(name.data()); } -void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value& value) noexcept +void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value &value) noexcept { // Calls Set Attribute on the underlying OpenTelemetry Span with the specified key/value pair. if (key == opentracing::ext::error) @@ -63,11 +63,13 @@ void SpanShim::SetTag(opentracing::string_view key, const opentracing::Value& va } } -void SpanShim::SetBaggageItem(opentracing::string_view restricted_key, opentracing::string_view value) noexcept +void SpanShim::SetBaggageItem(opentracing::string_view restricted_key, + opentracing::string_view value) noexcept { // Creates a new SpanContext Shim with a new OpenTelemetry Baggage containing the specified // Baggage key/value pair, and sets it as the current instance for this Span Shim. - if (restricted_key.empty() || value.empty()) return; + if (restricted_key.empty() || value.empty()) + return; // This operation MUST be safe to be called concurrently. const std::lock_guard guard(context_lock_); context_ = context_.newWithKeyValue(restricted_key.data(), value.data()); @@ -77,7 +79,8 @@ std::string SpanShim::BaggageItem(opentracing::string_view restricted_key) const { // Returns the value for the specified key in the OpenTelemetry Baggage // of the current SpanContext Shim, or null if none exists. - if (restricted_key.empty()) return ""; + if (restricted_key.empty()) + return ""; // This operation MUST be safe to be called concurrently. const std::lock_guard guard(context_lock_); std::string value; @@ -91,39 +94,43 @@ void SpanShim::Log(std::initializer_list fields) noexcept logImpl(fields, nullptr); } -void SpanShim::Log(opentracing::SystemTime timestamp, std::initializer_list fields) noexcept +void SpanShim::Log(opentracing::SystemTime timestamp, + std::initializer_list fields) noexcept { // If an explicit timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. logImpl(fields, ×tamp); } -void SpanShim::Log(opentracing::SystemTime timestamp, const std::vector& fields) noexcept +void SpanShim::Log(opentracing::SystemTime timestamp, + const std::vector &fields) noexcept { // If an explicit timestamp is specified, a conversion MUST // be done to match the OpenTracing and OpenTelemetry units. logImpl(fields, ×tamp); } -void SpanShim::logImpl(nostd::span fields, const opentracing::SystemTime* const timestamp) noexcept +void SpanShim::logImpl(nostd::span fields, + const opentracing::SystemTime *const timestamp) noexcept { // The Add Event’s name parameter MUST be the value with the event key // in the pair set, or else fallback to use the log literal string. - const auto event = std::find_if(fields.begin(), fields.end(), [](EventEntry item){ return item.first == "event"; }); + const auto &event = std::find_if(fields.begin(), fields.end(), + [](const EventEntry &item) { return item.first == "event"; }); auto name = (event != fields.end()) ? utils::stringFromValue(event->second) : std::string{"log"}; // If pair set contains an event=error entry, the values MUST be mapped to an Event // with the conventions outlined in the Exception semantic conventions document: bool is_error = (name == opentracing::ext::error); // A call to AddEvent is performed with name being set to exception - if (is_error) name = "exception"; + if (is_error) + name = "exception"; // Along the specified key/value pair set as additional event attributes... std::vector> attributes; attributes.reserve(fields.size()); - for (const auto& entry : fields) + for (const auto &entry : fields) { auto key = entry.first; - const auto& value = utils::attributeFromValue(entry.second); // ... including mapping of the following key/value pairs: // - error.kind maps to exception.type. // - message maps to exception.message. @@ -144,7 +151,7 @@ void SpanShim::logImpl(nostd::span fields, const opentracing:: } } - attributes.emplace_back(key, value); + attributes.emplace_back(key, utils::attributeFromValue(entry.second)); } // Calls Add Events on the underlying OpenTelemetry Span with the specified key/value pair set. if (timestamp) @@ -157,5 +164,5 @@ void SpanShim::logImpl(nostd::span fields, const opentracing:: } } -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index a3bef986e3..64082e1539 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -4,9 +4,9 @@ */ #include "opentelemetry/opentracingshim/tracer_shim.h" -#include "opentelemetry/opentracingshim/span_shim.h" -#include "opentelemetry/opentracingshim/shim_utils.h" #include "opentelemetry/opentracingshim/propagation.h" +#include "opentelemetry/opentracingshim/shim_utils.h" +#include "opentelemetry/opentracingshim/span_shim.h" #include "opentelemetry/context/propagation/global_propagator.h" #include "opentelemetry/trace/context.h" @@ -16,105 +16,117 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -std::unique_ptr TracerShim::StartSpanWithOptions(opentracing::string_view operation_name, - const opentracing::StartSpanOptions& options) const noexcept +std::unique_ptr TracerShim::StartSpanWithOptions( + opentracing::string_view operation_name, + const opentracing::StartSpanOptions &options) const noexcept { - if (is_closed_) return nullptr; + if (is_closed_) + return nullptr; - const auto& opts = utils::makeOptionsShim(options); - const auto& links = utils::makeIterableLinks(options); - const auto& attributes = utils::makeIterableTags(options); - const auto& baggage = utils::makeBaggage(options); - auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); - auto span_shim = new SpanShim(*this, span, baggage); + const auto &opts = utils::makeOptionsShim(options); + const auto &links = utils::makeIterableLinks(options); + const auto &attributes = utils::makeIterableTags(options); + const auto &baggage = utils::makeBaggage(options); + auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); + auto span_shim = new SpanShim(*this, span, baggage); // If an initial set of tags is specified and the OpenTracing error tag // is included after the OpenTelemetry Span was created. - const auto& error_entry = std::find_if(options.tags.begin(), options.tags.end(), - [](const std::pair& entry){ - return entry.first == opentracing::ext::error; - }); + const auto &error_entry = + std::find_if(options.tags.cbegin(), options.tags.cend(), + [](const std::pair &entry) { + return entry.first == opentracing::ext::error; + }); // The Shim layer MUST perform the same error handling as described in the Set Tag operation - if (error_entry != options.tags.end()) { + if (error_entry != options.tags.cend()) + { span_shim->handleError(error_entry->second); } return std::unique_ptr(span_shim); } -opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, - std::ostream& writer) const +opentracing::expected TracerShim::Inject(const opentracing::SpanContext &sc, + std::ostream &writer) const { // Errors MAY be raised if the specified Format is not recognized, // depending on the specific OpenTracing Language API. return opentracing::make_unexpected(opentracing::invalid_carrier_error); } -opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, - const opentracing::TextMapWriter& writer) const +opentracing::expected TracerShim::Inject(const opentracing::SpanContext &sc, + const opentracing::TextMapWriter &writer) const { // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.text_map - ? propagators_.text_map - : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + const auto &propagator = + propagators_.text_map + ? propagators_.text_map + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); return injectImpl(sc, writer, propagator); } -opentracing::expected TracerShim::Inject(const opentracing::SpanContext& sc, - const opentracing::HTTPHeadersWriter& writer) const +opentracing::expected TracerShim::Inject(const opentracing::SpanContext &sc, + const opentracing::HTTPHeadersWriter &writer) const { // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.http_headers - ? propagators_.http_headers - : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + const auto &propagator = + propagators_.http_headers + ? propagators_.http_headers + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); return injectImpl(sc, writer, propagator); } -opentracing::expected> TracerShim::Extract(std::istream& reader) const +opentracing::expected> TracerShim::Extract( + std::istream &reader) const { // Errors MAY be raised if either the Format is not recognized or no value // could be extracted, depending on the specific OpenTracing Language API. return opentracing::make_unexpected(opentracing::invalid_carrier_error); } -opentracing::expected> TracerShim::Extract(const opentracing::TextMapReader& reader) const +opentracing::expected> TracerShim::Extract( + const opentracing::TextMapReader &reader) const { // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.text_map - ? propagators_.text_map - : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + const auto &propagator = + propagators_.text_map + ? propagators_.text_map + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); return extractImpl(reader, propagator); } -opentracing::expected> TracerShim::Extract(const opentracing::HTTPHeadersReader& reader) const +opentracing::expected> TracerShim::Extract( + const opentracing::HTTPHeadersReader &reader) const { // TextMap and HttpHeaders formats MUST use their explicitly specified TextMapPropagator, // if any, or else use the global TextMapPropagator. - const auto& propagator = propagators_.http_headers - ? propagators_.http_headers - : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); + const auto &propagator = + propagators_.http_headers + ? propagators_.http_headers + : opentelemetry::context::propagation::GlobalTextMapPropagator::GetGlobalPropagator(); return extractImpl(reader, propagator); } template -opentracing::expected TracerShim::injectImpl(const opentracing::SpanContext& sc, - const T& writer, - const PropagatorPtr& propagator) const +opentracing::expected TracerShim::injectImpl(const opentracing::SpanContext &sc, + const T &writer, + const PropagatorPtr &propagator) const { // Inject the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. - if (auto context_shim = dynamic_cast(&sc)) + if (auto context_shim = dynamic_cast(&sc)) { auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); // It MUST inject any non-empty Baggage even amidst no valid SpanContext. - const auto& context = opentelemetry::baggage::SetBaggage(current_context, context_shim->baggage()); + const auto &context = + opentelemetry::baggage::SetBaggage(current_context, context_shim->baggage()); CarrierWriterShim carrier{writer}; propagator->Inject(carrier, context); @@ -125,26 +137,27 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex } template -opentracing::expected> TracerShim::extractImpl(const T& reader, - const PropagatorPtr& propagator) const +opentracing::expected> TracerShim::extractImpl( + const T &reader, + const PropagatorPtr &propagator) const { // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. CarrierReaderShim carrier{reader}; auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); - auto context = propagator->Extract(carrier, current_context); - auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); - auto baggage = opentelemetry::baggage::GetBaggage(context); + auto context = propagator->Extract(carrier, current_context); + auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); + auto baggage = opentelemetry::baggage::GetBaggage(context); // If the extracted SpanContext is invalid AND the extracted Baggage is empty, // this operation MUST return a null value, and otherwise it MUST return a // SpanContext Shim instance with the extracted values. - SpanContextShim* context_shim = (!span_context.IsValid() && utils::isBaggageEmpty(baggage)) - ? nullptr - : new SpanContextShim(span_context, baggage); + SpanContextShim *context_shim = (!span_context.IsValid() && utils::isBaggageEmpty(baggage)) + ? nullptr + : new SpanContextShim(span_context, baggage); return opentracing::make_expected(std::unique_ptr(context_shim)); } -} // namespace opentracingshim +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE \ No newline at end of file diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index e3b1645500..7f69ebdb61 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -24,14 +24,16 @@ TEST(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) shim::CarrierReaderShim tester{testee}; auto lookup_unsupported = testee.LookupKey("foo"); ASSERT_TRUE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), + opentracing::lookup_key_not_supported_error)); ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); ASSERT_EQ(testee.foreach_key_call_count, 1); - text_map["foo"] = "bar"; + text_map["foo"] = "bar"; auto lookup_found = testee.LookupKey("foo"); ASSERT_FALSE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), opentracing::lookup_key_not_supported_error)); + ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), + opentracing::lookup_key_not_supported_error)); ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); ASSERT_EQ(testee.foreach_key_call_count, 2); } @@ -47,11 +49,12 @@ TEST(PropagationTest, TextMapReader_Get_LookupKey_Supported) shim::CarrierReaderShim tester{testee}; auto lookup_not_found = testee.LookupKey("foo"); ASSERT_TRUE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_not_found.error(), opentracing::key_not_found_error)); + ASSERT_TRUE( + opentracing::are_errors_equal(lookup_not_found.error(), opentracing::key_not_found_error)); ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); ASSERT_EQ(testee.foreach_key_call_count, 1); - text_map["foo"] = "bar"; + text_map["foo"] = "bar"; auto lookup_found = testee.LookupKey("foo"); ASSERT_FALSE(text_map.empty()); ASSERT_EQ(lookup_found.value(), opentracing::string_view{"bar"}); @@ -67,7 +70,7 @@ TEST(PropagationTest, TextMapReader_Keys) shim::CarrierReaderShim tester{testee}; std::vector kvs; - auto callback = [&text_map,&kvs](nostd::string_view k){ + auto callback = [&text_map, &kvs](nostd::string_view k) { kvs.emplace_back(k); return !text_map.empty(); }; diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index a3a39ff41d..98cb406d17 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -14,8 +14,8 @@ #include "opentelemetry/trace/tracer_provider.h" #include "opentracing/propagation.h" -#include #include +#include namespace trace_api = opentelemetry::trace; namespace baggage = opentelemetry::baggage; @@ -23,14 +23,14 @@ namespace common = opentelemetry::common; namespace context = opentelemetry::context; namespace nostd = opentelemetry::nostd; -struct MockTracerProvider : public trace_api::TracerProvider +struct MockTracerProvider final : public trace_api::TracerProvider { nostd::shared_ptr GetTracer(nostd::string_view library_name, nostd::string_view, nostd::string_view) noexcept override { library_name_ = std::string{library_name}; - return nostd::shared_ptr(); + return nostd::shared_ptr(); } std::string library_name_; @@ -38,33 +38,32 @@ struct MockTracerProvider : public trace_api::TracerProvider struct MockSpan final : public trace_api::Span { - void SetAttribute(nostd::string_view key, - const common::AttributeValue& value) noexcept override + void SetAttribute(nostd::string_view key, const common::AttributeValue &value) noexcept override { attribute_ = {key.data(), value}; } void AddEvent(nostd::string_view name, common::SystemTimestamp timestamp, - const common::KeyValueIterable& attributes) noexcept override + const common::KeyValueIterable &attributes) noexcept override { std::unordered_map attribute_map; attribute_map.reserve(attributes.size()); - attributes.ForEachKeyValue([&attribute_map](nostd::string_view key, const common::AttributeValue& value){ - attribute_map.emplace(key.data(), value); - return true; - }); + attributes.ForEachKeyValue( + [&attribute_map](nostd::string_view key, const common::AttributeValue &value) { + attribute_map.emplace(key.data(), value); + return true; + }); event_ = {name.data(), timestamp, attribute_map}; } void AddEvent(nostd::string_view name, - const common::KeyValueIterable& attributes) noexcept override + const common::KeyValueIterable &attributes) noexcept override { AddEvent(name, {}, attributes); } - void AddEvent(nostd::string_view name, - common::SystemTimestamp timestamp) noexcept override {} + void AddEvent(nostd::string_view name, common::SystemTimestamp timestamp) noexcept override {} void AddEvent(nostd::string_view name) noexcept override {} @@ -75,14 +74,20 @@ struct MockSpan final : public trace_api::Span void UpdateName(nostd::string_view name) noexcept override { name_ = name.data(); } - void End(const trace_api::EndSpanOptions& options) noexcept override { options_ = options; } + void End(const trace_api::EndSpanOptions &options) noexcept override { options_ = options; } bool IsRecording() const noexcept override { return false; } - trace_api::SpanContext GetContext() const noexcept override { return trace_api::SpanContext(false, false); } + trace_api::SpanContext GetContext() const noexcept override + { + return trace_api::SpanContext(false, false); + } std::pair attribute_; - std::tuple> event_; + std::tuple> + event_; std::pair status_; std::string name_; trace_api::EndSpanOptions options_; @@ -95,12 +100,13 @@ struct MockPropagator : public context::propagation::TextMapPropagator context::Context &context) noexcept override { std::vector> kvs; - carrier.Keys([&carrier,&kvs](nostd::string_view k){ + carrier.Keys([&carrier, &kvs](nostd::string_view k) { kvs.emplace_back(k, carrier.Get(k)); return true; }); is_extracted = true; - return baggage::SetBaggage(context, nostd::shared_ptr(new baggage::Baggage(kvs))); + return baggage::SetBaggage(context, + nostd::shared_ptr(new baggage::Baggage(kvs))); } // Sets the context for carrier with self defined rules. @@ -108,7 +114,7 @@ struct MockPropagator : public context::propagation::TextMapPropagator const context::Context &context) noexcept override { auto baggage = baggage::GetBaggage(context); - baggage->GetAllEntries([&carrier](nostd::string_view k, nostd::string_view v){ + baggage->GetAllEntries([&carrier](nostd::string_view k, nostd::string_view v) { carrier.Set(k, v); return true; }); @@ -122,64 +128,81 @@ struct MockPropagator : public context::propagation::TextMapPropagator } bool is_extracted = false; - bool is_injected = false; + bool is_injected = false; }; -struct TextMapCarrier : opentracing::TextMapReader, opentracing::TextMapWriter { - TextMapCarrier(std::unordered_map& text_map_) - : text_map(text_map_) {} +struct TextMapCarrier : opentracing::TextMapReader, opentracing::TextMapWriter +{ + TextMapCarrier(std::unordered_map &text_map_) : text_map(text_map_) {} - opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { + opentracing::expected Set(opentracing::string_view key, + opentracing::string_view value) const override + { text_map[key] = value; return {}; } - opentracing::expected LookupKey(opentracing::string_view key) const override { - if (!supports_lookup) { + opentracing::expected LookupKey( + opentracing::string_view key) const override + { + if (!supports_lookup) + { return opentracing::make_unexpected(opentracing::lookup_key_not_supported_error); } auto iter = text_map.find(key); - if (iter != text_map.end()) { + if (iter != text_map.end()) + { return opentracing::string_view{iter->second}; - } else { + } + else + { return opentracing::make_unexpected(opentracing::key_not_found_error); } } opentracing::expected ForeachKey( - std::function(opentracing::string_view key, opentracing::string_view value)> f) - const override { + std::function(opentracing::string_view key, + opentracing::string_view value)> f) const override + { ++foreach_key_call_count; - for (const auto& key_value : text_map) { + for (const auto &key_value : text_map) + { auto result = f(key_value.first, key_value.second); - if (!result) return result; + if (!result) + return result; } return {}; } - bool supports_lookup = false; + bool supports_lookup = false; mutable int foreach_key_call_count = 0; - std::unordered_map& text_map; + std::unordered_map &text_map; }; -struct HTTPHeadersCarrier : opentracing::HTTPHeadersReader, opentracing::HTTPHeadersWriter { - HTTPHeadersCarrier(std::unordered_map& text_map_) - : text_map(text_map_) {} +struct HTTPHeadersCarrier : opentracing::HTTPHeadersReader, opentracing::HTTPHeadersWriter +{ + HTTPHeadersCarrier(std::unordered_map &text_map_) : text_map(text_map_) + {} - opentracing::expected Set(opentracing::string_view key, opentracing::string_view value) const override { + opentracing::expected Set(opentracing::string_view key, + opentracing::string_view value) const override + { text_map[key] = value; return {}; } opentracing::expected ForeachKey( - std::function(opentracing::string_view key, opentracing::string_view value)> f) - const override { - for (const auto& key_value : text_map) { + std::function(opentracing::string_view key, + opentracing::string_view value)> f) const override + { + for (const auto &key_value : text_map) + { auto result = f(key_value.first, key_value.second); - if (!result) return result; + if (!result) + return result; } return {}; } - std::unordered_map& text_map; + std::unordered_map &text_map; }; diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index 2bf3ba6256..11de49e861 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -25,7 +25,7 @@ TEST(ShimUtilsTest, IsBaggageEmpty) auto empty = nostd::shared_ptr(new baggage::Baggage({})); ASSERT_TRUE(shim::utils::isBaggageEmpty(empty)); - std::map list{{ "foo", "bar" }}; + std::map list{{"foo", "bar"}}; auto non_empty = nostd::shared_ptr(new baggage::Baggage(list)); ASSERT_FALSE(shim::utils::isBaggageEmpty(non_empty)); } @@ -38,7 +38,8 @@ TEST(ShimUtilsTest, StringFromValue) ASSERT_EQ(shim::utils::stringFromValue(42l), "42"); ASSERT_EQ(shim::utils::stringFromValue(55ul), "55"); ASSERT_EQ(shim::utils::stringFromValue(std::string{"a string"}), "a string"); - ASSERT_EQ(shim::utils::stringFromValue(opentracing::string_view{"a string view"}), "a string view"); + ASSERT_EQ(shim::utils::stringFromValue(opentracing::string_view{"a string view"}), + "a string view"); ASSERT_EQ(shim::utils::stringFromValue(nullptr), ""); ASSERT_EQ(shim::utils::stringFromValue("a char ptr"), "a char ptr"); @@ -105,9 +106,12 @@ TEST(ShimUtilsTest, MakeOptionsShim_EmptyRefs) options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); auto options_shim = shim::utils::makeOptionsShim(options); - ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); - ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); - ASSERT_EQ(nostd::get(options_shim.parent), trace_api::SpanContext::GetInvalid()); + ASSERT_EQ(options_shim.start_system_time, + common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, + common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(nostd::get(options_shim.parent), + trace_api::SpanContext::GetInvalid()); } TEST(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) @@ -115,79 +119,80 @@ TEST(ShimUtilsTest, MakeOptionsShim_InvalidSpanContext) opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); - options.references = {{ opentracing::SpanReferenceType::FollowsFromRef, nullptr }}; + options.references = {{opentracing::SpanReferenceType::FollowsFromRef, nullptr}}; auto options_shim = shim::utils::makeOptionsShim(options); - ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); - ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); - ASSERT_EQ(nostd::get(options_shim.parent), trace_api::SpanContext::GetInvalid()); + ASSERT_EQ(options_shim.start_system_time, + common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, + common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(nostd::get(options_shim.parent), + trace_api::SpanContext::GetInvalid()); } TEST(ShimUtilsTest, MakeOptionsShim_FirstChildOf) { auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); - auto span_context = static_cast(span_context_shim.get()); + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context = static_cast(span_context_shim.get()); opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); - options.references = { - { opentracing::SpanReferenceType::FollowsFromRef, nullptr }, - { opentracing::SpanReferenceType::ChildOfRef, span_context }, - { opentracing::SpanReferenceType::ChildOfRef, nullptr } - }; + options.references = {{opentracing::SpanReferenceType::FollowsFromRef, nullptr}, + {opentracing::SpanReferenceType::ChildOfRef, span_context}, + {opentracing::SpanReferenceType::ChildOfRef, nullptr}}; auto options_shim = shim::utils::makeOptionsShim(options); - ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); - ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(options_shim.start_system_time, + common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, + common::SteadyTimestamp{options.start_steady_timestamp}); ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); } TEST(ShimUtilsTest, MakeOptionsShim_FirstInList) { auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); - auto span_context = static_cast(span_context_shim.get()); + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context = static_cast(span_context_shim.get()); opentracing::StartSpanOptions options; options.start_system_timestamp = opentracing::SystemTime::time_point::clock::now(); options.start_steady_timestamp = opentracing::SteadyTime::time_point::clock::now(); - options.references = { - { opentracing::SpanReferenceType::FollowsFromRef, span_context }, - { opentracing::SpanReferenceType::FollowsFromRef, nullptr } - }; + options.references = {{opentracing::SpanReferenceType::FollowsFromRef, span_context}, + {opentracing::SpanReferenceType::FollowsFromRef, nullptr}}; auto options_shim = shim::utils::makeOptionsShim(options); - ASSERT_EQ(options_shim.start_system_time, common::SystemTimestamp{options.start_system_timestamp}); - ASSERT_EQ(options_shim.start_steady_time, common::SteadyTimestamp{options.start_steady_timestamp}); + ASSERT_EQ(options_shim.start_system_time, + common::SystemTimestamp{options.start_system_timestamp}); + ASSERT_EQ(options_shim.start_steady_time, + common::SteadyTimestamp{options.start_steady_timestamp}); ASSERT_EQ(nostd::get(options_shim.parent), span_context_shim->context()); } TEST(ShimUtilsTest, MakeIterableLinks) { auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); - auto span_context1 = static_cast(span_context_shim1.get()); + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context1 = static_cast(span_context_shim1.get()); auto span_context_shim2 = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); - auto span_context2 = static_cast(span_context_shim2.get()); + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + auto span_context2 = static_cast(span_context_shim2.get()); opentracing::StartSpanOptions options; auto empty = shim::utils::makeIterableLinks(options); ASSERT_EQ(empty.size(), 0); - options.references = { - { opentracing::SpanReferenceType::FollowsFromRef, nullptr }, - { opentracing::SpanReferenceType::FollowsFromRef, span_context1 }, - { opentracing::SpanReferenceType::ChildOfRef, span_context2 } - }; - auto full = shim::utils::makeIterableLinks(options); + options.references = {{opentracing::SpanReferenceType::FollowsFromRef, nullptr}, + {opentracing::SpanReferenceType::FollowsFromRef, span_context1}, + {opentracing::SpanReferenceType::ChildOfRef, span_context2}}; + auto full = shim::utils::makeIterableLinks(options); ASSERT_EQ(full.size(), 3); std::vector> links; - full.ForEachKeyValue([&links](trace_api::SpanContext ctx, const common::KeyValueIterable& it){ - it.ForEachKeyValue([&links, &ctx](nostd::string_view key, common::AttributeValue value){ + full.ForEachKeyValue([&links](trace_api::SpanContext ctx, const common::KeyValueIterable &it) { + it.ForEachKeyValue([&links, &ctx](nostd::string_view key, common::AttributeValue value) { links.emplace_back(ctx, key, value); return false; }); @@ -215,9 +220,9 @@ TEST(ShimUtilsTest, MakeBaggage_EmptyRefs) ASSERT_TRUE(baggage->GetValue("foo", value)); ASSERT_EQ(value, "bar"); - auto context = context::RuntimeContext::GetCurrent(); + auto context = context::RuntimeContext::GetCurrent(); auto new_context = baggage::SetBaggage(context, baggage); - auto token = context::RuntimeContext::Attach(new_context); + auto token = context::RuntimeContext::Attach(new_context); ASSERT_EQ(context::RuntimeContext::GetCurrent(), new_context); opentracing::StartSpanOptions options; @@ -229,19 +234,17 @@ TEST(ShimUtilsTest, MakeBaggage_EmptyRefs) TEST(ShimUtilsTest, MakeBaggage_NonEmptyRefs) { auto span_context_shim1 = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), - baggage::Baggage::GetDefault()->Set("test", "foo")->Set("test1", "hello"))); - auto span_context1 = static_cast(span_context_shim1.get()); + trace_api::SpanContext::GetInvalid(), + baggage::Baggage::GetDefault()->Set("test", "foo")->Set("test1", "hello"))); + auto span_context1 = static_cast(span_context_shim1.get()); auto span_context_shim2 = nostd::shared_ptr(new shim::SpanContextShim( - trace_api::SpanContext::GetInvalid(), - baggage::Baggage::GetDefault()->Set("test", "bar")->Set("test2", "world"))); - auto span_context2 = static_cast(span_context_shim2.get()); + trace_api::SpanContext::GetInvalid(), + baggage::Baggage::GetDefault()->Set("test", "bar")->Set("test2", "world"))); + auto span_context2 = static_cast(span_context_shim2.get()); opentracing::StartSpanOptions options; - options.references = { - { opentracing::SpanReferenceType::FollowsFromRef, span_context1 }, - { opentracing::SpanReferenceType::ChildOfRef, span_context2 } - }; + options.references = {{opentracing::SpanReferenceType::FollowsFromRef, span_context1}, + {opentracing::SpanReferenceType::ChildOfRef, span_context2}}; auto baggage = shim::utils::makeBaggage(options); std::string value; @@ -259,12 +262,12 @@ TEST(ShimUtilsTest, MakeIterableTags) auto empty = shim::utils::makeIterableTags(options); ASSERT_EQ(empty.size(), 0); - options.tags = {{ "foo", 42.0 }, { "bar", true }, { "baz", "test" }}; - auto full = shim::utils::makeIterableTags(options); + options.tags = {{"foo", 42.0}, {"bar", true}, {"baz", "test"}}; + auto full = shim::utils::makeIterableTags(options); ASSERT_EQ(full.size(), 3); std::vector> attributes; - full.ForEachKeyValue([&attributes](nostd::string_view key, common::AttributeValue value){ + full.ForEachKeyValue([&attributes](nostd::string_view key, common::AttributeValue value) { attributes.push_back({key, value}); return true; }); @@ -273,5 +276,5 @@ TEST(ShimUtilsTest, MakeIterableTags) ASSERT_EQ(attributes[1].first, "bar"); ASSERT_TRUE(nostd::get(attributes[1].second)); ASSERT_EQ(attributes[2].first, "baz"); - ASSERT_STREQ(nostd::get(attributes[2].second), "test" ); + ASSERT_STREQ(nostd::get(attributes[2].second), "test"); } \ No newline at end of file diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index 0b9e780417..f51aa3fbe5 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -24,15 +24,12 @@ class SpanContextShimTest : public testing::Test virtual void SetUp() { auto span_context = trace_api::SpanContext::GetInvalid(); - auto baggage = baggage::Baggage::GetDefault()->Set("foo", "bar"); - span_context_shim = nostd::unique_ptr( - new shim::SpanContextShim(span_context, baggage)); + auto baggage = baggage::Baggage::GetDefault()->Set("foo", "bar"); + span_context_shim = + nostd::unique_ptr(new shim::SpanContextShim(span_context, baggage)); } - virtual void TearDown() - { - span_context_shim.reset(); - } + virtual void TearDown() { span_context_shim.reset(); } }; TEST_F(SpanContextShimTest, BaggageItem) @@ -60,18 +57,17 @@ TEST_F(SpanContextShimTest, NewWithKeyValue) TEST_F(SpanContextShimTest, ForeachBaggageItem) { - std::initializer_list> list{ - { "foo", "bar" }, { "bar", "baz" }, { "baz", "foo" } - }; + std::initializer_list> list{ + {"foo", "bar"}, {"bar", "baz"}, {"baz", "foo"}}; nostd::shared_ptr baggage(new baggage::Baggage(list)); shim::SpanContextShim new_span_context_shim(span_context_shim->context(), baggage); std::vector concatenated; - new_span_context_shim.ForeachBaggageItem([&concatenated] - (const std::string& key, const std::string& value){ - concatenated.emplace_back(key + ":" + value); - return true; - }); + new_span_context_shim.ForeachBaggageItem( + [&concatenated](const std::string &key, const std::string &value) { + concatenated.emplace_back(key + ":" + value); + return true; + }); ASSERT_EQ(concatenated.size(), 3); ASSERT_EQ(concatenated[0], "foo:bar"); @@ -81,8 +77,8 @@ TEST_F(SpanContextShimTest, ForeachBaggageItem) TEST_F(SpanContextShimTest, Clone) { - auto new_span_context = span_context_shim->Clone(); - auto new_span_context_shim = dynamic_cast(new_span_context.get()); + auto new_span_context = span_context_shim->Clone(); + auto new_span_context_shim = dynamic_cast(new_span_context.get()); ASSERT_TRUE(new_span_context_shim != nullptr); ASSERT_NE(span_context_shim.get(), new_span_context_shim); ASSERT_EQ(span_context_shim->context(), new_span_context_shim->context()); diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 8bb874cdd8..1bded35a35 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -19,24 +19,20 @@ class SpanShimTest : public testing::Test { public: nostd::unique_ptr span_shim; - MockSpan* mock_span; + MockSpan *mock_span; protected: virtual void SetUp() { - mock_span = new MockSpan(); - auto span = nostd::shared_ptr(mock_span); - auto tracer = shim::TracerShim::createTracerShim(); - auto tracer_shim = dynamic_cast(tracer.get()); - auto baggage = baggage::Baggage::GetDefault()->Set("baggage", "item"); - span_shim = nostd::unique_ptr( - new shim::SpanShim(*tracer_shim, span, baggage)); + mock_span = new MockSpan(); + auto span = nostd::shared_ptr(mock_span); + auto tracer = shim::TracerShim::createTracerShim(); + auto tracer_shim = dynamic_cast(tracer.get()); + auto baggage = baggage::Baggage::GetDefault()->Set("baggage", "item"); + span_shim = nostd::unique_ptr(new shim::SpanShim(*tracer_shim, span, baggage)); } - virtual void TearDown() - { - span_shim.reset(); - } + virtual void TearDown() { span_shim.reset(); } }; TEST_F(SpanShimTest, HandleError) @@ -109,10 +105,10 @@ TEST_F(SpanShimTest, SetBaggageItem) TEST_F(SpanShimTest, SetBaggageItem_MultiThreaded) { - auto span = nostd::shared_ptr(new MockSpan()); - auto tracer = shim::TracerShim::createTracerShim(); - auto tracer_shim = dynamic_cast(tracer.get()); - auto baggage = baggage::Baggage::GetDefault(); + auto span = nostd::shared_ptr(new MockSpan()); + auto tracer = shim::TracerShim::createTracerShim(); + auto tracer_shim = dynamic_cast(tracer.get()); + auto baggage = baggage::Baggage::GetDefault(); shim::SpanShim span_shim(*tracer_shim, span, baggage); std::vector threads; @@ -124,10 +120,11 @@ TEST_F(SpanShimTest, SetBaggageItem_MultiThreaded) { keys.emplace_back("key-" + std::to_string(index)); values.emplace_back("value-" + std::to_string(index)); - threads.emplace_back(std::bind(&shim::SpanShim::SetBaggageItem, &span_shim, keys[index], values[index])); + threads.emplace_back( + std::bind(&shim::SpanShim::SetBaggageItem, &span_shim, keys[index], values[index])); } - for (auto& thread : threads) + for (auto &thread : threads) { thread.join(); } @@ -177,8 +174,11 @@ TEST_F(SpanShimTest, Log_Event) auto logtime = opentracing::SystemTime::time_point::clock::now(); std::initializer_list> fields{ - {"event", "test!"}, {"foo", opentracing::string_view{"bar"}}, - {"error.kind", 42}, {"message","hello"}, {"stack","overflow"}}; + {"event", "test!"}, + {"foo", opentracing::string_view{"bar"}}, + {"error.kind", 42}, + {"message", "hello"}, + {"stack", "overflow"}}; span_shim->Log(logtime, fields); std::tie(name, timestamp, attributes) = mock_span->event_; @@ -200,8 +200,11 @@ TEST_F(SpanShimTest, Log_Error) auto logtime = opentracing::SystemTime::time_point::clock::now(); std::vector> fields{ - {"event", "error"}, {"foo", opentracing::string_view{"bar"}}, - {"error.kind", 42}, {"message","hello"}, {"stack","overflow"}}; + {"event", "error"}, + {"foo", opentracing::string_view{"bar"}}, + {"error.kind", 42}, + {"message", "hello"}, + {"stack", "overflow"}}; span_shim->Log(logtime, fields); std::tie(name, timestamp, attributes) = mock_span->event_; diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 24b5818c12..4ebb2f2ee5 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -5,10 +5,10 @@ #include "shim_mocks.h" -#include "opentelemetry/opentracingshim/tracer_shim.h" -#include "opentelemetry/opentracingshim/span_shim.h" -#include "opentelemetry/opentracingshim/span_context_shim.h" #include "opentelemetry/opentracingshim/shim_utils.h" +#include "opentelemetry/opentracingshim/span_context_shim.h" +#include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/opentracingshim/tracer_shim.h" #include "opentracing/noop.h" @@ -24,30 +24,27 @@ class TracerShimTest : public testing::Test { public: std::shared_ptr tracer_shim; - MockPropagator* text_map_format; - MockPropagator* http_headers_format; + MockPropagator *text_map_format; + MockPropagator *http_headers_format; protected: virtual void SetUp() { using context::propagation::TextMapPropagator; - text_map_format = new MockPropagator(); + text_map_format = new MockPropagator(); http_headers_format = new MockPropagator(); - tracer_shim = shim::TracerShim::createTracerShim(trace_api::Provider::GetTracerProvider(), { - .text_map = nostd::shared_ptr(text_map_format), - .http_headers = nostd::shared_ptr(http_headers_format) - }); + tracer_shim = shim::TracerShim::createTracerShim( + trace_api::Provider::GetTracerProvider(), + {.text_map = nostd::shared_ptr(text_map_format), + .http_headers = nostd::shared_ptr(http_headers_format)}); } - virtual void TearDown() - { - tracer_shim.reset(); - } + virtual void TearDown() { tracer_shim.reset(); } }; -TEST_F(TracerShimTest, TracerProviderName) +TEST_F(TracerShimTest, TracerName) { auto mock_provider_ptr = new MockTracerProvider(); nostd::shared_ptr provider(mock_provider_ptr); @@ -65,15 +62,15 @@ TEST_F(TracerShimTest, SpanReferenceToCreatingTracer) TEST_F(TracerShimTest, SpanParentChildRelationship) { auto span_shim1 = tracer_shim->StartSpan("a"); - auto span_shim2 = tracer_shim->StartSpan("b", { opentracing::ChildOf(&span_shim1->context()) }); + auto span_shim2 = tracer_shim->StartSpan("b", {opentracing::ChildOf(&span_shim1->context())}); ASSERT_NE(span_shim1, nullptr); ASSERT_NE(span_shim2, nullptr); ASSERT_NE(span_shim1, span_shim2); ASSERT_EQ(span_shim1->context().ToSpanID(), span_shim2->context().ToSpanID()); ASSERT_EQ(span_shim1->context().ToTraceID(), span_shim2->context().ToTraceID()); - auto span_context_shim1 = dynamic_cast(&span_shim1->context()); - auto span_context_shim2 = dynamic_cast(&span_shim2->context()); + auto span_context_shim1 = dynamic_cast(&span_shim1->context()); + auto span_context_shim2 = dynamic_cast(&span_shim2->context()); ASSERT_TRUE(span_context_shim1 != nullptr); ASSERT_TRUE(span_context_shim2 != nullptr); ASSERT_EQ(span_context_shim1->context(), span_context_shim2->context()); @@ -96,7 +93,7 @@ TEST_F(TracerShimTest, Close) TEST_F(TracerShimTest, InjectInvalidCarrier) { auto span_shim = tracer_shim->StartSpan("a"); - auto result = tracer_shim->Inject(span_shim->context(), std::cout); + auto result = tracer_shim->Inject(span_shim->context(), std::cout); ASSERT_TRUE(opentracing::are_errors_equal(result.error(), opentracing::invalid_carrier_error)); } @@ -104,9 +101,10 @@ TEST_F(TracerShimTest, InjectNullContext) { std::unordered_map text_map; auto noop_tracer = opentracing::MakeNoopTracer(); - auto span = noop_tracer->StartSpan("a"); - auto result = tracer_shim->Inject(span->context(), TextMapCarrier{text_map}); - ASSERT_TRUE(opentracing::are_errors_equal(result.error(), opentracing::invalid_span_context_error)); + auto span = noop_tracer->StartSpan("a"); + auto result = tracer_shim->Inject(span->context(), TextMapCarrier{text_map}); + ASSERT_TRUE( + opentracing::are_errors_equal(result.error(), opentracing::invalid_span_context_error)); ASSERT_TRUE(text_map.empty()); } @@ -182,7 +180,7 @@ TEST_F(TracerShimTest, ExtractOnlyBaggage) auto span_context = tracer_shim->Extract(TextMapCarrier{text_map}); ASSERT_TRUE(span_context.value() != nullptr); - auto span_context_shim = dynamic_cast(span_context.value().get()); + auto span_context_shim = dynamic_cast(span_context.value().get()); ASSERT_TRUE(span_context_shim != nullptr); ASSERT_FALSE(span_context_shim->context().IsValid()); ASSERT_FALSE(shim::utils::isBaggageEmpty(span_context_shim->baggage())); From 9df73513ae1223a496b346a7784963ba2131e58f Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Tue, 10 Jan 2023 09:00:04 -0500 Subject: [PATCH 20/46] Minor UT tuning --- opentracing-shim/test/propagation_test.cc | 1 - opentracing-shim/test/span_shim_test.cc | 12 +++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index 7f69ebdb61..d89fb8d7b0 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -99,7 +99,6 @@ TEST(PropagationTest, TextMapWriter_Set) tester.Set("foo", "bar"); tester.Set("bar", "baz"); tester.Set("baz", "foo"); - ASSERT_FALSE(text_map.empty()); ASSERT_EQ(text_map.size(), 3); ASSERT_EQ(text_map["foo"], "bar"); ASSERT_EQ(text_map["bar"], "baz"); diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 1bded35a35..ae501bbb7f 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -47,6 +47,10 @@ TEST_F(SpanShimTest, HandleError) ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kOk); span_shim->handleError(nullptr); ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kUnset); + span_shim->handleError("unknown"); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kUnset); + span_shim->handleError(42); + ASSERT_EQ(mock_span->status_.first, trace_api::StatusCode::kUnset); } TEST_F(SpanShimTest, FinishWithOptions) @@ -80,6 +84,8 @@ TEST_F(SpanShimTest, SetTag_Error) ASSERT_NE(mock_span->attribute_.first, "error"); span_shim->SetTag("error", "false"); ASSERT_NE(mock_span->attribute_.first, "error"); + span_shim->SetTag("error", 42); + ASSERT_NE(mock_span->attribute_.first, "error"); span_shim->SetTag("error", nullptr); ASSERT_NE(mock_span->attribute_.first, "error"); } @@ -174,7 +180,7 @@ TEST_F(SpanShimTest, Log_Event) auto logtime = opentracing::SystemTime::time_point::clock::now(); std::initializer_list> fields{ - {"event", "test!"}, + {"event", "normal"}, {"foo", opentracing::string_view{"bar"}}, {"error.kind", 42}, {"message", "hello"}, @@ -182,10 +188,10 @@ TEST_F(SpanShimTest, Log_Event) span_shim->Log(logtime, fields); std::tie(name, timestamp, attributes) = mock_span->event_; - ASSERT_EQ(name, "test!"); + ASSERT_EQ(name, "normal"); ASSERT_EQ(timestamp, common::SystemTimestamp{logtime}); ASSERT_EQ(attributes.size(), 5); - ASSERT_STREQ(nostd::get(attributes["event"]), "test!"); + ASSERT_STREQ(nostd::get(attributes["event"]), "normal"); ASSERT_EQ(nostd::get(attributes["foo"]), nostd::string_view{"bar"}); ASSERT_EQ(nostd::get(attributes["error.kind"]), 42); ASSERT_STREQ(nostd::get(attributes["message"]), "hello"); From 96da88250893fb50cbcb782c9af037b9b2b70b09 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Tue, 10 Jan 2023 16:25:18 -0500 Subject: [PATCH 21/46] Enable Opentracing shim in cmake.maintainer.test job --- .github/workflows/ci.yml | 1 - ci/do_ci.sh | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7a692615fe..638db1e76b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -489,7 +489,6 @@ jobs: - name: run tests run: ./ci/do_ci.sh format - windows: name: CMake -> exporter proto runs-on: windows-2019 diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 3b0592d5c0..37bdd2d889 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -103,6 +103,7 @@ elif [[ "$1" == "cmake.maintainer.test" ]]; then -DWITH_METRICS_EXEMPLAR_PREVIEW=ON \ -DWITH_ASYNC_EXPORT_PREVIEW=ON \ -DOTELCPP_MAINTAINER_MODE=ON \ + -DWITH_OPENTRACING=ON \ "${SRC_DIR}" make -k make test From b9178efb1d101ef195df8ac82838bd2981c62b8f Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Tue, 10 Jan 2023 18:51:26 -0500 Subject: [PATCH 22/46] Link with Opentracing lib --- opentracing-shim/CMakeLists.txt | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt index 8af1d209ba..ddfdb4332d 100644 --- a/opentracing-shim/CMakeLists.txt +++ b/opentracing-shim/CMakeLists.txt @@ -5,19 +5,21 @@ add_library(${this_target} src/span_shim.cc src/span_context_shim.cc set_target_properties(${this_target} PROPERTIES EXPORT_NAME opentracing_shim) +target_include_directories( + ${this_target} PUBLIC "$" + "$") + if(OPENTRACING_DIR) include_directories( "${CMAKE_BINARY_DIR}/${OPENTRACING_DIR}/include" "${CMAKE_SOURCE_DIR}/${OPENTRACING_DIR}/include" "${CMAKE_SOURCE_DIR}/${OPENTRACING_DIR}/3rd_party/include") + target_link_libraries(${this_target} opentelemetry_api opentracing) +else() + target_link_libraries(${this_target} opentelemetry_api + OpenTracing::opentracing) endif() -target_include_directories( - ${this_target} PUBLIC "$" - "$") - -target_link_libraries(${this_target} PUBLIC opentelemetry_api) - install( TARGETS ${this_target} EXPORT "${PROJECT_NAME}-target" From 20c99ec6d97680626d2ab931d829734d98462870 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 11 Jan 2023 18:02:30 -0500 Subject: [PATCH 23/46] Cannot compile shim for Windows because Opentracing Bazel build supports *nix --- ci/do_ci.ps1 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ci/do_ci.ps1 b/ci/do_ci.ps1 index 4ca64c0924..b414d4fecd 100644 --- a/ci/do_ci.ps1 +++ b/ci/do_ci.ps1 @@ -7,6 +7,7 @@ $SRC_DIR = (Get-Item -Path ".\").FullName $BAZEL_OPTIONS = "--copt=-DENABLE_LOGS_PREVIEW --copt=-DENABLE_ASYNC_EXPORT" $BAZEL_TEST_OPTIONS = "$BAZEL_OPTIONS --test_output=errors" +$BAZEL_EXCLUDE = "-//opentracing-shim:opentracing_shim" if (!(test-path build)) { mkdir build @@ -22,7 +23,7 @@ $VCPKG_DIR = Join-Path "$SRC_DIR" "tools" "vcpkg" switch ($action) { "bazel.build" { - bazel build --copt=-DENABLE_TEST $BAZEL_OPTIONS --action_env=VCPKG_DIR=$VCPKG_DIR -- //... + bazel build --copt=-DENABLE_TEST $BAZEL_OPTIONS --action_env=VCPKG_DIR=$VCPKG_DIR -- //... $BAZEL_EXCLUDE $exit = $LASTEXITCODE if ($exit -ne 0) { exit $exit From 7a0ca8d8c15e49c262d98f4ebb56e413bcca849d Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 11 Jan 2023 19:14:20 -0500 Subject: [PATCH 24/46] Comments on why shim is ignored in some tests --- ci/do_ci.ps1 | 1 + ci/do_ci.sh | 2 ++ 2 files changed, 3 insertions(+) diff --git a/ci/do_ci.ps1 b/ci/do_ci.ps1 index b414d4fecd..05efea4229 100644 --- a/ci/do_ci.ps1 +++ b/ci/do_ci.ps1 @@ -7,6 +7,7 @@ $SRC_DIR = (Get-Item -Path ".\").FullName $BAZEL_OPTIONS = "--copt=-DENABLE_LOGS_PREVIEW --copt=-DENABLE_ASYNC_EXPORT" $BAZEL_TEST_OPTIONS = "$BAZEL_OPTIONS --test_output=errors" +# Shim has a dependency on Opentracing package which lacks support for Windows $BAZEL_EXCLUDE = "-//opentracing-shim:opentracing_shim" if (!(test-path build)) { diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 37bdd2d889..a32ed14223 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -275,12 +275,14 @@ elif [[ "$1" == "bazel.legacy.test" ]]; then exit 0 elif [[ "$1" == "bazel.noexcept" ]]; then # there are some exceptions and error handling code from the Prometheus and Jaeger Clients + # as well as Opentracing shim (due to some third party code in its Opentracing dependency) # that make this test always fail. ignore Prometheus and Jaeger exporters in the noexcept here. bazel $BAZEL_STARTUP_OPTIONS build --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test -//opentracing-shim/... bazel $BAZEL_STARTUP_OPTIONS test --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test -//opentracing-shim/... exit 0 elif [[ "$1" == "bazel.nortti" ]]; then # there are some exceptions and error handling code from the Prometheus and Jaeger Clients + # as well as Opentracing shim (which requires the use of dynamic_cast in some situations) # that make this test always fail. ignore Prometheus and Jaeger exporters in the noexcept here. bazel $BAZEL_STARTUP_OPTIONS build --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//opentracing-shim/... bazel $BAZEL_STARTUP_OPTIONS test --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//opentracing-shim/... From 0708bb1cf3167de9afedcfb5d7803fdda8be260c Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 11 Jan 2023 19:25:17 -0500 Subject: [PATCH 25/46] Move comments block inside function body --- .../opentelemetry/opentracingshim/tracer_shim.h | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h index c16bfaa363..987bc91ba4 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h @@ -27,17 +27,17 @@ struct OpenTracingPropagators class TracerShim : public opentracing::Tracer { public: - // This operation MUST accept the following parameters: - // - An OpenTelemetry TracerProvider. This operation MUST use this TracerProvider to obtain a - // Tracer with the name opentracing-shim along with the current shim library version. - // - OpenTelemetry Propagators to be used to perform injection and extraction for the the - // OpenTracing TextMap and HTTPHeaders formats. If not specified, no Propagator values will - // be stored in the Shim, and the global OpenTelemetry TextMap propagator will be used for - // both OpenTracing TextMap and HTTPHeaders formats. static inline std::shared_ptr createTracerShim( const TracerProviderPtr &provider = opentelemetry::trace::Provider::GetTracerProvider(), const OpenTracingPropagators &propagators = {}) noexcept { + // This operation MUST accept the following parameters: + // - An OpenTelemetry TracerProvider. This operation MUST use this TracerProvider to obtain a + // Tracer with the name opentracing-shim along with the current shim library version. + // - OpenTelemetry Propagators to be used to perform injection and extraction for the the + // OpenTracing TextMap and HTTPHeaders formats. If not specified, no Propagator values will + // be stored in the Shim, and the global OpenTelemetry TextMap propagator will be used for + // both OpenTracing TextMap and HTTPHeaders formats. return std::shared_ptr( new (std::nothrow) TracerShim(provider->GetTracer("opentracing-shim"), propagators)); } From f6bc7dedf3b155ce6d8b2a6cc33da9cae5bfab1d Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Thu, 12 Jan 2023 01:23:45 -0500 Subject: [PATCH 26/46] Cleanup --- .../include/opentelemetry/opentracingshim/propagation.h | 5 ----- .../opentelemetry/opentracingshim/span_context_shim.h | 3 ++- .../include/opentelemetry/opentracingshim/span_shim.h | 3 ++- .../include/opentelemetry/opentracingshim/tracer_shim.h | 4 ++-- opentracing-shim/src/span_context_shim.cc | 2 +- opentracing-shim/src/span_shim.cc | 2 +- opentracing-shim/src/tracer_shim.cc | 2 +- opentracing-shim/test/propagation_test.cc | 2 +- opentracing-shim/test/shim_utils_test.cc | 2 +- opentracing-shim/test/span_context_shim_test.cc | 2 +- opentracing-shim/test/span_shim_test.cc | 2 +- opentracing-shim/test/tracer_shim_test.cc | 2 +- 12 files changed, 14 insertions(+), 17 deletions(-) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h index b0faeaffd2..d1d4971c5f 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h @@ -23,13 +23,11 @@ class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCar public: CarrierWriterShim(const T &writer) : writer_(writer) {} - // returns the value associated with the passed key. virtual nostd::string_view Get(nostd::string_view key) const noexcept override { return ""; // Not required for Opentracing writer } - // stores the key-value pair. virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override { writer_.Set(key.data(), value.data()); @@ -46,7 +44,6 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar public: CarrierReaderShim(const T &reader) : reader_(reader) {} - // returns the value associated with the passed key. virtual nostd::string_view Get(nostd::string_view key) const noexcept override { nostd::string_view value; @@ -73,13 +70,11 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar return value; } - // stores the key-value pair. virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override { // Not required for Opentracing reader } - // list of all the keys in the carrier. virtual bool Keys(nostd::function_ref callback) const noexcept override { return reader_ diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h index c20f903fb4..ceaa7ae730 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h @@ -22,11 +22,12 @@ class SpanContextShim final : public opentracing::SpanContext const BaggagePtr &baggage) : context_(context), baggage_(baggage) {} + inline const opentelemetry::trace::SpanContext &context() const { return context_; } inline const BaggagePtr baggage() const { return baggage_; } SpanContextShim newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept; bool BaggageItem(nostd::string_view key, std::string &value) const noexcept; - // Overrides + using VisitBaggageItem = std::function; void ForeachBaggageItem(VisitBaggageItem f) const override; std::unique_ptr Clone() const noexcept override; diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h index 98673c82d2..2b675ba863 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h @@ -27,8 +27,9 @@ class SpanShim : public opentracing::Span explicit SpanShim(const TracerShim &tracer, const SpanPtr &span, const BaggagePtr &baggage) : tracer_(tracer), span_(span), context_(span->GetContext(), baggage) {} + void handleError(const opentracing::Value &value) noexcept; - // Overrides + void FinishWithOptions( const opentracing::FinishSpanOptions &finish_span_options) noexcept override; void SetOperationName(opentracing::string_view name) noexcept override; diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h index 987bc91ba4..116137df97 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h @@ -34,14 +34,14 @@ class TracerShim : public opentracing::Tracer // This operation MUST accept the following parameters: // - An OpenTelemetry TracerProvider. This operation MUST use this TracerProvider to obtain a // Tracer with the name opentracing-shim along with the current shim library version. - // - OpenTelemetry Propagators to be used to perform injection and extraction for the the + // - OpenTelemetry Propagators to be used to perform injection and extraction for the // OpenTracing TextMap and HTTPHeaders formats. If not specified, no Propagator values will // be stored in the Shim, and the global OpenTelemetry TextMap propagator will be used for // both OpenTracing TextMap and HTTPHeaders formats. return std::shared_ptr( new (std::nothrow) TracerShim(provider->GetTracer("opentracing-shim"), propagators)); } - // Overrides + std::unique_ptr StartSpanWithOptions( opentracing::string_view operation_name, const opentracing::StartSpanOptions &options) const noexcept override; diff --git a/opentracing-shim/src/span_context_shim.cc b/opentracing-shim/src/span_context_shim.cc index 589eaa359e..54af4da9a3 100644 --- a/opentracing-shim/src/span_context_shim.cc +++ b/opentracing-shim/src/span_context_shim.cc @@ -43,4 +43,4 @@ std::string SpanContextShim::ToSpanID() const noexcept } } // namespace opentracingshim -OPENTELEMETRY_END_NAMESPACE \ No newline at end of file +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 15029de696..5c914df965 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -165,4 +165,4 @@ void SpanShim::logImpl(nostd::span fields, } } // namespace opentracingshim -OPENTELEMETRY_END_NAMESPACE \ No newline at end of file +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index 64082e1539..682ed6d89e 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -160,4 +160,4 @@ opentracing::expected> TracerShim::ext } } // namespace opentracingshim -OPENTELEMETRY_END_NAMESPACE \ No newline at end of file +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index d89fb8d7b0..98cfddd230 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -103,4 +103,4 @@ TEST(PropagationTest, TextMapWriter_Set) ASSERT_EQ(text_map["foo"], "bar"); ASSERT_EQ(text_map["bar"], "baz"); ASSERT_EQ(text_map["baz"], "foo"); -} \ No newline at end of file +} diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index 11de49e861..05b89af4bf 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -277,4 +277,4 @@ TEST(ShimUtilsTest, MakeIterableTags) ASSERT_TRUE(nostd::get(attributes[1].second)); ASSERT_EQ(attributes[2].first, "baz"); ASSERT_STREQ(nostd::get(attributes[2].second), "test"); -} \ No newline at end of file +} diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index f51aa3fbe5..9fcdcd28da 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -90,4 +90,4 @@ TEST_F(SpanContextShimTest, Clone) ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); ASSERT_TRUE(new_span_context_shim->BaggageItem("foo", new_value)); ASSERT_EQ(value, new_value); -} \ No newline at end of file +} diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index ae501bbb7f..02b627fa15 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -222,4 +222,4 @@ TEST_F(SpanShimTest, Log_Error) ASSERT_EQ(nostd::get(attributes["exception.type"]), 42); ASSERT_STREQ(nostd::get(attributes["exception.message"]), "hello"); ASSERT_STREQ(nostd::get(attributes["exception.stacktrace"]), "overflow"); -} \ No newline at end of file +} diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 4ebb2f2ee5..b8d4411666 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -188,4 +188,4 @@ TEST_F(TracerShimTest, ExtractOnlyBaggage) std::string value; ASSERT_TRUE(span_context_shim->BaggageItem("foo", value)); ASSERT_EQ(value, "bar"); -} \ No newline at end of file +} From 6636cc5ff54bba46f4ad305a6fcc087f85d952a6 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Thu, 12 Jan 2023 18:23:27 -0500 Subject: [PATCH 27/46] Fix error in package exclusion --- ci/do_ci.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/do_ci.ps1 b/ci/do_ci.ps1 index 05efea4229..fa1223856d 100644 --- a/ci/do_ci.ps1 +++ b/ci/do_ci.ps1 @@ -8,7 +8,7 @@ $SRC_DIR = (Get-Item -Path ".\").FullName $BAZEL_OPTIONS = "--copt=-DENABLE_LOGS_PREVIEW --copt=-DENABLE_ASYNC_EXPORT" $BAZEL_TEST_OPTIONS = "$BAZEL_OPTIONS --test_output=errors" # Shim has a dependency on Opentracing package which lacks support for Windows -$BAZEL_EXCLUDE = "-//opentracing-shim:opentracing_shim" +$BAZEL_EXCLUDE = "-//opentracing-shim/..." if (!(test-path build)) { mkdir build From 7b3d99aba76125e123caa239624012d34fc0a112 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Thu, 12 Jan 2023 18:24:31 -0500 Subject: [PATCH 28/46] Fix clang/gcc compilation warnings/errors --- opentracing-shim/BUILD | 1 + opentracing-shim/CMakeLists.txt | 4 +- .../opentracingshim/propagation.h | 4 +- .../opentracingshim/shim_utils.h | 99 +++---------------- .../opentelemetry/opentracingshim/span_shim.h | 4 +- .../opentracingshim/tracer_shim.h | 2 +- opentracing-shim/src/shim_utils.cc | 92 +++++++++++++++++ opentracing-shim/src/tracer_shim.cc | 7 +- opentracing-shim/test/shim_mocks.h | 6 +- .../test/span_context_shim_test.cc | 4 +- opentracing-shim/test/span_shim_test.cc | 4 +- opentracing-shim/test/tracer_shim_test.cc | 4 +- 12 files changed, 126 insertions(+), 105 deletions(-) create mode 100644 opentracing-shim/src/shim_utils.cc diff --git a/opentracing-shim/BUILD b/opentracing-shim/BUILD index b3ed93f461..ff5fe76ce7 100644 --- a/opentracing-shim/BUILD +++ b/opentracing-shim/BUILD @@ -3,6 +3,7 @@ package(default_visibility = ["//visibility:public"]) cc_library( name = "opentracing_shim", srcs = [ + "src/shim_utils.cc", "src/span_context_shim.cc", "src/span_shim.cc", "src/tracer_shim.cc", diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt index ddfdb4332d..1065d31412 100644 --- a/opentracing-shim/CMakeLists.txt +++ b/opentracing-shim/CMakeLists.txt @@ -1,7 +1,7 @@ set(this_target opentelemetry_opentracing_shim) -add_library(${this_target} src/span_shim.cc src/span_context_shim.cc - src/tracer_shim.cc) +add_library(${this_target} src/shim_utils.cc src/span_shim.cc + src/span_context_shim.cc src/tracer_shim.cc) set_target_properties(${this_target} PROPERTIES EXPORT_NAME opentracing_shim) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h index d1d4971c5f..3cb1356dbb 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h @@ -23,7 +23,7 @@ class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCar public: CarrierWriterShim(const T &writer) : writer_(writer) {} - virtual nostd::string_view Get(nostd::string_view key) const noexcept override + virtual nostd::string_view Get(nostd::string_view) const noexcept override { return ""; // Not required for Opentracing writer } @@ -70,7 +70,7 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar return value; } - virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override + virtual void Set(nostd::string_view, nostd::string_view) noexcept override { // Not required for Opentracing reader } diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index 8f30cf228a..95ad8895b2 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -7,21 +7,14 @@ #include "opentelemetry/opentracingshim/span_context_shim.h" -#include "opentelemetry/baggage/baggage.h" -#include "opentelemetry/baggage/baggage_context.h" -#include "opentelemetry/common/attribute_value.h" -#include "opentelemetry/common/key_value_iterable.h" -#include "opentelemetry/context/propagation/text_map_propagator.h" -#include "opentelemetry/nostd/type_traits.h" #include "opentelemetry/trace/semantic_conventions.h" -#include "opentelemetry/trace/span_context_kv_iterable.h" #include "opentelemetry/trace/tracer.h" -#include "opentracing/propagation.h" #include "opentracing/tracer.h" -#include "opentracing/value.h" OPENTELEMETRY_BEGIN_NAMESPACE -namespace opentracingshim::utils +namespace opentracingshim +{ +namespace utils { static inline opentelemetry::common::AttributeValue attributeFromValue( @@ -35,7 +28,7 @@ static inline opentelemetry::common::AttributeValue attributeFromValue( AttributeValue operator()(double v) { return v; } AttributeValue operator()(int64_t v) { return v; } AttributeValue operator()(uint64_t v) { return v; } - AttributeValue operator()(const std::string &v) { return nostd::string_view{}; } + AttributeValue operator()(const std::string &) { return nostd::string_view{}; } AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } AttributeValue operator()(std::nullptr_t) { return nostd::string_view{}; } AttributeValue operator()(const char *v) { return v; } @@ -87,40 +80,6 @@ static inline bool isBaggageEmpty(const nostd::shared_ptr &entry) { - return entry.first == SpanReferenceType::ChildOfRef; - }); - // The first SpanContext with Child Of type in the entire list is used as parent, - // else the first SpanContext is used as parent - auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; - - if (auto context_shim = dynamic_cast(context)) - { - options_shim.parent = context_shim->context(); - } - } - - return options_shim; -} - class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIterable { public: @@ -162,17 +121,12 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter return true; } - size_t size() const noexcept { return refs_.size(); } + size_t size() const noexcept override { return refs_.size(); } private: const RefsList &refs_; }; -static LinksIterable makeIterableLinks(const opentracing::StartSpanOptions &options) noexcept -{ - return LinksIterable(options.references); -} - class TagsIterable final : public opentelemetry::common::KeyValueIterable { public: @@ -198,40 +152,13 @@ class TagsIterable final : public opentelemetry::common::KeyValueIterable const std::vector> &tags_; }; -static TagsIterable makeIterableTags(const opentracing::StartSpanOptions &options) noexcept -{ - return TagsIterable(options.tags); -} - -static nostd::shared_ptr makeBaggage( - const opentracing::StartSpanOptions &options) noexcept -{ - using namespace opentelemetry::baggage; - - std::unordered_map baggage_items; - // If a list of Span references is specified... - for (const auto &entry : options.references) - { - if (auto context_shim = dynamic_cast(entry.second)) - { - // The union of their Baggage values MUST be used as the initial Baggage of the newly created - // Span. - context_shim->ForeachBaggageItem( - [&baggage_items](const std::string &key, const std::string &value) { - // It is unspecified which Baggage value is used in the case of repeated keys. - if (baggage_items.find(key) == baggage_items.end()) - { - baggage_items.emplace(key, value); // Here, only insert if key not already present - } - return true; - }); - } - } - // If no such list of references is specified, the current Baggage - // MUST be used as the initial value of the newly created Span. - return baggage_items.empty() ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) - : nostd::shared_ptr(new Baggage(baggage_items)); -} +opentelemetry::trace::StartSpanOptions makeOptionsShim( + const opentracing::StartSpanOptions &options) noexcept; +LinksIterable makeIterableLinks(const opentracing::StartSpanOptions &options) noexcept; +TagsIterable makeIterableTags(const opentracing::StartSpanOptions &options) noexcept; +nostd::shared_ptr makeBaggage( + const opentracing::StartSpanOptions &options) noexcept; -} // namespace opentracingshim::utils +} // namespace utils +} // namespace opentracingshim OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h index 2b675ba863..4fe48852c1 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_shim.h @@ -42,8 +42,8 @@ class SpanShim : public opentracing::Span std::initializer_list fields) noexcept override; void Log(opentracing::SystemTime timestamp, const std::vector &fields) noexcept override; - inline const opentracing::SpanContext &context() const noexcept override { return context_; }; - inline const opentracing::Tracer &tracer() const noexcept override { return tracer_; }; + inline const opentracing::SpanContext &context() const noexcept override { return context_; } + inline const opentracing::Tracer &tracer() const noexcept override { return tracer_; } private: void logImpl(nostd::span fields, diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h index 116137df97..b5ce90c0b5 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h @@ -57,7 +57,7 @@ class TracerShim : public opentracing::Tracer const opentracing::TextMapReader &reader) const override; opentracing::expected> Extract( const opentracing::HTTPHeadersReader &reader) const override; - inline void Close() noexcept override { is_closed_ = true; }; + inline void Close() noexcept override { is_closed_ = true; } private: explicit TracerShim(const TracerPtr &tracer, const OpenTracingPropagators &propagators) diff --git a/opentracing-shim/src/shim_utils.cc b/opentracing-shim/src/shim_utils.cc new file mode 100644 index 0000000000..25fdfb53f2 --- /dev/null +++ b/opentracing-shim/src/shim_utils.cc @@ -0,0 +1,92 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "opentelemetry/opentracingshim/shim_utils.h" + +#include "opentelemetry/baggage/baggage_context.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace opentracingshim +{ +namespace utils +{ + +opentelemetry::trace::StartSpanOptions makeOptionsShim( + const opentracing::StartSpanOptions &options) noexcept +{ + using opentracing::SpanReferenceType; + // If an explicit start timestamp is specified, a conversion MUST + // be done to match the OpenTracing and OpenTelemetry units. + opentelemetry::trace::StartSpanOptions options_shim; + options_shim.start_system_time = + opentelemetry::common::SystemTimestamp{options.start_system_timestamp}; + options_shim.start_steady_time = + opentelemetry::common::SteadyTimestamp{options.start_steady_timestamp}; + + const auto &refs = options.references; + // If a list of Span references is specified... + if (!refs.empty()) + { + const auto &first_child_of = std::find_if( + refs.cbegin(), refs.cend(), + [](const std::pair &entry) { + return entry.first == SpanReferenceType::ChildOfRef; + }); + // The first SpanContext with Child Of type in the entire list is used as parent, + // else the first SpanContext is used as parent + auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; + + if (auto context_shim = dynamic_cast(context)) + { + options_shim.parent = context_shim->context(); + } + } + + return options_shim; +} + +LinksIterable makeIterableLinks(const opentracing::StartSpanOptions &options) noexcept +{ + return LinksIterable(options.references); +} + +TagsIterable makeIterableTags(const opentracing::StartSpanOptions &options) noexcept +{ + return TagsIterable(options.tags); +} + +nostd::shared_ptr makeBaggage( + const opentracing::StartSpanOptions &options) noexcept +{ + using namespace opentelemetry::baggage; + + std::unordered_map baggage_items; + // If a list of Span references is specified... + for (const auto &entry : options.references) + { + if (auto context_shim = dynamic_cast(entry.second)) + { + // The union of their Baggage values MUST be used as the initial Baggage of the newly created + // Span. + context_shim->ForeachBaggageItem( + [&baggage_items](const std::string &key, const std::string &value) { + // It is unspecified which Baggage value is used in the case of repeated keys. + if (baggage_items.find(key) == baggage_items.end()) + { + baggage_items.emplace(key, value); // Here, only insert if key not already present + } + return true; + }); + } + } + // If no such list of references is specified, the current Baggage + // MUST be used as the initial value of the newly created Span. + return baggage_items.empty() ? GetBaggage(opentelemetry::context::RuntimeContext::GetCurrent()) + : nostd::shared_ptr(new Baggage(baggage_items)); +} + +} // namespace utils +} // namespace opentracingshim +OPENTELEMETRY_END_NAMESPACE diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index 682ed6d89e..1b494998d6 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -8,6 +8,7 @@ #include "opentelemetry/opentracingshim/shim_utils.h" #include "opentelemetry/opentracingshim/span_shim.h" +#include "opentelemetry/baggage/baggage_context.h" #include "opentelemetry/context/propagation/global_propagator.h" #include "opentelemetry/trace/context.h" #include "opentracing/ext/tags.h" @@ -46,8 +47,8 @@ std::unique_ptr TracerShim::StartSpanWithOptions( return std::unique_ptr(span_shim); } -opentracing::expected TracerShim::Inject(const opentracing::SpanContext &sc, - std::ostream &writer) const +opentracing::expected TracerShim::Inject(const opentracing::SpanContext &, + std::ostream &) const { // Errors MAY be raised if the specified Format is not recognized, // depending on the specific OpenTracing Language API. @@ -81,7 +82,7 @@ opentracing::expected TracerShim::Inject(const opentracing::SpanContext &s } opentracing::expected> TracerShim::Extract( - std::istream &reader) const + std::istream &) const { // Errors MAY be raised if either the Format is not recognized or no value // could be extracted, depending on the specific OpenTracing Language API. diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 98cb406d17..4ece6f63fc 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -63,9 +63,9 @@ struct MockSpan final : public trace_api::Span AddEvent(name, {}, attributes); } - void AddEvent(nostd::string_view name, common::SystemTimestamp timestamp) noexcept override {} + void AddEvent(nostd::string_view, common::SystemTimestamp) noexcept override {} - void AddEvent(nostd::string_view name) noexcept override {} + void AddEvent(nostd::string_view) noexcept override {} void SetStatus(trace_api::StatusCode code, nostd::string_view description) noexcept override { @@ -122,7 +122,7 @@ struct MockPropagator : public context::propagation::TextMapPropagator } // Gets the fields set in the carrier by the `inject` method - bool Fields(nostd::function_ref callback) const noexcept override + bool Fields(nostd::function_ref) const noexcept override { return true; } diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index 9fcdcd28da..bb888141cc 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -21,7 +21,7 @@ class SpanContextShimTest : public testing::Test nostd::unique_ptr span_context_shim; protected: - virtual void SetUp() + virtual void SetUp() override { auto span_context = trace_api::SpanContext::GetInvalid(); auto baggage = baggage::Baggage::GetDefault()->Set("foo", "bar"); @@ -29,7 +29,7 @@ class SpanContextShimTest : public testing::Test nostd::unique_ptr(new shim::SpanContextShim(span_context, baggage)); } - virtual void TearDown() { span_context_shim.reset(); } + virtual void TearDown() override { span_context_shim.reset(); } }; TEST_F(SpanContextShimTest, BaggageItem) diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 02b627fa15..6fa8bafbc1 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -22,7 +22,7 @@ class SpanShimTest : public testing::Test MockSpan *mock_span; protected: - virtual void SetUp() + virtual void SetUp() override { mock_span = new MockSpan(); auto span = nostd::shared_ptr(mock_span); @@ -32,7 +32,7 @@ class SpanShimTest : public testing::Test span_shim = nostd::unique_ptr(new shim::SpanShim(*tracer_shim, span, baggage)); } - virtual void TearDown() { span_shim.reset(); } + virtual void TearDown() override { span_shim.reset(); } }; TEST_F(SpanShimTest, HandleError) diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index b8d4411666..431033575a 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -28,7 +28,7 @@ class TracerShimTest : public testing::Test MockPropagator *http_headers_format; protected: - virtual void SetUp() + virtual void SetUp() override { using context::propagation::TextMapPropagator; @@ -41,7 +41,7 @@ class TracerShimTest : public testing::Test .http_headers = nostd::shared_ptr(http_headers_format)}); } - virtual void TearDown() { tracer_shim.reset(); } + virtual void TearDown() override { tracer_shim.reset(); } }; TEST_F(TracerShimTest, TracerName) From 18ff6091d2e4c90e584e3b15553a44d61a01ce38 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Thu, 12 Jan 2023 19:42:49 -0500 Subject: [PATCH 29/46] Move to own ci job --- .github/workflows/ci.yml | 14 ++++++++++++++ ci/do_ci.sh | 11 ++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 638db1e76b..898fd4f2de 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -127,6 +127,20 @@ jobs: sudo ./ci/install_abseil.sh ./ci/do_ci.sh cmake.abseil.test + cmake_opentracing_shim_test: + name: CMake test (with opentracing-shim) + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v3 + with: + submodules: 'recursive' + - name: setup + run: | + sudo ./ci/setup_cmake.sh + sudo ./ci/setup_ci_environment.sh + - name: run cmake tests (enable opentracing-shim) + run: ./ci/do_ci.sh cmake.opentracing_shim.test + cmake_gcc_48_test: name: CMake gcc 4.8 (without otlp exporter) runs-on: ubuntu-18.04 diff --git a/ci/do_ci.sh b/ci/do_ci.sh index a32ed14223..8be61e12cb 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -103,7 +103,6 @@ elif [[ "$1" == "cmake.maintainer.test" ]]; then -DWITH_METRICS_EXEMPLAR_PREVIEW=ON \ -DWITH_ASYNC_EXPORT_PREVIEW=ON \ -DOTELCPP_MAINTAINER_MODE=ON \ - -DWITH_OPENTRACING=ON \ "${SRC_DIR}" make -k make test @@ -137,6 +136,16 @@ elif [[ "$1" == "cmake.abseil.test" ]]; then make make test exit 0 +elif [[ "$1" == "cmake.opentracing_shim.test" ]]; then + cd "${BUILD_DIR}" + rm -rf * + cmake -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_CXX_FLAGS="-Werror $CXXFLAGS" \ + -DWITH_OPENTRACING=ON \ + "${SRC_DIR}" + make + make test + exit 0 elif [[ "$1" == "cmake.c++20.test" ]]; then cd "${BUILD_DIR}" rm -rf * From 0457d0bdccf0b479f6ccd88437fa922a1afd1c45 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Fri, 13 Jan 2023 18:29:14 -0500 Subject: [PATCH 30/46] Fix copy-paste error --- opentracing-shim/test/propagation_test.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index 98cfddd230..2d0fc054fd 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -30,9 +30,9 @@ TEST(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) ASSERT_EQ(testee.foreach_key_call_count, 1); text_map["foo"] = "bar"; - auto lookup_found = testee.LookupKey("foo"); + auto lookup_still_unsupported = testee.LookupKey("foo"); ASSERT_FALSE(text_map.empty()); - ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), + ASSERT_TRUE(opentracing::are_errors_equal(lookup_still_unsupported.error(), opentracing::lookup_key_not_supported_error)); ASSERT_EQ(tester.Get("foo"), nostd::string_view{"bar"}); ASSERT_EQ(testee.foreach_key_call_count, 2); From 43ddff2b90e58d6297e8c1c1a35232d7e46804cf Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Fri, 13 Jan 2023 19:08:30 -0500 Subject: [PATCH 31/46] Format... --- opentracing-shim/test/propagation_test.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index 2d0fc054fd..7831b1ee82 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -29,7 +29,7 @@ TEST(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) ASSERT_EQ(tester.Get("foo"), nostd::string_view{}); ASSERT_EQ(testee.foreach_key_call_count, 1); - text_map["foo"] = "bar"; + text_map["foo"] = "bar"; auto lookup_still_unsupported = testee.LookupKey("foo"); ASSERT_FALSE(text_map.empty()); ASSERT_TRUE(opentracing::are_errors_equal(lookup_still_unsupported.error(), From d14167462e119507a238134d320cc4241990e4e7 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sat, 14 Jan 2023 00:12:10 -0500 Subject: [PATCH 32/46] Ignore CXXFLAGS for Opentracing --- CMakeLists.txt | 3 +++ ci/do_ci.sh | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 0d461a7392..6e93bd78d0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -482,10 +482,13 @@ if(WITH_OPENTRACING) set(OPENTRACING_DIR "third_party/opentracing-cpp") message("Trying to use local ${OPENTRACING_DIR} from submodule") if(EXISTS "${PROJECT_SOURCE_DIR}/${OPENTRACING_DIR}/.git") + set(SAVED_CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) + set(CMAKE_CXX_FLAGS OFF) set(SAVED_BUILD_TESTING ${BUILD_TESTING}) set(BUILD_TESTING OFF) add_subdirectory(${OPENTRACING_DIR}) set(BUILD_TESTING ${SAVED_BUILD_TESTING}) + set(CMAKE_CXX_FLAGS ${SAVED_CMAKE_CXX_FLAGS}) else() message( FATAL_ERROR diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 8be61e12cb..929b29463a 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -139,7 +139,7 @@ elif [[ "$1" == "cmake.abseil.test" ]]; then elif [[ "$1" == "cmake.opentracing_shim.test" ]]; then cd "${BUILD_DIR}" rm -rf * - cmake -DCMAKE_BUILD_TYPE=Debug \ + cmake -DCMAKE_BUILD_TYPE=Debug \ -DCMAKE_CXX_FLAGS="-Werror $CXXFLAGS" \ -DWITH_OPENTRACING=ON \ "${SRC_DIR}" From 3276cc01e7abfee0945d4e6b79ef06c0366ee397 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sat, 14 Jan 2023 00:39:39 -0500 Subject: [PATCH 33/46] Not sure why CI fails to exclude shim in Windows Bazel... --- ci/do_ci.ps1 | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ci/do_ci.ps1 b/ci/do_ci.ps1 index fa1223856d..cbefee399f 100644 --- a/ci/do_ci.ps1 +++ b/ci/do_ci.ps1 @@ -7,8 +7,6 @@ $SRC_DIR = (Get-Item -Path ".\").FullName $BAZEL_OPTIONS = "--copt=-DENABLE_LOGS_PREVIEW --copt=-DENABLE_ASYNC_EXPORT" $BAZEL_TEST_OPTIONS = "$BAZEL_OPTIONS --test_output=errors" -# Shim has a dependency on Opentracing package which lacks support for Windows -$BAZEL_EXCLUDE = "-//opentracing-shim/..." if (!(test-path build)) { mkdir build @@ -24,7 +22,7 @@ $VCPKG_DIR = Join-Path "$SRC_DIR" "tools" "vcpkg" switch ($action) { "bazel.build" { - bazel build --copt=-DENABLE_TEST $BAZEL_OPTIONS --action_env=VCPKG_DIR=$VCPKG_DIR -- //... $BAZEL_EXCLUDE + bazel build --copt=-DENABLE_TEST $BAZEL_OPTIONS --action_env=VCPKG_DIR=$VCPKG_DIR -- //... -//opentracing-shim/... $exit = $LASTEXITCODE if ($exit -ne 0) { exit $exit From 07113bc02c89b29d72540e7d087505dce78ec511 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sat, 14 Jan 2023 20:54:25 -0500 Subject: [PATCH 34/46] Fix typo in CXX flags --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6e93bd78d0..ab6bdd96fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -483,7 +483,7 @@ if(WITH_OPENTRACING) message("Trying to use local ${OPENTRACING_DIR} from submodule") if(EXISTS "${PROJECT_SOURCE_DIR}/${OPENTRACING_DIR}/.git") set(SAVED_CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) - set(CMAKE_CXX_FLAGS OFF) + set(CMAKE_CXX_FLAGS "") set(SAVED_BUILD_TESTING ${BUILD_TESTING}) set(BUILD_TESTING OFF) add_subdirectory(${OPENTRACING_DIR}) From a2787090c93dd6c42ac097bd38bdaf599d09059a Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 15 Jan 2023 12:31:51 -0500 Subject: [PATCH 35/46] Attempt removing shim via deleted_packages --- ci/do_ci.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ci/do_ci.ps1 b/ci/do_ci.ps1 index cbefee399f..43514a58f3 100644 --- a/ci/do_ci.ps1 +++ b/ci/do_ci.ps1 @@ -22,7 +22,7 @@ $VCPKG_DIR = Join-Path "$SRC_DIR" "tools" "vcpkg" switch ($action) { "bazel.build" { - bazel build --copt=-DENABLE_TEST $BAZEL_OPTIONS --action_env=VCPKG_DIR=$VCPKG_DIR -- //... -//opentracing-shim/... + bazel build --copt=-DENABLE_TEST $BAZEL_OPTIONS --action_env=VCPKG_DIR=$VCPKG_DIR --deleted_packages=opentracing-shim -- //... $exit = $LASTEXITCODE if ($exit -ne 0) { exit $exit From f74f67f3ad06048946816fb9ee84ddc46b2e874f Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Fri, 20 Jan 2023 22:27:22 -0500 Subject: [PATCH 36/46] Disable redundant-move --- CMakeLists.txt | 3 --- ci/do_ci.sh | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ab6bdd96fa..0d461a7392 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -482,13 +482,10 @@ if(WITH_OPENTRACING) set(OPENTRACING_DIR "third_party/opentracing-cpp") message("Trying to use local ${OPENTRACING_DIR} from submodule") if(EXISTS "${PROJECT_SOURCE_DIR}/${OPENTRACING_DIR}/.git") - set(SAVED_CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) - set(CMAKE_CXX_FLAGS "") set(SAVED_BUILD_TESTING ${BUILD_TESTING}) set(BUILD_TESTING OFF) add_subdirectory(${OPENTRACING_DIR}) set(BUILD_TESTING ${SAVED_BUILD_TESTING}) - set(CMAKE_CXX_FLAGS ${SAVED_CMAKE_CXX_FLAGS}) else() message( FATAL_ERROR diff --git a/ci/do_ci.sh b/ci/do_ci.sh index 929b29463a..3b1e59bf1b 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -140,7 +140,7 @@ elif [[ "$1" == "cmake.opentracing_shim.test" ]]; then cd "${BUILD_DIR}" rm -rf * cmake -DCMAKE_BUILD_TYPE=Debug \ - -DCMAKE_CXX_FLAGS="-Werror $CXXFLAGS" \ + -DCMAKE_CXX_FLAGS="-Werror -Wno-error=redundant-move $CXXFLAGS" \ -DWITH_OPENTRACING=ON \ "${SRC_DIR}" make From 57b3051161c09e03b36d65065bce2df703bc40cb Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 5 Feb 2023 19:35:58 -0500 Subject: [PATCH 37/46] Update references to OpenTracing --- docs/dependencies.md | 7 +++++++ third_party_release | 1 + 2 files changed, 8 insertions(+) diff --git a/docs/dependencies.md b/docs/dependencies.md index 7094eeae52..a1724eb76c 100644 --- a/docs/dependencies.md +++ b/docs/dependencies.md @@ -104,3 +104,10 @@ Both these dependencies are listed here: - [Zpages](/ext/src/zpages): - None + +- [Opentracing](/opentracing-shim) + shim: + - [`opentracing-cpp`](https://github.com/opentracing/opentracing-cpp) + OpenTracing API for C++ + - A bridge layer implementing the OpenTracing API using the OpenTelemetry API + - License: `Apache License 2.0` diff --git a/third_party_release b/third_party_release index 3362b23db9..70ae928686 100644 --- a/third_party_release +++ b/third_party_release @@ -19,5 +19,6 @@ googletest=release-1.12.1 ms-gsl=v3.1.0-67-g6f45293 nlohmann-json=v3.10.5 opentelemetry-proto=v0.19.0 +opentracing-cpp=v1.6.0 prometheus-cpp=v1.0.0 vcpkg=2022.08.15 From cc360d77b6ad86d669384d3c690d21a3db3f47cc Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 5 Feb 2023 19:45:41 -0500 Subject: [PATCH 38/46] Use static_cast when RTTI is disabled --- .../opentracingshim/shim_utils.h | 3 ++- .../opentracingshim/span_context_shim.h | 22 +++++++++++++++ opentracing-shim/src/shim_utils.cc | 27 +++++++++---------- opentracing-shim/src/tracer_shim.cc | 2 +- .../test/span_context_shim_test.cc | 17 +++++++++++- opentracing-shim/test/span_shim_test.cc | 4 +-- opentracing-shim/test/tracer_shim_test.cc | 6 ++--- 7 files changed, 58 insertions(+), 23 deletions(-) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index 95ad8895b2..b9efe7832d 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -98,7 +98,6 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter for (const auto &entry : refs_) { - auto context_shim = dynamic_cast(entry.second); nostd::string_view span_kind; if (entry.first == SpanReferenceType::ChildOfRef) @@ -110,6 +109,8 @@ class LinksIterable final : public opentelemetry::trace::SpanContextKeyValueIter span_kind = OpentracingRefTypeValues::kFollowsFrom; } + auto context_shim = SpanContextShim::extractFrom(entry.second); + if (context_shim && !span_kind.empty() && !callback(context_shim->context(), opentelemetry::common::KeyValueIterableView( {{kOpentracingRefType, span_kind}}))) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h index ceaa7ae730..375d5cc321 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h @@ -23,6 +23,13 @@ class SpanContextShim final : public opentracing::SpanContext : context_(context), baggage_(baggage) {} + SpanContextShim &operator=(const SpanContextShim &other) + { + context_ = other.context_; + baggage_ = other.baggage_; + return *this; + } + inline const opentelemetry::trace::SpanContext &context() const { return context_; } inline const BaggagePtr baggage() const { return baggage_; } SpanContextShim newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept; @@ -34,6 +41,16 @@ class SpanContextShim final : public opentracing::SpanContext std::string ToTraceID() const noexcept override; std::string ToSpanID() const noexcept override; + static inline const SpanContextShim *extractFrom(const opentracing::SpanContext *span_context) + { +#ifndef OPENTELEMETRY_RTTI_ENABLED + auto result = static_cast(span_context); + return result && result->provides_context_and_baggage_ == kUniqueTag ? result : nullptr; +#else + return dynamic_cast(span_context); +#endif + } + private: template static std::string toHexString(const T &id_item) @@ -45,6 +62,11 @@ class SpanContextShim final : public opentracing::SpanContext opentelemetry::trace::SpanContext context_; BaggagePtr baggage_; + +#ifndef OPENTELEMETRY_RTTI_ENABLED + static constexpr uint64_t kUniqueTag = 0x07e1ba99a9e5; + const uint64_t provides_context_and_baggage_ = kUniqueTag; +#endif }; } // namespace opentracingshim diff --git a/opentracing-shim/src/shim_utils.cc b/opentracing-shim/src/shim_utils.cc index 25fdfb53f2..8829eafdf3 100644 --- a/opentracing-shim/src/shim_utils.cc +++ b/opentracing-shim/src/shim_utils.cc @@ -38,7 +38,7 @@ opentelemetry::trace::StartSpanOptions makeOptionsShim( // else the first SpanContext is used as parent auto context = (first_child_of != refs.cend()) ? first_child_of->second : refs.cbegin()->second; - if (auto context_shim = dynamic_cast(context)) + if (auto context_shim = SpanContextShim::extractFrom(context)) { options_shim.parent = context_shim->context(); } @@ -66,20 +66,17 @@ nostd::shared_ptr makeBaggage( // If a list of Span references is specified... for (const auto &entry : options.references) { - if (auto context_shim = dynamic_cast(entry.second)) - { - // The union of their Baggage values MUST be used as the initial Baggage of the newly created - // Span. - context_shim->ForeachBaggageItem( - [&baggage_items](const std::string &key, const std::string &value) { - // It is unspecified which Baggage value is used in the case of repeated keys. - if (baggage_items.find(key) == baggage_items.end()) - { - baggage_items.emplace(key, value); // Here, only insert if key not already present - } - return true; - }); - } + // The union of their Baggage values MUST be used + // as the initial Baggage of the newly created Span. + entry.second->ForeachBaggageItem( + [&baggage_items](const std::string &key, const std::string &value) { + // It is unspecified which Baggage value is used in the case of repeated keys. + if (baggage_items.find(key) == baggage_items.end()) + { + baggage_items.emplace(key, value); // Here, only insert if key not already present + } + return true; + }); } // If no such list of references is specified, the current Baggage // MUST be used as the initial value of the newly created Span. diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index 1b494998d6..bdadd3292d 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -122,7 +122,7 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex { // Inject the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. - if (auto context_shim = dynamic_cast(&sc)) + if (auto context_shim = SpanContextShim::extractFrom(&sc)) { auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); // It MUST inject any non-empty Baggage even amidst no valid SpanContext. diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index bb888141cc..a6a9077bd2 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -8,6 +8,8 @@ #include "opentelemetry/baggage/baggage.h" #include "opentelemetry/trace/span_context.h" +#include "opentracing/noop.h" + #include namespace trace_api = opentelemetry::trace; @@ -32,6 +34,19 @@ class SpanContextShimTest : public testing::Test virtual void TearDown() override { span_context_shim.reset(); } }; +TEST_F(SpanContextShimTest, ExtractFrom) +{ + ASSERT_TRUE(shim::SpanContextShim::extractFrom(nullptr) == nullptr); + + auto span_context = + &opentracing::MakeNoopTracer()->StartSpanWithOptions("operation", {})->context(); + ASSERT_TRUE(shim::SpanContextShim::extractFrom(span_context) == nullptr); + + auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( + trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); + ASSERT_TRUE(shim::SpanContextShim::extractFrom(span_context_shim.get()) != nullptr); +} + TEST_F(SpanContextShimTest, BaggageItem) { std::string value; @@ -78,7 +93,7 @@ TEST_F(SpanContextShimTest, ForeachBaggageItem) TEST_F(SpanContextShimTest, Clone) { auto new_span_context = span_context_shim->Clone(); - auto new_span_context_shim = dynamic_cast(new_span_context.get()); + auto new_span_context_shim = static_cast(new_span_context.get()); ASSERT_TRUE(new_span_context_shim != nullptr); ASSERT_NE(span_context_shim.get(), new_span_context_shim); ASSERT_EQ(span_context_shim->context(), new_span_context_shim->context()); diff --git a/opentracing-shim/test/span_shim_test.cc b/opentracing-shim/test/span_shim_test.cc index 6fa8bafbc1..d73f3e0061 100644 --- a/opentracing-shim/test/span_shim_test.cc +++ b/opentracing-shim/test/span_shim_test.cc @@ -27,7 +27,7 @@ class SpanShimTest : public testing::Test mock_span = new MockSpan(); auto span = nostd::shared_ptr(mock_span); auto tracer = shim::TracerShim::createTracerShim(); - auto tracer_shim = dynamic_cast(tracer.get()); + auto tracer_shim = static_cast(tracer.get()); auto baggage = baggage::Baggage::GetDefault()->Set("baggage", "item"); span_shim = nostd::unique_ptr(new shim::SpanShim(*tracer_shim, span, baggage)); } @@ -113,7 +113,7 @@ TEST_F(SpanShimTest, SetBaggageItem_MultiThreaded) { auto span = nostd::shared_ptr(new MockSpan()); auto tracer = shim::TracerShim::createTracerShim(); - auto tracer_shim = dynamic_cast(tracer.get()); + auto tracer_shim = static_cast(tracer.get()); auto baggage = baggage::Baggage::GetDefault(); shim::SpanShim span_shim(*tracer_shim, span, baggage); diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 431033575a..9a5679a999 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -69,8 +69,8 @@ TEST_F(TracerShimTest, SpanParentChildRelationship) ASSERT_EQ(span_shim1->context().ToSpanID(), span_shim2->context().ToSpanID()); ASSERT_EQ(span_shim1->context().ToTraceID(), span_shim2->context().ToTraceID()); - auto span_context_shim1 = dynamic_cast(&span_shim1->context()); - auto span_context_shim2 = dynamic_cast(&span_shim2->context()); + auto span_context_shim1 = static_cast(&span_shim1->context()); + auto span_context_shim2 = static_cast(&span_shim2->context()); ASSERT_TRUE(span_context_shim1 != nullptr); ASSERT_TRUE(span_context_shim2 != nullptr); ASSERT_EQ(span_context_shim1->context(), span_context_shim2->context()); @@ -180,7 +180,7 @@ TEST_F(TracerShimTest, ExtractOnlyBaggage) auto span_context = tracer_shim->Extract(TextMapCarrier{text_map}); ASSERT_TRUE(span_context.value() != nullptr); - auto span_context_shim = dynamic_cast(span_context.value().get()); + auto span_context_shim = static_cast(span_context.value().get()); ASSERT_TRUE(span_context_shim != nullptr); ASSERT_FALSE(span_context_shim->context().IsValid()); ASSERT_FALSE(shim::utils::isBaggageEmpty(span_context_shim->baggage())); From ecff29851b47b6f64f426ad3460bcd4672cc59a5 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Sun, 5 Feb 2023 19:47:30 -0500 Subject: [PATCH 39/46] Micro-optimizations --- .../opentracingshim/propagation.h | 14 ++++------- .../opentracingshim/span_context_shim.h | 11 ++------- .../opentracingshim/tracer_shim.h | 7 +++--- opentracing-shim/src/span_shim.cc | 24 ++++++++----------- opentracing-shim/src/tracer_shim.cc | 16 ++++++------- opentracing-shim/test/propagation_test.cc | 8 +++---- 6 files changed, 31 insertions(+), 49 deletions(-) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h index 3cb1356dbb..c226d9da83 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/propagation.h @@ -16,16 +16,14 @@ OPENTELEMETRY_BEGIN_NAMESPACE namespace opentracingshim { -template ::value, bool> = true> class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCarrier { public: - CarrierWriterShim(const T &writer) : writer_(writer) {} + CarrierWriterShim(const opentracing::TextMapWriter &writer) : writer_(writer) {} virtual nostd::string_view Get(nostd::string_view) const noexcept override { - return ""; // Not required for Opentracing writer + return {}; // Not required for Opentracing writer } virtual void Set(nostd::string_view key, nostd::string_view value) noexcept override @@ -34,15 +32,13 @@ class CarrierWriterShim : public opentelemetry::context::propagation::TextMapCar } private: - const T &writer_; + const opentracing::TextMapWriter &writer_; }; -template ::value, bool> = true> class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCarrier { public: - CarrierReaderShim(const T &reader) : reader_(reader) {} + CarrierReaderShim(const opentracing::TextMapReader &reader) : reader_(reader) {} virtual nostd::string_view Get(nostd::string_view key) const noexcept override { @@ -87,7 +83,7 @@ class CarrierReaderShim : public opentelemetry::context::propagation::TextMapCar } private: - const T &reader_; + const opentracing::TextMapReader &reader_; }; } // namespace opentracingshim diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h index 375d5cc321..62fec23c1a 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/span_context_shim.h @@ -23,13 +23,6 @@ class SpanContextShim final : public opentracing::SpanContext : context_(context), baggage_(baggage) {} - SpanContextShim &operator=(const SpanContextShim &other) - { - context_ = other.context_; - baggage_ = other.baggage_; - return *this; - } - inline const opentelemetry::trace::SpanContext &context() const { return context_; } inline const BaggagePtr baggage() const { return baggage_; } SpanContextShim newWithKeyValue(nostd::string_view key, nostd::string_view value) const noexcept; @@ -64,8 +57,8 @@ class SpanContextShim final : public opentracing::SpanContext BaggagePtr baggage_; #ifndef OPENTELEMETRY_RTTI_ENABLED - static constexpr uint64_t kUniqueTag = 0x07e1ba99a9e5; - const uint64_t provides_context_and_baggage_ = kUniqueTag; + static constexpr uint64_t kUniqueTag = 0x07e1ca578e57a71c; + uint64_t provides_context_and_baggage_ = kUniqueTag; #endif }; diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h index b5ce90c0b5..7f2d492efd 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/tracer_shim.h @@ -63,13 +63,12 @@ class TracerShim : public opentracing::Tracer explicit TracerShim(const TracerPtr &tracer, const OpenTracingPropagators &propagators) : tracer_(tracer), propagators_(propagators) {} - template + opentracing::expected injectImpl(const opentracing::SpanContext &sc, - const T &writer, + const opentracing::TextMapWriter &writer, const PropagatorPtr &propagator) const; - template opentracing::expected> extractImpl( - const T &reader, + const opentracing::TextMapReader &reader, const PropagatorPtr &propagator) const; TracerPtr tracer_; diff --git a/opentracing-shim/src/span_shim.cc b/opentracing-shim/src/span_shim.cc index 5c914df965..808b6b9e74 100644 --- a/opentracing-shim/src/span_shim.cc +++ b/opentracing-shim/src/span_shim.cc @@ -20,17 +20,15 @@ void SpanShim::handleError(const opentracing::Value &value) noexcept { using opentelemetry::trace::StatusCode; // The error tag MUST be mapped to StatusCode: - // - true maps to Error. - // - false maps to Ok - // - no value being set maps to Unset. - auto code = StatusCode::kUnset; const auto &error_tag = utils::stringFromValue(value); + // - no value being set maps to Unset. + auto code = StatusCode::kUnset; - if (error_tag == "true") + if (error_tag == "true") // - true maps to Error. { code = StatusCode::kError; } - else if (error_tag == "false") + else if (error_tag == "false") // - false maps to Ok. { code = StatusCode::kOk; } @@ -125,27 +123,24 @@ void SpanShim::logImpl(nostd::span fields, if (is_error) name = "exception"; // Along the specified key/value pair set as additional event attributes... - std::vector> attributes; + std::vector> attributes; attributes.reserve(fields.size()); for (const auto &entry : fields) { - auto key = entry.first; + nostd::string_view key = entry.first.data(); // ... including mapping of the following key/value pairs: - // - error.kind maps to exception.type. - // - message maps to exception.message. - // - stack maps to exception.stacktrace. if (is_error) { - if (key == "error.kind") + if (key == "error.kind") // - error.kind maps to exception.type. { key = opentelemetry::trace::SemanticConventions::kExceptionType; } - else if (key == "message") + else if (key == "message") // - message maps to exception.message. { key = opentelemetry::trace::SemanticConventions::kExceptionMessage; } - else if (key == "stack") + else if (key == "stack") // - stack maps to exception.stacktrace. { key = opentelemetry::trace::SemanticConventions::kExceptionStacktrace; } @@ -153,6 +148,7 @@ void SpanShim::logImpl(nostd::span fields, attributes.emplace_back(key, utils::attributeFromValue(entry.second)); } + // Calls Add Events on the underlying OpenTelemetry Span with the specified key/value pair set. if (timestamp) { diff --git a/opentracing-shim/src/tracer_shim.cc b/opentracing-shim/src/tracer_shim.cc index bdadd3292d..c8805d15ef 100644 --- a/opentracing-shim/src/tracer_shim.cc +++ b/opentracing-shim/src/tracer_shim.cc @@ -29,7 +29,7 @@ std::unique_ptr TracerShim::StartSpanWithOptions( const auto &attributes = utils::makeIterableTags(options); const auto &baggage = utils::makeBaggage(options); auto span = tracer_->StartSpan(operation_name.data(), attributes, links, opts); - auto span_shim = new SpanShim(*this, span, baggage); + auto span_shim = new (std::nothrow) SpanShim(*this, span, baggage); // If an initial set of tags is specified and the OpenTracing error tag // is included after the OpenTelemetry Span was created. @@ -39,7 +39,7 @@ std::unique_ptr TracerShim::StartSpanWithOptions( return entry.first == opentracing::ext::error; }); // The Shim layer MUST perform the same error handling as described in the Set Tag operation - if (error_entry != options.tags.cend()) + if (span_shim && error_entry != options.tags.cend()) { span_shim->handleError(error_entry->second); } @@ -115,9 +115,8 @@ opentracing::expected> TracerShim::Ext return extractImpl(reader, propagator); } -template opentracing::expected TracerShim::injectImpl(const opentracing::SpanContext &sc, - const T &writer, + const opentracing::TextMapWriter &writer, const PropagatorPtr &propagator) const { // Inject the underlying OpenTelemetry Span and Baggage using either the explicitly registered @@ -129,7 +128,7 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex const auto &context = opentelemetry::baggage::SetBaggage(current_context, context_shim->baggage()); - CarrierWriterShim carrier{writer}; + CarrierWriterShim carrier{writer}; propagator->Inject(carrier, context); return opentracing::make_expected(); } @@ -137,14 +136,13 @@ opentracing::expected TracerShim::injectImpl(const opentracing::SpanContex return opentracing::make_unexpected(opentracing::invalid_span_context_error); } -template opentracing::expected> TracerShim::extractImpl( - const T &reader, + const opentracing::TextMapReader &reader, const PropagatorPtr &propagator) const { // Extract the underlying OpenTelemetry Span and Baggage using either the explicitly registered // or the global OpenTelemetry Propagators, as configured at construction time. - CarrierReaderShim carrier{reader}; + CarrierReaderShim carrier{reader}; auto current_context = opentelemetry::context::RuntimeContext::GetCurrent(); auto context = propagator->Extract(carrier, current_context); auto span_context = opentelemetry::trace::GetSpan(context)->GetContext(); @@ -155,7 +153,7 @@ opentracing::expected> TracerShim::ext // SpanContext Shim instance with the extracted values. SpanContextShim *context_shim = (!span_context.IsValid() && utils::isBaggageEmpty(baggage)) ? nullptr - : new SpanContextShim(span_context, baggage); + : new (std::nothrow) SpanContextShim(span_context, baggage); return opentracing::make_expected(std::unique_ptr(context_shim)); } diff --git a/opentracing-shim/test/propagation_test.cc b/opentracing-shim/test/propagation_test.cc index 7831b1ee82..eb59630405 100644 --- a/opentracing-shim/test/propagation_test.cc +++ b/opentracing-shim/test/propagation_test.cc @@ -21,7 +21,7 @@ TEST(PropagationTest, TextMapReader_Get_LookupKey_Unsupported) ASSERT_FALSE(testee.supports_lookup); ASSERT_EQ(testee.foreach_key_call_count, 0); - shim::CarrierReaderShim tester{testee}; + shim::CarrierReaderShim tester{testee}; auto lookup_unsupported = testee.LookupKey("foo"); ASSERT_TRUE(text_map.empty()); ASSERT_TRUE(opentracing::are_errors_equal(lookup_unsupported.error(), @@ -46,7 +46,7 @@ TEST(PropagationTest, TextMapReader_Get_LookupKey_Supported) ASSERT_TRUE(testee.supports_lookup); ASSERT_EQ(testee.foreach_key_call_count, 0); - shim::CarrierReaderShim tester{testee}; + shim::CarrierReaderShim tester{testee}; auto lookup_not_found = testee.LookupKey("foo"); ASSERT_TRUE(text_map.empty()); ASSERT_TRUE( @@ -68,7 +68,7 @@ TEST(PropagationTest, TextMapReader_Keys) TextMapCarrier testee{text_map}; ASSERT_EQ(testee.foreach_key_call_count, 0); - shim::CarrierReaderShim tester{testee}; + shim::CarrierReaderShim tester{testee}; std::vector kvs; auto callback = [&text_map, &kvs](nostd::string_view k) { kvs.emplace_back(k); @@ -93,7 +93,7 @@ TEST(PropagationTest, TextMapWriter_Set) { std::unordered_map text_map; TextMapCarrier testee{text_map}; - shim::CarrierWriterShim tester{testee}; + shim::CarrierWriterShim tester{testee}; ASSERT_TRUE(text_map.empty()); tester.Set("foo", "bar"); From 4cf746ffbb0d42a8ded7add714be73347652ae9c Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 6 Feb 2023 00:54:15 -0500 Subject: [PATCH 40/46] Unit test for start span with error tag --- opentracing-shim/test/shim_mocks.h | 48 +++++++++++++++++------ opentracing-shim/test/tracer_shim_test.cc | 30 ++++++++++++++ 2 files changed, 65 insertions(+), 13 deletions(-) diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 4ece6f63fc..3d9bcc6e39 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -23,19 +23,6 @@ namespace common = opentelemetry::common; namespace context = opentelemetry::context; namespace nostd = opentelemetry::nostd; -struct MockTracerProvider final : public trace_api::TracerProvider -{ - nostd::shared_ptr GetTracer(nostd::string_view library_name, - nostd::string_view, - nostd::string_view) noexcept override - { - library_name_ = std::string{library_name}; - return nostd::shared_ptr(); - } - - std::string library_name_; -}; - struct MockSpan final : public trace_api::Span { void SetAttribute(nostd::string_view key, const common::AttributeValue &value) noexcept override @@ -93,6 +80,41 @@ struct MockSpan final : public trace_api::Span trace_api::EndSpanOptions options_; }; +struct MockTracer final : public trace_api::Tracer +{ + nostd::shared_ptr StartSpan( + nostd::string_view name, + const common::KeyValueIterable &, + const trace_api::SpanContextKeyValueIterable &, + const trace_api::StartSpanOptions &) noexcept override + { + span_ = new MockSpan(); + span_->name_ = std::string{name}; + return nostd::shared_ptr(span_); + } + + void ForceFlushWithMicroseconds(uint64_t) noexcept override {} + + void CloseWithMicroseconds(uint64_t) noexcept override {} + + MockSpan *span_; +}; + +struct MockTracerProvider final : public trace_api::TracerProvider +{ + nostd::shared_ptr GetTracer(nostd::string_view library_name, + nostd::string_view, + nostd::string_view) noexcept override + { + library_name_ = std::string{library_name}; + tracer_ = new MockTracer(); + return nostd::shared_ptr(tracer_); + } + + std::string library_name_; + MockTracer *tracer_ = new MockTracer(); +}; + struct MockPropagator : public context::propagation::TextMapPropagator { // Returns the context that is stored in the carrier with the TextMapCarrier as extractor. diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 9a5679a999..2d966cf03d 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -90,6 +90,36 @@ TEST_F(TracerShimTest, Close) ASSERT_TRUE(span_shim == nullptr); } +TEST_F(TracerShimTest, SpanHandleErrorTagAtCreation) +{ + auto mock_provider_ptr = new MockTracerProvider(); + nostd::shared_ptr provider(mock_provider_ptr); + auto tracer_shim = shim::TracerShim::createTracerShim(provider); + auto span_shim = tracer_shim->StartSpanWithOptions("test", {}); + ASSERT_TRUE(span_shim != nullptr); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test"); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kUnset); + + opentracing::StartSpanOptions options; + options.tags = {{"event", "normal"}}; + auto span_shim1 = tracer_shim->StartSpanWithOptions("test1", options); + ASSERT_TRUE(span_shim1 != nullptr); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test1"); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kUnset); + + options.tags = {{"error", true}}; + auto span_shim2 = tracer_shim->StartSpanWithOptions("test2", options); + ASSERT_TRUE(span_shim2 != nullptr); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test2"); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kError); + + options.tags = {{"error", "false"}}; + auto span_shim3 = tracer_shim->StartSpanWithOptions("test3", options); + ASSERT_TRUE(span_shim3 != nullptr); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test3"); + ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kOk); +} + TEST_F(TracerShimTest, InjectInvalidCarrier) { auto span_shim = tracer_shim->StartSpan("a"); From d50091571e4a7bb4bdaee8994313795a86621531 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 6 Feb 2023 01:42:52 -0500 Subject: [PATCH 41/46] Remove exclusion of shim in bazel no-rtti test --- ci/do_ci.sh | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ci/do_ci.sh b/ci/do_ci.sh index b12fc65d45..1e74617e56 100755 --- a/ci/do_ci.sh +++ b/ci/do_ci.sh @@ -293,16 +293,15 @@ elif [[ "$1" == "bazel.legacy.test" ]]; then elif [[ "$1" == "bazel.noexcept" ]]; then # there are some exceptions and error handling code from the Prometheus and Jaeger Clients # as well as Opentracing shim (due to some third party code in its Opentracing dependency) - # that make this test always fail. ignore Prometheus and Jaeger exporters in the noexcept here. + # that make this test always fail. Ignore these packages in the noexcept test here. bazel $BAZEL_STARTUP_OPTIONS build --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test -//opentracing-shim/... bazel $BAZEL_STARTUP_OPTIONS test --copt=-fno-exceptions --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//examples/prometheus/... -//sdk/test/metrics:attributes_hashmap_test -//opentracing-shim/... exit 0 elif [[ "$1" == "bazel.nortti" ]]; then # there are some exceptions and error handling code from the Prometheus and Jaeger Clients - # as well as Opentracing shim (which requires the use of dynamic_cast in some situations) - # that make this test always fail. ignore Prometheus and Jaeger exporters in the noexcept here. - bazel $BAZEL_STARTUP_OPTIONS build --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//opentracing-shim/... - bazel $BAZEL_STARTUP_OPTIONS test --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... -//opentracing-shim/... + # that make this test always fail. Ignore these packages in the nortti test here. + bazel $BAZEL_STARTUP_OPTIONS build --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... + bazel $BAZEL_STARTUP_OPTIONS test --cxxopt=-fno-rtti --build_tag_filters=-jaeger $BAZEL_TEST_OPTIONS_ASYNC -- //... -//exporters/prometheus/... -//exporters/jaeger/... exit 0 elif [[ "$1" == "bazel.asan" ]]; then bazel $BAZEL_STARTUP_OPTIONS test --config=asan $BAZEL_TEST_OPTIONS_ASYNC //... From 72ea0fb853f783e895e50f69e6691bed81e844b3 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 6 Feb 2023 01:43:53 -0500 Subject: [PATCH 42/46] Run opentracing-shim test job on latest Ubuntu --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2609013048..49681115c1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,7 +133,7 @@ jobs: cmake_opentracing_shim_test: name: CMake test (with opentracing-shim) - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: From 1877e2d07ba64d19d2fe1d877d16e808d3bff2bc Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 6 Feb 2023 09:18:25 -0500 Subject: [PATCH 43/46] Fix problems with UTs reported by Valgrind --- opentracing-shim/test/shim_mocks.h | 2 +- opentracing-shim/test/span_context_shim_test.cc | 6 +++--- opentracing-shim/test/tracer_shim_test.cc | 12 +++++------- 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/opentracing-shim/test/shim_mocks.h b/opentracing-shim/test/shim_mocks.h index 3d9bcc6e39..555f6cb65b 100644 --- a/opentracing-shim/test/shim_mocks.h +++ b/opentracing-shim/test/shim_mocks.h @@ -112,7 +112,7 @@ struct MockTracerProvider final : public trace_api::TracerProvider } std::string library_name_; - MockTracer *tracer_ = new MockTracer(); + MockTracer *tracer_; }; struct MockPropagator : public context::propagation::TextMapPropagator diff --git a/opentracing-shim/test/span_context_shim_test.cc b/opentracing-shim/test/span_context_shim_test.cc index a6a9077bd2..93978f079a 100644 --- a/opentracing-shim/test/span_context_shim_test.cc +++ b/opentracing-shim/test/span_context_shim_test.cc @@ -38,9 +38,9 @@ TEST_F(SpanContextShimTest, ExtractFrom) { ASSERT_TRUE(shim::SpanContextShim::extractFrom(nullptr) == nullptr); - auto span_context = - &opentracing::MakeNoopTracer()->StartSpanWithOptions("operation", {})->context(); - ASSERT_TRUE(shim::SpanContextShim::extractFrom(span_context) == nullptr); + auto tracer = opentracing::MakeNoopTracer(); + auto span = tracer->StartSpanWithOptions("operation", {}); + ASSERT_TRUE(shim::SpanContextShim::extractFrom(&span->context()) == nullptr); auto span_context_shim = nostd::shared_ptr(new shim::SpanContextShim( trace_api::SpanContext::GetInvalid(), baggage::Baggage::GetDefault())); diff --git a/opentracing-shim/test/tracer_shim_test.cc b/opentracing-shim/test/tracer_shim_test.cc index 2d966cf03d..7a06175323 100644 --- a/opentracing-shim/test/tracer_shim_test.cc +++ b/opentracing-shim/test/tracer_shim_test.cc @@ -97,24 +97,22 @@ TEST_F(TracerShimTest, SpanHandleErrorTagAtCreation) auto tracer_shim = shim::TracerShim::createTracerShim(provider); auto span_shim = tracer_shim->StartSpanWithOptions("test", {}); ASSERT_TRUE(span_shim != nullptr); + ASSERT_TRUE(mock_provider_ptr->tracer_ != nullptr); + ASSERT_TRUE(mock_provider_ptr->tracer_->span_ != nullptr); ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test"); ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kUnset); - opentracing::StartSpanOptions options; - options.tags = {{"event", "normal"}}; - auto span_shim1 = tracer_shim->StartSpanWithOptions("test1", options); + auto span_shim1 = tracer_shim->StartSpanWithOptions("test1", {.tags = {{"event", "normal"}}}); ASSERT_TRUE(span_shim1 != nullptr); ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test1"); ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kUnset); - options.tags = {{"error", true}}; - auto span_shim2 = tracer_shim->StartSpanWithOptions("test2", options); + auto span_shim2 = tracer_shim->StartSpanWithOptions("test2", {.tags = {{"error", true}}}); ASSERT_TRUE(span_shim2 != nullptr); ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test2"); ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kError); - options.tags = {{"error", "false"}}; - auto span_shim3 = tracer_shim->StartSpanWithOptions("test3", options); + auto span_shim3 = tracer_shim->StartSpanWithOptions("test3", {.tags = {{"error", "false"}}}); ASSERT_TRUE(span_shim3 != nullptr); ASSERT_EQ(mock_provider_ptr->tracer_->span_->name_, "test3"); ASSERT_EQ(mock_provider_ptr->tracer_->span_->status_.first, trace_api::StatusCode::kOk); From 241ff460d2d8c80f32c5492c7a7563532a7b286d Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Tue, 7 Feb 2023 19:24:58 -0500 Subject: [PATCH 44/46] Put back string => string_view mapping --- .../include/opentelemetry/opentracingshim/shim_utils.h | 2 +- opentracing-shim/test/shim_utils_test.cc | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h index b9efe7832d..871bed590f 100644 --- a/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h +++ b/opentracing-shim/include/opentelemetry/opentracingshim/shim_utils.h @@ -28,7 +28,7 @@ static inline opentelemetry::common::AttributeValue attributeFromValue( AttributeValue operator()(double v) { return v; } AttributeValue operator()(int64_t v) { return v; } AttributeValue operator()(uint64_t v) { return v; } - AttributeValue operator()(const std::string &) { return nostd::string_view{}; } + AttributeValue operator()(const std::string &v) { return nostd::string_view{v}; } AttributeValue operator()(opentracing::string_view v) { return nostd::string_view{v.data()}; } AttributeValue operator()(std::nullptr_t) { return nostd::string_view{}; } AttributeValue operator()(const char *v) { return v; } diff --git a/opentracing-shim/test/shim_utils_test.cc b/opentracing-shim/test/shim_utils_test.cc index 05b89af4bf..aa2316f2d2 100644 --- a/opentracing-shim/test/shim_utils_test.cc +++ b/opentracing-shim/test/shim_utils_test.cc @@ -72,9 +72,10 @@ TEST(ShimUtilsTest, AttributeFromValue) ASSERT_EQ(value.index(), common::AttributeType::kTypeUInt64); ASSERT_EQ(nostd::get(value), 55ul); - value = shim::utils::attributeFromValue(std::string{"a string"}); + opentracing::Value str{std::string{"a string"}}; + value = shim::utils::attributeFromValue(str); ASSERT_EQ(value.index(), common::AttributeType::kTypeString); - ASSERT_EQ(nostd::get(value), nostd::string_view{}); + ASSERT_EQ(nostd::get(value), nostd::string_view{"a string"}); value = shim::utils::attributeFromValue(opentracing::string_view{"a string view"}); ASSERT_EQ(value.index(), common::AttributeType::kTypeString); From afd1b4dc08cc8708cc44286459ef5b3fc678493a Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Wed, 8 Feb 2023 21:37:45 -0500 Subject: [PATCH 45/46] Add copyright and license --- opentracing-shim/BUILD | 3 +++ opentracing-shim/CMakeLists.txt | 3 +++ 2 files changed, 6 insertions(+) diff --git a/opentracing-shim/BUILD b/opentracing-shim/BUILD index ff5fe76ce7..e7d90a4b4d 100644 --- a/opentracing-shim/BUILD +++ b/opentracing-shim/BUILD @@ -1,3 +1,6 @@ +# Copyright The OpenTelemetry Authors +# SPDX-License-Identifier: Apache-2.0 + package(default_visibility = ["//visibility:public"]) cc_library( diff --git a/opentracing-shim/CMakeLists.txt b/opentracing-shim/CMakeLists.txt index 1065d31412..2e89fca540 100644 --- a/opentracing-shim/CMakeLists.txt +++ b/opentracing-shim/CMakeLists.txt @@ -1,3 +1,6 @@ +# Copyright The OpenTelemetry Authors +# SPDX-License-Identifier: Apache-2.0 + set(this_target opentelemetry_opentracing_shim) add_library(${this_target} src/shim_utils.cc src/span_shim.cc From a4cd53724392ef56a09658695b1c30646d8ae1c5 Mon Sep 17 00:00:00 2001 From: Alex Emirov Date: Mon, 20 Feb 2023 17:00:45 -0500 Subject: [PATCH 46/46] Fix prometheus commit --- third_party/prometheus-cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/third_party/prometheus-cpp b/third_party/prometheus-cpp index 4ea303fa66..c9ffcdda90 160000 --- a/third_party/prometheus-cpp +++ b/third_party/prometheus-cpp @@ -1 +1 @@ -Subproject commit 4ea303fa66e4c26dc4df67045fa0edf09c2f3077 +Subproject commit c9ffcdda9086ffd9e1283ea7a0276d831f3c8a8d