diff --git a/CHANGELOG.md b/CHANGELOG.md index 6870f59e2e..b05b5b6d66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,9 @@ Increment the: ## [Unreleased] +* [CONFIGURATION] Add support for the composite sampler configuration + (programmatic and from yaml) + ([#4366](https://github.com/open-telemetry/opentelemetry-cpp/pull/4366)) * [SDK] `OTELResourceDetector` now percent-decodes values parsed from the `OTEL_RESOURCE_ATTRIBUTES` environment variable, per the W3C Baggage value grammar the resource spec defers to. A malformed escape sequence is left diff --git a/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h b/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h index a270a4c17f..64045b5176 100644 --- a/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h +++ b/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h @@ -15,7 +15,9 @@ namespace configuration class ComposableProbabilitySamplerConfiguration : public ComposableSamplerConfiguration { public: - static constexpr double kDefaultRatio = 1.0; + static constexpr double kDefaultRatio = 1.0; // schema: minimum 0, maximum 1 + static constexpr double kMinRatio = 0.0; + static constexpr double kMaxRatio = 1.0; ComposableProbabilitySamplerConfiguration() = default; double ratio{kDefaultRatio}; diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h b/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h index 9274670fd4..e719cd9257 100644 --- a/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h +++ b/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h @@ -27,6 +27,11 @@ namespace trace class ComposableProbabilitySampler : public ComposableSampler { public: + /** + * @param ratio the sampling probability: either 0 (never sample) or a + * value in [2^-56, 1.0]. Other values (including NaN) log a warning and + * fall back to the default of 1.0. + */ explicit ComposableProbabilitySampler(double ratio); SamplingIntent GetSamplingIntent( diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h new file mode 100644 index 0000000000..0177790bdb --- /dev/null +++ b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h @@ -0,0 +1,80 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include + +#include "opentelemetry/sdk/trace/samplers/predicate.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/version.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace sdk +{ +namespace trace +{ + +/** + * Matching criteria for RuleBasedPredicate. A criteria group left at its + * default is inactive and matches every span. + */ +struct RuleBasedPredicateOptions +{ + bool match_values = false; + std::string values_key; + std::vector values; + + bool match_patterns = false; + std::string patterns_key; + std::vector included; + std::vector excluded; + + bool match_parent_none = false; + bool match_parent_remote = false; + bool match_parent_local = false; + + bool match_span_kind_internal = false; + bool match_span_kind_server = false; + bool match_span_kind_client = false; + bool match_span_kind_producer = false; + bool match_span_kind_consumer = false; + + // Significant digits used to format double attribute values for matching. + int double_precision = 6; +}; + +/** + * RuleBasedPredicate matches a span when every active criteria group in its + * options matches: parent kind, span kind, an attribute equal to one of the + * given values, and an attribute matching the included/excluded wildcard + * patterns (excluded wins). Non-string attributes are matched by their string + * representation; doubles are formatted with %g at double_precision significant + * digits, so 404.0 matches "404". + */ +class RuleBasedPredicate : public Predicate +{ +public: + explicit RuleBasedPredicate(RuleBasedPredicateOptions options); + + bool SpanMatches( + const opentelemetry::trace::SpanContext &parent_context, + nostd::string_view name, + opentelemetry::trace::SpanKind span_kind, + const opentelemetry::common::KeyValueIterable &attributes, + const opentelemetry::trace::SpanContextKeyValueIterable &links) const noexcept override; + + nostd::string_view GetDescription() const noexcept override; + +private: + bool ParentMatches(const opentelemetry::trace::SpanContext &parent_context) const noexcept; + bool SpanKindMatches(opentelemetry::trace::SpanKind span_kind) const noexcept; + + RuleBasedPredicateOptions options_; +}; + +} // namespace trace +} // namespace sdk +OPENTELEMETRY_END_NAMESPACE diff --git a/sdk/src/common/wildcard_match.h b/sdk/src/common/wildcard_match.h index 5a72994471..b7e9264269 100644 --- a/sdk/src/common/wildcard_match.h +++ b/sdk/src/common/wildcard_match.h @@ -4,8 +4,8 @@ #pragma once #include -#include +#include "opentelemetry/nostd/string_view.h" #include "opentelemetry/version.h" OPENTELEMETRY_BEGIN_NAMESPACE @@ -18,11 +18,11 @@ namespace common * Matches a text string against a pattern containing '?' (any single character) * and '*' (any sequence of characters, including empty) wildcards. */ -inline bool WildcardMatch(const std::string &pattern, const std::string &text) +inline bool WildcardMatch(nostd::string_view pattern, nostd::string_view text) { size_t p = 0; size_t t = 0; - size_t star_p = std::string::npos; + size_t star_p = nostd::string_view::npos; size_t star_t = 0; while (t < text.size()) @@ -38,7 +38,7 @@ inline bool WildcardMatch(const std::string &pattern, const std::string &text) star_t = t; ++p; } - else if (star_p != std::string::npos) + else if (star_p != nostd::string_view::npos) { p = star_p + 1; ++star_t; diff --git a/sdk/src/configuration/configuration_parser.cc b/sdk/src/configuration/configuration_parser.cc index 91782e5360..8728607ca5 100644 --- a/sdk/src/configuration/configuration_parser.cc +++ b/sdk/src/configuration/configuration_parser.cc @@ -1843,6 +1843,13 @@ ConfigurationParser::ParseComposableProbabilitySamplerConfiguration( using Config = ComposableProbabilitySamplerConfiguration; auto model = std::make_unique(); model->ratio = node->GetDouble("ratio", Config::kDefaultRatio); + if (!(model->ratio >= Config::kMinRatio && model->ratio <= Config::kMaxRatio)) + { + std::string message("Illegal ratio: "); + message.append(std::to_string(model->ratio)); + throw InvalidSchemaException(node->Location(), message); + } + return model; } diff --git a/sdk/src/configuration/sdk_builder.cc b/sdk/src/configuration/sdk_builder.cc index ab8a2f4ed8..de22c29f00 100644 --- a/sdk/src/configuration/sdk_builder.cc +++ b/sdk/src/configuration/sdk_builder.cc @@ -33,7 +33,15 @@ #include "opentelemetry/sdk/configuration/boolean_array_attribute_value_configuration.h" #include "opentelemetry/sdk/configuration/boolean_attribute_value_configuration.h" #include "opentelemetry/sdk/configuration/cardinality_limits_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_off_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_on_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_parent_threshold_sampler_configuration.h" #include "opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_patterns_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_values_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_configuration.h" +#include "opentelemetry/sdk/configuration/composable_sampler_configuration.h" #include "opentelemetry/sdk/configuration/configuration.h" #include "opentelemetry/sdk/configuration/configured_sdk.h" #include "opentelemetry/sdk/configuration/console_log_record_exporter_builder.h" @@ -174,8 +182,16 @@ #include "opentelemetry/sdk/trace/sampler.h" #include "opentelemetry/sdk/trace/samplers/always_off_factory.h" #include "opentelemetry/sdk/trace/samplers/always_on_factory.h" +#include "opentelemetry/sdk/trace/samplers/composable_always_off.h" +#include "opentelemetry/sdk/trace/samplers/composable_always_on.h" +#include "opentelemetry/sdk/trace/samplers/composable_parent_threshold.h" +#include "opentelemetry/sdk/trace/samplers/composable_probability.h" +#include "opentelemetry/sdk/trace/samplers/composable_rule_based.h" +#include "opentelemetry/sdk/trace/samplers/composable_sampler.h" +#include "opentelemetry/sdk/trace/samplers/composite_sampler_factory.h" #include "opentelemetry/sdk/trace/samplers/parent_factory.h" #include "opentelemetry/sdk/trace/samplers/probability_factory.h" +#include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" #include "opentelemetry/sdk/trace/samplers/trace_id_ratio_factory.h" #include "opentelemetry/sdk/trace/simple_processor_factory.h" #include "opentelemetry/sdk/trace/span_limits.h" @@ -428,6 +444,166 @@ class ResourceAttributeValueSetter std::string name_; }; +class ComposableSamplerBuilder + : public opentelemetry::sdk::configuration::SamplerConfigurationVisitor +{ +public: + // NOLINTBEGIN(misc-no-recursion) + static std::shared_ptr Build( + const opentelemetry::sdk::configuration::ComposableSamplerConfiguration *model) + { + ComposableSamplerBuilder builder; + model->Accept(&builder); + return std::move(builder.sampler); + } + + ComposableSamplerBuilder() = default; + ComposableSamplerBuilder(ComposableSamplerBuilder &&) = delete; + ComposableSamplerBuilder(const ComposableSamplerBuilder &) = delete; + ComposableSamplerBuilder &operator=(ComposableSamplerBuilder &&) = delete; + ComposableSamplerBuilder &operator=(const ComposableSamplerBuilder &other) = delete; + ~ComposableSamplerBuilder() override = default; + + void VisitComposableAlwaysOff( + const opentelemetry::sdk::configuration::ComposableAlwaysOffSamplerConfiguration + * /* model */) override + { + sampler = std::make_shared(); + } + + void VisitComposableAlwaysOn( + const opentelemetry::sdk::configuration::ComposableAlwaysOnSamplerConfiguration * /* model */) + override + { + sampler = std::make_shared(); + } + + void VisitComposableProbability( + const opentelemetry::sdk::configuration::ComposableProbabilitySamplerConfiguration *model) + override + { + sampler = + std::make_shared(model->ratio); + } + + void VisitComposableParentThreshold( + const opentelemetry::sdk::configuration::ComposableParentThresholdSamplerConfiguration *model) + override + { + std::shared_ptr root; + if (model->root != nullptr) + { + root = Build(model->root.get()); + } + else + { + root = std::make_shared(); + } + sampler = std::make_shared(root); + } + + void VisitComposableRuleBased( + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerConfiguration *model) + override + { + std::vector rules; + rules.reserve(model->rules.size()); + for (const auto &rule : model->rules) + { + if (rule == nullptr || rule->sampler == nullptr) + { + OTEL_INTERNAL_LOG_WARN("Ignoring a rule with no sampler"); + continue; + } + opentelemetry::sdk::trace::PredicatedSampler predicated; + predicated.predicate = std::make_shared( + MakePredicateOptions(rule.get())); + predicated.sampler = Build(rule->sampler.get()); + rules.push_back(std::move(predicated)); + } + sampler = + std::make_shared(std::move(rules)); + } + // NOLINTEND(misc-no-recursion) + + // The model only ever nests ComposableSamplerConfiguration here, so the + // plain sampler visits are unreachable. + void VisitAlwaysOff( + const opentelemetry::sdk::configuration::AlwaysOffSamplerConfiguration * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitAlwaysOn( + const opentelemetry::sdk::configuration::AlwaysOnSamplerConfiguration * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitJaegerRemote(const opentelemetry::sdk::configuration::JaegerRemoteSamplerConfiguration + * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitParentBased(const opentelemetry::sdk::configuration::ParentBasedSamplerConfiguration + * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitProbability(const opentelemetry::sdk::configuration::ProbabilitySamplerConfiguration + * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitTraceIdRatioBased( + const opentelemetry::sdk::configuration::TraceIdRatioBasedSamplerConfiguration * /* model */) + override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitExtension( + const opentelemetry::sdk::configuration::ExtensionSamplerConfiguration * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + std::shared_ptr sampler; + +private: + static opentelemetry::sdk::trace::RuleBasedPredicateOptions MakePredicateOptions( + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerRuleConfiguration *rule) + { + opentelemetry::sdk::trace::RuleBasedPredicateOptions options; + if (rule->attribute_values != nullptr) + { + options.match_values = true; + options.values_key = rule->attribute_values->key; + options.values = rule->attribute_values->values; + } + if (rule->attribute_patterns != nullptr) + { + options.match_patterns = true; + options.patterns_key = rule->attribute_patterns->key; + options.included = rule->attribute_patterns->included; + options.excluded = rule->attribute_patterns->excluded; + } + options.match_parent_none = rule->match_parent_none; + options.match_parent_remote = rule->match_parent_remote; + options.match_parent_local = rule->match_parent_local; + + options.match_span_kind_internal = rule->match_span_kind_internal; + options.match_span_kind_server = rule->match_span_kind_server; + options.match_span_kind_client = rule->match_span_kind_client; + options.match_span_kind_producer = rule->match_span_kind_producer; + options.match_span_kind_consumer = rule->match_span_kind_consumer; + return options; + } +}; + class SamplerBuilder : public opentelemetry::sdk::configuration::SamplerConfigurationVisitor { public: @@ -482,42 +658,43 @@ class SamplerBuilder : public opentelemetry::sdk::configuration::SamplerConfigur } void VisitComposableAlwaysOff( - const opentelemetry::sdk::configuration::ComposableAlwaysOffSamplerConfiguration - * /* model */) override + const opentelemetry::sdk::configuration::ComposableAlwaysOffSamplerConfiguration *model) + override { - sampler = opentelemetry::sdk::trace::AlwaysOffSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableAlwaysOn( - const opentelemetry::sdk::configuration::ComposableAlwaysOnSamplerConfiguration * /* model */) + const opentelemetry::sdk::configuration::ComposableAlwaysOnSamplerConfiguration *model) override { - sampler = opentelemetry::sdk::trace::AlwaysOnSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableProbability( const opentelemetry::sdk::configuration::ComposableProbabilitySamplerConfiguration *model) override { - sampler = opentelemetry::sdk::trace::TraceIdRatioBasedSamplerFactory::Create(model->ratio); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableParentThreshold( - const opentelemetry::sdk::configuration::ComposableParentThresholdSamplerConfiguration - * /* model */) override + const opentelemetry::sdk::configuration::ComposableParentThresholdSamplerConfiguration *model) + override { - // FIXME-SDK: https://github.com/open-telemetry/opentelemetry-cpp/issues/4028 - OTEL_INTERNAL_LOG_WARN("ComposableParentThresholdSampler not yet fully supported by SDK"); - sampler = opentelemetry::sdk::trace::AlwaysOnSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableRuleBased( - const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerConfiguration - * /* model */) override + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerConfiguration *model) + override { - // FIXME-SDK: https://github.com/open-telemetry/opentelemetry-cpp/issues/4028 - OTEL_INTERNAL_LOG_WARN("ComposableRuleBasedSampler not yet fully supported by SDK"); - sampler = opentelemetry::sdk::trace::AlwaysOnSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } std::unique_ptr sampler; diff --git a/sdk/src/trace/BUILD b/sdk/src/trace/BUILD index 854ce7d261..182bbfc5e9 100644 --- a/sdk/src/trace/BUILD +++ b/sdk/src/trace/BUILD @@ -18,6 +18,7 @@ cc_library( "//sdk/src/common:env_variables", "//sdk/src/common:global_log_handler", "//sdk/src/common:random", + "//sdk/src/common:wildcard_match", "//sdk/src/resource", ], ) diff --git a/sdk/src/trace/CMakeLists.txt b/sdk/src/trace/CMakeLists.txt index 5408f5877d..e2736343ee 100644 --- a/sdk/src/trace/CMakeLists.txt +++ b/sdk/src/trace/CMakeLists.txt @@ -31,6 +31,7 @@ add_library( samplers/composable_probability.cc samplers/composable_parent_threshold.cc samplers/composable_rule_based.cc + samplers/rule_based_predicate.cc multi_recordable.cc random_id_generator.cc random_id_generator_factory.cc diff --git a/sdk/src/trace/samplers/composable_probability.cc b/sdk/src/trace/samplers/composable_probability.cc index be341242c4..a3f5e72531 100644 --- a/sdk/src/trace/samplers/composable_probability.cc +++ b/sdk/src/trace/samplers/composable_probability.cc @@ -20,14 +20,7 @@ namespace trace ComposableProbabilitySampler::ComposableProbabilitySampler(double ratio) { - if (ratio > 1.0) - { - ratio = 1.0; - } - if (ratio < 0.0) - { - ratio = 0.0; - } + ratio = ValidateRatio(ratio, "ComposableProbabilitySampler"); uint64_t threshold = CalculateThreshold(ratio); // A threshold of kMaxThreshold means 0% sampling. The specification asks for // this to behave like ComposableAlwaysOff: a non-probabilistic drop. diff --git a/sdk/src/trace/samplers/ot_trace_state.cc b/sdk/src/trace/samplers/ot_trace_state.cc index 6b85141236..aa495acb6c 100644 --- a/sdk/src/trace/samplers/ot_trace_state.cc +++ b/sdk/src/trace/samplers/ot_trace_state.cc @@ -116,6 +116,19 @@ uint64_t CalculateThreshold(double sampling_probability) noexcept return kMaxThreshold - kept; } +double ValidateRatio(double ratio, const char *sampler_name) noexcept +{ + // 2^-56; hex float literals would need C++17. + constexpr double kMinRatio = 1.0 / static_cast(kMaxThreshold); + if (ratio == 0.0 || (ratio >= kMinRatio && ratio <= 1.0)) + { + return ratio; + } + OTEL_INTERNAL_LOG_WARN("[" << sampler_name << "] ratio " << ratio + << " is not 0 or within [2^-56, 1.0], using the default 1.0"); + return 1.0; +} + uint64_t GetRandomnessFromTraceId(const opentelemetry::trace::TraceId &trace_id) noexcept { const uint8_t *data = trace_id.Id().data(); diff --git a/sdk/src/trace/samplers/ot_trace_state.h b/sdk/src/trace/samplers/ot_trace_state.h index ef59923c62..1862b5d5f6 100644 --- a/sdk/src/trace/samplers/ot_trace_state.h +++ b/sdk/src/trace/samplers/ot_trace_state.h @@ -33,6 +33,11 @@ static constexpr uint64_t kMaxRandomValue = kMaxThreshold - 1; // range [0, kMaxThreshold]. uint64_t CalculateThreshold(double sampling_probability) noexcept; +// Returns ratio unchanged when it is 0 or within [2^-56, 1.0]. Anything else +// (including NaN) logs a warning under sampler_name and returns the +// configuration default 1.0. +double ValidateRatio(double ratio, const char *sampler_name) noexcept; + // Extracts the 56-bit randomness value from the least significant 56 bits of // the trace id, as specified by W3C Trace Context Level 2. uint64_t GetRandomnessFromTraceId(const opentelemetry::trace::TraceId &trace_id) noexcept; diff --git a/sdk/src/trace/samplers/probability.cc b/sdk/src/trace/samplers/probability.cc index 3675e97087..31d4f62667 100644 --- a/sdk/src/trace/samplers/probability.cc +++ b/sdk/src/trace/samplers/probability.cc @@ -4,7 +4,6 @@ #include #include #include -#include #include #include "opentelemetry/nostd/shared_ptr.h" @@ -22,31 +21,6 @@ namespace trace_api = opentelemetry::trace; -namespace -{ -// Valid ratios are 0 (never sample) and [2^-56, 1.0]; 2^-56 is the smallest -// probability expressible with a 56-bit threshold. -bool IsValidRatio(double ratio) noexcept -{ - // 2^-56; hex float literals would need C++17. - constexpr double kMinRatio = 1.0 / static_cast(opentelemetry::sdk::trace::kMaxThreshold); - return ratio == 0.0 || (ratio >= kMinRatio && ratio <= 1.0); -} - -// Anything invalid (including NaN) logs a warning and returns 1.0, the -// default of the configuration specification. -double ValidateRatio(double ratio) noexcept -{ - if (IsValidRatio(ratio)) - { - return ratio; - } - OTEL_INTERNAL_LOG_WARN("[ProbabilitySampler] ratio " - << ratio << " is not 0 or within [2^-56, 1.0], using the default 1.0"); - return 1.0; -} -} // namespace - OPENTELEMETRY_BEGIN_NAMESPACE namespace sdk { @@ -54,9 +28,11 @@ namespace trace { ProbabilitySampler::ProbabilitySampler(double ratio) - : description_("ProbabilitySampler{" + std::to_string(IsValidRatio(ratio) ? ratio : 1.0) + "}"), - threshold_(CalculateThreshold(ValidateRatio(ratio))) -{} +{ + const double valid_ratio = ValidateRatio(ratio, "ProbabilitySampler"); + description_ = "ProbabilitySampler{" + std::to_string(valid_ratio) + "}"; + threshold_ = CalculateThreshold(valid_ratio); +} SamplingResult ProbabilitySampler::ShouldSample( const trace_api::SpanContext &parent_context, diff --git a/sdk/src/trace/samplers/rule_based_predicate.cc b/sdk/src/trace/samplers/rule_based_predicate.cc new file mode 100644 index 0000000000..51e27f2162 --- /dev/null +++ b/sdk/src/trace/samplers/rule_based_predicate.cc @@ -0,0 +1,242 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" + +#include +#include +#include +#include +#include +#include + +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/key_value_iterable.h" +#include "opentelemetry/nostd/function_ref.h" +#include "opentelemetry/nostd/span.h" +#include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/nostd/variant.h" +#include "opentelemetry/sdk/common/attribute_utils.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/version.h" + +#include "src/common/wildcard_match.h" + +namespace +{ + +using opentelemetry::nostd::function_ref; +using opentelemetry::sdk::common::WildcardMatch; +namespace nostd = opentelemetry::nostd; + +// Fits the widest value below: a 17 significant digit double takes 24 characters, an int64 20. +constexpr std::size_t kValueBufferSize = 32; + +// Checks every string form of an attribute value; array values match if any item matches. +class ValueMatcher +{ +public: + ValueMatcher(function_ref check, int double_precision) + : check_(check), double_precision_(double_precision) + {} + + bool operator()(bool v) const { return check_(v ? "true" : "false"); } + bool operator()(int32_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRId32, v)); + } + bool operator()(int64_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRId64, v)); + } + bool operator()(uint32_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRIu32, v)); + } + bool operator()(uint64_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRIu64, v)); + } + bool operator()(double v) const + { + if (std::isnan(v)) + { + return check_("NaN"); + } + if (std::isinf(v)) + { + return check_(v < 0 ? "-Infinity" : "Infinity"); + } + char buffer[kValueBufferSize]; + return CheckWritten(buffer, + std::snprintf(buffer, sizeof(buffer), "%.*g", double_precision_, v)); + } + bool operator()(const char *v) const { return v != nullptr && check_(v); } + bool operator()(nostd::string_view v) const { return check_(v); } + // Array values match when any item matches. + template + bool operator()(nostd::span v) const + { + for (const auto &value : v) + { + if ((*this)(value)) + { + return true; + } + } + return false; + } + // Byte arrays have no string form to match. + bool operator()(nostd::span /* v */) const { return false; } + +private: + // A failed or truncated write cannot match. + bool CheckWritten(const char *buffer, int length) const + { + if (length < 0 || length >= static_cast(kValueBufferSize)) + { + return false; + } + return check_(nostd::string_view(buffer, static_cast(length))); + } + + function_ref check_; + int double_precision_; +}; + +bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, + const std::string &key, + int double_precision, + function_ref check) noexcept +{ + bool matched = false; + attributes.ForEachKeyValue( + [&](nostd::string_view attr_key, opentelemetry::common::AttributeValue value) { + if (attr_key != key) + { + return true; + } + const auto result = + opentelemetry::sdk::common::VisitVariant(ValueMatcher(check, double_precision), value); + matched = result.second && result.first; + return false; + }); + return matched; +} + +} // namespace + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace sdk +{ +namespace trace +{ + +RuleBasedPredicate::RuleBasedPredicate(RuleBasedPredicateOptions options) + : options_(std::move(options)) +{} + +bool RuleBasedPredicate::SpanMatches( + const opentelemetry::trace::SpanContext &parent_context, + nostd::string_view /* name */, + opentelemetry::trace::SpanKind span_kind, + const opentelemetry::common::KeyValueIterable &attributes, + const opentelemetry::trace::SpanContextKeyValueIterable & /* links */) const noexcept +{ + if (!ParentMatches(parent_context)) + { + return false; + } + if (!SpanKindMatches(span_kind)) + { + return false; + } + if (options_.match_values && + !AttributeMatches(attributes, options_.values_key, options_.double_precision, + [this](nostd::string_view candidate) { + return std::find(options_.values.begin(), options_.values.end(), + candidate) != options_.values.end(); + })) + { + return false; + } + if (options_.match_patterns && + !AttributeMatches(attributes, options_.patterns_key, options_.double_precision, + [this](nostd::string_view candidate) { + for (const auto &pattern : options_.excluded) + { + if (WildcardMatch(pattern, candidate)) + { + return false; + } + } + if (options_.included.empty()) + { + return true; + } + for (const auto &pattern : options_.included) + { + if (WildcardMatch(pattern, candidate)) + { + return true; + } + } + return false; + })) + { + return false; + } + return true; +} + +nostd::string_view RuleBasedPredicate::GetDescription() const noexcept +{ + return "RuleBasedPredicate"; +} + +bool RuleBasedPredicate::ParentMatches( + const opentelemetry::trace::SpanContext &parent_context) const noexcept +{ + if (!(options_.match_parent_none || options_.match_parent_remote || options_.match_parent_local)) + { + return true; + } + if (!parent_context.IsValid()) + { + return options_.match_parent_none; + } + return parent_context.IsRemote() ? options_.match_parent_remote : options_.match_parent_local; +} + +bool RuleBasedPredicate::SpanKindMatches(opentelemetry::trace::SpanKind span_kind) const noexcept +{ + if (!(options_.match_span_kind_internal || options_.match_span_kind_server || + options_.match_span_kind_client || options_.match_span_kind_producer || + options_.match_span_kind_consumer)) + { + return true; + } + switch (span_kind) + { + case opentelemetry::trace::SpanKind::kInternal: + return options_.match_span_kind_internal; + case opentelemetry::trace::SpanKind::kServer: + return options_.match_span_kind_server; + case opentelemetry::trace::SpanKind::kClient: + return options_.match_span_kind_client; + case opentelemetry::trace::SpanKind::kProducer: + return options_.match_span_kind_producer; + case opentelemetry::trace::SpanKind::kConsumer: + return options_.match_span_kind_consumer; + } + return false; +} + +} // namespace trace +} // namespace sdk +OPENTELEMETRY_END_NAMESPACE diff --git a/sdk/test/configuration/sdk_builder_test.cc b/sdk/test/configuration/sdk_builder_test.cc index 5a47530a0b..2d8bb243da 100644 --- a/sdk/test/configuration/sdk_builder_test.cc +++ b/sdk/test/configuration/sdk_builder_test.cc @@ -4,17 +4,32 @@ #include #include +#include +#include #include #include #include #include #include "config_test_common.h" +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/key_value_iterable_view.h" #include "opentelemetry/logs/severity.h" +#include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/nostd/utility.h" #include "opentelemetry/sdk/configuration/always_off_sampler_configuration.h" #include "opentelemetry/sdk/configuration/always_on_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_off_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_on_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_parent_threshold_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_patterns_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_values_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_configuration.h" +#include "opentelemetry/sdk/configuration/composable_sampler_configuration.h" #include "opentelemetry/sdk/configuration/extension_push_metric_exporter_builder.h" #include "opentelemetry/sdk/configuration/extension_push_metric_exporter_configuration.h" #include "opentelemetry/sdk/configuration/instrument_type.h" @@ -54,6 +69,12 @@ #include "opentelemetry/sdk/trace/sampler.h" #include "opentelemetry/sdk/trace/span_limits.h" #include "opentelemetry/sdk/trace/tracer_provider.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_context_kv_iterable_view.h" +#include "opentelemetry/trace/span_id.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/trace/trace_flags.h" +#include "opentelemetry/trace/trace_id.h" using opentelemetry::sdk::configuration::Registry; using opentelemetry::sdk::configuration::SdkBuilder; @@ -64,6 +85,48 @@ namespace logs = opentelemetry::logs; namespace logs_sdk = opentelemetry::sdk::logs; namespace scope_sdk = opentelemetry::sdk::instrumentationscope; namespace config_sdk = opentelemetry::sdk::configuration; +namespace trace_api = opentelemetry::trace; + +namespace +{ + +using RuleAttrMap = std::map; + +opentelemetry::sdk::trace::Decision SampleWith(opentelemetry::sdk::trace::Sampler &sampler, + const trace_api::SpanContext &parent, + trace_api::SpanKind span_kind, + const RuleAttrMap &attrs) +{ + uint8_t trace_buf[trace_api::TraceId::kSize] = {1}; + std::vector>> links; + opentelemetry::common::KeyValueIterableView attrs_view{attrs}; + trace_api::SpanContextKeyValueIterableView links_view{links}; + auto result = sampler.ShouldSample(parent, trace_api::TraceId(trace_buf), "span", span_kind, + attrs_view, links_view); + return result.decision; +} + +trace_api::SpanContext MakeRuleParent(bool sampled, bool is_remote) +{ + uint8_t trace_buf[trace_api::TraceId::kSize] = {1}; + uint8_t span_buf[trace_api::SpanId::kSize] = {1}; + return trace_api::SpanContext(trace_api::TraceId(trace_buf), trace_api::SpanId(span_buf), + trace_api::TraceFlags(sampled ? 1 : 0), is_remote); +} + +// Builds composite(rule_based{[rule]}) where the rule maps to always_on. +std::unique_ptr BuildRuleSampler( + std::unique_ptr rule) +{ + rule->sampler = std::make_unique(); + auto rule_based_config = std::make_unique(); + rule_based_config->rules.push_back(std::move(rule)); + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + return builder.CreateSampler(sampler_config); +} + +} // namespace //------------------------------------------------------------------------------ // Tests for the SdkBuilder class methods that create SDK components from configuration models @@ -273,6 +336,365 @@ TEST(SdkBuilder, CreateProbabilitySampler) } } +TEST(SdkBuilder, CreateComposableAlwaysOnSampler) +{ + auto composable_config = std::make_unique(); + std::unique_ptr sampler_config = std::move(composable_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableAlwaysOnSampler})"); +} + +TEST(SdkBuilder, CreateComposableAlwaysOffSampler) +{ + auto composable_config = std::make_unique(); + std::unique_ptr sampler_config = std::move(composable_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableAlwaysOffSampler})"); +} + +TEST(SdkBuilder, CreateComposableProbabilitySampler) +{ + auto composable_probability_sampler_config = + std::make_unique(); + composable_probability_sampler_config->ratio = 0.25; + std::unique_ptr sampler_config = + std::move(composable_probability_sampler_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableProbabilitySampler{0.250000}})"); +} + +TEST(SdkBuilder, CreateComposableParentThresholdSampler) +{ + auto root_config = std::make_unique(); + root_config->ratio = 0.25; + auto parent_config = + std::make_unique(); + parent_config->root = std::move(root_config); + std::unique_ptr sampler_config = std::move(parent_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ( + std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableParentThresholdSampler{ComposableProbabilitySampler{0.250000}}})"); +} + +TEST(SdkBuilder, CreateComposableParentThresholdSamplerNullRoot) +{ + auto parent_config = + std::make_unique(); + parent_config->root = nullptr; + std::unique_ptr sampler_config = std::move(parent_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableParentThresholdSampler{ComposableAlwaysOnSampler}})"); +} + +TEST(SdkBuilder, CreateComposableParentThresholdSamplerNestedDepth3) +{ + auto innermost_config = std::make_unique(); + innermost_config->ratio = 0.25; + + auto middle_config = + std::make_unique(); + middle_config->root = std::move(innermost_config); + + auto outer_config = std::make_unique(); + outer_config->root = std::move(middle_config); + + std::unique_ptr sampler_config = std::move(outer_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableParentThresholdSampler{ComposableParentThresholdSampler{)" + R"(ComposableProbabilitySampler{0.250000}}}})"); +} + +TEST(SdkBuilder, CreateComposableRuleBasedSampler) +{ + auto rule_based_config = std::make_unique(); + + auto rule = std::make_unique(); + auto attribute_values = + std::make_unique(); + attribute_values->key = "http.route"; + attribute_values->values = {"/health"}; + rule->attribute_values = std::move(attribute_values); + rule->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(rule)); + + auto fallback = std::make_unique(); + fallback->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(fallback)); + + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ( + std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableRuleBasedSampler{ComposableAlwaysOffSampler,ComposableAlwaysOnSampler}})"); +} + +TEST(SdkBuilder, RuleBasedPredicateAttributeValues) +{ + using config_sdk::ComposableRuleBasedSamplerRuleAttributeValuesConfiguration; + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + auto parent = MakeRuleParent(true, true); + + // string attribute, exact match + { + auto rule = std::make_unique(); + auto values = std::make_unique(); + values->key = "http.route"; + values->values = {"/health", "/metrics"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/health"}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/users"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + } + + // non-string attribute matches via string representation + { + auto rule = std::make_unique(); + auto values = std::make_unique(); + values->key = "http.response.status_code"; + values->values = {"404"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"http.response.status_code", static_cast(404)}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"http.response.status_code", static_cast(200)}}), + Decision::DROP); + } + + // array attribute matches if any element matches + { + auto rule = std::make_unique(); + auto values = std::make_unique(); + values->key = "tags"; + values->values = {"b"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + std::vector matching_tags{"a", "b"}; + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"tags", opentelemetry::nostd::span( + matching_tags.data(), matching_tags.size())}}), + Decision::RECORD_AND_SAMPLE); + + std::vector non_matching_tags{"x", "z"}; + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"tags", opentelemetry::nostd::span( + non_matching_tags.data(), non_matching_tags.size())}}), + Decision::DROP); + } +} + +TEST(SdkBuilder, RuleBasedPredicateAttributePatterns) +{ + using config_sdk::ComposableRuleBasedSamplerRuleAttributePatternsConfiguration; + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + auto parent = MakeRuleParent(true, true); + + // included glob, excluded overrides + auto rule = std::make_unique(); + auto patterns = std::make_unique(); + patterns->key = "url.path"; + patterns->included = {"/api/*"}; + patterns->excluded = {"/api/health?"}; + rule->attribute_patterns = std::move(patterns); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"url.path", "/api/users"}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"url.path", "/api/healthz"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"url.path", "/other"}}), + Decision::DROP); + + // excluded only: no included patterns means match-all, then filter by excluded + { + auto excluded_only_rule = std::make_unique(); + auto excluded_only_patterns = + std::make_unique(); + excluded_only_patterns->key = "url.path"; + excluded_only_patterns->excluded = {"/internal/*"}; + excluded_only_rule->attribute_patterns = std::move(excluded_only_patterns); + auto excluded_only_sampler = BuildRuleSampler(std::move(excluded_only_rule)); + ASSERT_NE(excluded_only_sampler, nullptr); + + EXPECT_EQ(SampleWith(*excluded_only_sampler, parent, trace_api::SpanKind::kServer, + {{"url.path", "/internal/x"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*excluded_only_sampler, parent, trace_api::SpanKind::kServer, + {{"url.path", "/public/x"}}), + Decision::RECORD_AND_SAMPLE); + } +} + +TEST(SdkBuilder, RuleBasedPredicateSpanKindAndParent) +{ + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + // span kind + { + auto rule = std::make_unique(); + rule->match_span_kind_server = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + auto parent = MakeRuleParent(true, true); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kClient, {}), Decision::DROP); + } + + // parent: remote only + { + auto rule = std::make_unique(); + rule->match_parent_remote = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, true), trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, false), trace_api::SpanKind::kServer, {}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer, {}), + Decision::DROP); + } + + // parent: local only + { + auto rule = std::make_unique(); + rule->match_parent_local = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, false), trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, true), trace_api::SpanKind::kServer, {}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer, {}), + Decision::DROP); + } + + // parent: none only (root spans) + { + auto rule = std::make_unique(); + rule->match_parent_none = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, true), trace_api::SpanKind::kServer, {}), + Decision::DROP); + } + + // span kind and attribute values: both conditions must match (AND, not OR) + { + using config_sdk::ComposableRuleBasedSamplerRuleAttributeValuesConfiguration; + + auto rule = std::make_unique(); + rule->match_span_kind_server = true; + auto values = std::make_unique(); + values->key = "http.route"; + values->values = {"/health"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + auto parent = MakeRuleParent(true, true); + + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/health"}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/other"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kClient, {{"http.route", "/health"}}), + Decision::DROP); + } +} + +TEST(SdkBuilder, RuleBasedFirstMatchAndDefaults) +{ + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + auto parent = MakeRuleParent(true, true); + + // first match wins: rule 1 (no conditions -> matches all) is always_off, rule 2 always_on + { + auto rule_based_config = + std::make_unique(); + auto first = std::make_unique(); + first->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(first)); + auto second = std::make_unique(); + second->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(second)); + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + } + + // empty rules -> nothing matches -> drop + { + auto rule_based_config = + std::make_unique(); + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + } +} + TEST(SdkBuilder, CreatePeriodicMetricReader) { auto exporter = std::make_unique(); diff --git a/sdk/test/configuration/yaml_trace_test.cc b/sdk/test/configuration/yaml_trace_test.cc index 43d2c43eba..d02af743be 100644 --- a/sdk/test/configuration/yaml_trace_test.cc +++ b/sdk/test/configuration/yaml_trace_test.cc @@ -1197,6 +1197,63 @@ file_format: "1.0-trace" EXPECT_DOUBLE_EQ(visitor.ratio, 0.25); } +TEST(YamlTrace, composable_probability_sampler_ratio_too_small) +{ + std::string yaml = R"( +file_format: "1.0-trace" +tracer_provider: + processors: + - simple: + exporter: + console: + sampler: + composite/development: + probability: + ratio: -0.5 +)"; + + auto config = DoParse(yaml); + ASSERT_EQ(config, nullptr); +} + +TEST(YamlTrace, composable_probability_sampler_ratio_nan) +{ + std::string yaml = R"( +file_format: "1.0-trace" +tracer_provider: + processors: + - simple: + exporter: + console: + sampler: + composite/development: + probability: + ratio: nan +)"; + + auto config = DoParse(yaml); + ASSERT_EQ(config, nullptr); +} + +TEST(YamlTrace, composable_probability_sampler_ratio_too_large) +{ + std::string yaml = R"( +file_format: "1.0-trace" +tracer_provider: + processors: + - simple: + exporter: + console: + sampler: + composite/development: + probability: + ratio: 1.5 +)"; + + auto config = DoParse(yaml); + ASSERT_EQ(config, nullptr); +} + TEST(YamlTrace, composable_rule_based_sampler) { std::string yaml = R"( diff --git a/sdk/test/trace/composable_sampler_test.cc b/sdk/test/trace/composable_sampler_test.cc index d612d9a974..2e6245096a 100644 --- a/sdk/test/trace/composable_sampler_test.cc +++ b/sdk/test/trace/composable_sampler_test.cc @@ -3,6 +3,8 @@ #include #include +#include +#include #include #include #include @@ -10,6 +12,7 @@ #include +#include "opentelemetry/common/attribute_value.h" #include "opentelemetry/common/key_value_iterable_view.h" #include "opentelemetry/nostd/shared_ptr.h" #include "opentelemetry/nostd/span.h" @@ -26,6 +29,7 @@ #include "opentelemetry/sdk/trace/samplers/composite_sampler.h" #include "opentelemetry/sdk/trace/samplers/composite_sampler_factory.h" #include "opentelemetry/sdk/trace/samplers/predicate.h" +#include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" #include "opentelemetry/trace/span_context.h" #include "opentelemetry/trace/span_context_kv_iterable_view.h" #include "opentelemetry/trace/span_id.h" @@ -48,6 +52,8 @@ using opentelemetry::sdk::trace::CompositeSamplerFactory; using opentelemetry::sdk::trace::Decision; using opentelemetry::sdk::trace::Predicate; using opentelemetry::sdk::trace::PredicatedSampler; +using opentelemetry::sdk::trace::RuleBasedPredicate; +using opentelemetry::sdk::trace::RuleBasedPredicateOptions; using opentelemetry::sdk::trace::SamplingIntent; namespace @@ -81,6 +87,25 @@ trace_api::SpanContext MakeParent(bool sampled, const std::string &ot_value) trace_api::TraceFlags(sampled ? 1 : 0), true, trace_state); } +trace_api::SpanContext MakeParent(bool remote) +{ + constexpr uint8_t trace_bytes[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + constexpr uint8_t span_bytes[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + return trace_api::SpanContext(trace_api::TraceId(trace_bytes), trace_api::SpanId(span_bytes), + trace_api::TraceFlags(trace_api::TraceFlags::kIsSampled), remote); +} + +bool Matches(const RuleBasedPredicate &pred, + const std::map &attrs, + const trace_api::SpanContext &parent = trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind kind = trace_api::SpanKind::kInternal) +{ + common::KeyValueIterableView> attributes(attrs); + LinkVec link_vec; + trace_api::SpanContextKeyValueIterableView links(link_vec); + return pred.SpanMatches(parent, "span", kind, attributes, links); +} + std::string OtOf(const opentelemetry::sdk::trace::SamplingResult &result) { std::string value; @@ -362,14 +387,288 @@ TEST(ComposableSampler, ThresholdOmittedOverSizeLimit) EXPECT_EQ(parent_ot, ot); } -TEST(ComposableSampler, RatioClampedToValidRange) +TEST(ComposableSampler, InvalidRatioUsesDefault) { - auto over = CompositeSamplerFactory::Create(std::make_shared(2.0)); + for (double ratio : {2.0, -1.0, 1e-20}) + { + ComposableProbabilitySampler sampler(ratio); + EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{1.000000}"); + } + auto invalid = + CompositeSamplerFactory::Create(std::make_shared(-1.0)); EXPECT_EQ(Decision::RECORD_AND_SAMPLE, - Sample(*over, trace_api::SpanContext::GetInvalid(), MakeTraceId(0x00))); + Sample(*invalid, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); +} - auto under = - CompositeSamplerFactory::Create(std::make_shared(-1.0)); - EXPECT_EQ(Decision::DROP, - Sample(*under, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); +TEST(ComposableSampler, ZeroRatioIsValidAndDrops) +{ + ComposableProbabilitySampler sampler(0.0); + EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{0.000000}"); + auto zero = CompositeSamplerFactory::Create(std::make_shared(0.0)); + EXPECT_EQ(Decision::DROP, Sample(*zero, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); +} + +TEST(ComposableSampler, ProbabilityNanRatioUsesDefault) +{ + ComposableProbabilitySampler sampler(std::numeric_limits::quiet_NaN()); + EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{1.000000}"); +} + +TEST(RuleBasedPredicate, EmptyOptionsMatchEverySpan) +{ + RuleBasedPredicate pred(RuleBasedPredicateOptions{}); + EXPECT_TRUE(Matches(pred, {})); + EXPECT_TRUE(Matches(pred, {{"any", "value"}}, MakeParent(true), trace_api::SpanKind::kServer)); + EXPECT_EQ(std::string{pred.GetDescription()}, "RuleBasedPredicate"); +} + +TEST(RuleBasedPredicate, ParentMatching) +{ + RuleBasedPredicateOptions none; + none.match_parent_none = true; + RuleBasedPredicate root_only(std::move(none)); + EXPECT_TRUE(Matches(root_only, {})); + EXPECT_FALSE(Matches(root_only, {}, MakeParent(true))); + + RuleBasedPredicateOptions remote; + remote.match_parent_remote = true; + RuleBasedPredicate remote_only(std::move(remote)); + EXPECT_TRUE(Matches(remote_only, {}, MakeParent(true))); + EXPECT_FALSE(Matches(remote_only, {}, MakeParent(false))); + EXPECT_FALSE(Matches(remote_only, {})); +} + +TEST(RuleBasedPredicate, SpanKindMatching) +{ + struct KindCase + { + trace_api::SpanKind kind; + bool RuleBasedPredicateOptions::*flag; + }; + const KindCase cases[] = { + {trace_api::SpanKind::kInternal, &RuleBasedPredicateOptions::match_span_kind_internal}, + {trace_api::SpanKind::kServer, &RuleBasedPredicateOptions::match_span_kind_server}, + {trace_api::SpanKind::kClient, &RuleBasedPredicateOptions::match_span_kind_client}, + {trace_api::SpanKind::kProducer, &RuleBasedPredicateOptions::match_span_kind_producer}, + {trace_api::SpanKind::kConsumer, &RuleBasedPredicateOptions::match_span_kind_consumer}}; + + RuleBasedPredicate any_kind(RuleBasedPredicateOptions{}); + for (const auto &selected : cases) + { + EXPECT_TRUE(Matches(any_kind, {}, trace_api::SpanContext::GetInvalid(), selected.kind)); + + RuleBasedPredicateOptions options; + options.*selected.flag = true; + RuleBasedPredicate pred(std::move(options)); + for (const auto &other : cases) + { + EXPECT_EQ(selected.kind == other.kind, + Matches(pred, {}, trace_api::SpanContext::GetInvalid(), other.kind)) + << "span kind " << static_cast(other.kind); + } + } +} + +TEST(RuleBasedPredicate, AttributeValues) +{ + RuleBasedPredicateOptions options; + options.match_values = true; + options.values_key = "service"; + options.values = {"a", "42", + "true", "-2147483648", + "4294967295", "9223372036854775807", + "0.5", "18446744073709551615"}; + RuleBasedPredicate pred(std::move(options)); + EXPECT_TRUE(Matches(pred, {{"service", "a"}})); + EXPECT_FALSE(Matches(pred, {{"service", "b"}})); + EXPECT_FALSE(Matches(pred, {{"other", "a"}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(nullptr)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::string_view("a")}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::string_view("b")}})); + EXPECT_TRUE(Matches(pred, {{"service", true}})); + EXPECT_FALSE(Matches(pred, {{"service", false}})); + EXPECT_TRUE(Matches(pred, {{"service", static_cast(42)}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::min()}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(43)}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::max()}})); + EXPECT_FALSE(Matches(pred, {{"service", std::numeric_limits::min()}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::max()}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(0)}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::max()}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(0)}})); + EXPECT_TRUE(Matches(pred, {{"service", 0.5}})); + EXPECT_FALSE(Matches(pred, {{"service", 0.25}})); + + // Arrays match when any item matches. + static const bool bools[] = {false, true}; + static const bool no_bools[] = {false}; + static const int32_t int32s[] = {1, 42}; + static const int32_t no_int32s[] = {1, 2}; + static const int64_t int64s[] = {1, std::numeric_limits::max()}; + static const int64_t no_int64s[] = {1, 2}; + static const uint32_t uint32s[] = {1, std::numeric_limits::max()}; + static const uint32_t no_uint32s[] = {1, 2}; + static const uint64_t uint64s[] = {1, std::numeric_limits::max()}; + static const uint64_t no_uint64s[] = {1, 2}; + static const double doubles[] = {0.25, 0.5}; + static const double no_doubles[] = {0.25, 0.75}; + static const opentelemetry::nostd::string_view items[] = {"x", "a"}; + static const opentelemetry::nostd::string_view no_items[] = {"x", "y"}; + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(bools)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_bools)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(int32s)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_int32s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(int64s)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_int64s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(uint32s)}})); + EXPECT_FALSE( + Matches(pred, {{"service", opentelemetry::nostd::span(no_uint32s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(uint64s)}})); + EXPECT_FALSE( + Matches(pred, {{"service", opentelemetry::nostd::span(no_uint64s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(doubles)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_doubles)}})); + EXPECT_TRUE(Matches( + pred, + {{"service", opentelemetry::nostd::span(items)}})); + EXPECT_FALSE(Matches( + pred, {{"service", + opentelemetry::nostd::span(no_items)}})); + + // A byte array has no string representation, so it never matches. + static const uint8_t bytes[] = {42}; + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(bytes)}})); +} + +TEST(RuleBasedPredicate, AttributePatterns) +{ + RuleBasedPredicateOptions options; + options.match_patterns = true; + options.patterns_key = "url"; + options.included = {"/api/*"}; + options.excluded = {"/api/health"}; + RuleBasedPredicate pred(std::move(options)); + EXPECT_TRUE(Matches(pred, {{"url", "/api/users"}})); + EXPECT_FALSE(Matches(pred, {{"url", "/api/health"}})); + EXPECT_FALSE(Matches(pred, {{"url", "/other"}})); + EXPECT_TRUE(Matches(pred, {{"url", opentelemetry::nostd::string_view("/api/users")}})); + EXPECT_FALSE(Matches(pred, {{"url", opentelemetry::nostd::string_view("/other")}})); + + static const opentelemetry::nostd::string_view urls[] = {"/other", "/api/users"}; + static const opentelemetry::nostd::string_view no_urls[] = {"/other", "/api/health"}; + EXPECT_TRUE(Matches( + pred, {{"url", opentelemetry::nostd::span(urls)}})); + EXPECT_FALSE(Matches( + pred, + {{"url", opentelemetry::nostd::span(no_urls)}})); + + RuleBasedPredicateOptions excluded_only; + excluded_only.match_patterns = true; + excluded_only.patterns_key = "url"; + excluded_only.excluded = {"/internal/*"}; + RuleBasedPredicate not_internal(std::move(excluded_only)); + EXPECT_TRUE(Matches(not_internal, {{"url", "/public"}})); + EXPECT_FALSE(Matches(not_internal, {{"url", "/internal/x"}})); + + // A pattern of "4*" matches any http.response.status_code in 400-499, whatever numeric type + // carries it. + RuleBasedPredicateOptions status; + status.match_patterns = true; + status.patterns_key = "http.response.status_code"; + status.included = {"4*"}; + RuleBasedPredicate client_error(std::move(status)); + auto status_code = [&client_error](common::AttributeValue value) { + return Matches(client_error, {{"http.response.status_code", value}}); + }; + EXPECT_TRUE(status_code(static_cast(404))); + EXPECT_TRUE(status_code(static_cast(451))); + EXPECT_TRUE(status_code(static_cast(400))); + EXPECT_TRUE(status_code(static_cast(499))); + EXPECT_TRUE(status_code(404.0)); + EXPECT_FALSE(status_code(static_cast(200))); + EXPECT_FALSE(status_code(200.0)); + + // Arrays match when any item matches. + static const int32_t int32s[] = {200, 404}; + static const int32_t no_int32s[] = {200, 500}; + static const int64_t int64s[] = {200, 451}; + static const int64_t no_int64s[] = {200, 500}; + static const uint32_t uint32s[] = {200, 400}; + static const uint32_t no_uint32s[] = {200, 500}; + static const uint64_t uint64s[] = {200, 499}; + static const uint64_t no_uint64s[] = {200, 500}; + static const double doubles[] = {200.0, 404.0}; + static const double no_doubles[] = {200.0, 500.0}; + EXPECT_TRUE(status_code(opentelemetry::nostd::span(int32s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_int32s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(int64s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_int64s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(uint32s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_uint32s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(uint64s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_uint64s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(doubles))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_doubles))); + + static const uint8_t bytes[] = {4}; + EXPECT_FALSE(status_code(opentelemetry::nostd::span(bytes))); + + RuleBasedPredicateOptions truthy; + truthy.match_patterns = true; + truthy.patterns_key = "enabled"; + truthy.included = {"tr*"}; + RuleBasedPredicate enabled(std::move(truthy)); + EXPECT_TRUE(Matches(enabled, {{"enabled", true}})); + EXPECT_FALSE(Matches(enabled, {{"enabled", false}})); + + static const bool flags[] = {false, true}; + static const bool no_flags[] = {false, false}; + EXPECT_TRUE(Matches(enabled, {{"enabled", opentelemetry::nostd::span(flags)}})); + EXPECT_FALSE(Matches(enabled, {{"enabled", opentelemetry::nostd::span(no_flags)}})); + + // Doubles are formatted with %g at 6 significant digits by default, so 404.0 is "404" rather + // than "404.000000", and negative zero keeps its sign. + RuleBasedPredicateOptions numbers; + numbers.match_patterns = true; + numbers.patterns_key = "value"; + numbers.included = {"404", "0.1", "1.23457e+06", "1e+20", "1e-20", "-0", + "0.666667", "1.79769e+308", "NaN", "Infinity", "-Infinity"}; + RuleBasedPredicate number(std::move(numbers)); + EXPECT_TRUE(Matches(number, {{"value", 404.0}})); + EXPECT_TRUE(Matches(number, {{"value", 0.1}})); + EXPECT_TRUE(Matches(number, {{"value", 1234567.89}})); + EXPECT_TRUE(Matches(number, {{"value", 1e20}})); + EXPECT_TRUE(Matches(number, {{"value", 1e-20}})); + EXPECT_TRUE(Matches(number, {{"value", -0.0}})); + EXPECT_FALSE(Matches(number, {{"value", 0.0}})); + EXPECT_TRUE(Matches(number, {{"value", 2.0 / 3.0}})); + EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::max()}})); + EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::quiet_NaN()}})); + EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::infinity()}})); + EXPECT_TRUE(Matches(number, {{"value", -std::numeric_limits::infinity()}})); + EXPECT_FALSE(Matches(number, {{"value", 0.2}})); + + // double_precision widens the match beyond the 6 significant digit default. + RuleBasedPredicateOptions precise; + precise.match_patterns = true; + precise.patterns_key = "value"; + precise.included = {"1234567.89"}; + precise.double_precision = 15; + RuleBasedPredicate wide(std::move(precise)); + EXPECT_TRUE(Matches(wide, {{"value", 1234567.89}})); + EXPECT_FALSE(Matches(wide, {{"value", 1234567.0}})); +} + +TEST(RuleBasedPredicate, ActiveGroupsAreAnded) +{ + RuleBasedPredicateOptions options; + options.match_values = true; + options.values_key = "service"; + options.values = {"a"}; + options.match_span_kind_server = true; + RuleBasedPredicate pred(std::move(options)); + EXPECT_TRUE(Matches(pred, {{"service", "a"}}, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer)); + EXPECT_FALSE(Matches(pred, {{"service", "a"}}, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kClient)); }