diff --git a/BUILD.bazel b/BUILD.bazel index 459624d9..d539ac51 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -80,6 +80,8 @@ cc_library( "src/datadog/telemetry/log_binned_distr.cpp", "src/datadog/telemetry/log_binned_distr.h", "src/datadog/telemetry/metric_context.h", + "src/datadog/telemetry/metric_handle.cpp", + "src/datadog/telemetry/status_tags.h", "src/datadog/telemetry/telemetry.cpp", "src/datadog/telemetry/telemetry_impl.cpp", "src/datadog/telemetry/telemetry_impl.h", @@ -151,6 +153,7 @@ cc_library( "include/datadog/span_sampler_config.h", "include/datadog/string_view.h", "include/datadog/telemetry/configuration.h", + "include/datadog/telemetry/metric_handle.h", "include/datadog/telemetry/metrics.h", "include/datadog/telemetry/product.h", "include/datadog/telemetry/telemetry.h", diff --git a/CMakeLists.txt b/CMakeLists.txt index 42f8e26e..679f8b03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,6 +135,7 @@ target_sources(dd-trace-cpp-objects include/datadog/remote_config/listener.h include/datadog/remote_config/product.h include/datadog/telemetry/configuration.h + include/datadog/telemetry/metric_handle.h include/datadog/telemetry/metrics.h include/datadog/telemetry/product.h include/datadog/telemetry/telemetry.h @@ -185,6 +186,7 @@ target_sources(dd-trace-cpp-objects src/datadog/telemetry/configuration.cpp src/datadog/telemetry/log_bin_index.cpp src/datadog/telemetry/log_binned_distr.cpp + src/datadog/telemetry/metric_handle.cpp src/datadog/telemetry/telemetry.cpp src/datadog/telemetry/telemetry_impl.cpp src/datadog/baggage.cpp diff --git a/include/datadog/telemetry/metric_handle.h b/include/datadog/telemetry/metric_handle.h new file mode 100644 index 00000000..3348bbd4 --- /dev/null +++ b/include/datadog/telemetry/metric_handle.h @@ -0,0 +1,440 @@ +#pragma once + +// Metrics registered once with all their tags. Recording a point then takes +// plain values: no tag strings are built, copied or hashed. A +// details::MetricRegistry creates the handles and takes their series. +// +// A struct describes the tags. Its static `tag_fields()` returns a std::tuple +// of tag() calls, which bind each field to a tag name. String tags come in two +// kinds: +// * values known in advance: an enum field. `tag_value_names(Enum{})`, found +// by argument-dependent lookup, returns a std::array with one name per +// value, in order. +// * values not known in advance: a TagString field. +// test/telemetry/test_metric_handle.cpp has examples. +// +// Telemetry does not collect these handles yet. + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace datadog::telemetry { + +// A tag value not known in advance, such as a version. Creating one stores +// the string in a global table; copying it copies a small number. The table +// holds at most 65535 strings. Later new strings all read as "other". +class TagString { + public: + static constexpr std::uint64_t id_count = std::uint64_t{1} << 16; + + // The empty string. + TagString() = default; + explicit TagString(tracing::StringView value); + + std::uint16_t id() const { return id_; } + std::string value() const; + + private: + std::uint16_t id_ = 0; +}; + +namespace details { + +// Identifies one series of a metric: one combination of its tag values. Each +// tag's value is multiplied by the tag's stride, and the results added. +using SeriesId = std::uint64_t; + +// One tag of a metric: reads the tag's field from a tag struct, and renders +// the tag's values. The tag struct's type is hidden, so that MetricBase does +// not depend on it. +class TagCodec { + public: + virtual ~TagCodec() = default; + // The value of the tag's field in `*tags`, as a number. `tags` points to the + // tag struct that the codec was made for. + virtual std::uint64_t read(const void* tags) const = 0; + // "name:value", or an empty string if the tag is not sent. + virtual std::string render(std::uint64_t value) const = 0; +}; + +std::string interned_string(std::uint64_t id); +// "name:value_name" for each value name. +std::vector render_names( + const std::string& name, const std::vector& value_names); + +// A bool or enum field. Value i renders as rendered[i]. +template +class NamedTag final : public TagCodec { + public: + NamedTag(Field Tags::*field, std::vector rendered) + : field_(field), rendered_(std::move(rendered)) {} + + std::uint64_t read(const void* tags) const override { + return static_cast(static_cast(tags)->*field_); + } + + std::string render(std::uint64_t value) const override { + return rendered_[value]; + } + + private: + Field Tags::*field_; + std::vector rendered_; +}; + +// An optional enum field. Value 0 is an empty field, which is not sent. Value +// i + 1 renders as rendered[i]. +template +class OptionalTag final : public TagCodec { + public: + OptionalTag(tracing::Optional Tags::*field, + std::vector rendered) + : field_(field), rendered_(std::move(rendered)) {} + + std::uint64_t read(const void* tags) const override { + const auto& value = static_cast(tags)->*field_; + return value ? static_cast(*value) + 1 : 0; + } + + std::string render(std::uint64_t value) const override { + return value == 0 ? std::string() : rendered_[value - 1]; + } + + private: + tracing::Optional Tags::*field_; + std::vector rendered_; +}; + +// A TagString field. The value is the string's id. +template +class StringTag final : public TagCodec { + public: + StringTag(TagString Tags::*field, std::string name) + : field_(field), name_(std::move(name)) {} + + std::uint64_t read(const void* tags) const override { + return (static_cast(tags)->*field_).id(); + } + + std::string render(std::uint64_t value) const override { + return name_ + ":" + interned_string(value); + } + + private: + TagString Tags::*field_; + std::string name_; +}; + +template +constexpr std::uint64_t enum_value_count() { + return std::tuple_size< + std::decay_t>::value; +} + +template +std::vector enum_value_names() { + std::vector names; + for (const char* name : tag_value_names(Enum{})) names.emplace_back(name); + return names; +} + +// One tag of a metric. Build it with tag(). The tag's values are numbered +// from 0 to ValueCount - 1. +template +struct TagField { + using TagStruct = Tags; + static constexpr std::uint64_t value_count = ValueCount; + std::unique_ptr codec; +}; + +// True if each combination of the fields' values has its own SeriesId. +template +constexpr bool fits_in_series_id(const std::tuple*) { + std::uint64_t combinations = 1; + for (std::uint64_t count : + std::initializer_list{Fields::value_count...}) { + if (count == 0 || + combinations > std::numeric_limits::max() / count) { + return false; + } + combinations *= count; + } + return true; +} + +// Tags of a metric that has only fixed tags. +struct NoTags { + static std::tuple<> tag_fields() { return {}; } +}; + +// One series of a metric: the metric, the series' tags and its value. +template +struct MetricSeries { + Metric metric; + std::vector tags; + typename Metric::Value value; +}; + +class MetricRegistry; + +// The integer of each series. Counters add the values recorded for a series; +// rates keep the last one. Thread-safe. +template +class SeriesIntegers { + public: + using Value = std::uint64_t; + + void record(SeriesId series, std::uint64_t value) { + std::lock_guard lock(mutex_); + Value& current = values_[series]; + current = keep_last ? value : current + value; + } + + std::vector> take() { + std::unordered_map taken; + { + std::lock_guard lock(mutex_); + taken.swap(values_); + } + return {taken.begin(), taken.end()}; + } + + private: + std::mutex mutex_; + std::unordered_map values_; +}; + +// The sketch of each series. Recording adds the value to it. Thread-safe. +class SeriesSketches { + public: + using Value = EncodedSketch; + + SeriesSketches(); + ~SeriesSketches(); + + void record(SeriesId series, std::uint64_t value); + std::vector> take(); + + private: + struct Impl; + std::unique_ptr impl_; +}; + +// Everything about a metric handle that depends neither on its Tags type nor +// on how it stores its values. +template +class MetricBase { + public: + // Removes the series recorded so far, and appends them to `series`. + virtual void take_series(std::vector>& series) = 0; + + protected: + // Handles are not deleted through MetricBase. + ~MetricBase() = default; + + MetricBase(Metric metric, std::vector fixed_tags, + std::vector value_counts, + std::vector> tags); + + const Metric& metric() const { return metric_; } + // The series of the tag struct `*tags`. Empty if a value is out of range. + tracing::Optional series_id(const void* tags) const; + // The fixed tags, then the tags of series `id` that are sent. + std::vector series_tags(SeriesId id) const; + + private: + Metric metric_; + std::vector fixed_tags_; + std::vector value_counts_; + std::vector> tags_; + std::vector strides_; +}; + +// A metric registered with all its tags. Only a MetricRegistry creates them. +// `Store` keeps the value of each series: record() combines a new value into +// it, and take() removes them. record() is thread-safe. +template +class MetricHandle final : public MetricBase { + static_assert( + fits_in_series_id(static_cast(nullptr)), + "Too many combinations of tag values for a 64-bit SeriesId"); + static_assert( + std::is_same_v() + .take())::value_type::second_type, + typename Metric::Value>, + "The store's values must have the metric's Value type"); + + public: + void record(const Tags& tags, std::uint64_t value) { + if (const auto series = this->series_id(&tags)) { + store_.record(*series, value); + } + } + + void take_series(std::vector>& series) override { + for (auto& [id, value] : store_.take()) { + series.push_back( + {this->metric(), this->series_tags(id), std::move(value)}); + } + } + + private: + friend class MetricRegistry; + + MetricHandle(Metric metric, std::vector fixed_tags) + : MetricHandle(std::move(metric), std::move(fixed_tags), + Tags::tag_fields()) {} + + // The codecs read `Tags` structs, so every field must be one of Tags. + template + MetricHandle(Metric metric, std::vector fixed_tags, + std::tuple fields) + : MetricBase(std::move(metric), std::move(fixed_tags), + {Fields::value_count...}, + codecs(std::move(fields))) { + static_assert((std::is_same_v && ...), + "tag_fields() must only bind fields of its own struct"); + } + + template + static std::vector> codecs( + std::tuple fields) { + std::vector> codecs; + std::apply( + [&codecs](auto&... field) { + (codecs.push_back(std::move(field.codec)), ...); + }, + fields); + return codecs; + } + + Store store_; +}; + +} // namespace details + +template +details::TagField tag(const std::string& name, bool Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, {"false", "true"}))}; +} + +template >> +details::TagField()> tag( + const std::string& name, Enum Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, details::enum_value_names()))}; +} + +// An empty field is not sent. +template +details::TagField() + 1> tag( + const std::string& name, tracing::Optional Tags::*field) { + return {std::make_unique>( + field, details::render_names(name, details::enum_value_names()))}; +} + +template +details::TagField tag(const std::string& name, + TagString Tags::*field) { + return {std::make_unique>(field, name)}; +} + +// Recording a value adds it to the series' count. +template +using CounterHandle = + details::MetricHandle>; + +// Recording a value replaces the series' rate. +template +using RateHandle = + details::MetricHandle>; + +// Recording a value adds it to the series' sketch. +template +using DistributionHandle = + details::MetricHandle; + +namespace details { + +// Creates metric handles, and takes the series of those still in use. The +// registry holds only weak references: a handle that its caller drops is +// forgotten, with the values it recorded since the last take. Creating and +// taking lock the registry; recording does not. +class MetricRegistry { + public: + template + std::shared_ptr> counter( + Counter metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), std::move(fixed_tags)); + } + + template + std::shared_ptr> rate( + Rate metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), std::move(fixed_tags)); + } + + template + std::shared_ptr> distribution( + Distribution metric, std::vector fixed_tags = {}) { + return add>(std::move(metric), + std::move(fixed_tags)); + } + + // Removes and returns the series that the handles of `Metric` recorded + // since the last call. Forgets the handles that were dropped. + template + std::vector> take() { + std::vector> series; + std::lock_guard lock(mutex_); + auto& handles = std::get>(handles_); + for (const auto& weak_handle : handles) { + if (const auto handle = weak_handle.lock()) handle->take_series(series); + } + handles.erase(std::remove_if(handles.begin(), handles.end(), + [](const auto& weak_handle) { + return weak_handle.expired(); + }), + handles.end()); + return series; + } + + private: + template + using Handles = std::vector>>; + + template + std::shared_ptr add(Metric metric, + std::vector fixed_tags) { + std::shared_ptr handle( + new Handle(std::move(metric), std::move(fixed_tags))); + std::lock_guard lock(mutex_); + std::get>(handles_).push_back(handle); + return handle; + } + + std::mutex mutex_; + std::tuple, Handles, Handles> handles_; +}; + +} // namespace details +} // namespace datadog::telemetry diff --git a/include/datadog/telemetry/metrics.h b/include/datadog/telemetry/metrics.h index 3cca54e3..d83beeb4 100644 --- a/include/datadog/telemetry/metrics.h +++ b/include/datadog/telemetry/metrics.h @@ -1,6 +1,8 @@ #pragma once +#include #include +#include namespace datadog { namespace telemetry { @@ -9,11 +11,18 @@ namespace details { enum class MetricType : char { counter, rate, distribution }; } +/// A DDSketch protobuf message, as bytes. +using EncodedSketch = std::string; + /// TODO: pre-compute hash? template struct Metric final { /// The type of the metric. static constexpr details::MetricType type = T; + /// The value of one series: a count or a rate, or the sketch of a + /// distribution. + using Value = std::conditional_t; /// The name of the metric that will be published. A transformation occurs /// based on the name and whether it is "common" or "language-specific" when /// it is recorded. diff --git a/include/datadog/telemetry/telemetry.h b/include/datadog/telemetry/telemetry.h index c0da7bb6..f45f0ec6 100644 --- a/include/datadog/telemetry/telemetry.h +++ b/include/datadog/telemetry/telemetry.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -115,47 +116,40 @@ void error(std::string message); void error(std::string message, std::string stacktrace); } // namespace log +namespace details { + +/// The registry of the running telemetry, or null if telemetry is not running. +MetricRegistry* metric_registry(); + +/// Calls `create` with the registry of the running telemetry. If telemetry is +/// not running, uses a registry that is never sent instead. +template +auto create_handle(const Create& create) { + if (MetricRegistry* registry = metric_registry()) return create(*registry); + MetricRegistry never_sent; + return create(never_sent); +} + +} // namespace details + /// The `counter` namespace provides functions to track values. /// Counters can be useful for tracking the total number of an event occurring /// in one time interval. For example, the amount of requests, errors or jobs /// processed every 10 seconds. namespace counter { -/// Increments the specified counter by 1. -/// -/// @param `counter` the counter to increment. -void increment(const Counter& counter); - -/// Increments the specified counter by 1. -/// -/// @param `counter` the counter to increment. -/// @param `tags` the distribution tags. -void increment(const Counter& counter, const std::vector& tags); - -/// Decrements the specified counter by 1. -/// -/// @param `counter` the counter to decrement. -void decrement(const Counter& counter); - -/// Decrements the specified counter by 1. +/// Creates a counter handle, sent by telemetry. Call it after `init`. Without +/// telemetry, the handle records values that are never sent. /// -/// @param `counter` the counter to decrement. -/// @param `tags` the distribution tags. -void decrement(const Counter& counter, const std::vector& tags); - -/// Sets the counter to a specific value. -/// -/// @param `counter` the counter to update. -/// @param `value` the value to assign to the counter. -void set(const Counter& counter, uint64_t value); - -/// Sets the counter to a specific value. -/// -/// @param `counter` the counter to update. -/// @param `tags` the distribution tags. -/// @param `value` the value to assign to the counter. -void set(const Counter& counter, const std::vector& tags, - uint64_t value); +/// @param `metric` the counter. +/// @param `fixed_tags` tags sent with every point, as "name:value". +template +std::shared_ptr> create( + Counter metric, std::vector fixed_tags = {}) { + return details::create_handle([&](details::MetricRegistry& registry) { + return registry.counter(std::move(metric), std::move(fixed_tags)); + }); +} } // namespace counter @@ -164,18 +158,18 @@ void set(const Counter& counter, const std::vector& tags, /// one time interval. For example, the number of requests per second. namespace rate { -/// Sets the rate to a specific value. +/// Creates a rate handle, sent by telemetry. Call it after `init`. Without +/// telemetry, the handle records values that are never sent. /// -/// @param `rate` the rate to update. -/// @param `value` the value to assign to the counter. -void set(const Rate& rate, uint64_t value); - -/// Sets the rate to a specific value. -/// -/// @param `rate` the rate to update. -/// @param `tags` the distribution tags. -/// @param `value` the value to assign to the counter. -void set(const Rate& rate, const std::vector&, uint64_t value); +/// @param `metric` the rate. +/// @param `fixed_tags` tags sent with every point, as "name:value". +template +std::shared_ptr> create( + Rate metric, std::vector fixed_tags = {}) { + return details::create_handle([&](details::MetricRegistry& registry) { + return registry.rate(std::move(metric), std::move(fixed_tags)); + }); +} } // namespace rate @@ -184,19 +178,20 @@ void set(const Rate& rate, const std::vector&, uint64_t value); /// payload sizes. namespace distribution { -/// Adds a value to the distribution. -/// -/// @param `distribution` the distribution to update. -/// @param `value` the value to add to the distribution. -void add(const Distribution& distribution, uint64_t value); - -/// Adds a value to the distribution. -/// -/// @param `distribution` the distribution to update. -/// @param `tags` the distribution tags. -/// @param `value` the value to add to the distribution. -void add(const Distribution& distribution, const std::vector& tags, - uint64_t value); +/// Creates a distribution handle, sent by telemetry as DDSketches. Call it +/// after `init`. Without telemetry, the handle records values that are never +/// sent. +/// +/// @param `metric` the distribution. +/// @param `fixed_tags` tags sent with every series, as "name:value". +template +std::shared_ptr> create( + Distribution metric, std::vector fixed_tags = {}) { + return details::create_handle([&](details::MetricRegistry& registry) { + return registry.distribution(std::move(metric), + std::move(fixed_tags)); + }); +} } // namespace distribution diff --git a/src/datadog/base64.cpp b/src/datadog/base64.cpp index 35aa4833..fb52f17c 100644 --- a/src/datadog/base64.cpp +++ b/src/datadog/base64.cpp @@ -28,6 +28,12 @@ constexpr uint8_t k_base64_table[] = { _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _}; +namespace { + +void append_encoded_group(std::string& output, StringView group); + +} // namespace + std::string base64_decode(StringView input) { const size_t in_size = input.size(); @@ -84,5 +90,39 @@ std::string base64_decode(StringView input) { return output; } +std::string base64_encode(StringView input) { + std::string output; + output.reserve((input.size() + 2) / 3 * 4); + for (size_t offset = 0; offset < input.size(); offset += 3) { + append_encoded_group(output, input.substr(offset, 3)); + } + return output; +} + +namespace { + +constexpr char k_base64_alphabet[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// Appends the 4 characters for a group of 1 to 3 bytes. Missing bytes become +// '=' padding. +void append_encoded_group(std::string& output, StringView group) { + uint32_t bits = 0; + for (size_t position = 0; position < 3; ++position) { + bits <<= 8; + if (position < group.size()) { + bits |= static_cast(group[position]); + } + } + const size_t encoded_chars = group.size() + 1; + for (size_t position = 0; position < 4; ++position) { + const uint32_t sextet = (bits >> (18 - 6 * position)) & 0x3F; + output.push_back(position < encoded_chars ? k_base64_alphabet[sextet] + : '='); + } +} + +} // namespace + } // namespace tracing } // namespace datadog diff --git a/src/datadog/base64.h b/src/datadog/base64.h index aa56c925..4064722f 100644 --- a/src/datadog/base64.h +++ b/src/datadog/base64.h @@ -11,5 +11,8 @@ namespace tracing { // `input` is not padded, then return the empty string instead. std::string base64_decode(StringView input); +// Return the padded base64 encoding of the specified `input`. +std::string base64_encode(StringView input); + } // namespace tracing } // namespace datadog diff --git a/src/datadog/datadog_agent.cpp b/src/datadog/datadog_agent.cpp index fe1db162..846466b8 100644 --- a/src/datadog/datadog_agent.cpp +++ b/src/datadog/datadog_agent.cpp @@ -261,11 +261,12 @@ void DatadogAgent::flush() { auto encode_result = msgpack_encode(body, trace_chunks); auto end = std::chrono::steady_clock::now(); - telemetry::distribution::add( - metrics::tracer::trace_chunk_serialization_duration, - std::chrono::duration_cast(end - beg).count()); - telemetry::distribution::add(metrics::tracer::trace_chunk_serialized_bytes, - static_cast(body.size())); + metrics::tracer_metrics().trace_chunk_serialization_duration->record( + {}, static_cast( + std::chrono::duration_cast(end - beg) + .count())); + metrics::tracer_metrics().trace_chunk_serialized_bytes->record( + {}, static_cast(body.size())); if (auto* error = encode_result.if_error()) { logger_->log_error(*error); @@ -295,21 +296,9 @@ void DatadogAgent::flush() { logger = logger_](int response_status, const DictReader& /*response_headers*/, std::string response_body) { - if (response_status >= 500) { - telemetry::counter::increment(metrics::tracer::api::responses, - {"status_code:5xx"}); - } else if (response_status >= 400) { - telemetry::counter::increment(metrics::tracer::api::responses, - {"status_code:4xx"}); - } else if (response_status >= 300) { - telemetry::counter::increment(metrics::tracer::api::responses, - {"status_code:3xx"}); - } else if (response_status >= 200) { - telemetry::counter::increment(metrics::tracer::api::responses, - {"status_code:2xx"}); - } else if (response_status >= 100) { - telemetry::counter::increment(metrics::tracer::api::responses, - {"status_code:1xx"}); + if (const auto tags = + telemetry::StatusTags::from_http_status(response_status)) { + metrics::tracer_metrics().api_responses->record(*tags, 1); } if (response_status != 200) { logger->log_error([&](auto& stream) { @@ -347,15 +336,14 @@ void DatadogAgent::flush() { // request or retrieving the response. It's invoked // asynchronously. auto on_error = [logger = logger_](Error error) { - telemetry::counter::increment(metrics::tracer::api::errors, - {"type:network"}); + metrics::tracer_metrics().api_errors->record({}, 1); logger->log_error(error.with_prefix( "Error occurred during HTTP request for submitting traces: ")); }; - telemetry::counter::increment(metrics::tracer::api::requests); - telemetry::distribution::add(metrics::tracer::api::bytes_sent, - static_cast(body.size())); + metrics::tracer_metrics().api_requests->record({}, 1); + metrics::tracer_metrics().api_bytes_sent->record( + {}, static_cast(body.size())); auto post_result = http_client_->post(traces_endpoint_, std::move(set_request_headers), @@ -363,8 +351,7 @@ void DatadogAgent::flush() { std::move(on_error), clock_().tick + request_timeout_); if (auto* error = post_result.if_error()) { // NOTE(@dmehala): `technical` is a better kind of errors. - telemetry::counter::increment(metrics::tracer::api::errors, - {"type:network"}); + metrics::tracer_metrics().api_errors->record({}, 1); logger_->log_error( error->with_prefix("Unexpected error submitting traces: ")); } diff --git a/src/datadog/telemetry/log.h b/src/datadog/telemetry/log.h index ff0c5814..eec96c62 100644 --- a/src/datadog/telemetry/log.h +++ b/src/datadog/telemetry/log.h @@ -1,12 +1,18 @@ #include #include +#include #include namespace datadog::telemetry { enum class LogLevel : char { ERROR, WARNING }; +// The names of the `level` tag of the logs_created metric. +constexpr std::array tag_value_names(LogLevel) { + return {"error", "warning"}; +} + struct LogMessage final { std::string message; LogLevel level; diff --git a/src/datadog/telemetry/metric_handle.cpp b/src/datadog/telemetry/metric_handle.cpp new file mode 100644 index 00000000..f1e0574e --- /dev/null +++ b/src/datadog/telemetry/metric_handle.cpp @@ -0,0 +1,163 @@ +#include + +#include "log_binned_distr.h" + +namespace datadog::telemetry { +namespace { + +// Id of every new string once the table is full. +constexpr std::uint16_t overflow_id = 0xFFFF; + +// The strings of TagString values. Id 0 is the empty string. +class StringTable { + public: + static StringTable& instance() { + static StringTable table; + return table; + } + + std::uint16_t intern(tracing::StringView value); + std::string value(std::uint16_t id); + + private: + StringTable() { add(""); } + std::uint16_t add(const std::string& value); + + std::mutex mutex_; + std::vector strings_; + std::unordered_map ids_; +}; + +std::vector series_id_strides( + const std::vector& value_counts); + +} // namespace + +TagString::TagString(tracing::StringView value) + : id_(StringTable::instance().intern(value)) {} + +std::string TagString::value() const { return details::interned_string(id_); } + +namespace details { + +std::string interned_string(std::uint64_t id) { + return StringTable::instance().value(static_cast(id)); +} + +std::vector render_names( + const std::string& name, const std::vector& value_names) { + std::vector rendered; + for (const std::string& value_name : value_names) { + rendered.push_back(name + ":" + value_name); + } + return rendered; +} + +template +MetricBase::MetricBase( + Metric metric, std::vector fixed_tags, + std::vector value_counts, + std::vector> tags) + : metric_(std::move(metric)), + fixed_tags_(std::move(fixed_tags)), + value_counts_(std::move(value_counts)), + tags_(std::move(tags)), + strides_(series_id_strides(value_counts_)) {} + +template +tracing::Optional MetricBase::series_id( + const void* tags) const { + SeriesId id = 0; + for (std::size_t index = 0; index < tags_.size(); ++index) { + const std::uint64_t value = tags_[index]->read(tags); + if (value >= value_counts_[index]) return tracing::nullopt; + id += value * strides_[index]; + } + return id; +} + +template +std::vector MetricBase::series_tags(SeriesId id) const { + std::vector tags = fixed_tags_; + for (std::size_t index = 0; index < tags_.size(); ++index) { + const std::uint64_t value = id / strides_[index] % value_counts_[index]; + std::string rendered = tags_[index]->render(value); + if (!rendered.empty()) tags.push_back(std::move(rendered)); + } + return tags; +} + +template class MetricBase; +template class MetricBase; +template class MetricBase; + +struct SeriesSketches::Impl { + std::mutex mutex; + std::unordered_map sketches; +}; + +SeriesSketches::SeriesSketches() : impl_(std::make_unique()) {} + +SeriesSketches::~SeriesSketches() = default; + +void SeriesSketches::record(SeriesId series, std::uint64_t value) { + std::lock_guard lock(impl_->mutex); + impl_->sketches[series].record(static_cast(value)); +} + +std::vector> SeriesSketches::take() { + std::unordered_map taken; + { + std::lock_guard lock(impl_->mutex); + taken.swap(impl_->sketches); + } + std::vector> encoded; + for (const auto& [series, sketch] : taken) { + encoded.emplace_back(series, sketch.encode_protobuf()); + } + return encoded; +} + +} // namespace details + +namespace { + +std::uint16_t StringTable::intern(tracing::StringView value) { + const std::string key(value); + std::lock_guard lock(mutex_); + if (const auto found = ids_.find(key); found != ids_.end()) { + return found->second; + } + if (strings_.size() >= overflow_id) return overflow_id; + return add(key); +} + +std::string StringTable::value(std::uint16_t id) { + if (id == overflow_id) return "other"; + std::lock_guard lock(mutex_); + return id < strings_.size() ? strings_[id] : std::string(); +} + +// Expects the lock to be held, or the table to be under construction. +std::uint16_t StringTable::add(const std::string& value) { + const auto id = static_cast(strings_.size()); + strings_.push_back(value); + ids_.emplace(value, id); + return id; +} + +// The last tag has stride 1. Each other tag's stride is the number of +// combinations of the values of the tags after it. +std::vector series_id_strides( + const std::vector& value_counts) { + std::vector strides(value_counts.size()); + details::SeriesId stride = 1; + for (std::size_t index = value_counts.size(); index-- > 0;) { + strides[index] = stride; + stride *= value_counts[index]; + } + return strides; +} + +} // namespace +} // namespace datadog::telemetry diff --git a/src/datadog/telemetry/status_tags.h b/src/datadog/telemetry/status_tags.h new file mode 100644 index 00000000..fd2bfc74 --- /dev/null +++ b/src/datadog/telemetry/status_tags.h @@ -0,0 +1,44 @@ +#pragma once + +// The `status_code` tag of the metrics that count HTTP responses. + +#include +#include + +#include +#include + +namespace datadog::telemetry { + +enum class StatusClass { + informational, + success, + redirection, + client_error, + server_error +}; + +constexpr std::array tag_value_names(StatusClass) { + return {"1xx", "2xx", "3xx", "4xx", "5xx"}; +} + +struct StatusTags { + StatusClass status_code = StatusClass::success; + + // The class of an HTTP status, such as 4xx for 404. Empty for a status + // below 100. + static tracing::Optional from_http_status(int status) { + if (status >= 500) return StatusTags{StatusClass::server_error}; + if (status >= 400) return StatusTags{StatusClass::client_error}; + if (status >= 300) return StatusTags{StatusClass::redirection}; + if (status >= 200) return StatusTags{StatusClass::success}; + if (status >= 100) return StatusTags{StatusClass::informational}; + return tracing::nullopt; + } + + static auto tag_fields() { + return std::tuple{tag("status_code", &StatusTags::status_code)}; + } +}; + +} // namespace datadog::telemetry diff --git a/src/datadog/telemetry/telemetry.cpp b/src/datadog/telemetry/telemetry.cpp index fbdb7099..9ebfe3d8 100644 --- a/src/datadog/telemetry/telemetry.cpp +++ b/src/datadog/telemetry/telemetry.cpp @@ -109,6 +109,17 @@ void capture_product_change(const Product& product) { instance()); } +details::MetricRegistry* details::metric_registry() { + return std::visit( + details::Overload{ + [](std::shared_ptr& telemetry) -> MetricRegistry* { + return &telemetry->metrics(); + }, + [](NoopTelemetry) -> MetricRegistry* { return nullptr; }, + }, + instance()); +} + namespace log { void warning(std::string message) { std::visit(details::Overload{ @@ -141,116 +152,4 @@ void error(std::string message, std::string stacktrace) { } } // namespace log -namespace counter { -void increment(const Counter& counter) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->increment_counter(counter); - }, - [](auto&&) {}, - }, - instance()); -} - -void increment(const Counter& counter, const std::vector& tags) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->increment_counter(counter, tags); - }, - [](auto&&) {}, - }, - instance()); -} - -void decrement(const Counter& counter) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->decrement_counter(counter); - }, - [](auto&&) {}, - }, - instance()); -} - -void decrement(const Counter& counter, const std::vector& tags) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->decrement_counter(counter, tags); - }, - [](auto&&) {}, - }, - instance()); -} - -void set(const Counter& counter, uint64_t value) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->set_counter(counter, value); - }, - [](auto&&) {}, - }, - instance()); -} - -void set(const Counter& counter, const std::vector& tags, - uint64_t value) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->set_counter(counter, tags, value); - }, - [](auto&&) {}, - }, - instance()); -} - -} // namespace counter - -namespace rate { -void set(const Rate& rate, uint64_t value) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->set_rate(rate, value); - }, - [](auto&&) {}, - }, - instance()); -} - -void set(const Rate& rate, const std::vector& tags, - uint64_t value) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->set_rate(rate, tags, value); - }, - [](auto&&) {}, - }, - instance()); -} -} // namespace rate - -namespace distribution { - -void add(const Distribution& distribution, uint64_t value) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->add_datapoint(distribution, value); - }, - [](auto&&) {}, - }, - instance()); -} - -void add(const Distribution& distribution, const std::vector& tags, - uint64_t value) { - std::visit(details::Overload{ - [&](std::shared_ptr& telemetry) { - telemetry->add_datapoint(distribution, tags, value); - }, - [](auto&&) {}, - }, - instance()); -} - -} // namespace distribution - } // namespace datadog::telemetry diff --git a/src/datadog/telemetry/telemetry_impl.cpp b/src/datadog/telemetry/telemetry_impl.cpp index 46583039..d8ed40c8 100644 --- a/src/datadog/telemetry/telemetry_impl.cpp +++ b/src/datadog/telemetry/telemetry_impl.cpp @@ -10,6 +10,7 @@ #include +#include "base64.h" #include "datadog_agent.h" #include "platform_util.h" @@ -17,40 +18,6 @@ using namespace datadog::tracing; using namespace std::chrono_literals; namespace datadog::telemetry { -namespace internal_metrics { - -/// The number of logs created with a given log level. Useful for calculating -/// impact for other features (automatic sending of logs). Levels should be one -/// of `debug`, `info`, `warn`, `error`, `critical`. -const telemetry::Counter logs_created{"logs_created", "general", true}; - -/// The number of requests sent to the api endpoint in the agent that errored, -/// tagged by the error type (e.g. `type:timeout`, `type:network`, -/// `type:status_code`) and Endpoint (`endpoint:agent`, `endpoint:agentless`). -const telemetry::Counter errors{"telemetry_api.errors", "telemetry", true}; - -/// The number of requests sent to a telemetry endpoint, regardless of success, -/// tagged by the endpoint (`endpoint:agent`, `endpoint:agentless`). -const telemetry::Counter requests{"telemetry_api.requests", "telemetry", true}; - -/// The number of responses received from the endpoint, tagged with status code -/// (`status_code:200`, `status_code:404`) and endpoint (`endpoint:agent`, -/// `endpoint:agentless`). -const telemetry::Counter responses{"telemetry_api.responses", "telemetry", - true}; - -/// The size of the payload sent to the stats endpoint in bytes, tagged by the -/// endpoint (`endpoint:agent`, `endpoint:agentless`). -const telemetry::Distribution bytes_sent{"telemetry_api.bytes", "telemetry", - true}; - -/// The time it takes to send the payload sent to the endpoint in ms, tagged by -/// the endpoint (`endpoint:agent`, `endpoint:agentless`). -[[maybe_unused]] const telemetry::Distribution request_duration{ - "telemetry_api.ms", "telemetry", true}; - -} // namespace internal_metrics - namespace { constexpr std::chrono::steady_clock::duration request_timeout = 2s; @@ -188,25 +155,28 @@ void encode_metrics( } } -nlohmann::json encode_distributions( - const std::unordered_map, - std::vector>& distributions) { - auto j = nlohmann::json::array(); - - for (const auto& [metric_ctx, values] : distributions) { - auto series = nlohmann::json{ - {"metric", metric_ctx.id.name}, - {"common", metric_ctx.id.common}, - {"namespace", metric_ctx.id.scope}, - {"points", values}, +// The `sketches` payload of the distribution handles' series, or nothing if +// there are none. +Optional sketches_payload( + const std::vector>& distributions) { + if (distributions.empty()) return nullopt; + auto series = nlohmann::json::array(); + for (const auto& distribution : distributions) { + auto encoded = nlohmann::json{ + {"metric", distribution.metric.name}, + {"common", distribution.metric.common}, + {"namespace", distribution.metric.scope}, + {"sketch_b64", base64_encode(distribution.value)}, }; - if (!metric_ctx.tags.empty()) { - series.emplace("tags", metric_ctx.tags); + if (!distribution.tags.empty()) { + encoded.emplace("tags", distribution.tags); } - j.emplace_back(series); + series.emplace_back(std::move(encoded)); } - - return j; + return nlohmann::json{ + {"request_type", "sketches"}, + {"payload", nlohmann::json{{"series", std::move(series)}}}, + }; } nlohmann::json encode_product(const Product& product) { @@ -245,6 +215,16 @@ Telemetry::Telemetry(FinalizedConfiguration config, http_client_(client), clock_(std::move(clock)), scheduler_(event_scheduler), + logs_created_( + metrics_.counter({"logs_created", "general", true})), + api_requests_(metrics_.counter( + {"telemetry_api.requests", "telemetry", true}, {"endpoint:agent"})), + api_responses_(metrics_.counter( + {"telemetry_api.responses", "telemetry", true}, {"endpoint:agent"})), + api_errors_(metrics_.counter({"telemetry_api.errors", "telemetry", true}, + {"type:network", "endpoint:agent"})), + api_bytes_sent_(metrics_.distribution( + {"telemetry_api.bytes", "telemetry", true}, {"endpoint:agent"})), host_info_(get_host_info()) {} std::shared_ptr Telemetry::create( @@ -297,19 +277,19 @@ Telemetry::~Telemetry() { void Telemetry::log_error(std::string message) { if (!config_.report_logs) return; - increment_counter(internal_metrics::logs_created, {"level:error"}); + logs_created_->record({LogLevel::ERROR}, 1); log(std::move(message), LogLevel::ERROR); } void Telemetry::log_error(std::string message, std::string stacktrace) { if (!config_.report_logs) return; - increment_counter(internal_metrics::logs_created, {"level:error"}); + logs_created_->record({LogLevel::ERROR}, 1); log(std::move(message), LogLevel::ERROR, stacktrace); } void Telemetry::log_warning(std::string message) { if (!config_.report_logs) return; - increment_counter(internal_metrics::logs_created, {"level:warning"}); + logs_created_->record({LogLevel::WARNING}, 1); log(std::move(message), LogLevel::WARNING); } @@ -347,17 +327,15 @@ void Telemetry::app_started() { "Error occurred during HTTP request for telemetry: ")); }; - increment_counter(internal_metrics::requests, {"endpoint:agent"}); - add_datapoint(internal_metrics::bytes_sent, {"endpoint:agent"}, - payload.size()); + api_requests_->record({}, 1); + api_bytes_sent_->record({}, payload.size()); auto post_result = http_client_->post(telemetry_endpoint_, on_headers, std::move(payload), std::move(on_response), std::move(on_error), clock_().tick + request_timeout); if (auto* error = post_result.if_error()) { - increment_counter(internal_metrics::errors, - {"type:network", "endpoint:agent"}); + api_errors_->record({}, 1); logger_->log_error( error->with_prefix("Unexpected error submitting telemetry event: ")); } @@ -407,21 +385,8 @@ void Telemetry::send_payload(StringView request_type, std::string payload) { int response_status, const DictReader&, std::string response_body) { if (auto self = weak.lock()) { - if (response_status >= 500) { - self->increment_counter(internal_metrics::responses, - {"status_code:5xx", "endpoint:agent"}); - } else if (response_status >= 400) { - self->increment_counter(internal_metrics::responses, - {"status_code:4xx", "endpoint:agent"}); - } else if (response_status >= 300) { - self->increment_counter(internal_metrics::responses, - {"status_code:3xx", "endpoint:agent"}); - } else if (response_status >= 200) { - self->increment_counter(internal_metrics::responses, - {"status_code:2xx", "endpoint:agent"}); - } else if (response_status >= 100) { - self->increment_counter(internal_metrics::responses, - {"status_code:1xx", "endpoint:agent"}); + if (const auto tags = StatusTags::from_http_status(response_status)) { + self->api_responses_->record(*tags, 1); } } if (response_status < 200 || response_status >= 300) { @@ -436,24 +401,21 @@ void Telemetry::send_payload(StringView request_type, std::string payload) { // Callback for unsuccessful telemetry HTTP requests. auto on_error = [weak = weak_from_this(), logger = logger_](Error error) { if (auto self = weak.lock()) { - self->increment_counter(internal_metrics::errors, - {"type:network", "endpoint:agent"}); + self->api_errors_->record({}, 1); } logger->log_error(error.with_prefix( "Error occurred during HTTP request for telemetry: ")); }; - increment_counter(internal_metrics::requests, {"endpoint:agent"}); - add_datapoint(internal_metrics::bytes_sent, {"endpoint:agent"}, - payload.size()); + api_requests_->record({}, 1); + api_bytes_sent_->record({}, payload.size()); auto post_result = client->post(telemetry_endpoint_, set_telemetry_headers, std::move(payload), std::move(on_response), std::move(on_error), clock_().tick + request_timeout); if (auto* error = post_result.if_error()) { - increment_counter(internal_metrics::errors, - {"type:network", "endpoint:agent"}); + api_errors_->record({}, 1); logger_->log_error( error->with_prefix("Unexpected error submitting telemetry event: ")); } @@ -488,13 +450,6 @@ std::string Telemetry::heartbeat_and_telemetry() { batch_payloads.emplace_back(std::move(heartbeat)); append_product_change(batch_payloads); - std::unordered_map, std::vector> - distributions; - { - std::lock_guard l{distributions_mutex_}; - std::swap(distributions_, distributions); - } - std::unordered_map, MetricSnapshot> counters_snapshot; { std::lock_guard l{counter_mutex_}; @@ -520,18 +475,8 @@ std::string Telemetry::heartbeat_and_telemetry() { batch_payloads.emplace_back(std::move(generate_metrics)); } - if (auto distributions_series = encode_distributions(distributions); - !distributions.empty()) { - auto distributions_json = nlohmann::json{ - {"request_type", "distributions"}, - { - "payload", - nlohmann::json{ - {"series", distributions_series}, - }, - }, - }; - batch_payloads.emplace_back(std::move(distributions_json)); + if (auto sketches = sketches_payload(metrics_.take())) { + batch_payloads.emplace_back(std::move(*sketches)); } std::vector old_logs; @@ -583,18 +528,8 @@ std::string Telemetry::app_closing_payload() { batch_payloads.emplace_back(std::move(generate_metrics)); } - if (auto distributions_series = encode_distributions(distributions_); - !distributions_.empty()) { - auto distributions_json = nlohmann::json{ - {"request_type", "distributions"}, - { - "payload", - nlohmann::json{ - {"series", distributions_series}, - }, - }, - }; - batch_payloads.emplace_back(std::move(distributions_json)); + if (auto sketches = sketches_payload(metrics_.take())) { + batch_payloads.emplace_back(std::move(*sketches)); } if (!logs_.empty()) { @@ -830,26 +765,14 @@ void Telemetry::capture_metrics() { clock_().wall.time_since_epoch()) .count(); - std::unordered_map, uint64_t> counter_snapshot; - { - std::lock_guard l{counter_mutex_}; - std::swap(counter_snapshot, counters_); - } - - for (auto& [counter, value] : counter_snapshot) { - auto& counter_snapshots = counters_snapshot_[counter]; - counter_snapshots.emplace_back(std::make_pair(timepoint, value)); + for (auto& series : metrics_.take()) { + counters_snapshot_[{series.metric, std::move(series.tags)}].emplace_back( + timepoint, series.value); } - std::unordered_map, uint64_t> rate_snapshot; - { - std::lock_guard l{rate_mutex_}; - std::swap(rate_snapshot, rates_); - } - - for (auto& [rate, value] : rate_snapshot) { - auto& rates_snapshots = rates_snapshot_[rate]; - rates_snapshots.emplace_back(std::make_pair(timepoint, value)); + for (auto& series : metrics_.take()) { + rates_snapshot_[{series.metric, std::move(series.tags)}].emplace_back( + timepoint, series.value); } } @@ -863,57 +786,4 @@ void Telemetry::log(std::string message, telemetry::LogLevel level, telemetry::LogMessage{std::move(message), level, stacktrace, timestamp}); } -void Telemetry::increment_counter(const Counter& id) { - increment_counter(id, {}); -} - -void Telemetry::increment_counter(const Counter& id, - const std::vector& tags) { - std::lock_guard l{counter_mutex_}; - counters_[{id, tags}] += 1; -} - -void Telemetry::decrement_counter(const Counter& id) { - decrement_counter(id, {}); -} - -void Telemetry::decrement_counter(const Counter& id, - const std::vector& tags) { - std::lock_guard l{counter_mutex_}; - auto& v = counters_[{id, tags}]; - if (v > 0) v -= 1; -} - -void Telemetry::set_counter(const Counter& id, uint64_t value) { - set_counter(id, {}, value); -} - -void Telemetry::set_counter(const Counter& id, - const std::vector& tags, - uint64_t value) { - std::lock_guard l{counter_mutex_}; - counters_[{id, tags}] = value; -} - -void Telemetry::set_rate(const Rate& id, uint64_t value) { - set_rate(id, {}, value); -} - -void Telemetry::set_rate(const Rate& id, const std::vector& tags, - uint64_t value) { - std::lock_guard l{rate_mutex_}; - rates_[{id, tags}] = value; -} - -void Telemetry::add_datapoint(const Distribution& id, uint64_t value) { - add_datapoint(id, {}, value); -} - -void Telemetry::add_datapoint(const Distribution& id, - const std::vector& tags, - uint64_t value) { - std::lock_guard l{distributions_mutex_}; - distributions_[{id, tags}].emplace_back(value); -} - } // namespace datadog::telemetry diff --git a/src/datadog/telemetry/telemetry_impl.h b/src/datadog/telemetry/telemetry_impl.h index 2e432a32..be039ae0 100644 --- a/src/datadog/telemetry/telemetry_impl.h +++ b/src/datadog/telemetry/telemetry_impl.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -16,11 +17,19 @@ #include "log.h" #include "metric_context.h" #include "platform_util.h" +#include "status_tags.h" namespace datadog::telemetry { using MetricSnapshot = std::vector>; +// The `level` tag of the logs_created metric. +struct LogTags { + LogLevel level = LogLevel::ERROR; + + static auto tag_fields() { return std::tuple{tag("level", &LogTags::level)}; } +}; + // The `Telemetry` class is responsible for handling internal telemetry data to // track Datadog product usage. It _can_ collect and report logs and metrics. // @@ -42,19 +51,21 @@ class Telemetry final : public std::enable_shared_from_this { // Counter std::mutex counter_mutex_; - std::unordered_map, uint64_t> counters_; std::unordered_map, MetricSnapshot> counters_snapshot_; // Rate std::mutex rate_mutex_; - std::unordered_map, uint64_t> rates_; std::unordered_map, MetricSnapshot> rates_snapshot_; - // Distribution - // TODO: split distribution in array of N element? - std::mutex distributions_mutex_; - std::unordered_map, std::vector> - distributions_; + // The metric handles created with this Telemetry. + details::MetricRegistry metrics_; + + // The metrics of this Telemetry itself. + std::shared_ptr> logs_created_; + std::shared_ptr> api_requests_; + std::shared_ptr> api_responses_; + std::shared_ptr> api_errors_; + std::shared_ptr> api_bytes_sent_; // Configuration std::vector configuration_snapshot_; @@ -120,26 +131,8 @@ class Telemetry final : public std::enable_shared_from_this { // After this call the Telemetry object is inert and safe to destroy. void shutdown(); - // Counter - void increment_counter(const Counter& counter); - void increment_counter(const Counter& counter, - const std::vector& tags); - void decrement_counter(const Counter& counter); - void decrement_counter(const Counter& counter, - const std::vector& tags); - void set_counter(const Counter& counter, uint64_t value); - void set_counter(const Counter& counter, const std::vector& tags, - uint64_t value); - - // Rate - void set_rate(const Rate& rate, uint64_t value); - void set_rate(const Rate& rate, const std::vector& tags, - uint64_t value); - - // Distribution - void add_datapoint(const Distribution& distribution, uint64_t value); - void add_datapoint(const Distribution& distribution, - const std::vector& tags, uint64_t value); + // Creates the metric handles that this Telemetry sends. + details::MetricRegistry& metrics() { return metrics_; } private: void app_started(); diff --git a/src/datadog/telemetry_metrics.cpp b/src/datadog/telemetry_metrics.cpp index 485de8e1..7aa9ab01 100644 --- a/src/datadog/telemetry_metrics.cpp +++ b/src/datadog/telemetry_metrics.cpp @@ -1,65 +1,72 @@ #include "telemetry_metrics.h" -namespace datadog::tracing::metrics { - -namespace tracer { -const telemetry::Counter spans_created = {"spans_created", "tracers", true}; -const telemetry::Counter spans_dropped = {"spans_dropped", "tracers", true}; -const telemetry::Counter spans_finished = {"spans_finished", "tracers", true}; - -const telemetry::Counter trace_segments_created = {"trace_segments_created", - "tracers", true}; - -const telemetry::Counter trace_segments_closed = {"trace_segments_closed", - "tracers", true}; - -const telemetry::Distribution trace_chunk_size = {"trace_chunk_size", "tracers", - true}; - -const telemetry::Distribution trace_chunk_serialized_bytes = { - "trace_chunk_serialization.bytes", "tracers", true}; - -const telemetry::Distribution trace_chunk_serialization_duration = { - "trace_chunk_serialization.ms", "tracers", true}; - -const telemetry::Counter trace_chunks_enqueued = {"trace_chunks_enqueued", - "tracers", true}; - -const telemetry::Counter trace_chunks_enqueued_for_serialization = { - "trace_chunks_enqueued_for_serialization", "tracers", true}; - -const telemetry::Counter trace_chunks_dropped = {"trace_chunks_dropped", - "tracers", true}; - -const telemetry::Counter trace_chunks_sent = {"trace_chunks_sent", "tracers", - true}; - -const telemetry::Counter context_header_truncated = { - "context_header.truncated", - "tracers", - true, -}; - -namespace api { -const telemetry::Counter requests = {"trace_api.requests", "tracers", true}; -const telemetry::Counter responses = {"trace_api.responses", "tracers", true}; -const telemetry::Distribution bytes_sent = {"trace_api.bytes", "tracers", true}; -const telemetry::Distribution request_duration = {"trace_api.ms", "tracers", - true}; -const telemetry::Counter errors = {"trace_api.errors", "tracers", true}; -} // namespace api - -namespace trace_context { -const telemetry::Counter injected = {"context_header_style.injected", "tracers", - true}; -const telemetry::Counter extracted = {"context_header_style.extracted", - "tracers", true}; -const telemetry::Counter truncated = {"context_header.truncated", "tracers", - true}; -const telemetry::Counter malformed = {"context_header_style.malformed", - "tracers", true}; -} // namespace trace_context - -} // namespace tracer +#include +namespace datadog::tracing::metrics { +namespace { + +TracerMetrics make_tracer_metrics(); + +} // namespace + +// Never destroyed: without `telemetry::shutdown`, Telemetry sends its last +// metrics while static objects are destroyed, and the handles must still be +// there. +const TracerMetrics& tracer_metrics() { + static const TracerMetrics* const metrics = + new TracerMetrics(make_tracer_metrics()); + return *metrics; +} + +namespace { + +using namespace datadog::telemetry; + +TracerMetrics make_tracer_metrics() { + TracerMetrics metrics; + metrics.spans_created = counter::create({"spans_created", "tracers", true}, + {"integration_name:datadog"}); + metrics.spans_dropped = + counter::create({"spans_dropped", "tracers", true}, {"reason:p0_drop"}); + metrics.spans_finished = counter::create({"spans_finished", "tracers", true}, + {"integration_name:datadog"}); + metrics.trace_chunk_size = + distribution::create({"trace_chunk_size", "tracers", true}); + metrics.trace_chunk_serialized_bytes = distribution::create( + {"trace_chunk_serialization.bytes", "tracers", true}); + metrics.trace_chunk_serialization_duration = + distribution::create({"trace_chunk_serialization.ms", "tracers", true}); + metrics.trace_chunks_enqueued = + counter::create({"trace_chunks_enqueued", "tracers", true}); + metrics.trace_chunks_dropped = counter::create( + {"trace_chunks_dropped", "tracers", true}, {"reason:p0_drop"}); + metrics.trace_chunks_sent = + counter::create({"trace_chunks_sent", "tracers", true}); + metrics.trace_segments_created = + counter::create({"trace_segments_created", "tracers", true}); + metrics.trace_segments_closed = + counter::create({"trace_segments_closed", "tracers", true}); + + metrics.api_requests = + counter::create({"trace_api.requests", "tracers", true}); + metrics.api_responses = + counter::create({"trace_api.responses", "tracers", true}); + metrics.api_bytes_sent = + distribution::create({"trace_api.bytes", "tracers", true}); + metrics.api_errors = + counter::create({"trace_api.errors", "tracers", true}, {"type:network"}); + + metrics.context_injected = counter::create( + {"context_header_style.injected", "tracers", true}); + metrics.context_extracted = counter::create( + {"context_header_style.extracted", "tracers", true}); + metrics.context_truncated = counter::create( + {"context_header.truncated", "tracers", true}); + metrics.context_malformed = + counter::create({"context_header_style.malformed", "tracers", true}, + {"header_style:baggage"}); + return metrics; +} + +} // namespace } // namespace datadog::tracing::metrics diff --git a/src/datadog/telemetry_metrics.h b/src/datadog/telemetry_metrics.h index ef0f55d0..b3094956 100644 --- a/src/datadog/telemetry_metrics.h +++ b/src/datadog/telemetry_metrics.h @@ -1,120 +1,135 @@ #pragma once -#include +#include + +#include +#include +#include + +#include "telemetry/status_tags.h" namespace datadog::tracing::metrics { -namespace tracer { - -/// The number of spans created by the tracer, tagged by manual API -/// (`integration_name:datadog`, `integration_name:otel` or -/// `integration_name:opentracing`). -extern const telemetry::Counter spans_created; - -/// The number of spans dropped and the reason for being dropped, for example -/// `reason:p0_drop` (the span was part of a p0 trace that was droped by the -/// tracer), `reason:overfull_buffer` (the local buffer was full, and the span -/// had to be dropped), `reason:serialization_error` (there was an error -/// serializing the span and it had to be dropped) -extern const telemetry::Counter spans_dropped; - -/// The number of spans finished, optionally (if implementation allows) tagged -/// manual API (`integration_name:datadog`, `integration_name:otel` or -/// `integration_name:opentracing`). -extern const telemetry::Counter spans_finished; - -/// The number of spans in the trace chunk when it is enqueued. -extern const telemetry::Distribution trace_chunk_size; - -/// The size in bytes of the serialized trace chunk. -extern const telemetry::Distribution trace_chunk_serialized_bytes; - -/// The time it takes to serialize a trace chunk. -extern const telemetry::Distribution trace_chunk_serialization_duration; - -/// The number of times a trace chunk is enqueued for sampling/serialization. In -/// partial-flush scenarios, multiple trace chunks may be enqueued per trace -/// segment/local trace. -extern const telemetry::Counter trace_chunks_enqueued; - -/// The number of trace chunks kept for serialization. Excludes single-span -/// sampling spans. Tagged by one of `reason:p0_keep` (the trace was a p0 trace -/// that was kept for sending to the agent) or `reason:default` - The tracer is -/// not dropping p0 spans, so the span was enqueued 'by default' for sending to -/// the trace-agent). -extern const telemetry::Counter trace_chunks_enqueued_for_serialization; - -/// The number of trace chunks dropped prior to serialization, tagged by reason. -/// Includes traces which are dropped due to errors, overfull buffers, as well -/// as due to sampling decision. For example `reason:p0_drop` (the span a p0 -/// trace that was droped by the tracer), `reason:overfull_buffer` (the local -/// buffer was full, and the trace chunk had to be dropped), -/// `reason:serialization_error` (there was an error serializing the trace and -/// it had to be dropped). -extern const telemetry::Counter trace_chunks_dropped; - -/// The number of trace chunks attempted to be sent to the backend, regardless -/// of response. -extern const telemetry::Counter trace_chunks_sent; - -/// The number of trace segments (local traces) created, tagged with -/// new/continued depending on whether this is a new trace (no distributed -/// context information) or continued (has distributed context). -extern const telemetry::Counter trace_segments_created; - -/// The number of trace segments (local traces) closed. In non partial flush -/// scenarios, trace_segments_closed == trace_chunks_enqueued. -extern const telemetry::Counter trace_segments_closed; - -namespace api { - -/// The number of requests sent to the trace endpoint in the agent, regardless -/// of success. -extern const telemetry::Counter requests; - -/// The number of responses received from the trace endpoint, tagged with status -/// code, e.g. `status_code:200`, `status_code:404`. May also use -/// `status_code:5xx` for example as a catch-all for 2xx, 3xx, 4xx, 5xx -/// responses. -extern const telemetry::Counter responses; - -/// The size of the payload sent to the endpoint in bytes. -extern const telemetry::Distribution bytes_sent; - -/// The time it takes to flush the trace payload to the agent. Note that this is -/// not the per trace time, this is the per payload time. -extern const telemetry::Distribution request_duration; - -/// The number of requests sent to the trace endpoint in the agent that errored, -/// tagged by the error type (e.g. `type:timeout`, `type:network`, -/// `type:status_code`). -extern const telemetry::Counter errors; - -} // namespace api - -namespace trace_context { - -/// The number of times distributed context is injected into an outgoing span, -/// tagged by header style (`header_style:tracecontext`, `header_style:datadog`, -/// `header_style:b3multi`, `header_style:b3single`, `header_style:baggage`) -extern const telemetry::Counter injected; - -/// The number of times distributed context is successfully extracted from an -/// outgoing span, tagged by header style (`header_style:tracecontext`, -/// `header_style:datadog`, `header_style:b3multi`, `header_style:b3single`, -/// `header_style:baggage`) -extern const telemetry::Counter extracted; - -/// The number of times a context propagation header is truncated, tagged by the -/// reason for truncation (`truncation_reason:baggage_item_count_exceeded`, -/// `truncation_reason:baggage_byte_count_exceeded`) -extern const telemetry::Counter truncated; - -/// The number of times baggage headers are dropped because they're malformed -/// (missing key/value/'='), tagged by header style (`header_style:baggage`) -extern const telemetry::Counter malformed; -} // namespace trace_context - -} // namespace tracer +// Whether a trace segment starts a new trace or continues a distributed one. +enum class Continuation { new_trace, continued }; + +constexpr std::array tag_value_names(Continuation) { + return {"new", "continued"}; +} + +struct SegmentTags { + Continuation new_continued = Continuation::new_trace; + + static auto tag_fields() { + return std::tuple{ + telemetry::tag("new_continued", &SegmentTags::new_continued)}; + } +}; + +// The style of a trace context header. +enum class HeaderStyle { datadog, b3multi, tracecontext, baggage, none }; + +constexpr std::array tag_value_names(HeaderStyle) { + return {"datadog", "b3multi", "tracecontext", "baggage", "none"}; +} + +struct HeaderStyleTags { + HeaderStyle header_style = HeaderStyle::datadog; + + static auto tag_fields() { + return std::tuple{ + telemetry::tag("header_style", &HeaderStyleTags::header_style)}; + } +}; + +// Why a trace context header was truncated. +enum class TruncationReason { + baggage_item_count_exceeded, + baggage_byte_count_exceeded +}; + +constexpr std::array tag_value_names(TruncationReason) { + return {"baggage_item_count_exceeded", "baggage_byte_count_exceeded"}; +} + +struct TruncationTags { + TruncationReason truncation_reason = + TruncationReason::baggage_item_count_exceeded; + + static auto tag_fields() { + return std::tuple{telemetry::tag("truncation_reason", + &TruncationTags::truncation_reason)}; + } +}; + +// The metrics of the tracer. Every tracer of a process shares them. +struct TracerMetrics { + /// The number of spans created by the tracer, tagged by manual API + /// (`integration_name:datadog`). + std::shared_ptr> spans_created; + /// The number of spans dropped and the reason for being dropped + /// (`reason:p0_drop`: the span was part of a p0 trace that was dropped by + /// the tracer). + std::shared_ptr> spans_dropped; + /// The number of spans finished, tagged by manual API + /// (`integration_name:datadog`). + std::shared_ptr> spans_finished; + /// The number of spans in the trace chunk when it is enqueued. + std::shared_ptr> trace_chunk_size; + /// The size in bytes of the serialized trace chunk. + std::shared_ptr> trace_chunk_serialized_bytes; + /// The time it takes to serialize a trace chunk. + std::shared_ptr> + trace_chunk_serialization_duration; + /// The number of times a trace chunk is enqueued for sampling/serialization. + /// In partial-flush scenarios, multiple trace chunks may be enqueued per + /// trace segment/local trace. + std::shared_ptr> trace_chunks_enqueued; + /// The number of trace chunks dropped prior to serialization, tagged by + /// reason (`reason:p0_drop`: the trace was a p0 trace that was dropped by + /// the tracer). + std::shared_ptr> trace_chunks_dropped; + /// The number of trace chunks attempted to be sent to the backend, + /// regardless of response. + std::shared_ptr> trace_chunks_sent; + /// The number of trace segments (local traces) created, tagged with + /// new/continued depending on whether this is a new trace (no distributed + /// context information) or continued (has distributed context). + std::shared_ptr> trace_segments_created; + /// The number of trace segments (local traces) closed. In non partial flush + /// scenarios, trace_segments_closed == trace_chunks_enqueued. + std::shared_ptr> trace_segments_closed; + + /// The number of requests sent to the trace endpoint in the agent, + /// regardless of success. + std::shared_ptr> api_requests; + /// The number of responses received from the trace endpoint, tagged with + /// the status code class (`status_code:2xx` and so on). + std::shared_ptr> + api_responses; + /// The size of the payload sent to the endpoint in bytes. + std::shared_ptr> api_bytes_sent; + /// The number of requests sent to the trace endpoint in the agent that + /// errored, tagged by the error type (`type:network`). + std::shared_ptr> api_errors; + + /// The number of times distributed context is injected into an outgoing + /// span, tagged by header style. + std::shared_ptr> context_injected; + /// The number of times distributed context is successfully extracted from + /// an incoming request, tagged by header style. + std::shared_ptr> context_extracted; + /// The number of times a context propagation header is truncated, tagged by + /// the reason for truncation. + std::shared_ptr> context_truncated; + /// The number of times baggage headers are dropped because they're + /// malformed (missing key/value/'='), tagged by header style + /// (`header_style:baggage`). + std::shared_ptr> context_malformed; +}; + +// The metrics of the tracer, created on first use. Call it only after +// `telemetry::init`: before, the metrics would never be sent. +const TracerMetrics& tracer_metrics(); } // namespace datadog::tracing::metrics diff --git a/src/datadog/trace_segment.cpp b/src/datadog/trace_segment.cpp index fa0f8965..746a5fad 100644 --- a/src/datadog/trace_segment.cpp +++ b/src/datadog/trace_segment.cpp @@ -304,8 +304,7 @@ Optional TraceSegment::w3c_link_context( Logger& TraceSegment::logger() const { return *logger_; } void TraceSegment::register_span(std::unique_ptr span) { - telemetry::counter::increment(metrics::tracer::spans_created, - {"integration_name:datadog"}); + metrics::tracer_metrics().spans_created->record({}, 1); std::lock_guard lock(mutex_); assert(spans_.empty() || num_finished_spans_ < spans_.size()); @@ -314,8 +313,7 @@ void TraceSegment::register_span(std::unique_ptr span) { void TraceSegment::span_finished() { { - telemetry::counter::increment(metrics::tracer::spans_finished, - {"integration_name:datadog"}); + metrics::tracer_metrics().spans_finished->record({}, 1); std::lock_guard lock(mutex_); ++num_finished_spans_; assert(num_finished_spans_ <= spans_.size()); @@ -324,7 +322,7 @@ void TraceSegment::span_finished() { } } - telemetry::counter::increment(metrics::tracer::trace_chunks_enqueued); + metrics::tracer_metrics().trace_chunks_enqueued->record({}, 1); // We don't need the lock anymore. There's nobody left to call our methods. // On the other hand, there's nobody left to contend for the mutex, so it @@ -335,8 +333,7 @@ void TraceSegment::span_finished() { // All of our spans are finished. Run the span sampler, finalize the spans, // and then send the spans to the collector. if (sampling_decision_->priority <= 0) { - telemetry::counter::increment(metrics::tracer::trace_chunks_dropped, - {"reason:p0_drop"}); + metrics::tracer_metrics().trace_chunks_dropped->record({}, 1); // Span sampling happens when the trace is dropped. for (const auto& span_ptr : spans_) { SpanData& span = *span_ptr; @@ -346,8 +343,7 @@ void TraceSegment::span_finished() { } const SamplingDecision decision = rule->decide(span); if (decision.priority <= 0) { - telemetry::counter::increment(metrics::tracer::spans_dropped, - {"reason:p0_drop"}); + metrics::tracer_metrics().spans_dropped->record({}, 1); continue; } @@ -408,10 +404,9 @@ void TraceSegment::span_finished() { maybe_calculate_http_endpoint(resource_renaming_mode_, local_root); if (config_manager_->report_traces()) { - telemetry::distribution::add(metrics::tracer::trace_chunk_size, - spans_.size()); + metrics::tracer_metrics().trace_chunk_size->record({}, spans_.size()); - telemetry::counter::increment(metrics::tracer::trace_chunks_sent); + metrics::tracer_metrics().trace_chunks_sent->record({}, 1); const auto result = collector_->send(std::move(spans_), trace_sampler_); if (auto* error = result.if_error()) { logger_->log_error( @@ -419,7 +414,7 @@ void TraceSegment::span_finished() { } } - telemetry::counter::increment(metrics::tracer::trace_segments_closed); + metrics::tracer_metrics().trace_segments_closed->record({}, 1); } void TraceSegment::override_sampling_priority(SamplingPriority priority) { @@ -562,8 +557,8 @@ bool TraceSegment::inject(DictWriter& writer, const SpanData& span, trace_tags_too_large = true; } - telemetry::counter::increment(metrics::tracer::trace_context::injected, - {"header_style:datadog"}); + metrics::tracer_metrics().context_injected->record( + {metrics::HeaderStyle::datadog}, 1); break; case PropagationStyle::B3: if (span.trace_id.high) { @@ -581,8 +576,8 @@ bool TraceSegment::inject(DictWriter& writer, const SpanData& span, *logger_)) { trace_tags_too_large = true; } - telemetry::counter::increment(metrics::tracer::trace_context::injected, - {"header_style:b3multi"}); + metrics::tracer_metrics().context_injected->record( + {metrics::HeaderStyle::b3multi}, 1); break; case PropagationStyle::W3C: { const Optional resolved_otel_w3c_tracestate = @@ -597,8 +592,8 @@ bool TraceSegment::inject(DictWriter& writer, const SpanData& span, trace_tags, additional_datadog_w3c_tracestate_, resolved_otel_w3c_tracestate, additional_w3c_tracestate_)); - telemetry::counter::increment(metrics::tracer::trace_context::injected, - {"header_style:tracecontext"}); + metrics::tracer_metrics().context_injected->record( + {metrics::HeaderStyle::tracecontext}, 1); break; } default: diff --git a/src/datadog/tracer.cpp b/src/datadog/tracer.cpp index 4872dcea..72ca6a8c 100644 --- a/src/datadog/tracer.cpp +++ b/src/datadog/tracer.cpp @@ -241,8 +241,8 @@ Span Tracer::create_span(const SpanConfig& config) { } const auto span_data_ptr = span_data.get(); - telemetry::counter::increment(metrics::tracer::trace_segments_created, - {"new_continued:new"}); + metrics::tracer_metrics().trace_segments_created->record( + {metrics::Continuation::new_trace}, 1); const auto segment = std::make_shared( logger_, collector_, config_manager_->trace_sampler(), span_sampler_, defaults, config_manager_, runtime_id_, injection_styles_, hostname_, @@ -282,23 +282,23 @@ Expected Tracer::extract_span(const DictReader& reader, for (const auto style : extraction_styles_) { using Extractor = decltype(&extract_datadog); // function pointer Extractor extract; - std::string extracted_tag; ///< for telemetry + metrics::HeaderStyle header_style; ///< for telemetry switch (style) { case PropagationStyle::DATADOG: extract = &extract_datadog; - extracted_tag = "header_style:datadog"; + header_style = metrics::HeaderStyle::datadog; break; case PropagationStyle::B3: extract = &extract_b3; - extracted_tag = "header_style:b3multi"; + header_style = metrics::HeaderStyle::b3multi; break; case PropagationStyle::W3C: extract = &extract_w3c; - extracted_tag = "header_style:tracecontext"; + header_style = metrics::HeaderStyle::tracecontext; break; default: extract = &extract_none; - extracted_tag = "header_style:none"; + header_style = metrics::HeaderStyle::none; } audited_reader.entries_found.clear(); auto data = extract(audited_reader, span_data->tags, *logger_); @@ -307,8 +307,7 @@ Expected Tracer::extract_span(const DictReader& reader, extraction_error_prefix(style, audited_reader.entries_found)); } - telemetry::counter::increment(metrics::tracer::trace_context::extracted, - {extracted_tag}); + metrics::tracer_metrics().context_extracted->record({header_style}, 1); if (!first_style_with_trace_id && data->trace_id.has_value()) { first_style_with_trace_id = style; @@ -476,8 +475,8 @@ Expected Tracer::extract_span(const DictReader& reader, } const auto span_data_ptr = span_data.get(); - telemetry::counter::increment(metrics::tracer::trace_segments_created, - {"new_continued:continued"}); + metrics::tracer_metrics().trace_segments_created->record( + {metrics::Continuation::continued}, 1); const auto segment = std::make_shared( logger_, collector_, config_manager_->trace_sampler(), span_sampler_, config_manager_->span_defaults(), config_manager_, runtime_id_, @@ -554,12 +553,11 @@ Expected Tracer::extract_baggage( auto maybe_baggage = Baggage::extract(reader, baggage_opts_); if (maybe_baggage) { - telemetry::counter::increment(metrics::tracer::trace_context::extracted, - {"header_style:baggage"}); + metrics::tracer_metrics().context_extracted->record( + {metrics::HeaderStyle::baggage}, 1); } else if (auto err = maybe_baggage.if_error()) { if (err->code == Baggage::Error::MALFORMED_BAGGAGE_HEADER) { - telemetry::counter::increment(metrics::tracer::trace_context::malformed, - {"header_style:baggage"}); + metrics::tracer_metrics().context_malformed->record({}, 1); } } return maybe_baggage; @@ -586,16 +584,14 @@ Expected Tracer::inject(const Baggage& baggage, DictWriter& writer) { err->with_prefix("failed to serialize all baggage items: ")); if (err->code == Error::Code::BAGGAGE_MAXIMUM_BYTES_REACHED) { - telemetry::counter::increment( - metrics::tracer::trace_context::truncated, - {"truncation_reason:baggage_byte_count_exceeded"}); + metrics::tracer_metrics().context_truncated->record( + {metrics::TruncationReason::baggage_byte_count_exceeded}, 1); } else if (err->code == Error::Code::BAGGAGE_MAXIMUM_ITEMS_REACHED) { - telemetry::counter::increment( - metrics::tracer::trace_context::truncated, - {"truncation_reason:baggage_item_count_exceeded"}); + metrics::tracer_metrics().context_truncated->record( + {metrics::TruncationReason::baggage_item_count_exceeded}, 1); } else { - telemetry::counter::increment(metrics::tracer::trace_context::injected, - {"header_style:baggage"}); + metrics::tracer_metrics().context_injected->record( + {metrics::HeaderStyle::baggage}, 1); } } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 148e9e0b..85b9340a 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -21,6 +21,7 @@ add_executable(tests # telemetry test cases telemetry/test_configuration.cpp telemetry/test_log_binned_distr.cpp + telemetry/test_metric_handle.cpp telemetry/test_telemetry.cpp # test cases diff --git a/test/telemetry/test_metric_handle.cpp b/test/telemetry/test_metric_handle.cpp new file mode 100644 index 00000000..df2daa3c --- /dev/null +++ b/test/telemetry/test_metric_handle.cpp @@ -0,0 +1,165 @@ +#include + +#include + +#include "datadog/telemetry/log_binned_distr.h" +#include "test.h" + +using namespace datadog::telemetry; +using datadog::tracing::Optional; + +#define METRIC_HANDLE_TEST(x) TEST_CASE(x, "[telemetry][metric_handle]") + +namespace { + +enum class Step { request_first, request_body }; + +std::array tag_value_names(Step) { + return {"req.first", "req.body"}; +} + +struct RequestTags { + TagString rules_version; + bool blocked = false; + Optional step; + + static auto tag_fields() { + using Self = RequestTags; + return std::tuple{tag("rules_version", &Self::rules_version), + tag("blocked", &Self::blocked), tag("step", &Self::step)}; + } +}; + +// Only the first two values have names. +enum class Size { small, large, unnamed }; + +std::array tag_value_names(Size) { return {"small", "large"}; } + +struct SizeTags { + Size size = Size::small; + + static auto tag_fields() { return std::tuple{tag("size", &SizeTags::size)}; } +}; + +struct TooManyTags { + TagString first, second, third, fourth, fifth; + + static auto tag_fields() { + using Self = TooManyTags; + return std::tuple{tag("first", &Self::first), tag("second", &Self::second), + tag("third", &Self::third), tag("fourth", &Self::fourth), + tag("fifth", &Self::fifth)}; + } +}; + +// A handle for TooManyTags would not compile: 65536^5 combinations do not fit +// in a 64-bit series id. +static_assert(!details::fits_in_series_id( + static_cast(nullptr))); +static_assert(details::fits_in_series_id( + static_cast(nullptr))); + +template +std::map, typename Metric::Value> by_tags( + const std::vector>& series) { + std::map, typename Metric::Value> result; + for (const auto& one_series : series) { + result[one_series.tags] = one_series.value; + } + return result; +} + +std::string sketch_of(std::initializer_list values) { + LogBinnedDistr sketch; + for (double value : values) sketch.record(value); + return sketch.encode_protobuf(); +} + +} // namespace + +METRIC_HANDLE_TEST("a counter without tags has one series") { + details::MetricRegistry registry; + const auto requests = registry.counter({"requests", "tracers", true}, + {"integration_name:datadog"}); + requests->record({}, 1); + requests->record({}, 1); + + const auto series = registry.take(); + REQUIRE(series.size() == 1); + CHECK(series[0].metric.name == "requests"); + CHECK(series[0].tags == std::vector{"integration_name:datadog"}); + CHECK(series[0].value == 2); + CHECK(registry.take().empty()); +} + +METRIC_HANDLE_TEST("each combination of tag values is a series") { + details::MetricRegistry registry; + const auto requests = registry.counter( + {"waf.requests", "appsec", true}, {"waf_version:1.30.1"}); + RequestTags tags; + tags.rules_version = TagString{"1.18.2"}; + requests->record(tags, 1); + tags.blocked = true; + tags.step = Step::request_body; + requests->record(tags, 1); + tags.rules_version = TagString{"1.18.2"}; // the same string, interned again + requests->record(tags, 1); + + using Counts = std::map, std::uint64_t>; + CHECK( + by_tags(registry.take()) == + Counts{ + {{"waf_version:1.30.1", "rules_version:1.18.2", "blocked:false"}, 1}, + {{"waf_version:1.30.1", "rules_version:1.18.2", "blocked:true", + "step:req.body"}, + 2}, + }); +} + +METRIC_HANDLE_TEST("a dropped handle is forgotten") { + details::MetricRegistry registry; + auto requests = + registry.counter({"requests", "tracers", true}, {"version:1"}); + requests->record({}, 1); + requests = registry.counter({"requests", "tracers", true}, {"version:2"}); + requests->record({}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == Counts{{{"version:2"}, 1}}); +} + +METRIC_HANDLE_TEST("a rate keeps its last value") { + details::MetricRegistry registry; + const auto rate = registry.rate({"spans", "tracers", true}); + rate->record({}, 5); + rate->record({}, 3); + CHECK(registry.take().at(0).value == 3); +} + +METRIC_HANDLE_TEST("a distribution has one sketch per series") { + details::MetricRegistry registry; + const auto duration = + registry.distribution({"waf.duration", "appsec", true}); + RequestTags tags; + duration->record(tags, 100); + duration->record(tags, 250); + tags.blocked = true; + duration->record(tags, 7); + + using Sketches = std::map, EncodedSketch>; + CHECK(by_tags(registry.take()) == + Sketches{ + {{"rules_version:", "blocked:false"}, sketch_of({100, 250})}, + {{"rules_version:", "blocked:true"}, sketch_of({7})}, + }); +} + +METRIC_HANDLE_TEST("an enum value without a name is dropped") { + details::MetricRegistry registry; + const auto bodies = registry.counter({"bodies", "appsec", true}); + bodies->record({Size::large}, 1); + bodies->record({Size::unnamed}, 1); + + using Counts = std::map, std::uint64_t>; + CHECK(by_tags(registry.take()) == Counts{{{"size:large"}, 1}}); +} diff --git a/test/telemetry/test_telemetry.cpp b/test/telemetry/test_telemetry.cpp index 9a0cfb41..3491d3bb 100644 --- a/test/telemetry/test_telemetry.cpp +++ b/test/telemetry/test_telemetry.cpp @@ -9,7 +9,9 @@ #include #include "../common/environment.h" +#include "datadog/base64.h" #include "datadog/runtime_id.h" +#include "datadog/telemetry/log_binned_distr.h" #include "datadog/telemetry/telemetry_impl.h" #include "mocks/http_clients.h" #include "mocks/loggers.h" @@ -42,6 +44,30 @@ std::optional find_payload(const nlohmann::json& messages, return std::nullopt; }; +struct ErrorTags { + bool error = false; + + static auto tag_fields() { + return std::tuple{tag("error", &ErrorTags::error)}; + } +}; + +std::string sketch_b64(std::initializer_list values) { + LogBinnedDistr sketch; + for (double value : values) sketch.record(value); + return base64_encode(sketch.encode_protobuf()); +} + +// The series of `payload` in the namespace `scope`. +nlohmann::json series_in(const nlohmann::json& payload, + std::string_view scope) { + auto series = nlohmann::json::array(); + for (const auto& one_series : payload["payload"]["series"]) { + if (one_series["namespace"] == scope) series.push_back(one_series); + } + return series; +} + struct FakeEventScheduler : public EventScheduler { size_t count_tasks = 0; std::function heartbeat_callback = nullptr; @@ -613,357 +639,136 @@ TELEMETRY_IMPLEMENTATION_TEST("Tracer telemetry API") { } SECTION("metrics reporting") { - SECTION("counters are correctly serialized in generate-metrics payload") { + SECTION("counter and rate handles are sent with the metrics") { client->clear(); - /// test cases for counters: - /// - can't decrement below zero. -> is that a telemetry requirements? - /// - rates or counter reset to zero after capture. - const Counter my_counter{"my_counter", "counter-test", true}; - telemetry->increment_counter(my_counter); // = 1 - telemetry->increment_counter(my_counter); // = 2 - telemetry->increment_counter(my_counter); // = 3 - telemetry->decrement_counter(my_counter); // = 2 - scheduler->trigger_metrics_capture(); - - telemetry->increment_counter(my_counter); // = 1 - scheduler->trigger_metrics_capture(); + auto requests = telemetry->metrics().counter( + {"handle_requests", "handle-test", true}, + {"integration_name:datadog"}); + auto rate = + telemetry->metrics().rate({"handle_rate", "handle-test", false}); + requests->record({true}, 1); + requests->record({true}, 2); + rate->record({}, 7); - telemetry->set_counter(my_counter, 42); - telemetry->set_counter(my_counter, {"event:test"}, 100); - telemetry->decrement_counter(my_counter, {"event:test"}); scheduler->trigger_metrics_capture(); - - // Expect 2 series: - // - `my_counter` without tags: 3 datapoint (2, 1, 42) with the same - // timestamp. - // - `my_counter` with `event:test` tags: 1 datapoint (99). scheduler->trigger_heartbeat(); auto message_batch = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch) == true); - REQUIRE(message_batch["payload"].size() >= 2); - - auto generate_metrics = - find_payload(message_batch["payload"], "generate-metrics"); - REQUIRE(generate_metrics.has_value()); - auto payload = (*generate_metrics)["payload"]; - - auto series = payload["series"]; - REQUIRE(series.size() >= 2); - - const auto expected_metrics = nlohmann::json::parse(R"( - [ - { - "common": true, - "metric": "my_counter", - "namespace": "counter-test", - "points": [ - [ 1672484400, 99 ] - ], - "tags": [ "event:test" ], - "type": "count" - }, - { - "common": true, - "metric": "my_counter", - "namespace": "counter-test", - "points": [ - [ 1672484400, 2 ], - [ 1672484400, 1 ], - [ 1672484400, 42 ] - ], - "type": "count" - } - ] - )"); - - for (const auto& s : series) { - if (s["metric"] == "my_counter") { - if (s.contains("tags")) { - CHECK(s == expected_metrics[0]); - } else { - CHECK(s == expected_metrics[1]); - } - } - } - - // Make sure the next heartbeat doesn't contains counters if no - // datapoint has been incremented, decremented or set. - client->clear(); - scheduler->trigger_heartbeat(); - - auto message_batch2 = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch2) == true); - REQUIRE(message_batch2["payload"].size() >= 1); - - CHECK(find_payload(message_batch["payload"], "app-heartbeat")); - } - - SECTION("counters can't go below zero") { - client->clear(); - const Counter positive_counter{"positive_counter", "counter-test2", true}; - telemetry->decrement_counter(positive_counter); // = 0 - telemetry->decrement_counter(positive_counter); // = 0 - telemetry->decrement_counter(positive_counter); // = 0 - - scheduler->trigger_metrics_capture(); - scheduler->trigger_heartbeat(); - - auto message_batch = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch) == true); - REQUIRE(message_batch["payload"].size() >= 2); - auto generate_metrics = find_payload(message_batch["payload"], "generate-metrics"); REQUIRE(generate_metrics); - auto payload = (*generate_metrics)["payload"]; - - auto series = payload["series"]; - REQUIRE(series.size() >= 1); - - const auto expected_metric = nlohmann::json::parse(R"( - { - "common": true, - "metric": "positive_counter", - "namespace": "counter-test2", - "points": [ - [ 1672484400, 0 ] - ], - "type": "count" - } - )"); - - for (const auto& s : series) { - if (s["metric"] == "positive_counter") { - CHECK(s == expected_metric); + std::vector handle_series; + for (const auto& series : (*generate_metrics)["payload"]["series"]) { + if (series["namespace"] == "handle-test") { + handle_series.push_back(series); } } - } - - SECTION("rate") { - client->clear(); - - Rate rps{"request", "rate-test", true}; - telemetry->set_rate(rps, 1000); - - scheduler->trigger_metrics_capture(); - - telemetry->set_rate(rps, 2000); - telemetry->set_rate(rps, 5000); - telemetry->set_rate(rps, {"status:2xx"}, 5000); - - scheduler->trigger_metrics_capture(); - // Expect 2 series: - // - `request` without tags: 2 datapoint (1000, 5000) - // - `request` with tags: 1 datapoint (5000) - scheduler->trigger_heartbeat(); - - auto message_batch = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch) == true); - REQUIRE(message_batch["payload"].size() >= 2); - auto generate_metrics = - find_payload(message_batch["payload"], "generate-metrics"); - REQUIRE(generate_metrics); - auto payload = (*generate_metrics)["payload"]; - - auto series = payload["series"]; - REQUIRE(series.size() >= 2); - - const auto expected_metrics = nlohmann::json::parse(R"( - [ - { - "common": true, - "metric": "request", - "namespace": "rate-test", - "points": [ - [ 1672484400, 5000 ] - ], - "tags": [ "status:2xx" ], - "type": "rate" - }, - { - "common": true, - "metric": "request", - "namespace": "rate-test", - "points": [ - [ 1672484400, 1000 ], - [ 1672484400, 5000 ] - ], - "type": "rate" - } - ] - )"); - - for (const auto& s : series) { - if (s["metric"] == "request") { - if (s.contains("tags")) { - CHECK(s == expected_metrics[0]); - } else { - CHECK(s == expected_metrics[1]); - } + const auto expected = nlohmann::json::parse(R"([ + { + "common": true, + "metric": "handle_requests", + "namespace": "handle-test", + "points": [[1672484400, 3]], + "tags": ["integration_name:datadog", "error:true"], + "type": "count" + }, + { + "common": false, + "metric": "handle_rate", + "namespace": "handle-test", + "points": [[1672484400, 7]], + "type": "rate" } + ])"); + REQUIRE(handle_series.size() == 2); + for (const auto& series : expected) { + CHECK(std::count(handle_series.begin(), handle_series.end(), series) == + 1); } - - // Make sure the next heartbeat doesn't contains distributions if no - // datapoint has been added to a distribution. - client->clear(); - scheduler->trigger_heartbeat(); - - auto message_batch2 = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch2) == true); - REQUIRE(message_batch2["payload"].size() >= 1); - CHECK(find_payload(message_batch["payload"], "app-heartbeat")); } - SECTION("distribution") { + SECTION("distribution handles are sent as sketches") { client->clear(); + auto duration = telemetry->metrics().distribution( + {"handle_duration", "handle-test", true}); + duration->record({false}, 100); + duration->record({false}, 250); - Distribution response_time{"response_time", "dist-test", false}; - telemetry->add_datapoint(response_time, 128); - telemetry->add_datapoint(response_time, 42); - telemetry->add_datapoint(response_time, 3000); - - // Add a tag, this will add a new serie to the distribution payload. - telemetry->add_datapoint(response_time, {"status:200", "method:GET"}, - 6530); - - Distribution request_size{"request_size", "dist-test-2", true}; - telemetry->add_datapoint(request_size, 1843); - telemetry->add_datapoint(request_size, 4135); - - // Expect 3 series: - // - `response_time` without tags: 3 datapoint (128, 42, 3000). - // - `response_time` with 2 tags: 1 datapoint (6530). - // - `request_size`: 2 datapoint (1843, 4135). scheduler->trigger_heartbeat(); auto message_batch = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch) == true); - REQUIRE(message_batch["payload"].size() == 2); - - auto distribution_message = message_batch["payload"][1]; - REQUIRE(distribution_message["request_type"] == "distributions"); - - auto distribution_series = distribution_message["payload"]["series"]; - REQUIRE(distribution_series.size() >= 3); - - const auto expected_series = nlohmann::json::parse(R"([ - { - "common":false, - "metric":"response_time", - "namespace":"dist-test", - "points": [6530], - "tags":["status:200","method:GET"] - }, + auto sketches = find_payload(message_batch["payload"], "sketches"); + REQUIRE(sketches); + auto expected = nlohmann::json::parse(R"([ { - "common":true, - "metric": "request_size", - "namespace":"dist-test-2", - "points":[1843,4135] - }, - { - "common": false, - "metric":"response_time", - "namespace":"dist-test", - "points":[128,42,3000] + "common": true, + "metric": "handle_duration", + "namespace": "handle-test", + "tags": ["error:false"] } ])"); - - for (const auto& s : distribution_series) { - if (s["metric"] == "response_time") { - if (s.contains("tags")) { - CHECK(s == expected_series[0]); - } else { - CHECK(s == expected_series[2]); - } - } else if (s["metric"] == "request_size") { - CHECK(s == expected_series[1]); - } - } - - // Make sure the next heartbeat doesn't contains distributions if no - // datapoint has been added to a distribution. - client->clear(); - scheduler->trigger_heartbeat(); - - auto message_batch2 = nlohmann::json::parse(client->request_body); - REQUIRE(is_valid_telemetry_payload(message_batch2) == true); - REQUIRE(message_batch2["payload"].size() >= 1); - CHECK(find_payload(message_batch["payload"], "app-heartbeat")); + expected[0]["sketch_b64"] = sketch_b64({100, 250}); + CHECK(series_in(*sketches, "handle-test") == expected); } SECTION("dtor sends metrics and distributions") { - // metrics captured before the aggregation task - const Distribution response_time{"response_time", "dist-test", false}; - const Rate rps{"request", "rate-test", true}; - const Counter my_counter{"my_counter", "counter-test", true}; + // The handles outlive the Telemetry, which sends them when destroyed. + std::shared_ptr> counter; + std::shared_ptr> rate; + std::shared_ptr> distribution; { auto tmp_telemetry = Telemetry::create(*finalize_config(), tracer_signature, logger, client, scheduler, *url, clock); - tmp_telemetry->increment_counter(my_counter); // = 1 - tmp_telemetry->add_datapoint(response_time, 128); - tmp_telemetry->set_rate(rps, 1000); + counter = tmp_telemetry->metrics().counter( + {"my_counter", "counter-test", true}); + rate = tmp_telemetry->metrics().rate({"request", "rate-test", true}); + distribution = tmp_telemetry->metrics().distribution( + {"response_time", "dist-test", false}); + counter->record({}, 1); + rate->record({}, 1000); + distribution->record({}, 128); client->clear(); } - // Expect 2 metrics with 1 datapoint each and 1 ditribution auto message_batch = nlohmann::json::parse(client->request_body); REQUIRE(is_valid_telemetry_payload(message_batch) == true); - REQUIRE(message_batch["payload"].size() == 3); - - for (const auto& payload : message_batch["payload"]) { - const auto& req_type = payload["request_type"]; - if (req_type == "generate-metrics") { - const auto& metrics_series = payload["payload"]["series"]; - REQUIRE(metrics_series.size() >= 2); - - for (const auto& s : metrics_series) { - if (s["metric"] == "my_counter") { - const auto expected_counter = nlohmann::json::parse(R"( - { - "common":true, - "metric":"my_counter", - "namespace":"counter-test", - "type": "count", - "points": [[1672484400, 1]] - } - )"); - CHECK(s == expected_counter); - } else if (s["metric"] == "request") { - const auto expected_rate = nlohmann::json::parse(R"( - { - "common":true, - "metric":"request", - "namespace":"rate-test", - "type": "rate", - "points": [[1672484400, 1000]] - } - )"); - CHECK(s == expected_rate); - } - } - } else if (req_type == "distributions") { - const auto& distribution_series = payload["payload"]["series"]; - REQUIRE(distribution_series.size() >= 1); - - const auto expected_d0 = nlohmann::json::parse(R"( - { - "common":false, - "metric":"response_time", - "namespace":"dist-test", - "points": [128] - } - )"); - - for (const auto& d : distribution_series) { - if (d["metric"] == "response_time") { - CHECK(d == expected_d0); - }; - } + auto generate_metrics = + find_payload(message_batch["payload"], "generate-metrics"); + REQUIRE(generate_metrics); + const auto expected_metrics = nlohmann::json::parse(R"([ + { + "common": true, + "metric": "my_counter", + "namespace": "counter-test", + "points": [[1672484400, 1]], + "type": "count" + }, + { + "common": true, + "metric": "request", + "namespace": "rate-test", + "points": [[1672484400, 1000]], + "type": "rate" } + ])"); + const auto& sent = (*generate_metrics)["payload"]["series"]; + for (const auto& series : expected_metrics) { + CHECK(std::count(sent.begin(), sent.end(), series) == 1); } + + auto sketches = find_payload(message_batch["payload"], "sketches"); + REQUIRE(sketches); + auto expected_sketches = nlohmann::json::parse(R"([ + { + "common": false, + "metric": "response_time", + "namespace": "dist-test" + } + ])"); + expected_sketches[0]["sketch_b64"] = sketch_b64({128}); + CHECK(series_in(*sketches, "dist-test") == expected_sketches); } } diff --git a/test/test_base64.cpp b/test/test_base64.cpp index 298b6577..33af765a 100644 --- a/test/test_base64.cpp +++ b/test/test_base64.cpp @@ -30,3 +30,18 @@ BASE64_TEST("padding") { CHECK(base64_decode("bGlnaHQgd28=") == "light wo"); CHECK(base64_decode("bGlnaHQgd29y") == "light wor"); } + +BASE64_TEST("encode") { + CHECK(base64_encode("") == ""); + CHECK(base64_encode("f") == "Zg=="); + CHECK(base64_encode("fo") == "Zm8="); + CHECK(base64_encode("foo") == "Zm9v"); + CHECK(base64_encode("foob") == "Zm9vYg=="); + CHECK(base64_encode("fooba") == "Zm9vYmE="); + CHECK(base64_encode("foobar") == "Zm9vYmFy"); +} + +BASE64_TEST("encode bytes above 0x7f") { + CHECK(base64_encode("\xff\xfe") == "//4="); + CHECK(base64_encode(std::string("\x00\x80\xfb", 3)) == "AID7"); +}