diff --git a/BUILD.bazel b/BUILD.bazel index e8a1e8d4..d539ac51 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -81,6 +81,7 @@ cc_library( "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", diff --git a/include/datadog/telemetry/telemetry.h b/include/datadog/telemetry/telemetry.h index 0cb6497f..f45f0ec6 100644 --- a/include/datadog/telemetry/telemetry.h +++ b/include/datadog/telemetry/telemetry.h @@ -151,42 +151,6 @@ std::shared_ptr> create( }); } -/// 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. -/// -/// @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); - } // namespace counter /// The `rate` namespace provides support for rate metrics-values. @@ -207,19 +171,6 @@ std::shared_ptr> create( }); } -/// Sets the rate to a specific value. -/// -/// @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); - } // namespace rate /// The `distribution` namespace provides support for statistical distribution. @@ -242,20 +193,6 @@ std::shared_ptr> create( }); } -/// 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); - } // namespace distribution } // namespace datadog::telemetry 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/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 d8379467..9ebfe3d8 100644 --- a/src/datadog/telemetry/telemetry.cpp +++ b/src/datadog/telemetry/telemetry.cpp @@ -152,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 96870f23..d8ed40c8 100644 --- a/src/datadog/telemetry/telemetry_impl.cpp +++ b/src/datadog/telemetry/telemetry_impl.cpp @@ -18,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; @@ -189,27 +155,6 @@ 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}, - }; - if (!metric_ctx.tags.empty()) { - series.emplace("tags", metric_ctx.tags); - } - j.emplace_back(series); - } - - return j; -} - // The `sketches` payload of the distribution handles' series, or nothing if // there are none. Optional sketches_payload( @@ -270,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( @@ -322,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); } @@ -372,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: ")); } @@ -432,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) { @@ -461,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: ")); } @@ -513,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_}; @@ -545,20 +475,6 @@ 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)); } @@ -612,20 +528,6 @@ 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)); } @@ -863,28 +765,6 @@ 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)); - } - - 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()) { counters_snapshot_[{series.metric, std::move(series.tags)}].emplace_back( timepoint, series.value); @@ -906,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 c2facc85..be039ae0 100644 --- a/src/datadog/telemetry/telemetry_impl.h +++ b/src/datadog/telemetry/telemetry_impl.h @@ -17,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. // @@ -43,23 +51,22 @@ 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_; @@ -124,27 +131,6 @@ 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_; } 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/telemetry/test_telemetry.cpp b/test/telemetry/test_telemetry.cpp index fa772242..3491d3bb 100644 --- a/test/telemetry/test_telemetry.cpp +++ b/test/telemetry/test_telemetry.cpp @@ -44,11 +44,11 @@ std::optional find_payload(const nlohmann::json& messages, return std::nullopt; }; -struct StatusTags { +struct ErrorTags { bool error = false; static auto tag_fields() { - return std::tuple{tag("error", &StatusTags::error)}; + return std::tuple{tag("error", &ErrorTags::error)}; } }; @@ -58,6 +58,16 @@ std::string sketch_b64(std::initializer_list values) { 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; @@ -629,212 +639,9 @@ TELEMETRY_IMPLEMENTATION_TEST("Tracer telemetry API") { } SECTION("metrics reporting") { - SECTION("counters are correctly serialized in generate-metrics payload") { - 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(); - - 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); - } - } - } - - 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]); - } - } - } - - // 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("counter and rate handles are sent with the metrics") { client->clear(); - auto requests = telemetry->metrics().counter( + auto requests = telemetry->metrics().counter( {"handle_requests", "handle-test", true}, {"integration_name:datadog"}); auto rate = @@ -883,7 +690,7 @@ TELEMETRY_IMPLEMENTATION_TEST("Tracer telemetry API") { SECTION("distribution handles are sent as sketches") { client->clear(); - auto duration = telemetry->metrics().distribution( + auto duration = telemetry->metrics().distribution( {"handle_duration", "handle-test", true}); duration->record({false}, 100); duration->record({false}, 250); @@ -902,157 +709,66 @@ TELEMETRY_IMPLEMENTATION_TEST("Tracer telemetry API") { } ])"); expected[0]["sketch_b64"] = sketch_b64({100, 250}); - CHECK((*sketches)["payload"]["series"] == expected); - } - - SECTION("distribution") { - client->clear(); - - 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"] - }, - { - "common":true, - "metric": "request_size", - "namespace":"dist-test-2", - "points":[1843,4135] - }, - { - "common": false, - "metric":"response_time", - "namespace":"dist-test", - "points":[128,42,3000] - } - ])"); - - 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")); + 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); } }