diff --git a/src/datadog/datadog_agent.cpp b/src/datadog/datadog_agent.cpp index fe1db162..01a5954a 100644 --- a/src/datadog/datadog_agent.cpp +++ b/src/datadog/datadog_agent.cpp @@ -261,6 +261,8 @@ void DatadogAgent::flush() { auto encode_result = msgpack_encode(body, trace_chunks); auto end = std::chrono::steady_clock::now(); + // TODO: wrong unit?!: trace_chunk_serialization_duration is + // "trace_chunk_serialization.ms", but we're sending microseconds! telemetry::distribution::add( metrics::tracer::trace_chunk_serialization_duration, std::chrono::duration_cast(end - beg).count()); diff --git a/src/datadog/telemetry/telemetry.cpp b/src/datadog/telemetry/telemetry.cpp index fbdb7099..cfae2837 100644 --- a/src/datadog/telemetry/telemetry.cpp +++ b/src/datadog/telemetry/telemetry.cpp @@ -4,28 +4,25 @@ #include "telemetry_impl.h" namespace datadog::telemetry { -namespace details { -/// NOTE(@dmehala): Generic overload function (P0051R3) like implementation. +namespace details { +// Generic overload function (P0051R3) like implementation. template struct Overload : Ts... { using Ts::operator()...; }; -/// NOTE(@dmehala): Guide required for C++17. Remove once we switch to C++20. +// Guide required for C++17. Remove once we switch to C++20. template Overload(Ts...) -> Overload; - } // namespace details +// `TelemetryProxy` holds either the real implementation or a no-op +// implementation. using NoopTelemetry = std::monostate; - -/// `TelemetryProxy` holds either the real implementation or a no-op -/// implementation. using TelemetryProxy = std::variant>; -/// NOTE(@dmehala): Here to facilitate Meyer's singleton construction. -struct Ctor_param final { +struct TelemetryParameters final { FinalizedConfiguration configuration; tracing::TracerSignature tracer_signature; std::shared_ptr logger; @@ -35,38 +32,51 @@ struct Ctor_param final { tracing::Clock clock = tracing::default_clock; }; -TelemetryProxy make_telemetry(const tracing::Optional& init) { +TelemetryProxy make_telemetry( + const tracing::Optional& init) { if (!init || !init->configuration.enabled) return NoopTelemetry{}; - return Telemetry::create(init->configuration, init->tracer_signature, - init->logger, init->client, init->scheduler, - init->agent_url, init->clock); + + std::shared_ptr telemetry = Telemetry::create( + init->configuration, init->tracer_signature, init->logger, init->client, + init->scheduler, init->agent_url, init->clock); + + // Send the app-closing message when statics are destroyed. + struct ShutdownTelemetryAtExit { + std::shared_ptr telemetry_; + ~ShutdownTelemetryAtExit() { telemetry_->shutdown(); } + }; + static const ShutdownTelemetryAtExit shutdown_telemetry_at_exit{telemetry}; + + return telemetry; } TelemetryProxy& instance( - const tracing::Optional& init = tracing::nullopt) { - static TelemetryProxy telemetry = make_telemetry(init); + const tracing::Optional& init = tracing::nullopt) { + // This singleton is never destroyed on purpose because the Tracer's + // destructor needs it. + static TelemetryProxy& telemetry = *new TelemetryProxy{make_telemetry(init)}; return telemetry; } void init(FinalizedConfiguration configuration, + tracing::TracerSignature tracer_signature, std::shared_ptr logger, std::shared_ptr client, std::shared_ptr event_scheduler, tracing::HTTPClient::URL agent_url, tracing::Clock clock) { - instance(Ctor_param{configuration, - tracing::TracerSignature(tracing::RuntimeID::generate(), - tracing::get_process_name(), ""), - logger, client, event_scheduler, agent_url, clock}); + instance(TelemetryParameters{configuration, tracer_signature, logger, client, + event_scheduler, agent_url, clock}); } void init(FinalizedConfiguration configuration, - tracing::TracerSignature tracer_signature, std::shared_ptr logger, std::shared_ptr client, std::shared_ptr event_scheduler, tracing::HTTPClient::URL agent_url, tracing::Clock clock) { - instance(Ctor_param{configuration, tracer_signature, logger, client, - event_scheduler, agent_url, clock}); + init(configuration, + tracing::TracerSignature(tracing::RuntimeID::generate(), + tracing::get_process_name(), ""), + logger, client, event_scheduler, agent_url, clock); } void shutdown() { @@ -135,7 +145,7 @@ void error(std::string message, std::string stacktrace) { [&](std::shared_ptr& telemetry) { telemetry->log_error(message, stacktrace); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -147,7 +157,7 @@ void increment(const Counter& counter) { [&](std::shared_ptr& telemetry) { telemetry->increment_counter(counter); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -157,7 +167,7 @@ void increment(const Counter& counter, const std::vector& tags) { [&](std::shared_ptr& telemetry) { telemetry->increment_counter(counter, tags); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -167,7 +177,7 @@ void decrement(const Counter& counter) { [&](std::shared_ptr& telemetry) { telemetry->decrement_counter(counter); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -177,7 +187,7 @@ void decrement(const Counter& counter, const std::vector& tags) { [&](std::shared_ptr& telemetry) { telemetry->decrement_counter(counter, tags); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -187,7 +197,7 @@ void set(const Counter& counter, uint64_t value) { [&](std::shared_ptr& telemetry) { telemetry->set_counter(counter, value); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -198,7 +208,7 @@ void set(const Counter& counter, const std::vector& tags, [&](std::shared_ptr& telemetry) { telemetry->set_counter(counter, tags, value); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -211,7 +221,7 @@ void set(const Rate& rate, uint64_t value) { [&](std::shared_ptr& telemetry) { telemetry->set_rate(rate, value); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -222,7 +232,7 @@ void set(const Rate& rate, const std::vector& tags, [&](std::shared_ptr& telemetry) { telemetry->set_rate(rate, tags, value); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -235,7 +245,7 @@ void add(const Distribution& distribution, uint64_t value) { [&](std::shared_ptr& telemetry) { telemetry->add_datapoint(distribution, value); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } @@ -246,7 +256,7 @@ void add(const Distribution& distribution, const std::vector& tags, [&](std::shared_ptr& telemetry) { telemetry->add_datapoint(distribution, tags, value); }, - [](auto&&) {}, + [](NoopTelemetry) {}, }, instance()); } diff --git a/src/datadog/telemetry/telemetry_impl.cpp b/src/datadog/telemetry/telemetry_impl.cpp index 46583039..0a0cf3f1 100644 --- a/src/datadog/telemetry/telemetry_impl.cpp +++ b/src/datadog/telemetry/telemetry_impl.cpp @@ -17,35 +17,36 @@ 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`. +// 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`). +// 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`). +// 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`). +// 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`). +// 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`). +// 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}; @@ -288,12 +289,7 @@ void Telemetry::schedule_tasks() { })); } -Telemetry::~Telemetry() { - if (!tasks_.empty()) { - cancel_tasks(tasks_); - app_closing(); - } -} +Telemetry::~Telemetry() { shutdown(); } void Telemetry::log_error(std::string message) { if (!config_.report_logs) return; @@ -364,10 +360,10 @@ void Telemetry::app_started() { } void Telemetry::shutdown() { - // cancel_tasks clears tasks_, so ~Telemetry() becomes a no-op after this. + if (is_shut_down_.exchange(true)) return; cancel_tasks(tasks_); app_closing(); - std::lock_guard l{http_client_mutex_}; + std::lock_guard lock{http_client_mutex_}; http_client_.reset(); } @@ -382,7 +378,7 @@ void Telemetry::app_closing() { void Telemetry::send_payload(StringView request_type, std::string payload) { std::shared_ptr client; { - std::lock_guard l{http_client_mutex_}; + std::lock_guard lock{http_client_mutex_}; client = http_client_; } if (!client) return; @@ -491,19 +487,19 @@ std::string Telemetry::heartbeat_and_telemetry() { std::unordered_map, std::vector> distributions; { - std::lock_guard l{distributions_mutex_}; + std::lock_guard lock{distributions_mutex_}; std::swap(distributions_, distributions); } std::unordered_map, MetricSnapshot> counters_snapshot; { - std::lock_guard l{counter_mutex_}; + std::lock_guard lock{counter_mutex_}; std::swap(counters_snapshot_, counters_snapshot); } std::unordered_map, MetricSnapshot> rates_snapshot; { - std::lock_guard l{rate_mutex_}; + std::lock_guard lock{rate_mutex_}; std::swap(rates_snapshot_, rates_snapshot); } @@ -536,7 +532,7 @@ std::string Telemetry::heartbeat_and_telemetry() { std::vector old_logs; { - std::lock_guard l{log_mutex_}; + std::lock_guard lock{log_mutex_}; std::swap(old_logs, logs_); } @@ -832,7 +828,7 @@ void Telemetry::capture_metrics() { std::unordered_map, uint64_t> counter_snapshot; { - std::lock_guard l{counter_mutex_}; + std::lock_guard lock{counter_mutex_}; std::swap(counter_snapshot, counters_); } @@ -843,7 +839,7 @@ void Telemetry::capture_metrics() { std::unordered_map, uint64_t> rate_snapshot; { - std::lock_guard l{rate_mutex_}; + std::lock_guard lock{rate_mutex_}; std::swap(rate_snapshot, rates_); } @@ -855,10 +851,11 @@ void Telemetry::capture_metrics() { void Telemetry::log(std::string message, telemetry::LogLevel level, Optional stacktrace) { + if (is_shut_down_) return; auto timestamp = std::chrono::duration_cast( clock_().wall.time_since_epoch()) .count(); - std::lock_guard l{log_mutex_}; + std::lock_guard lock{log_mutex_}; logs_.emplace_back( telemetry::LogMessage{std::move(message), level, stacktrace, timestamp}); } @@ -869,7 +866,8 @@ void Telemetry::increment_counter(const Counter& id) { void Telemetry::increment_counter(const Counter& id, const std::vector& tags) { - std::lock_guard l{counter_mutex_}; + if (is_shut_down_) return; + std::lock_guard lock{counter_mutex_}; counters_[{id, tags}] += 1; } @@ -879,9 +877,10 @@ void Telemetry::decrement_counter(const 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; + if (is_shut_down_) return; + std::lock_guard lock{counter_mutex_}; + auto& value = counters_[{id, tags}]; + if (value > 0) value -= 1; } void Telemetry::set_counter(const Counter& id, uint64_t value) { @@ -891,7 +890,8 @@ void Telemetry::set_counter(const Counter& id, uint64_t value) { void Telemetry::set_counter(const Counter& id, const std::vector& tags, uint64_t value) { - std::lock_guard l{counter_mutex_}; + if (is_shut_down_) return; + std::lock_guard lock{counter_mutex_}; counters_[{id, tags}] = value; } @@ -901,7 +901,8 @@ void Telemetry::set_rate(const Rate& id, uint64_t value) { void Telemetry::set_rate(const Rate& id, const std::vector& tags, uint64_t value) { - std::lock_guard l{rate_mutex_}; + if (is_shut_down_) return; + std::lock_guard lock{rate_mutex_}; rates_[{id, tags}] = value; } @@ -912,7 +913,8 @@ void Telemetry::add_datapoint(const Distribution& id, uint64_t value) { void Telemetry::add_datapoint(const Distribution& id, const std::vector& tags, uint64_t value) { - std::lock_guard l{distributions_mutex_}; + if (is_shut_down_) return; + std::lock_guard lock{distributions_mutex_}; distributions_[{id, tags}].emplace_back(value); } diff --git a/src/datadog/telemetry/telemetry_impl.h b/src/datadog/telemetry/telemetry_impl.h index 2e432a32..56e8fb46 100644 --- a/src/datadog/telemetry/telemetry_impl.h +++ b/src/datadog/telemetry/telemetry_impl.h @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -78,6 +79,10 @@ class Telemetry final : public std::enable_shared_from_this { std::mutex http_client_mutex_; + // Used to skip recording after shutdown(), because the data can't be sent + // anymore. + std::atomic is_shut_down_{false}; + public: static std::shared_ptr create( FinalizedConfiguration configuration, diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 86a47e77..f32a697f 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -76,8 +76,13 @@ if(DD_TRACE_TRANSPORT STREQUAL "curl") target_link_libraries(tests PRIVATE CURL::libcurl_static) endif() -# Dedicated executable run by a test in test_otel_process_ctx.cpp +# Dedicated executable run by a test in test_tracer.cpp add_executable(exit_with_live_tracer exit_with_live_tracer.cpp) +target_include_directories(exit_with_live_tracer + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_SOURCE_DIR}/src +) target_link_libraries(exit_with_live_tracer PRIVATE dd-trace-cpp::static diff --git a/test/exit_with_live_tracer.cpp b/test/exit_with_live_tracer.cpp index 312de979..1cb63f88 100644 --- a/test/exit_with_live_tracer.cpp +++ b/test/exit_with_live_tracer.cpp @@ -1,37 +1,45 @@ // Executable that calls exit() while a Tracer, held by a static wrapper, is // still alive. -#include #include +#include "mocks/event_schedulers.h" +#include "mocks/http_clients.h" + namespace dd = datadog::tracing; namespace { -class NullCollector : public dd::Collector { - public: - dd::Expected send(std::vector>&&, - const std::shared_ptr&) override { - return dd::nullopt; - } - - std::string config() const override { return R"({"type": "NullCollector"})"; } -}; - // Created empty before main(), so before the library statics. std::optional tracer; } // namespace int main() { + const std::shared_ptr http_client = + std::make_shared(); + // Valid agent reply to avoid errors in log + http_client->response_status = 200; + http_client->response_body << "{}"; + + const std::shared_ptr event_scheduler = + std::make_shared(); + dd::TracerConfig config; - config.collector = std::make_shared(); - config.telemetry.enabled = false; + config.agent.http_client = http_client; + config.agent.event_scheduler = event_scheduler; + config.event_scheduler = event_scheduler; const dd::Expected finalized_config = dd::finalize_config(config); if (!finalized_config) { return EXIT_FAILURE; } tracer.emplace(*finalized_config); + + // Because the mock scheduler does nothing, the trace chunk is only flushed + // when the Tracer is destroyed. This trace chunk destruction uses both the + // OTel process context state and the telemetry singleton. + tracer->create_span(); + std::exit(EXIT_SUCCESS); } diff --git a/test/telemetry/test_telemetry.cpp b/test/telemetry/test_telemetry.cpp index 9a0cfb41..3f2b9a13 100644 --- a/test/telemetry/test_telemetry.cpp +++ b/test/telemetry/test_telemetry.cpp @@ -376,6 +376,21 @@ TELEMETRY_IMPLEMENTATION_TEST("Tracer telemetry lifecycle") { find_payload(message_batch["payload"], "app-closing"); REQUIRE(app_closing_payload.has_value()); } + + SECTION("shutdown() sends app-closing once, and a second call is safe") { + auto telemetry = Telemetry::create(*finalize_config(), tracer_signature, + logger, client, scheduler, *url); + client->clear(); + + telemetry->shutdown(); + auto message_batch = nlohmann::json::parse(client->request_body); + REQUIRE(is_valid_telemetry_payload(message_batch)); + REQUIRE(find_payload(message_batch["payload"], "app-closing")); + + client->clear(); + telemetry->shutdown(); + CHECK(client->request_body.empty()); + } } TELEMETRY_IMPLEMENTATION_TEST("session ID headers") { diff --git a/test/test_otel_process_ctx.cpp b/test/test_otel_process_ctx.cpp index aa6f6404..d38aa053 100644 --- a/test/test_otel_process_ctx.cpp +++ b/test/test_otel_process_ctx.cpp @@ -242,17 +242,3 @@ OTEL_CTX_TEST( } #endif } - -OTEL_CTX_TEST("exit() with a live Tracer in a static wrapper exits cleanly") { -#ifndef __linux__ - SUCCEED("OpenTelemetry process context is Linux-only"); -#else - // Run a dedicated process and check that it exits cleanly. It must be - // independent of other tests, to control the order of statics creation. - const std::string command = - std::string("'") + EXIT_WITH_LIVE_TRACER_EXECUTABLE + "'"; - const int status = std::system(command.c_str()); - REQUIRE(WIFEXITED(status)); - REQUIRE(WEXITSTATUS(status) == EXIT_SUCCESS); -#endif -} diff --git a/test/test_tracer.cpp b/test/test_tracer.cpp index 066a9781..e05b019d 100644 --- a/test/test_tracer.cpp +++ b/test/test_tracer.cpp @@ -1,6 +1,3 @@ -// These are tests for `Tracer`. `Tracer` is responsible for creating root -// spans and for extracting spans from propagated trace context. - #include #include #include @@ -39,8 +36,7 @@ #include "null_logger.h" #include "test.h" -namespace datadog { -namespace tracing { +namespace datadog::tracing { std::ostream& operator<<(std::ostream& stream, const Optional& code) { @@ -50,8 +46,7 @@ std::ostream& operator<<(std::ostream& stream, return stream << "null"; } -} // namespace tracing -} // namespace datadog +} // namespace datadog::tracing using namespace datadog::tracing; using namespace std::chrono_literals; @@ -2586,3 +2581,17 @@ TEST_TRACER("_dd.p.ksr is NOT set when overriding the sampling decision") { auto c = collector->first_span(); CHECK(c.tags.count(tags::internal::ksr) == 0); } + +TEST_TRACER("exit() with a live Tracer in a static wrapper exits cleanly") { +#ifndef __linux__ + SUCCEED("Runs on Linux only: it needs a POSIX shell"); +#else + // Run a dedicated process and check that it exits cleanly. It must be + // independent of other tests, to control the order of statics creation. + const std::string command = + std::string("'") + EXIT_WITH_LIVE_TRACER_EXECUTABLE + "'"; + const int status = std::system(command.c_str()); + REQUIRE(WIFEXITED(status)); + REQUIRE(WEXITSTATUS(status) == EXIT_SUCCESS); +#endif +}