1#![warn(missing_docs)]
40use std::{
41 borrow::Cow,
42 collections::{HashMap, HashSet},
43 fmt::{Debug, Display},
44 io::{Cursor, Read},
45 iter::{once, repeat_n},
46 sync::{
47 Arc,
48 atomic::{AtomicBool, AtomicI64, Ordering},
49 },
50 thread::JoinHandle,
51 time::{Duration, Instant},
52};
53
54use crossbeam::sync::{Parker, Unparker};
55use flate2::{
56 Compression,
57 bufread::{GzDecoder, GzEncoder},
58};
59use itertools::Itertools;
60use memory_stats::memory_stats;
61use nix::time::{ClockId, clock_gettime};
62use serde::{Deserialize, Serialize};
63use serde_json::{Value, json};
64use size_of::HumanBytes;
65use tracing::warn;
66
67#[derive(Copy, Clone, Debug)]
68struct Timestamp(
69 i64,
71);
72
73impl Timestamp {
74 fn now() -> Self {
75 let now = clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap();
76 Self(now.tv_sec() as i64 * 1_000_000_000 + now.tv_nsec() as i64)
77 }
78}
79
80impl From<Instant> for Timestamp {
81 fn from(value: Instant) -> Self {
82 let zero = unsafe { std::mem::zeroed::<Instant>() };
95 Self((value - zero).as_nanos() as i64)
96 }
97}
98
99impl Display for Timestamp {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 write!(f, "{}", self.0)
102 }
103}
104
105impl Serialize for Timestamp {
106 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
110 where
111 S: serde::Serializer,
112 {
113 let milliseconds = self.0 as f64 / 1_000_000.0;
114 milliseconds.serialize(serializer)
115 }
116}
117
118impl<'de> Deserialize<'de> for Timestamp {
119 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
123 where
124 D: serde::Deserializer<'de>,
125 {
126 let milliseconds = f64::deserialize(deserializer)?;
127 Ok(Self((milliseconds * 1_000_000.0) as i64))
128 }
129}
130
131impl Debug for Span {
132 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133 write!(f, "Span")?;
134 if let Some(inner) = &self.0 {
135 write!(f, "({})", &inner.name)?;
136 }
137 Ok(())
138 }
139}
140
141struct SpanInner {
142 start: Timestamp,
143 category: &'static str,
144 name: &'static str,
145 tooltip: String,
146}
147
148impl SpanInner {
149 #[cold]
150 fn new(name: &'static str) -> Self {
151 Self {
152 start: Timestamp::now(),
153 category: "Other",
154 name,
155 tooltip: String::new(),
156 }
157 }
158
159 #[cold]
160 fn record(self, is_span: bool) {
161 let marker = Marker {
162 start: self.start,
163 end: if is_span {
164 Timestamp::now()
165 } else {
166 self.start
167 },
168 category: self.category,
169 name: self.name,
170 tooltip: self.tooltip,
171 };
172 QUEUE.with(|queue| queue.push(marker));
173 }
174}
175
176pub struct Span(Option<SpanInner>);
188
189impl Span {
190 pub const BYTES: usize = std::mem::size_of::<Marker>();
193
194 #[must_use]
206 pub fn new(name: &'static str) -> Self {
207 Self(Capture::is_active().then(|| SpanInner::new(name)))
208 }
209
210 #[must_use]
217 pub fn with_category(mut self, category: &'static str) -> Self {
218 if let Some(inner) = &mut self.0 {
219 inner.category = category;
220 }
221 self
222 }
223
224 #[must_use]
232 pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
233 where
234 F: FnOnce() -> String,
235 {
236 if let Some(inner) = &mut self.0 {
237 inner.tooltip = tooltip();
238 }
239 self
240 }
241
242 #[must_use]
246 pub fn with_start(mut self, start: Instant) -> Self {
247 if let Some(inner) = &mut self.0 {
248 inner.start = start.into();
249 }
250 self
251 }
252
253 pub fn in_scope<F, T>(self, f: F) -> T
255 where
256 F: FnOnce() -> T,
257 {
258 f()
259 }
260
261 pub fn record(self) {
263 }
265
266 pub fn cancel(mut self) {
268 let _ = self.0.take();
269 }
270}
271
272impl Drop for Span {
273 fn drop(&mut self) {
274 if let Some(inner) = self.0.take() {
275 inner.record(true)
276 }
277 }
278}
279
280pub struct Event(Option<SpanInner>);
292
293impl Event {
294 #[must_use]
303 pub fn new(name: &'static str) -> Self {
304 Self(Capture::is_active().then(|| SpanInner::new(name)))
305 }
306
307 #[must_use]
314 pub fn with_category(mut self, category: &'static str) -> Self {
315 if let Some(inner) = &mut self.0 {
316 inner.category = category;
317 }
318 self
319 }
320
321 #[must_use]
329 pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
330 where
331 F: FnOnce() -> String,
332 {
333 if let Some(inner) = &mut self.0 {
334 inner.tooltip = tooltip();
335 }
336 self
337 }
338
339 pub fn record(self) {
341 if let Some(inner) = self.0 {
342 inner.record(false);
343 }
344 }
345}
346
347#[derive(Clone, Debug)]
349pub struct CaptureOptions {
350 memory_limit: Option<usize>,
351 record_rss: bool,
352}
353
354impl Default for CaptureOptions {
355 fn default() -> Self {
356 Self {
357 memory_limit: None,
358 record_rss: true,
359 }
360 }
361}
362
363impl CaptureOptions {
364 pub fn new() -> Self {
366 Self::default()
367 }
368
369 pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
376 Self {
377 memory_limit,
378 ..self
379 }
380 }
381
382 pub fn with_record_rss(self, record_rss: bool) -> Self {
387 Self { record_rss, ..self }
388 }
389
390 pub async fn start(self) -> Capture {
397 Capture::new(self, CAPTURE_MUTEX.lock().await)
398 }
399
400 pub fn blocking_start(self) -> Capture {
411 Capture::new(self, CAPTURE_MUTEX.blocking_lock())
412 }
413
414 pub fn try_start(self) -> Result<Capture, Self> {
421 let guard = match CAPTURE_MUTEX.try_lock() {
422 Ok(guard) => guard,
423 Err(_) => return Err(self),
424 };
425 Ok(Capture::new(self, guard))
426 }
427}
428
429static CAPTURE_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
430
431pub struct Capture {
438 _guard: tokio::sync::MutexGuard<'static, ()>,
439 memory: Option<JoinHandle<Vec<(Timestamp, usize)>>>,
440 unparker: Unparker,
441 request_exit: Arc<AtomicBool>,
442 block_limit: i64,
443}
444
445impl Capture {
446 fn new(params: CaptureOptions, guard: tokio::sync::MutexGuard<'static, ()>) -> Self {
447 if let Some(memory_limit) = params.memory_limit {
448 tracing::info!(
449 "marker capture limited to {}",
450 HumanBytes::from(memory_limit)
451 );
452 }
453 let block_limit = params.memory_limit.map_or(i64::MAX, |memory_limit| {
454 (memory_limit / BYTES_PER_BLOCK) as i64
455 });
456 let parker = Parker::new();
457 let unparker = parker.unparker().clone();
458 let request_exit = Arc::new(AtomicBool::new(false));
459 let memory = params.record_rss.then(|| {
460 std::thread::Builder::new()
461 .name(String::from("capture-rss"))
462 .spawn({
463 let request_exit = request_exit.clone();
464 move || {
465 let mut memory = Vec::new();
466 while !request_exit.load(Ordering::Acquire) {
467 if let Some(memory_stats) = memory_stats() {
468 memory.push((Timestamp::now(), memory_stats.physical_mem));
469 }
470 parker.park_timeout(Duration::from_millis(100));
471 }
472 memory
473 }
474 })
475 .expect("should be able to start a capture thread")
476 });
477 FREE_BLOCKS.store(block_limit, Ordering::Relaxed);
478 CAPTURING.store(true, Ordering::Release);
479 Self {
480 block_limit,
481 memory,
482 unparker,
483 request_exit,
484 _guard: guard,
485 }
486 }
487
488 pub fn finish(mut self) -> Annotations {
490 CAPTURING.store(false, Ordering::Release);
491 let remaining_blocks = FREE_BLOCKS.load(Ordering::Relaxed);
492 if remaining_blocks <= 0 {
493 tracing::info!("marker capture exceeded the limit");
494 } else {
495 let used_bytes = (self.block_limit - remaining_blocks) as usize * BYTES_PER_BLOCK;
496 tracing::info!("marker capture used {}", HumanBytes::from(used_bytes));
497 }
498
499 Annotations {
500 markers: self.take_markers(),
501 memory: self.take_memory(),
502 }
503 }
504
505 pub fn abort(self) {
509 tracing::info!("aborting profile annotation capture");
510 }
511
512 pub fn is_active() -> bool {
519 CAPTURING.load(Ordering::Acquire)
520 }
521
522 fn take_markers(&mut self) -> HashMap<usize, (Option<String>, Blocks)> {
523 let all_threads = ALL_THREAD_MARKERS.lock().unwrap();
524 let mut markers = HashMap::new();
525 for thread in &*all_threads {
526 markers.insert(thread.tid, (thread.name.clone(), thread.queue.take()));
527 }
528 markers
529 }
530
531 fn take_memory(&mut self) -> Vec<(Timestamp, usize)> {
532 if let Some(memory) = self.memory.take() {
533 self.request_exit.store(true, Ordering::Release);
534 self.unparker.unpark();
535 memory.join().unwrap_or_default()
536 } else {
537 Default::default()
538 }
539 }
540}
541
542impl Drop for Capture {
543 fn drop(&mut self) {
544 self.take_memory();
545
546 CAPTURING.store(false, Ordering::Release);
549 }
550}
551
552#[derive(thiserror::Error, Debug)]
554pub enum Error {
555 #[error("Error decompressing profile ")]
557 GzDecoderError(#[from] std::io::Error),
558
559 #[error("Error parsing profile")]
561 SerdeError(#[from] serde_json_path_to_error::Error),
562}
563
564#[derive(Default, Clone, Debug)]
566pub struct AnnotationOptions {
567 product: Option<String>,
568 os_cpu: Option<String>,
569}
570
571impl AnnotationOptions {
572 pub fn new() -> Self {
574 Self::default()
575 }
576
577 pub fn with_product(self, product: Option<impl Into<String>>) -> Self {
583 Self {
584 product: product.map(|s| s.into()),
585 ..self
586 }
587 }
588
589 pub fn with_os_cpu(self, os_cpu: Option<impl Into<String>>) -> Self {
595 Self {
596 os_cpu: os_cpu.map(|s| s.into()),
597 ..self
598 }
599 }
600}
601
602pub struct Annotations {
606 markers: HashMap<usize, (Option<String>, Blocks)>,
607 memory: Vec<(Timestamp, usize)>,
608}
609
610impl Annotations {
611 pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
618 let mut buffer = Vec::new();
621 let json = if profile.starts_with(&[0x1f, 0x8b]) {
622 GzDecoder::new(profile).read_to_end(&mut buffer)?;
623 &buffer
624 } else {
625 profile
626 };
627 let gzip = !buffer.is_empty();
628
629 let mut profile = serde_json_path_to_error::from_slice::<Profile>(json)?;
631 if let Some(product) = options.product {
632 profile.meta.product = product;
633 }
634 if let Some(os_cpu) = options.os_cpu {
635 profile.meta.os_cpu = os_cpu;
636 }
637 profile.meta.marker_schema.push(json!({
638 "name": "FelderaMarker",
639 "display": [
640 "marker-chart",
641 "marker-table"
642 ],
643 "chartLabel": "{marker.data.name}",
644 "tooltipLabel": "{marker.data.name}",
645 "tableLabel": "{marker.data.name}",
646 "description": "Marker generated by Feldera.",
647 "fields": [
648 {
649 "key": "name",
650 "label": "Name",
651 "format": "unique-string"
652 }
653 ]
654 }));
655 static CATEGORY_COLORS: [&str; 12] = [
658 "purple",
659 "green",
660 "orange",
661 "yellow",
662 "lightblue",
663 "blue",
664 "brown",
665 "magenta",
666 "red",
667 "lightred",
668 "darkgrey",
669 "grey",
670 ];
671 let mut categories = profile
672 .meta
673 .categories
674 .iter()
675 .enumerate()
676 .map(|(index, category)| (category.name.clone(), index))
677 .collect::<HashMap<_, _>>();
678 for (category, color) in self
679 .markers
680 .values()
681 .flat_map(|(_, markers)| markers.iter())
682 .map(|marker| marker.category)
683 .collect::<HashSet<_>>()
684 .into_iter()
685 .zip(CATEGORY_COLORS.iter().cycle())
686 {
687 categories.insert(category.into(), profile.meta.categories.len());
688 profile.meta.categories.push(Category {
689 color: (*color).into(),
690 name: category.into(),
691 other: [(String::from("subcategories"), json!(["Other"]))]
692 .into_iter()
693 .collect(),
694 });
695 }
696 for thread in &mut profile.threads {
697 if let Some(tid) = &thread.tid
698 && let Ok(tid) = tid.parse::<usize>()
699 && let Some((name, markers)) = self.markers.get(&tid)
700 {
701 if let Some(name) = name {
702 thread.name = Some(name.clone());
703 }
704 for marker in markers.iter() {
705 thread.markers.length += 1;
706 thread.markers.category.push(categories[marker.category]);
707 thread.markers.data.push(ProfileMarkerData {
708 type_: Cow::from("FelderaMarker"),
709 name: profile.shared.add_name(&marker.tooltip),
710 });
711 thread.markers.start_time.push(marker.start);
712 thread.markers.end_time.push(marker.end);
713 thread
714 .markers
715 .name
716 .push(profile.shared.add_name(marker.name));
717 thread.markers.phase.push(1);
718 }
719 }
720 }
721
722 if !self.memory.is_empty() {
723 profile.counters.push(RawCounter {
724 name: String::from("RSS"),
725 category: String::from("Memory"),
726 description: String::from("RSS in bytes"),
727 pid: profile.threads.first().unwrap().pid.clone(),
728 main_thread_index: 0,
729 samples: {
730 RawCounterSamplesTable {
731 time: self
732 .memory
733 .iter()
734 .copied()
735 .map(|(time, _rss)| time)
736 .collect(),
737 time_deltas: Vec::new(),
738 number: repeat_n(0, self.memory.len()).collect(),
739 count: once(self.memory[0].1 as i64)
740 .chain(
741 self.memory
742 .iter()
743 .map(|(_time, rss)| *rss as i64)
744 .tuple_windows()
745 .map(|(prev, next)| next - prev),
746 )
747 .collect(),
748 length: self.memory.len(),
749 other: Default::default(),
750 }
751 },
752 other: Default::default(),
753 });
754 }
755
756 let output = serde_json::to_vec(&profile).unwrap();
758 let output = if gzip {
759 let mut gzipped_output = Vec::new();
760 GzEncoder::new(Cursor::new(output), Compression::fast())
761 .read_to_end(&mut gzipped_output)
762 .unwrap();
763 gzipped_output
764 } else {
765 output
766 };
767
768 return Ok(output);
769
770 #[derive(Debug, Serialize, Deserialize)]
774 #[serde(rename_all = "camelCase")]
775 struct Profile {
776 meta: Meta,
777 threads: Vec<Thread>,
778 #[serde(default)]
779 counters: Vec<RawCounter>,
780 shared: Shared,
781 #[serde(flatten)]
782 other: HashMap<String, Value>,
783 }
784
785 #[derive(Debug, Serialize, Deserialize)]
786 #[serde(rename_all = "camelCase")]
787 struct Meta {
788 product: String,
789 #[serde(rename = "oscpu")]
790 os_cpu: String,
791 categories: Vec<Category>,
792 marker_schema: Vec<Value>,
793 #[serde(flatten)]
794 other: HashMap<String, Value>,
795 }
796
797 #[derive(Debug, Serialize, Deserialize)]
798 #[serde(rename_all = "camelCase")]
799 struct Category {
800 color: String,
801 name: String,
802 #[serde(flatten)]
803 other: HashMap<String, Value>,
804 }
805
806 #[derive(Debug, Serialize, Deserialize)]
807 #[serde(rename_all = "camelCase")]
808 struct Thread {
809 name: Option<String>,
810 #[serde(default)]
811 markers: ProfileMarkers,
812 tid: Option<String>,
813 pid: String,
814 #[serde(flatten)]
815 other: HashMap<String, Value>,
816 }
817
818 #[derive(Default, Debug, Serialize, Deserialize)]
819 #[serde(rename_all = "camelCase")]
820 struct ProfileMarkers {
821 length: usize,
822 category: Vec<usize>,
823 data: Vec<ProfileMarkerData>,
824 start_time: Vec<Timestamp>,
825 end_time: Vec<Timestamp>,
826 name: Vec<usize>,
827 phase: Vec<usize>,
828 }
829
830 #[derive(Default, Debug, Serialize, Deserialize)]
831 #[serde(rename_all = "camelCase")]
832 struct ProfileMarkerData {
833 #[serde(rename = "type")]
834 type_: Cow<'static, str>,
835 name: usize,
836 }
837
838 #[derive(Debug, Serialize, Deserialize)]
839 #[serde(rename_all = "camelCase")]
840 struct Shared {
841 string_array: Vec<String>,
842 #[serde(flatten)]
843 other: HashMap<String, Value>,
844 }
845
846 impl Shared {
847 fn add_name(&mut self, name: &str) -> usize {
848 let index = self.string_array.len();
849 self.string_array.push(name.into());
850 index
851 }
852 }
853
854 #[derive(Default, Debug, Serialize, Deserialize)]
855 #[serde(rename_all = "camelCase")]
856 struct RawCounter {
857 name: String,
858 category: String,
859 description: String,
860 pid: String,
861 main_thread_index: usize,
862 samples: RawCounterSamplesTable,
863 #[serde(flatten)]
864 other: HashMap<String, Value>,
865 }
866
867 #[derive(Default, Debug, Serialize, Deserialize)]
868 #[serde(rename_all = "camelCase")]
869 struct RawCounterSamplesTable {
870 #[serde(default, skip_serializing_if = "Vec::is_empty")]
871 time: Vec<Timestamp>,
872 #[serde(default, skip_serializing_if = "Vec::is_empty")]
873 time_deltas: Vec<Timestamp>,
874 #[serde(default, skip_serializing_if = "Vec::is_empty")]
875 number: Vec<usize>,
876 count: Vec<i64>,
877 length: usize,
878 #[serde(flatten)]
879 other: HashMap<String, Value>,
880 }
881 }
882}
883
884static CAPTURING: AtomicBool = AtomicBool::new(false);
886
887struct Marker {
889 start: Timestamp,
891 end: Timestamp,
893 category: &'static str,
895 name: &'static str,
897 tooltip: String,
899}
900
901struct ThreadMarkers {
903 tid: usize,
907
908 name: Option<String>,
913
914 queue: Arc<Queue>,
919}
920
921impl ThreadMarkers {
922 fn new(queue: Arc<Queue>) -> Self {
923 #[cfg(target_os = "linux")]
924 let tid = nix::unistd::gettid().as_raw() as usize;
925 #[cfg(not(target_os = "linux"))]
926 let tid = thread_id::get();
927
928 Self {
929 tid,
930 name: std::thread::current().name().map(|s| s.into()),
931 queue,
932 }
933 }
934}
935
936static ALL_THREAD_MARKERS: std::sync::Mutex<Vec<ThreadMarkers>> = std::sync::Mutex::new(Vec::new());
938
939static FREE_BLOCKS: AtomicI64 = AtomicI64::new(0);
940const MARKERS_PER_BLOCK: usize = 32;
941const BYTES_PER_BLOCK: usize = MARKERS_PER_BLOCK * Span::BYTES;
942
943struct Block(Vec<Marker>);
944impl Block {
945 fn new(marker: Marker) -> Self {
946 let mut markers = Vec::with_capacity(MARKERS_PER_BLOCK);
947 markers.push(marker);
948 Self(markers)
949 }
950 fn is_full(&self) -> bool {
951 self.0.len() >= self.0.capacity()
952 }
953 fn push(&mut self, marker: Marker) {
954 self.0.push(marker);
955 }
956}
957
958struct Blocks(Vec<Block>);
959
960impl Default for Blocks {
961 fn default() -> Self {
962 Self(Vec::with_capacity(32))
963 }
964}
965
966impl Blocks {
967 fn push(&mut self, marker: Marker) {
968 if let Some(block) = self.0.last_mut()
969 && !block.is_full()
970 {
971 block.push(marker);
972 } else {
973 match FREE_BLOCKS.fetch_sub(1, Ordering::Relaxed) {
974 1.. => self.0.push(Block::new(marker)),
975 0 => warn!("marker capture space exhausted"),
976 _ => (),
977 }
978 }
979 }
980
981 fn iter(&self) -> impl Iterator<Item = &Marker> {
982 self.0.iter().flat_map(|block| block.0.iter())
983 }
984}
985
986struct Queue(std::sync::Mutex<Blocks>);
987
988impl Queue {
989 fn new() -> Arc<Self> {
990 let queue = Arc::new(Self(Default::default()));
991 ALL_THREAD_MARKERS
992 .lock()
993 .unwrap()
994 .push(ThreadMarkers::new(queue.clone()));
995 queue
996 }
997
998 fn push(&self, marker: Marker) {
999 self.0.lock().unwrap().push(marker);
1000 }
1001
1002 fn take(&self) -> Blocks {
1003 std::mem::take(&mut *self.0.lock().unwrap())
1004 }
1005}
1006
1007thread_local! {
1008 static QUEUE: Arc<Queue> = Queue::new();
1009}