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>
107 where
108 S: serde::Serializer,
109 {
110 let microseconds = self.0 as f64 / 1_000_000.0;
111 microseconds.serialize(serializer)
112 }
113}
114
115impl<'de> Deserialize<'de> for Timestamp {
116 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
117 where
118 D: serde::Deserializer<'de>,
119 {
120 let microseconds = f64::deserialize(deserializer)?;
121 Ok(Self((microseconds * 1_000_000.0) as i64))
122 }
123}
124
125impl Debug for Span {
126 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127 write!(f, "Span")?;
128 if let Some(inner) = &self.0 {
129 write!(f, "({})", &inner.name)?;
130 }
131 Ok(())
132 }
133}
134
135struct SpanInner {
136 start: Timestamp,
137 category: &'static str,
138 name: &'static str,
139 tooltip: String,
140}
141
142impl SpanInner {
143 #[cold]
144 fn new(name: &'static str) -> Self {
145 Self {
146 start: Timestamp::now(),
147 category: "Other",
148 name,
149 tooltip: String::new(),
150 }
151 }
152
153 #[cold]
154 fn record(self, is_span: bool) {
155 let marker = Marker {
156 start: self.start,
157 end: if is_span {
158 Timestamp::now()
159 } else {
160 self.start
161 },
162 category: self.category,
163 name: self.name,
164 tooltip: self.tooltip,
165 };
166 QUEUE.with(|queue| queue.push(marker));
167 }
168}
169
170pub struct Span(Option<SpanInner>);
182
183impl Span {
184 pub const BYTES: usize = std::mem::size_of::<Marker>();
187
188 #[must_use]
200 pub fn new(name: &'static str) -> Self {
201 Self(Capture::is_active().then(|| SpanInner::new(name)))
202 }
203
204 #[must_use]
211 pub fn with_category(mut self, category: &'static str) -> Self {
212 if let Some(inner) = &mut self.0 {
213 inner.category = category;
214 }
215 self
216 }
217
218 #[must_use]
226 pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
227 where
228 F: FnOnce() -> String,
229 {
230 if let Some(inner) = &mut self.0 {
231 inner.tooltip = tooltip();
232 }
233 self
234 }
235
236 #[must_use]
240 pub fn with_start(mut self, start: Instant) -> Self {
241 if let Some(inner) = &mut self.0 {
242 inner.start = start.into();
243 }
244 self
245 }
246
247 pub fn in_scope<F, T>(self, f: F) -> T
249 where
250 F: FnOnce() -> T,
251 {
252 f()
253 }
254
255 pub fn record(self) {
257 }
259
260 pub fn cancel(mut self) {
262 let _ = self.0.take();
263 }
264}
265
266impl Drop for Span {
267 fn drop(&mut self) {
268 if let Some(inner) = self.0.take() {
269 inner.record(true)
270 }
271 }
272}
273
274pub struct Event(Option<SpanInner>);
286
287impl Event {
288 #[must_use]
297 pub fn new(name: &'static str) -> Self {
298 Self(Capture::is_active().then(|| SpanInner::new(name)))
299 }
300
301 #[must_use]
308 pub fn with_category(mut self, category: &'static str) -> Self {
309 if let Some(inner) = &mut self.0 {
310 inner.category = category;
311 }
312 self
313 }
314
315 #[must_use]
323 pub fn with_tooltip<F>(mut self, tooltip: F) -> Self
324 where
325 F: FnOnce() -> String,
326 {
327 if let Some(inner) = &mut self.0 {
328 inner.tooltip = tooltip();
329 }
330 self
331 }
332
333 pub fn record(self) {
335 if let Some(inner) = self.0 {
336 inner.record(false);
337 }
338 }
339}
340
341#[derive(Clone, Debug)]
343pub struct CaptureOptions {
344 memory_limit: Option<usize>,
345 record_rss: bool,
346}
347
348impl Default for CaptureOptions {
349 fn default() -> Self {
350 Self {
351 memory_limit: None,
352 record_rss: true,
353 }
354 }
355}
356
357impl CaptureOptions {
358 pub fn new() -> Self {
360 Self::default()
361 }
362
363 pub fn with_memory_limit(self, memory_limit: Option<usize>) -> Self {
370 Self {
371 memory_limit,
372 ..self
373 }
374 }
375
376 pub fn with_record_rss(self, record_rss: bool) -> Self {
381 Self { record_rss, ..self }
382 }
383
384 pub async fn start(self) -> Capture {
391 Capture::new(self, CAPTURE_MUTEX.lock().await)
392 }
393
394 pub fn blocking_start(self) -> Capture {
405 Capture::new(self, CAPTURE_MUTEX.blocking_lock())
406 }
407
408 pub fn try_start(self) -> Result<Capture, Self> {
415 let guard = match CAPTURE_MUTEX.try_lock() {
416 Ok(guard) => guard,
417 Err(_) => return Err(self),
418 };
419 Ok(Capture::new(self, guard))
420 }
421}
422
423static CAPTURE_MUTEX: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
424
425pub struct Capture {
432 _guard: tokio::sync::MutexGuard<'static, ()>,
433 memory: Option<JoinHandle<Vec<(Timestamp, usize)>>>,
434 unparker: Unparker,
435 request_exit: Arc<AtomicBool>,
436 block_limit: i64,
437}
438
439impl Capture {
440 fn new(params: CaptureOptions, guard: tokio::sync::MutexGuard<'static, ()>) -> Self {
441 if let Some(memory_limit) = params.memory_limit {
442 tracing::info!(
443 "marker capture limited to {}",
444 HumanBytes::from(memory_limit)
445 );
446 }
447 let block_limit = params.memory_limit.map_or(i64::MAX, |memory_limit| {
448 (memory_limit / BYTES_PER_BLOCK) as i64
449 });
450 let parker = Parker::new();
451 let unparker = parker.unparker().clone();
452 let request_exit = Arc::new(AtomicBool::new(false));
453 let memory = params.record_rss.then(|| {
454 std::thread::Builder::new()
455 .name(String::from("capture-rss"))
456 .spawn({
457 let request_exit = request_exit.clone();
458 move || {
459 let mut memory = Vec::new();
460 while !request_exit.load(Ordering::Acquire) {
461 if let Some(memory_stats) = memory_stats() {
462 memory.push((Timestamp::now(), memory_stats.physical_mem));
463 }
464 parker.park_timeout(Duration::from_millis(100));
465 }
466 memory
467 }
468 })
469 .expect("should be able to start a capture thread")
470 });
471 FREE_BLOCKS.store(block_limit, Ordering::Relaxed);
472 CAPTURING.store(true, Ordering::Release);
473 Self {
474 block_limit,
475 memory,
476 unparker,
477 request_exit,
478 _guard: guard,
479 }
480 }
481
482 pub fn finish(mut self) -> Annotations {
484 CAPTURING.store(false, Ordering::Release);
485 let remaining_blocks = FREE_BLOCKS.load(Ordering::Relaxed);
486 if remaining_blocks <= 0 {
487 tracing::info!("marker capture exceeded the limit");
488 } else {
489 let used_bytes = (self.block_limit - remaining_blocks) as usize * BYTES_PER_BLOCK;
490 tracing::info!("marker capture used {}", HumanBytes::from(used_bytes));
491 }
492
493 Annotations {
494 markers: self.take_markers(),
495 memory: self.take_memory(),
496 }
497 }
498
499 pub fn abort(self) {
503 tracing::info!("aborting profile annotation capture");
504 }
505
506 pub fn is_active() -> bool {
513 CAPTURING.load(Ordering::Acquire)
514 }
515
516 fn take_markers(&mut self) -> HashMap<usize, (Option<String>, Blocks)> {
517 let all_threads = ALL_THREAD_MARKERS.lock().unwrap();
518 let mut markers = HashMap::new();
519 for thread in &*all_threads {
520 markers.insert(thread.tid, (thread.name.clone(), thread.queue.take()));
521 }
522 markers
523 }
524
525 fn take_memory(&mut self) -> Vec<(Timestamp, usize)> {
526 if let Some(memory) = self.memory.take() {
527 self.request_exit.store(true, Ordering::Release);
528 self.unparker.unpark();
529 memory.join().unwrap_or_default()
530 } else {
531 Default::default()
532 }
533 }
534}
535
536impl Drop for Capture {
537 fn drop(&mut self) {
538 self.take_memory();
539
540 CAPTURING.store(false, Ordering::Release);
543 }
544}
545
546#[derive(thiserror::Error, Debug)]
548pub enum Error {
549 #[error("Error decompressing profile ")]
551 GzDecoderError(#[from] std::io::Error),
552
553 #[error("Error parsing profile")]
555 SerdeError(#[from] serde_json_path_to_error::Error),
556}
557
558#[derive(Default, Clone, Debug)]
560pub struct AnnotationOptions {
561 product: Option<String>,
562 os_cpu: Option<String>,
563}
564
565impl AnnotationOptions {
566 pub fn new() -> Self {
568 Self::default()
569 }
570
571 pub fn with_product(self, product: Option<impl Into<String>>) -> Self {
577 Self {
578 product: product.map(|s| s.into()),
579 ..self
580 }
581 }
582
583 pub fn with_os_cpu(self, os_cpu: Option<impl Into<String>>) -> Self {
589 Self {
590 os_cpu: os_cpu.map(|s| s.into()),
591 ..self
592 }
593 }
594}
595
596pub struct Annotations {
600 markers: HashMap<usize, (Option<String>, Blocks)>,
601 memory: Vec<(Timestamp, usize)>,
602}
603
604impl Annotations {
605 pub fn apply(&self, profile: &[u8], options: AnnotationOptions) -> Result<Vec<u8>, Error> {
612 let mut buffer = Vec::new();
615 let json = if profile.starts_with(&[0x1f, 0x8b]) {
616 GzDecoder::new(profile).read_to_end(&mut buffer)?;
617 &buffer
618 } else {
619 profile
620 };
621 let gzip = !buffer.is_empty();
622
623 let mut profile = serde_json_path_to_error::from_slice::<Profile>(json)?;
625 if let Some(product) = options.product {
626 profile.meta.product = product;
627 }
628 if let Some(os_cpu) = options.os_cpu {
629 profile.meta.os_cpu = os_cpu;
630 }
631 profile.meta.marker_schema.push(json!({
632 "name": "FelderaMarker",
633 "display": [
634 "marker-chart",
635 "marker-table"
636 ],
637 "chartLabel": "{marker.data.name}",
638 "tooltipLabel": "{marker.data.name}",
639 "tableLabel": "{marker.data.name}",
640 "description": "Marker generated by Feldera.",
641 "fields": [
642 {
643 "key": "name",
644 "label": "Name",
645 "format": "unique-string"
646 }
647 ]
648 }));
649 static CATEGORY_COLORS: [&str; 12] = [
652 "purple",
653 "green",
654 "orange",
655 "yellow",
656 "lightblue",
657 "blue",
658 "brown",
659 "magenta",
660 "red",
661 "lightred",
662 "darkgrey",
663 "grey",
664 ];
665 let mut categories = profile
666 .meta
667 .categories
668 .iter()
669 .enumerate()
670 .map(|(index, category)| (category.name.clone(), index))
671 .collect::<HashMap<_, _>>();
672 for (category, color) in self
673 .markers
674 .values()
675 .flat_map(|(_, markers)| markers.iter())
676 .map(|marker| marker.category)
677 .collect::<HashSet<_>>()
678 .into_iter()
679 .zip(CATEGORY_COLORS.iter().cycle())
680 {
681 categories.insert(category.into(), profile.meta.categories.len());
682 profile.meta.categories.push(Category {
683 color: (*color).into(),
684 name: category.into(),
685 other: [(String::from("subcategories"), json!(["Other"]))]
686 .into_iter()
687 .collect(),
688 });
689 }
690 for thread in &mut profile.threads {
691 if let Some(tid) = &thread.tid
692 && let Ok(tid) = tid.parse::<usize>()
693 && let Some((name, markers)) = self.markers.get(&tid)
694 {
695 if let Some(name) = name {
696 thread.name = Some(name.clone());
697 }
698 for marker in markers.iter() {
699 thread.markers.length += 1;
700 thread.markers.category.push(categories[marker.category]);
701 thread.markers.data.push(ProfileMarkerData {
702 type_: Cow::from("FelderaMarker"),
703 name: profile.shared.add_name(&marker.tooltip),
704 });
705 thread.markers.start_time.push(marker.start);
706 thread.markers.end_time.push(marker.end);
707 thread
708 .markers
709 .name
710 .push(profile.shared.add_name(marker.name));
711 thread.markers.phase.push(1);
712 }
713 }
714 }
715
716 if !self.memory.is_empty() {
717 profile.counters.push(RawCounter {
718 name: String::from("RSS"),
719 category: String::from("Memory"),
720 description: String::from("RSS in bytes"),
721 pid: profile.threads.first().unwrap().pid.clone(),
722 main_thread_index: 0,
723 samples: {
724 RawCounterSamplesTable {
725 time: self
726 .memory
727 .iter()
728 .copied()
729 .map(|(time, _rss)| time)
730 .collect(),
731 time_deltas: Vec::new(),
732 number: repeat_n(0, self.memory.len()).collect(),
733 count: once(self.memory[0].1 as i64)
734 .chain(
735 self.memory
736 .iter()
737 .map(|(_time, rss)| *rss as i64)
738 .tuple_windows()
739 .map(|(prev, next)| next - prev),
740 )
741 .collect(),
742 length: self.memory.len(),
743 other: Default::default(),
744 }
745 },
746 other: Default::default(),
747 });
748 }
749
750 let output = serde_json::to_vec(&profile).unwrap();
752 let output = if gzip {
753 let mut gzipped_output = Vec::new();
754 GzEncoder::new(Cursor::new(output), Compression::fast())
755 .read_to_end(&mut gzipped_output)
756 .unwrap();
757 gzipped_output
758 } else {
759 output
760 };
761
762 return Ok(output);
763
764 #[derive(Debug, Serialize, Deserialize)]
765 #[serde(rename_all = "camelCase")]
766 struct Profile {
767 meta: Meta,
768 threads: Vec<Thread>,
769 #[serde(default)]
770 counters: Vec<RawCounter>,
771 shared: Shared,
772 #[serde(flatten)]
773 other: HashMap<String, Value>,
774 }
775
776 #[derive(Debug, Serialize, Deserialize)]
777 #[serde(rename_all = "camelCase")]
778 struct Meta {
779 product: String,
780 #[serde(rename = "oscpu")]
781 os_cpu: String,
782 categories: Vec<Category>,
783 marker_schema: Vec<Value>,
784 #[serde(flatten)]
785 other: HashMap<String, Value>,
786 }
787
788 #[derive(Debug, Serialize, Deserialize)]
789 #[serde(rename_all = "camelCase")]
790 struct Category {
791 color: String,
792 name: String,
793 #[serde(flatten)]
794 other: HashMap<String, Value>,
795 }
796
797 #[derive(Debug, Serialize, Deserialize)]
798 #[serde(rename_all = "camelCase")]
799 struct Thread {
800 name: Option<String>,
801 #[serde(default)]
802 markers: ProfileMarkers,
803 tid: Option<String>,
804 pid: String,
805 #[serde(flatten)]
806 other: HashMap<String, Value>,
807 }
808
809 #[derive(Default, Debug, Serialize, Deserialize)]
810 #[serde(rename_all = "camelCase")]
811 struct ProfileMarkers {
812 length: usize,
813 category: Vec<usize>,
814 data: Vec<ProfileMarkerData>,
815 start_time: Vec<Timestamp>,
816 end_time: Vec<Timestamp>,
817 name: Vec<usize>,
818 phase: Vec<usize>,
819 }
820
821 #[derive(Default, Debug, Serialize, Deserialize)]
822 #[serde(rename_all = "camelCase")]
823 struct ProfileMarkerData {
824 #[serde(rename = "type")]
825 type_: Cow<'static, str>,
826 name: usize,
827 }
828
829 #[derive(Debug, Serialize, Deserialize)]
830 #[serde(rename_all = "camelCase")]
831 struct Shared {
832 string_array: Vec<String>,
833 #[serde(flatten)]
834 other: HashMap<String, Value>,
835 }
836
837 impl Shared {
838 fn add_name(&mut self, name: &str) -> usize {
839 let index = self.string_array.len();
840 self.string_array.push(name.into());
841 index
842 }
843 }
844
845 #[derive(Default, Debug, Serialize, Deserialize)]
846 #[serde(rename_all = "camelCase")]
847 struct RawCounter {
848 name: String,
849 category: String,
850 description: String,
851 pid: String,
852 main_thread_index: usize,
853 samples: RawCounterSamplesTable,
854 #[serde(flatten)]
855 other: HashMap<String, Value>,
856 }
857
858 #[derive(Default, Debug, Serialize, Deserialize)]
859 #[serde(rename_all = "camelCase")]
860 struct RawCounterSamplesTable {
861 #[serde(default, skip_serializing_if = "Vec::is_empty")]
862 time: Vec<Timestamp>,
863 #[serde(default, skip_serializing_if = "Vec::is_empty")]
864 time_deltas: Vec<Timestamp>,
865 #[serde(default, skip_serializing_if = "Vec::is_empty")]
866 number: Vec<usize>,
867 count: Vec<i64>,
868 length: usize,
869 #[serde(flatten)]
870 other: HashMap<String, Value>,
871 }
872 }
873}
874
875static CAPTURING: AtomicBool = AtomicBool::new(false);
877
878struct Marker {
880 start: Timestamp,
882 end: Timestamp,
884 category: &'static str,
886 name: &'static str,
888 tooltip: String,
890}
891
892struct ThreadMarkers {
894 tid: usize,
898
899 name: Option<String>,
904
905 queue: Arc<Queue>,
910}
911
912impl ThreadMarkers {
913 fn new(queue: Arc<Queue>) -> Self {
914 #[cfg(target_os = "linux")]
915 let tid = nix::unistd::gettid().as_raw() as usize;
916 #[cfg(not(target_os = "linux"))]
917 let tid = thread_id::get();
918
919 Self {
920 tid,
921 name: std::thread::current().name().map(|s| s.into()),
922 queue,
923 }
924 }
925}
926
927static ALL_THREAD_MARKERS: std::sync::Mutex<Vec<ThreadMarkers>> = std::sync::Mutex::new(Vec::new());
929
930static FREE_BLOCKS: AtomicI64 = AtomicI64::new(0);
931const MARKERS_PER_BLOCK: usize = 32;
932const BYTES_PER_BLOCK: usize = MARKERS_PER_BLOCK * Span::BYTES;
933
934struct Block(Vec<Marker>);
935impl Block {
936 fn new(marker: Marker) -> Self {
937 let mut markers = Vec::with_capacity(MARKERS_PER_BLOCK);
938 markers.push(marker);
939 Self(markers)
940 }
941 fn is_full(&self) -> bool {
942 self.0.len() >= self.0.capacity()
943 }
944 fn push(&mut self, marker: Marker) {
945 self.0.push(marker);
946 }
947}
948
949struct Blocks(Vec<Block>);
950
951impl Default for Blocks {
952 fn default() -> Self {
953 Self(Vec::with_capacity(32))
954 }
955}
956
957impl Blocks {
958 fn push(&mut self, marker: Marker) {
959 if let Some(block) = self.0.last_mut()
960 && !block.is_full()
961 {
962 block.push(marker);
963 } else {
964 match FREE_BLOCKS.fetch_sub(1, Ordering::Relaxed) {
965 1.. => self.0.push(Block::new(marker)),
966 0 => warn!("marker capture space exhausted"),
967 _ => (),
968 }
969 }
970 }
971
972 fn iter(&self) -> impl Iterator<Item = &Marker> {
973 self.0.iter().flat_map(|block| block.0.iter())
974 }
975}
976
977struct Queue(std::sync::Mutex<Blocks>);
978
979impl Queue {
980 fn new() -> Arc<Self> {
981 let queue = Arc::new(Self(Default::default()));
982 ALL_THREAD_MARKERS
983 .lock()
984 .unwrap()
985 .push(ThreadMarkers::new(queue.clone()));
986 queue
987 }
988
989 fn push(&self, marker: Marker) {
990 self.0.lock().unwrap().push(marker);
991 }
992
993 fn take(&self) -> Blocks {
994 std::mem::take(&mut *self.0.lock().unwrap())
995 }
996}
997
998thread_local! {
999 static QUEUE: Arc<Queue> = Queue::new();
1000}