pyroscope 1.0.9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,303 @@
1
+ use super::BackendConfig;
2
+ use crate::error::Result;
3
+ use std::{
4
+ collections::{hash_map::DefaultHasher, BTreeSet, HashMap},
5
+ hash::{Hash, Hasher},
6
+ };
7
+
8
+ /// Pyroscope Tag
9
+ #[derive(Debug, PartialOrd, Ord, Eq, PartialEq, Hash, Clone)]
10
+ pub struct Tag {
11
+ /// Tag key
12
+ pub key: String,
13
+ /// Tag value
14
+ pub value: String,
15
+ }
16
+
17
+ impl Tag {
18
+ /// Create a new Tag
19
+ pub fn new(key: String, value: String) -> Self {
20
+ Self { key, value }
21
+ }
22
+ }
23
+
24
+ impl std::fmt::Display for Tag {
25
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26
+ write!(f, "{}={}", self.key, self.value)
27
+ }
28
+ }
29
+
30
+ /// Stack buffer
31
+ #[derive(Debug, Default, Clone)]
32
+ pub struct StackBuffer {
33
+ /// Buffer data bucket
34
+ pub data: HashMap<StackTrace, usize>,
35
+ }
36
+
37
+ impl StackBuffer {
38
+ /// Create a new StackBuffer with the given data
39
+ pub fn new(data: HashMap<StackTrace, usize>) -> Self {
40
+ Self { data }
41
+ }
42
+
43
+ /// Record a new stack trace
44
+ pub fn record(&mut self, stack_trace: StackTrace) -> Result<()> {
45
+ *self.data.entry(stack_trace).or_insert(0) += 1;
46
+
47
+ Ok(())
48
+ }
49
+
50
+ /// Record a new stack trace with count
51
+ pub fn record_with_count(&mut self, stack_trace: StackTrace, count: usize) -> Result<()> {
52
+ *self.data.entry(stack_trace).or_insert(0) += count;
53
+
54
+ Ok(())
55
+ }
56
+
57
+ /// Clear the buffer
58
+ pub fn clear(&mut self) {
59
+ self.data.clear();
60
+ }
61
+ }
62
+
63
+ impl From<StackBuffer> for Vec<Report> {
64
+ fn from(stack_buffer: StackBuffer) -> Self {
65
+ stack_buffer
66
+ .data
67
+ .into_iter()
68
+ .fold(
69
+ HashMap::new(),
70
+ |acc: HashMap<usize, Report>, (stacktrace, count): (StackTrace, usize)| {
71
+ let mut acc = acc;
72
+ if let Some(report) = acc.get_mut(&stacktrace.metadata.get_id()) {
73
+ report.record_with_count(stacktrace, count);
74
+ } else {
75
+ let report = Report::new(HashMap::new());
76
+ let report_id = stacktrace.metadata.get_id();
77
+ let mut report = report.metadata(stacktrace.metadata.clone());
78
+ report.record_with_count(stacktrace, count);
79
+ acc.insert(report_id, report);
80
+ }
81
+ acc
82
+ },
83
+ )
84
+ .into_values()
85
+ .collect()
86
+ }
87
+ }
88
+
89
+ /// Metdata
90
+ /// Metadata attached to a StackTrace or a Report. For now, this is just tags.
91
+ #[derive(Debug, Default, Clone, Hash, PartialEq, Eq)]
92
+ pub struct Metadata {
93
+ /// Tags
94
+ pub tags: BTreeSet<Tag>,
95
+ }
96
+
97
+ impl Metadata {
98
+ /// Add a tag to the metadata
99
+ pub fn add_tag(&mut self, tag: Tag) {
100
+ self.tags.insert(tag);
101
+ }
102
+
103
+ /// Get the id of the metadata. This uses the hash of the Metadata type.
104
+ pub fn get_id(&self) -> usize {
105
+ let mut hasher = DefaultHasher::new();
106
+ self.hash(&mut hasher);
107
+ hasher.finish() as usize
108
+ }
109
+ }
110
+
111
+ /// The payload of a report batch: either structured stack-trace reports
112
+ /// (which will be encoded into pprof by the session layer) or pre-encoded
113
+ /// pprof bytes produced directly by a backend (e.g. jemalloc).
114
+ pub enum ReportData {
115
+ /// Structured stack-trace reports that must be pprof-encoded before sending.
116
+ Reports(Vec<Report>),
117
+ /// Pre-encoded pprof bytes (may already be gzipped). Used by backends
118
+ /// like jemalloc that produce a complete pprof profile directly.
119
+ RawPprof(Vec<u8>),
120
+ }
121
+
122
+ /// A batch of reports with a shared profile type.
123
+ pub struct ReportBatch {
124
+ /// Profile type name (e.g. "process_cpu", "memory")
125
+ pub profile_type: String,
126
+ /// Report data in this batch
127
+ pub data: ReportData,
128
+ }
129
+
130
+ /// Report
131
+ #[derive(Debug, Default, Clone)]
132
+ pub struct Report {
133
+ /// Report StackTraces
134
+ pub data: HashMap<StackTrace, usize>,
135
+ /// Metadata
136
+ pub metadata: Metadata,
137
+ }
138
+
139
+ /// Custom implementation of the Hash trait for Report.
140
+ /// Only the metadata is hashed.
141
+ impl Hash for Report {
142
+ fn hash<H: Hasher>(&self, state: &mut H) {
143
+ self.metadata.hash(state);
144
+ }
145
+ }
146
+
147
+ impl Report {
148
+ /// Create a new Report.
149
+ pub fn new(data: HashMap<StackTrace, usize>) -> Self {
150
+ Self {
151
+ data,
152
+ metadata: Metadata::default(),
153
+ }
154
+ }
155
+
156
+ /// Return an iterator over the StackTraces of the Report.
157
+ pub fn iter(&self) -> impl Iterator<Item = (&StackTrace, &usize)> {
158
+ self.data.iter()
159
+ }
160
+
161
+ /// Set the metadata of the report.
162
+ pub fn metadata(self, metadata: Metadata) -> Self {
163
+ Self {
164
+ data: self.data,
165
+ metadata,
166
+ }
167
+ }
168
+
169
+ pub fn record(&mut self, stack_trace: StackTrace) {
170
+ *self.data.entry(stack_trace).or_insert(0) += 1;
171
+ }
172
+
173
+ pub fn record_with_count(&mut self, stack_trace: StackTrace, count: usize) {
174
+ *self.data.entry(stack_trace).or_insert(0) += count;
175
+ }
176
+ }
177
+
178
+ /// StackTrace
179
+ /// A representation of a stack trace.
180
+ #[derive(Debug, Default, PartialEq, Eq, Hash, Clone)]
181
+ pub struct StackTrace {
182
+ /// Process ID
183
+ pub pid: Option<u32>,
184
+ /// Thread ID
185
+ pub thread_id: Option<crate::utils::ThreadId>,
186
+ /// Thread Name
187
+ pub thread_name: Option<String>,
188
+ /// Stack Trace
189
+ pub frames: Vec<StackFrame>,
190
+ /// Metadata
191
+ pub metadata: Metadata,
192
+ }
193
+
194
+ impl std::fmt::Display for StackTrace {
195
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196
+ write!(
197
+ f,
198
+ "{}",
199
+ &self
200
+ .frames
201
+ .iter()
202
+ .rev()
203
+ .map(|frame| format!("{frame}"))
204
+ .collect::<Vec<_>>()
205
+ .join(";")
206
+ )
207
+ }
208
+ }
209
+
210
+ impl StackTrace {
211
+ /// Create a new StackTrace
212
+ pub fn new(
213
+ config: &BackendConfig,
214
+ pid: Option<u32>,
215
+ thread_id: Option<crate::utils::ThreadId>,
216
+ thread_name: Option<String>,
217
+ frames: Vec<StackFrame>,
218
+ ) -> Self {
219
+ let mut metadata = Metadata::default();
220
+
221
+ if config.report_pid {
222
+ if let Some(pid) = pid {
223
+ metadata.add_tag(Tag::new("pid".to_owned(), pid.to_string()));
224
+ }
225
+ }
226
+
227
+ if config.report_thread_id {
228
+ if let Some(thread_id) = &thread_id {
229
+ metadata.add_tag(Tag::new("thread_id".to_owned(), thread_id.to_string()));
230
+ }
231
+ }
232
+
233
+ if config.report_thread_name {
234
+ if let Some(thread_name) = thread_name.clone() {
235
+ metadata.add_tag(Tag::new("thread_name".to_owned(), thread_name));
236
+ }
237
+ }
238
+
239
+ Self {
240
+ pid,
241
+ thread_id,
242
+ thread_name,
243
+ frames,
244
+ metadata,
245
+ }
246
+ }
247
+
248
+ /// Return an iterator over the frames of the stacktrace.
249
+ pub fn iter(&self) -> impl Iterator<Item = &StackFrame> {
250
+ self.frames.iter()
251
+ }
252
+ }
253
+
254
+ /// StackFrame
255
+ /// A representation of a stack frame.
256
+ #[derive(Debug, Default, PartialEq, Eq, Hash, Clone)]
257
+ pub struct StackFrame {
258
+ /// Module name
259
+ pub module: Option<String>,
260
+ /// Function name
261
+ pub name: Option<String>,
262
+ /// File name
263
+ pub filename: Option<String>,
264
+ /// File relative path
265
+ pub relative_path: Option<String>,
266
+ /// File absolute path
267
+ pub absolute_path: Option<String>,
268
+ /// Line number
269
+ pub line: Option<u32>,
270
+ }
271
+
272
+ impl StackFrame {
273
+ /// Create a new StackFrame.
274
+ pub fn new(
275
+ module: Option<String>,
276
+ name: Option<String>,
277
+ filename: Option<String>,
278
+ relative_path: Option<String>,
279
+ absolute_path: Option<String>,
280
+ line: Option<u32>,
281
+ ) -> Self {
282
+ Self {
283
+ module,
284
+ name,
285
+ filename,
286
+ relative_path,
287
+ absolute_path,
288
+ line,
289
+ }
290
+ }
291
+ }
292
+
293
+ impl std::fmt::Display for StackFrame {
294
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295
+ write!(
296
+ f,
297
+ "{}:{} - {}",
298
+ self.filename.as_ref().unwrap_or(&"".to_string()),
299
+ self.line.unwrap_or(0),
300
+ self.name.as_ref().unwrap_or(&"".to_string())
301
+ )
302
+ }
303
+ }
@@ -0,0 +1,233 @@
1
+ // @generated
2
+ // This file is @generated by prost-build.
3
+ #[derive(Clone, PartialEq, ::prost::Message)]
4
+ pub struct Profile {
5
+ /// A description of the samples associated with each Sample.value.
6
+ /// For a cpu profile this might be:
7
+ /// \[["cpu","nanoseconds"]\] or \[["wall","seconds"]\] or \[["syscall","count"]\]
8
+ /// For a heap profile, this might be:
9
+ /// \[["allocations","count"\], \["space","bytes"]\],
10
+ /// If one of the values represents the number of events represented
11
+ /// by the sample, by convention it should be at index 0 and use
12
+ /// sample_type.unit == "count".
13
+ #[prost(message, repeated, tag = "1")]
14
+ pub sample_type: ::prost::alloc::vec::Vec<ValueType>,
15
+ /// The set of samples recorded in this profile.
16
+ #[prost(message, repeated, tag = "2")]
17
+ pub sample: ::prost::alloc::vec::Vec<Sample>,
18
+ /// Mapping from address ranges to the image/binary/library mapped
19
+ /// into that address range. mapping\[0\] will be the main binary.
20
+ #[prost(message, repeated, tag = "3")]
21
+ pub mapping: ::prost::alloc::vec::Vec<Mapping>,
22
+ /// Useful program location
23
+ #[prost(message, repeated, tag = "4")]
24
+ pub location: ::prost::alloc::vec::Vec<Location>,
25
+ /// Functions referenced by locations
26
+ #[prost(message, repeated, tag = "5")]
27
+ pub function: ::prost::alloc::vec::Vec<Function>,
28
+ /// A common table for strings referenced by various messages.
29
+ /// string_table\[0\] must always be "".
30
+ #[prost(string, repeated, tag = "6")]
31
+ pub string_table: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
32
+ /// frames with Function.function_name fully matching the following
33
+ /// regexp will be dropped from the samples, along with their successors.
34
+ ///
35
+ /// Index into string table.
36
+ #[prost(int64, tag = "7")]
37
+ pub drop_frames: i64,
38
+ /// frames with Function.function_name fully matching the following
39
+ /// regexp will be kept, even if it matches drop_frames.
40
+ ///
41
+ /// Index into string table.
42
+ #[prost(int64, tag = "8")]
43
+ pub keep_frames: i64,
44
+ // The following fields are informational, do not affect
45
+ // interpretation of results.
46
+ /// Time of collection (UTC) represented as nanoseconds past the epoch.
47
+ #[prost(int64, tag = "9")]
48
+ pub time_nanos: i64,
49
+ /// Duration of the profile, if a duration makes sense.
50
+ #[prost(int64, tag = "10")]
51
+ pub duration_nanos: i64,
52
+ /// The kind of events between sampled ocurrences.
53
+ /// e.g \[ "cpu","cycles" \] or \[ "heap","bytes" \]
54
+ #[prost(message, optional, tag = "11")]
55
+ pub period_type: ::core::option::Option<ValueType>,
56
+ /// The number of events between sampled occurrences.
57
+ #[prost(int64, tag = "12")]
58
+ pub period: i64,
59
+ /// Freeform text associated to the profile.
60
+ ///
61
+ /// Indices into string table.
62
+ #[prost(int64, repeated, tag = "13")]
63
+ pub comment: ::prost::alloc::vec::Vec<i64>,
64
+ /// Index into the string table of the type of the preferred sample
65
+ /// value. If unset, clients should default to the last sample value.
66
+ #[prost(int64, tag = "14")]
67
+ pub default_sample_type: i64,
68
+ }
69
+ /// ValueType describes the semantics and measurement units of a value.
70
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
71
+ pub struct ValueType {
72
+ /// Index into string table.
73
+ #[prost(int64, tag = "1")]
74
+ pub r#type: i64,
75
+ /// Index into string table.
76
+ #[prost(int64, tag = "2")]
77
+ pub unit: i64,
78
+ }
79
+ /// Each Sample records values encountered in some program
80
+ /// context. The program context is typically a stack trace, perhaps
81
+ /// augmented with auxiliary information like the thread-id, some
82
+ /// indicator of a higher level request being handled etc.
83
+ #[derive(Clone, PartialEq, ::prost::Message)]
84
+ pub struct Sample {
85
+ /// The ids recorded here correspond to a Profile.location.id.
86
+ /// The leaf is at location_id\[0\].
87
+ #[prost(uint64, repeated, tag = "1")]
88
+ pub location_id: ::prost::alloc::vec::Vec<u64>,
89
+ /// The type and unit of each value is defined by the corresponding
90
+ /// entry in Profile.sample_type. All samples must have the same
91
+ /// number of values, the same as the length of Profile.sample_type.
92
+ /// When aggregating multiple samples into a single sample, the
93
+ /// result has a list of values that is the element-wise sum of the
94
+ /// lists of the originals.
95
+ #[prost(int64, repeated, tag = "2")]
96
+ pub value: ::prost::alloc::vec::Vec<i64>,
97
+ /// label includes additional context for this sample. It can include
98
+ /// things like a thread id, allocation size, etc
99
+ #[prost(message, repeated, tag = "3")]
100
+ pub label: ::prost::alloc::vec::Vec<Label>,
101
+ }
102
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
103
+ pub struct Label {
104
+ /// Index into string table
105
+ #[prost(int64, tag = "1")]
106
+ pub key: i64,
107
+ /// At most one of the following must be present
108
+ ///
109
+ /// Index into string table
110
+ #[prost(int64, tag = "2")]
111
+ pub str: i64,
112
+ #[prost(int64, tag = "3")]
113
+ pub num: i64,
114
+ /// Should only be present when num is present.
115
+ /// Specifies the units of num.
116
+ /// Use arbitrary string (for example, "requests") as a custom count unit.
117
+ /// If no unit is specified, consumer may apply heuristic to deduce the unit.
118
+ /// Consumers may also interpret units like "bytes" and "kilobytes" as memory
119
+ /// units and units like "seconds" and "nanoseconds" as time units,
120
+ /// and apply appropriate unit conversions to these.
121
+ ///
122
+ /// Index into string table
123
+ #[prost(int64, tag = "4")]
124
+ pub num_unit: i64,
125
+ }
126
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
127
+ pub struct Mapping {
128
+ /// Unique nonzero id for the mapping.
129
+ #[prost(uint64, tag = "1")]
130
+ pub id: u64,
131
+ /// Address at which the binary (or DLL) is loaded into memory.
132
+ #[prost(uint64, tag = "2")]
133
+ pub memory_start: u64,
134
+ /// The limit of the address range occupied by this mapping.
135
+ #[prost(uint64, tag = "3")]
136
+ pub memory_limit: u64,
137
+ /// Offset in the binary that corresponds to the first mapped address.
138
+ #[prost(uint64, tag = "4")]
139
+ pub file_offset: u64,
140
+ /// The object this entry is loaded from. This can be a filename on
141
+ /// disk for the main binary and shared libraries, or virtual
142
+ /// abstractions like "\[vdso\]".
143
+ ///
144
+ /// Index into string table
145
+ #[prost(int64, tag = "5")]
146
+ pub filename: i64,
147
+ /// A string that uniquely identifies a particular program version
148
+ /// with high probability. E.g., for binaries generated by GNU tools,
149
+ /// it could be the contents of the .note.gnu.build-id field.
150
+ ///
151
+ /// Index into string table
152
+ #[prost(int64, tag = "6")]
153
+ pub build_id: i64,
154
+ /// The following fields indicate the resolution of symbolic info.
155
+ #[prost(bool, tag = "7")]
156
+ pub has_functions: bool,
157
+ #[prost(bool, tag = "8")]
158
+ pub has_filenames: bool,
159
+ #[prost(bool, tag = "9")]
160
+ pub has_line_numbers: bool,
161
+ #[prost(bool, tag = "10")]
162
+ pub has_inline_frames: bool,
163
+ }
164
+ /// Describes function and line table debug information.
165
+ #[derive(Clone, PartialEq, ::prost::Message)]
166
+ pub struct Location {
167
+ /// Unique nonzero id for the location. A profile could use
168
+ /// instruction addresses or any integer sequence as ids.
169
+ #[prost(uint64, tag = "1")]
170
+ pub id: u64,
171
+ /// The id of the corresponding profile.Mapping for this location.
172
+ /// It can be unset if the mapping is unknown or not applicable for
173
+ /// this profile type.
174
+ #[prost(uint64, tag = "2")]
175
+ pub mapping_id: u64,
176
+ /// The instruction address for this location, if available. It
177
+ /// should be within \[Mapping.memory_start...Mapping.memory_limit\]
178
+ /// for the corresponding mapping. A non-leaf address may be in the
179
+ /// middle of a call instruction. It is up to display tools to find
180
+ /// the beginning of the instruction if necessary.
181
+ #[prost(uint64, tag = "3")]
182
+ pub address: u64,
183
+ /// Multiple line indicates this location has inlined functions,
184
+ /// where the last entry represents the caller into which the
185
+ /// preceding entries were inlined.
186
+ ///
187
+ /// E.g., if memcpy() is inlined into printf:
188
+ /// line\[0\].function_name == "memcpy"
189
+ /// line\[1\].function_name == "printf"
190
+ #[prost(message, repeated, tag = "4")]
191
+ pub line: ::prost::alloc::vec::Vec<Line>,
192
+ /// Provides an indication that multiple symbols map to this location's
193
+ /// address, for example due to identical code folding by the linker. In that
194
+ /// case the line information above represents one of the multiple
195
+ /// symbols. This field must be recomputed when the symbolization state of the
196
+ /// profile changes.
197
+ #[prost(bool, tag = "5")]
198
+ pub is_folded: bool,
199
+ }
200
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
201
+ pub struct Line {
202
+ /// The id of the corresponding profile.Function for this line.
203
+ #[prost(uint64, tag = "1")]
204
+ pub function_id: u64,
205
+ /// Line number in source code.
206
+ #[prost(int64, tag = "2")]
207
+ pub line: i64,
208
+ }
209
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
210
+ pub struct Function {
211
+ /// Unique nonzero id for the function.
212
+ #[prost(uint64, tag = "1")]
213
+ pub id: u64,
214
+ /// Name of the function, in human-readable form if available.
215
+ ///
216
+ /// Index into string table
217
+ #[prost(int64, tag = "2")]
218
+ pub name: i64,
219
+ /// Name of the function, as identified by the system.
220
+ /// For instance, it can be a C++ mangled name.
221
+ ///
222
+ /// Index into string table
223
+ #[prost(int64, tag = "3")]
224
+ pub system_name: i64,
225
+ /// Source file containing the function.
226
+ ///
227
+ /// Index into string table
228
+ #[prost(int64, tag = "4")]
229
+ pub filename: i64,
230
+ /// Line number in source file.
231
+ #[prost(int64, tag = "5")]
232
+ pub start_line: i64,
233
+ }
@@ -0,0 +1,3 @@
1
+ pub mod google;
2
+ pub mod push;
3
+ pub mod types;
@@ -0,0 +1,31 @@
1
+ // @generated
2
+ // This file is @generated by prost-build.
3
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
4
+ pub struct PushResponse {}
5
+ /// WriteRawRequest writes a pprof profile
6
+ #[derive(Clone, PartialEq, ::prost::Message)]
7
+ pub struct PushRequest {
8
+ /// series is a set raw pprof profiles and accompanying labels
9
+ #[prost(message, repeated, tag = "1")]
10
+ pub series: ::prost::alloc::vec::Vec<RawProfileSeries>,
11
+ }
12
+ /// RawProfileSeries represents the pprof profile and its associated labels
13
+ #[derive(Clone, PartialEq, ::prost::Message)]
14
+ pub struct RawProfileSeries {
15
+ /// LabelPair is the key value pairs to identify the corresponding profile
16
+ #[prost(message, repeated, tag = "1")]
17
+ pub labels: ::prost::alloc::vec::Vec<super::types::LabelPair>,
18
+ /// samples are the set of profile bytes
19
+ #[prost(message, repeated, tag = "2")]
20
+ pub samples: ::prost::alloc::vec::Vec<RawSample>,
21
+ }
22
+ /// RawSample is the set of bytes that correspond to a pprof profile
23
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
24
+ pub struct RawSample {
25
+ /// raw_profile is the set of bytes of the pprof profile
26
+ #[prost(bytes = "vec", tag = "1")]
27
+ pub raw_profile: ::prost::alloc::vec::Vec<u8>,
28
+ /// UUID of the profile
29
+ #[prost(string, tag = "2")]
30
+ pub id: ::prost::alloc::string::String,
31
+ }
@@ -0,0 +1,11 @@
1
+ // @generated
2
+ // This file is @generated by prost-build.
3
+ #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
4
+ pub struct LabelPair {
5
+ /// Label name
6
+ #[prost(string, tag = "1")]
7
+ pub name: ::prost::alloc::string::String,
8
+ /// Label value
9
+ #[prost(string, tag = "2")]
10
+ pub value: ::prost::alloc::string::String,
11
+ }
@@ -0,0 +1,2 @@
1
+ pub mod gen;
2
+ pub mod pprof;