diff --git a/Cargo.lock b/Cargo.lock index 2fc24a5abd..603aef25f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1785,6 +1785,26 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "enum-map" +version = "2.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6866f3bfdf8207509a033af1a75a7b08abda06bbaaeae6669323fd5a097df2e9" +dependencies = [ + "enum-map-derive", +] + +[[package]] +name = "enum-map-derive" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f282cfdfe92516eb26c2af8589c274c7c17681f5ecc03c18255fe741c6aa64eb" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.87", +] + [[package]] name = "enum-ordinalize" version = "3.1.15" @@ -3140,6 +3160,7 @@ dependencies = [ "crossbeam-utils", "cxx", "cxx-build", + "enum-map", "futures", "hashbrown 0.16.1", "http", @@ -3151,6 +3172,7 @@ dependencies = [ "libdd-profiling", "libdd-profiling-protobuf", "mime", + "opentelemetry-proto", "parking_lot", "proptest", "prost", @@ -3946,6 +3968,15 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "opentelemetry" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b84bcd6ae87133e903af7ef497404dda70c60d0ea14895fc8a5e6722754fc2a0" +dependencies = [ + "js-sys", +] + [[package]] name = "opentelemetry-jaeger" version = "0.16.0" @@ -3954,20 +3985,46 @@ checksum = "f8c0b12cd9e3f9b35b52f6e0dac66866c519b26f424f4bbf96e3fe8bfbdc5229" dependencies = [ "async-trait", "lazy_static", - "opentelemetry", + "opentelemetry 0.17.0", "opentelemetry-semantic-conventions", "thiserror 1.0.68", "thrift", "tokio", ] +[[package]] +name = "opentelemetry-proto" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7175df06de5eaee9909d4805a3d07e28bb752c34cab57fa9cff549da596b30f" +dependencies = [ + "opentelemetry 0.31.0", + "opentelemetry_sdk", + "prost", + "tonic", + "tonic-prost", +] + [[package]] name = "opentelemetry-semantic-conventions" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "985cc35d832d412224b2cffe2f9194b1b89b6aa5d0bef76d080dce09d90e62bd" dependencies = [ - "opentelemetry", + "opentelemetry 0.17.0", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ae4f5991976fd48df6d843de219ca6d31b01daaab2dad5af2badeded372bd" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry 0.31.0", + "thiserror 2.0.17", ] [[package]] @@ -5706,7 +5763,7 @@ dependencies = [ "futures", "futures-test", "humantime", - "opentelemetry", + "opentelemetry 0.17.0", "opentelemetry-jaeger", "pin-project", "pin-utils", @@ -6233,7 +6290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbbe89715c1dbbb790059e2565353978564924ee85017b5fff365c872ff6721f" dependencies = [ "once_cell", - "opentelemetry", + "opentelemetry 0.17.0", "tracing", "tracing-core", "tracing-subscriber", diff --git a/LICENSE-3rdparty.yml b/LICENSE-3rdparty.yml index 787f279383..d2d156aab7 100644 --- a/LICENSE-3rdparty.yml +++ b/LICENSE-3rdparty.yml @@ -19232,6 +19232,27 @@ third_party_libraries: DEALINGS IN THE SOFTWARE. - license: Apache-2.0 text: " Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n" +- package_name: opentelemetry + package_version: 0.31.0 + repository: https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry + license: Apache-2.0 + licenses: + - license: Apache-2.0 + text: NOT FOUND +- package_name: opentelemetry-proto + package_version: 0.31.0 + repository: https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-proto + license: Apache-2.0 + licenses: + - license: Apache-2.0 + text: NOT FOUND +- package_name: opentelemetry_sdk + package_version: 0.31.0 + repository: https://github.com/open-telemetry/opentelemetry-rust/tree/main/opentelemetry-sdk + license: Apache-2.0 + licenses: + - license: Apache-2.0 + text: NOT FOUND - package_name: os_info package_version: 3.14.0 repository: https://github.com/stanislav-tkach/os_info @@ -30824,9 +30845,9 @@ third_party_libraries: - package_name: stringmetrics package_version: 2.2.2 repository: https://github.com/pluots/stringmetrics - license: License specified in file ($CARGO_HOME/registry/src/index.crates.io-6f17d22bba15001f/stringmetrics-2.2.2/LICENSE) + license: License specified in file ($CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/stringmetrics-2.2.2/LICENSE) licenses: - - license: License specified in file ($CARGO_HOME/registry/src/index.crates.io-6f17d22bba15001f/stringmetrics-2.2.2/LICENSE) + - license: License specified in file ($CARGO_HOME/registry/src/index.crates.io-1949cf8c6b5b557f/stringmetrics-2.2.2/LICENSE) text: | Copyright 2022 Trevor Gross @@ -34313,6 +34334,34 @@ third_party_libraries: of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS +- package_name: tokio-stream + package_version: 0.1.16 + repository: https://github.com/tokio-rs/tokio + license: MIT + licenses: + - license: MIT + text: | + MIT License + + Copyright (c) Tokio Contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. - package_name: tokio-util package_version: 0.7.12 repository: https://github.com/tokio-rs/tokio @@ -35491,6 +35540,39 @@ third_party_libraries: See the License for the specific language governing permissions and limitations under the License. +- package_name: tonic + package_version: 0.14.2 + repository: https://github.com/hyperium/tonic + license: MIT + licenses: + - license: MIT + text: | + Copyright (c) 2025 Lucio Franco + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +- package_name: tonic-prost + package_version: 0.14.2 + repository: https://github.com/hyperium/tonic + license: MIT + licenses: + - license: MIT + text: NOT FOUND - package_name: tower package_version: 0.5.2 repository: https://github.com/tower-rs/tower diff --git a/libdd-profiling/Cargo.toml b/libdd-profiling/Cargo.toml index 8963e94219..12f5ed19e1 100644 --- a/libdd-profiling/Cargo.toml +++ b/libdd-profiling/Cargo.toml @@ -19,6 +19,7 @@ bench = false [features] default = [] cxx = ["dep:cxx", "dep:cxx-build"] +otel = ["dep:opentelemetry-proto", "dep:enum-map"] test-utils = ["libdd-common/test-utils"] [[bench]] @@ -45,6 +46,8 @@ libdd-alloc = { version = "1.0.0", path = "../libdd-alloc" } libdd-common = { version = "1.1.0", path = "../libdd-common", default-features = false, features = ["reqwest", "test-utils"] } libdd-profiling-protobuf = { version = "1.0.0", path = "../libdd-profiling-protobuf", features = ["prost_impls"] } mime = "0.3.16" +enum-map = { version = "2", optional = true } +opentelemetry-proto = { version = "0.31", optional = true, default-features = false, features = ["profiles", "gen-tonic-messages"] } parking_lot = { version = "0.12", default-features = false } prost = "0.14.1" rand = "0.8" diff --git a/libdd-profiling/src/api/mod.rs b/libdd-profiling/src/api/mod.rs index f95fd84be9..3bec015392 100644 --- a/libdd-profiling/src/api/mod.rs +++ b/libdd-profiling/src/api/mod.rs @@ -193,7 +193,7 @@ pub struct StringIdSample<'a> { pub labels: Vec, } -#[derive(Debug)] +#[derive(Clone, Copy, Debug)] #[cfg_attr(test, derive(bolero::generator::TypeGenerator))] pub enum UpscalingInfo { Poisson { diff --git a/libdd-profiling/src/api/sample_type.rs b/libdd-profiling/src/api/sample_type.rs index 1554fb46ca..43144d6fc7 100644 --- a/libdd-profiling/src/api/sample_type.rs +++ b/libdd-profiling/src/api/sample_type.rs @@ -12,6 +12,7 @@ use super::ValueType; /// - **dd-trace-dotnet**: Sample type definitions for allocations, locks, CPU, walltime, /// exceptions, live objects, HTTP requests /// - **pprof-nodejs**: `profile-serializer.ts` (value type functions) +#[cfg_attr(feature = "otel", derive(enum_map::Enum))] #[cfg_attr(test, derive(bolero::generator::TypeGenerator, strum::EnumIter))] #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] diff --git a/libdd-profiling/src/cxx.rs b/libdd-profiling/src/cxx.rs index 4f8a609079..237c787093 100644 --- a/libdd-profiling/src/cxx.rs +++ b/libdd-profiling/src/cxx.rs @@ -616,7 +616,7 @@ impl Profile { // Reset the profile and get the old one to serialize let old_profile = self.inner.reset_and_return_previous()?; let end_time = Some(std::time::SystemTime::now()); - let encoded = old_profile.serialize_into_compressed_pprof(end_time, None)?; + let encoded = old_profile.serialize_into_compressed(end_time, None)?; Ok(encoded.buffer) } } @@ -647,7 +647,7 @@ fn prepare_profile_for_export<'a>( )> { let old_profile = profile.inner.reset_and_return_previous()?; let end_time = Some(std::time::SystemTime::now()); - let encoded = old_profile.serialize_into_compressed_pprof(end_time, None)?; + let encoded = old_profile.serialize_into_compressed(end_time, None)?; let files_to_compress_vec: Vec = files_to_compress.iter().map(Into::into).collect(); diff --git a/libdd-profiling/src/exporter/profile_exporter.rs b/libdd-profiling/src/exporter/profile_exporter.rs index 7a7e0522c7..2c2ad67d82 100644 --- a/libdd-profiling/src/exporter/profile_exporter.rs +++ b/libdd-profiling/src/exporter/profile_exporter.rs @@ -280,7 +280,7 @@ impl ProfileExporter { let attachments: Vec<_> = additional_files .iter() .map(|f| f.name) - .chain(std::iter::once("profile.pprof")) + .chain(std::iter::once(profile.filename)) .collect(); let mut internal = internal_metadata.unwrap_or_else(|| json!({})); @@ -340,8 +340,8 @@ impl ProfileExporter { // Add profile Ok(form.part( - "profile.pprof", - reqwest::multipart::Part::bytes(profile.buffer).file_name("profile.pprof"), + profile.filename, + reqwest::multipart::Part::bytes(profile.buffer).file_name(profile.filename), )) } } diff --git a/libdd-profiling/src/internal/location.rs b/libdd-profiling/src/internal/location.rs index d9fcdbc448..adb97fe2ec 100644 --- a/libdd-profiling/src/internal/location.rs +++ b/libdd-profiling/src/internal/location.rs @@ -16,6 +16,17 @@ pub struct Location { pub line: i64, } +impl Default for Location { + fn default() -> Self { + Self { + mapping_id: None, + function_id: super::FunctionId::from_offset(0), + address: 0, + line: 0, + } + } +} + impl Item for Location { type Id = LocationId; } diff --git a/libdd-profiling/src/internal/mapping.rs b/libdd-profiling/src/internal/mapping.rs index 26ffe3596a..1be6e39372 100644 --- a/libdd-profiling/src/internal/mapping.rs +++ b/libdd-profiling/src/internal/mapping.rs @@ -6,7 +6,7 @@ use super::*; /// Represents a [pprof::Mapping] with some space-saving changes: /// - The id is not stored on the struct. It's stored in the container that holds the struct. /// - ids for linked objects use 32-bit numbers instead of 64 bit ones. -#[derive(Eq, PartialEq, Hash)] +#[derive(Default, Eq, PartialEq, Hash)] pub struct Mapping { /// Address at which the binary (or DLL) is loaded into memory. pub memory_start: u64, diff --git a/libdd-profiling/src/internal/mod.rs b/libdd-profiling/src/internal/mod.rs index 56e4fe65c6..512a06e507 100644 --- a/libdd-profiling/src/internal/mod.rs +++ b/libdd-profiling/src/internal/mod.rs @@ -7,7 +7,10 @@ mod function; mod label; mod location; mod mapping; +#[cfg(not(feature = "otel"))] mod observation; +#[cfg(feature = "otel")] +mod otel_style_observation; mod profile; mod sample; mod stack_trace; @@ -21,7 +24,10 @@ pub use label::*; pub use libdd_profiling_protobuf::ValueType; pub use location::*; pub use mapping::*; +#[cfg(not(feature = "otel"))] pub use observation::*; +#[cfg(feature = "otel")] +pub use otel_style_observation::*; pub use profile::*; pub use sample::*; pub use stack_trace::*; diff --git a/libdd-profiling/src/internal/otel_style_observation.rs b/libdd-profiling/src/internal/otel_style_observation.rs new file mode 100644 index 0000000000..5dd5e75e7f --- /dev/null +++ b/libdd-profiling/src/internal/otel_style_observation.rs @@ -0,0 +1,220 @@ +// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ +// SPDX-License-Identifier: Apache-2.0 + +use crate::{ + api::SampleType, + internal::{Sample, Timestamp}, +}; +use anyhow::Context; +use enum_map::EnumMap; +use std::collections::HashMap; +use std::sync::Arc; + +#[derive(Default)] +#[allow(clippy::type_complexity)] +pub struct Observations { + sample_types: Arc<[SampleType]>, + sample_type_index_map: EnumMap>, + pub paired_samples: Vec>, + pub aggregated: HashMap>, + pub aggregated2: HashMap<(SampleType, SampleType), HashMap>, + pub timestamped: HashMap>>, + pub timestamped2: + HashMap<(SampleType, SampleType), HashMap>>, +} + +impl Observations { + pub fn new( + sample_types: Arc<[SampleType]>, + sample_type_index_map: EnumMap>, + ) -> Self { + let len = sample_types.len(); + Self { + sample_types, + sample_type_index_map, + paired_samples: vec![None; len], + ..Default::default() + } + } + + pub fn pair_samples(&mut self, s1: SampleType, s2: SampleType) -> anyhow::Result<()> { + let i1 = self.sample_type_index_map[s1].context("invalid sample type")?; + let i2 = self.sample_type_index_map[s2].context("invalid sample type")?; + anyhow::ensure!( + self.paired_samples[i1].is_none() && self.paired_samples[i2].is_none(), + "sample type already paired" + ); + self.paired_samples[i1] = Some(i2); + self.paired_samples[i2] = Some(i1); + Ok(()) + } + + pub fn add( + &mut self, + sample: Sample, + timestamp: Option, + values: &[i64], + ) -> anyhow::Result<()> { + for i in 0..values.len() { + let val1 = values[i]; + + if let Some(pair) = self.paired_samples[i] { + let val2 = values[pair]; + let st1 = self.sample_types[i]; + let st2 = self.sample_types[pair]; + use enum_map::Enum as _; + // Process each pair exactly once by requiring the canonical-first type + // (lower enum index) to drive the insertion. This matches the ordering + // used by OtelUpscalingRules, which stores pair rules under the lower + // into_usize() type so both sides agree on which type is the map key. + if st1.into_usize() < st2.into_usize() && (val1 != 0 || val2 != 0) { + if let Some(ts) = timestamp { + self.timestamped2 + .entry((st1, st2)) + .or_default() + .entry(sample) + .or_default() + .push((val1, val2, ts)); + } else { + let entry = self + .aggregated2 + .entry((st1, st2)) + .or_default() + .entry(sample) + .or_insert((0, 0)); + entry.0 = entry.0.saturating_add(val1); + entry.1 = entry.1.saturating_add(val2); + } + } + } else if val1 != 0 { + let st = self.sample_types[i]; + if let Some(ts) = timestamp { + self.timestamped + .entry(st) + .or_default() + .entry(sample) + .or_default() + .push((val1, ts)); + } else { + let entry = self + .aggregated + .entry(st) + .or_default() + .entry(sample) + .or_insert(0); + *entry = entry.saturating_add(val1); + } + } + } + + Ok(()) + } + + pub fn is_empty(&self) -> bool { + self.aggregated.is_empty() && self.timestamped.is_empty() + } + + pub fn aggregated_samples_count(&self) -> usize { + self.aggregated + .values() + .map(|samples| samples.len()) + .sum::() + + self + .aggregated2 + .values() + .map(|samples| samples.len()) + .sum::() + } + + pub fn timestamped_samples_count(&self) -> usize { + self.timestamped + .iter() + .flat_map(|(_, v)| v.values().map(|v| v.len())) + .sum::() + + self + .timestamped2 + .iter() + .flat_map(|(_, v)| v.values().map(|v| v.len())) + .sum::() + } + + pub fn try_into_iter( + self, + ) -> std::io::Result, Vec)>> { + Ok(self.into_iter()) + } + + // TODO make this a trait impl + #[allow(clippy::should_implement_trait)] + pub fn into_iter(self) -> impl Iterator, Vec)> { + let index_map = self.sample_type_index_map; + + // Invariant: all keys in aggregated/aggregated2/timestamped/timestamped2 come from + // add(), which indexes into self.sample_types for non-zero values. So every + // sample_type key is present in index_map. + let len: usize = self.sample_types.len(); + let accum_iter = self + .aggregated + .into_iter() + .flat_map(move |(sample_type, inner)| { + #[allow(clippy::unwrap_used)] + let index = index_map[sample_type].unwrap(); + inner.into_iter().map(move |(sample, value)| { + let mut vals = vec![0; len]; + vals[index] = value; + (sample, None, vals) + }) + }); + + let accum2_iter = self + .aggregated2 + .into_iter() + .flat_map(move |((st1, st2), inner)| { + #[allow(clippy::unwrap_used)] + let index1 = index_map[st1].unwrap(); + #[allow(clippy::unwrap_used)] + let index2 = index_map[st2].unwrap(); + inner.into_iter().map(move |(sample, (val1, val2))| { + let mut vals = vec![0; len]; + vals[index1] = val1; + vals[index2] = val2; + (sample, None, vals) + }) + }); + + let ts_iter = self + .timestamped + .into_iter() + .flat_map(move |(sample_type, inner)| { + #[allow(clippy::unwrap_used)] + let index = index_map[sample_type].unwrap(); + inner.into_iter().flat_map(move |(sample, ts_vals)| { + ts_vals.into_iter().map(move |(value, ts)| { + let mut vals = vec![0; len]; + vals[index] = value; + (sample, Some(ts), vals) + }) + }) + }); + + let ts2_iter = self + .timestamped2 + .into_iter() + .flat_map(move |((st1, st2), inner)| { + #[allow(clippy::unwrap_used)] + let index1 = index_map[st1].unwrap(); + #[allow(clippy::unwrap_used)] + let index2 = index_map[st2].unwrap(); + inner.into_iter().flat_map(move |(sample, ts_vals)| { + ts_vals.into_iter().map(move |(val1, val2, ts)| { + let mut vals = vec![0; len]; + vals[index1] = val1; + vals[index2] = val2; + (sample, Some(ts), vals) + }) + }) + }); + + accum_iter.chain(accum2_iter).chain(ts_iter).chain(ts2_iter) + } +} diff --git a/libdd-profiling/src/internal/profile/fuzz_tests.rs b/libdd-profiling/src/internal/profile/fuzz_tests.rs index a134462254..e2c4c072ce 100644 --- a/libdd-profiling/src/internal/profile/fuzz_tests.rs +++ b/libdd-profiling/src/internal/profile/fuzz_tests.rs @@ -452,6 +452,7 @@ fn fuzz_add_sample<'a>( } #[test] +#[cfg_attr(feature = "otel", ignore)] fn fuzz_failure_001() { let sample_types = []; let expected_sample_types = &[]; @@ -501,6 +502,7 @@ fn fuzz_failure_001() { /// Fuzzes adding a bunch of samples to the profile. #[test] +#[cfg_attr(feature = "otel", ignore)] #[cfg_attr(miri, ignore)] fn test_fuzz_add_sample() { let sample_types_gen = Vec::::produce(); @@ -541,6 +543,7 @@ fn test_fuzz_add_sample() { } #[test] +#[cfg_attr(feature = "otel", ignore)] #[cfg_attr(miri, ignore)] fn fuzz_add_sample_with_fixed_sample_length() { let sample_length_gen = 1..=64usize; @@ -667,6 +670,7 @@ impl From<&FuzzOperation> for Operation { } #[test] +#[cfg_attr(feature = "otel", ignore)] #[cfg_attr(miri, ignore)] fn fuzz_api_function_calls() { let sample_length_gen = 1..=64usize; diff --git a/libdd-profiling/src/internal/profile/mod.rs b/libdd-profiling/src/internal/profile/mod.rs index 280cebcd7a..ba76a2fc92 100644 --- a/libdd-profiling/src/internal/profile/mod.rs +++ b/libdd-profiling/src/internal/profile/mod.rs @@ -10,6 +10,7 @@ mod profiles_dictionary_translator; pub use profiles_dictionary_translator::*; use self::api::UpscalingInfo; +use super::upscaling::ActiveUpscalingRules; use super::*; use crate::api::ManagedStringId; use crate::collections::identifiable::*; @@ -31,6 +32,15 @@ use std::sync::atomic::AtomicU64; use std::sync::{Arc, Mutex}; use std::time::{Duration, SystemTime}; +#[cfg(feature = "otel")] +use enum_map::EnumMap; +#[cfg(feature = "otel")] +use opentelemetry_proto::tonic::common::v1::{any_value, AnyValue}; +#[cfg(feature = "otel")] +use prost::Message; +#[cfg(feature = "otel")] +use std::io::Write; + pub struct Profile { /// Translates from the new Id2 APIs to the older internal APIs. Long-term, /// this should probably use the dictionary directly. @@ -45,14 +55,16 @@ pub struct Profile { mappings: FxIndexSet, observations: Observations, period: Option, - sample_types: Box<[api::SampleType]>, + #[cfg(feature = "otel")] + sample_type_index_map: EnumMap>, + sample_types: std::sync::Arc<[api::SampleType]>, stack_traces: FxIndexSet, start_time: SystemTime, strings: StringTable, string_storage: Option>>, string_storage_cached_profile_id: Option, timestamp_key: StringId, - upscaling_rules: UpscalingRules, + upscaling_rules: ActiveUpscalingRules, } pub struct EncodedProfile { @@ -60,6 +72,9 @@ pub struct EncodedProfile { pub end: SystemTime, pub buffer: Vec, pub endpoints_stats: ProfiledEndpointsStats, + /// The filename to use when uploading this profile as a multipart attachment, + /// e.g. `"profile.pprof"` or `"profile.otel"`. + pub filename: &'static str, } impl EncodedProfile { @@ -89,6 +104,7 @@ impl EncodedProfile { end, buffer, endpoints_stats, + filename: "profile.pprof", }) } } @@ -325,6 +341,17 @@ impl Profile { label_value: &str, upscaling_info: UpscalingInfo, ) -> anyhow::Result<()> { + anyhow::ensure!(offset_values.len() == 1 || offset_values.len() == 2); + #[cfg(feature = "otel")] + if offset_values.len() == 2 { + anyhow::ensure!( + self.observations.paired_samples[offset_values[0]] == Some(offset_values[1]) + ); + anyhow::ensure!( + self.observations.paired_samples[offset_values[1]] == Some(offset_values[0]) + ); + } + let label_name_id = self.try_intern(label_name)?; let label_value_id = self.try_intern(label_value)?; self.upscaling_rules.add( @@ -391,7 +418,7 @@ impl Profile { sample_types: &[api::SampleType], period: Option, ) -> io::Result { - Self::try_new_internal(period, sample_types.to_vec().into_boxed_slice(), None, None) + Self::try_new_internal(period, std::sync::Arc::from(sample_types), None, None) } /// Tries to create a profile with the given period and sample types. @@ -404,7 +431,7 @@ impl Profile { ) -> io::Result { Self::try_new_internal( period, - sample_types.to_vec().into_boxed_slice(), + std::sync::Arc::from(sample_types), None, Some(ProfilesDictionaryTranslator::new(profiles_dictionary)), ) @@ -418,7 +445,7 @@ impl Profile { ) -> io::Result { Self::try_new_internal( period, - sample_types.to_vec().into_boxed_slice(), + std::sync::Arc::from(sample_types), Some(string_storage), None, ) @@ -445,7 +472,7 @@ impl Profile { let mut profile = Profile::try_new_internal( self.period, - self.sample_types.clone(), + std::sync::Arc::clone(&self.sample_types), self.string_storage.clone(), profiles_dictionary_translator, ) @@ -455,6 +482,42 @@ impl Profile { Ok(profile) } + /// Serialize the aggregated profile to OpenTelemetry OTLP format (compressed). + /// + /// # Arguments + /// * `end_time` - Optional end time of the profile. Passing None will use the current time. + /// * `duration` - Optional duration of the profile. Passing None will try to calculate the + /// duration based on the end time minus the start time, but under anomalous conditions this + /// may fail as system clocks can be adjusted. The programmer may also accidentally pass an + /// earlier time. The duration will be set to zero these cases. + /// + /// See also [`encode_otel`](Profile::encode_otel) for the same encoding as a public API. + #[cfg(feature = "otel")] + pub fn serialize_into_compressed_otel( + self, + end_time: Option, + duration: Option, + ) -> anyhow::Result { + self.encode_otel(end_time, duration) + } + + /// Serialize the aggregated profile, choosing the output format at runtime. + /// + /// If the `DD_PROFILING_OTEL_FORMAT` environment variable is set to any non-empty value **and** + /// the crate was compiled with the `otel` feature, the profile is encoded as OTLP; otherwise + /// it falls back to pprof. + pub fn serialize_into_compressed( + self, + end_time: Option, + duration: Option, + ) -> anyhow::Result { + #[cfg(feature = "otel")] + if std::env::var_os("DD_PROFILING_OTEL_FORMAT").is_some() { + return self.encode_otel(end_time, duration); + } + self.serialize_into_compressed_pprof(end_time, duration) + } + /// Serialize the aggregated profile, adding the end time and duration. /// # Arguments /// * `end_time` - Optional end time of the profile. Passing None will use the current time. @@ -496,6 +559,377 @@ impl Profile { Ok(encoded_profile) } + /// Encode the profile to OpenTelemetry OTLP format (compressed). + /// + /// Returns an [`EncodedProfile`] with the compressed wire format. Use + /// [`serialize_into_compressed_otel`](Profile::serialize_into_compressed_otel) for the + /// conventional API with the same behavior. + #[cfg(feature = "otel")] + pub fn encode_otel( + mut self, + end_time: Option, + duration: Option, + ) -> anyhow::Result { + let end = end_time.unwrap_or_else(SystemTime::now); + let start = self.start_time; + let endpoints_stats = std::mem::take(&mut self.endpoints.stats); + let duration_nanos = duration + .unwrap_or_else(|| { + end.duration_since(start).unwrap_or({ + // Let's not throw away the whole profile just because the clocks were wrong. + // todo: log that the clock went backward (or programmer mistake). + Duration::ZERO + }) + }) + .as_nanos() + .min(i64::MAX as u128) as i64; + + let time_unix_nano = start + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap_or(Duration::ZERO) + .as_nanos() as u64; + let duration_nano = duration_nanos.max(0) as u64; + + // Intern period and sample types before taking strings so their type/unit strings are in + // the string table. + let period_type = self.period.map(|p| { + let vt = self.intern_sample_type(p.sample_type); + crate::otel::ValueType { + type_strindex: vt.r#type.value.to_raw_id() as i32, + unit_strindex: vt.unit.value.to_raw_id() as i32, + ..Default::default() + } + }); + let period = self.period.map(|period| period.value).unwrap_or(0); + + let sample_types = self.sample_types.clone(); + let mut otel_profiles: HashMap = sample_types + .iter() + .map(|st| { + let sample_type = self.intern_sample_type(*st); + let sample_type = Some(crate::otel::ValueType { + type_strindex: sample_type.r#type.value.to_raw_id() as i32, + unit_strindex: sample_type.unit.value.to_raw_id() as i32, + ..Default::default() + }); + let profile = crate::otel::Profile { + sample_type, + time_unix_nano, + duration_nano, + period_type, + period, + ..Default::default() + }; + (*st, profile) + }) + .collect(); + + // Collect label set attribute indices (including endpoints) before taking strings, since + // get_endpoint_for_label_set needs self. Endpoints are deduped into labels so they appear + // in the attribute_table built from labels. + // extended_label_sets holds the same data as Label values, indexed by LabelSetId raw id, + // so upscaling rules can be matched by label key/value during sample emission. + let label_sets_raw = std::mem::take(&mut self.label_sets); + let mut label_set_attr_indices: Vec> = Vec::with_capacity(label_sets_raw.len()); + let mut extended_label_sets: Vec> = Vec::with_capacity(label_sets_raw.len()); + for label_set in &label_sets_raw { + // Label: Copy, so endpoint_label remains usable after the and_then chain below. + let endpoint_label: Option