You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 lines
6.0KB

  1. use std::sync::mpsc::{Sender, Receiver, channel, SendError};
  2. use std::sync::Arc;
  3. use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH};
  4. use std::path::PathBuf;
  5. use std::thread::{self, JoinHandle};
  6. use std::io::{self, Write};
  7. use std::{mem, fs, env};
  8. use chrono::{DateTime, Utc, TimeZone};
  9. use hdrhistogram::{Histogram, Counter};
  10. use hdrhistogram::serialization::{Serializer, V2DeflateSerializer, V2Serializer};
  11. use hdrhistogram::serialization::interval_log::{IntervalLogWriterBuilder, Tag};
  12. type C = u64;
  13. pub fn nanos(d: Duration) -> u64 {
  14. d.as_secs() * 1_000_000_000_u64 + (d.subsec_nanos() as u64)
  15. }
  16. pub struct HistLog {
  17. series: &'static str,
  18. tag: &'static str,
  19. freq: Duration,
  20. last_sent: Instant,
  21. tx: Sender<Option<Entry>>,
  22. hist: Histogram<C>,
  23. thread: Option<Arc<thread::JoinHandle<()>>>,
  24. }
  25. pub struct Entry {
  26. pub tag: &'static str,
  27. pub start: SystemTime,
  28. pub end: SystemTime,
  29. pub hist: Histogram<C>,
  30. }
  31. impl HistLog {
  32. pub fn new(series: &'static str, tag: &'static str, freq: Duration) -> Self {
  33. let (tx, rx) = channel();
  34. let mut dir = env::home_dir().unwrap();
  35. dir.push("src/market-maker/var/hist");
  36. fs::create_dir_all(&dir).unwrap();
  37. let thread = Some(Arc::new(Self::scribe(series, rx, dir)));
  38. let last_sent = Instant::now();
  39. let hist = Histogram::new(3).unwrap();
  40. Self { series, tag, freq, last_sent, tx, hist, thread }
  41. }
  42. pub fn clone_with_tag(&self, tag: &'static str) -> HistLog {
  43. let thread = self.thread.as_ref().map(|x| Arc::clone(x)).unwrap();
  44. assert!(self.thread.is_some(), "self.thread is {:?}", self.thread);
  45. let tx = self.tx.clone();
  46. Self {
  47. series: self.series,
  48. tag,
  49. freq: self.freq,
  50. last_sent: Instant::now(),
  51. tx,
  52. hist: self.hist.clone(),
  53. thread: Some(thread),
  54. }
  55. }
  56. pub fn clone_with_tag_and_freq(&self, tag: &'static str, freq: Duration) -> HistLog {
  57. let mut clone = self.clone_with_tag(tag);
  58. clone.freq = freq;
  59. clone
  60. }
  61. pub fn record(&mut self, value: u64) {
  62. let _ = self.hist.record(value);
  63. }
  64. /// If for some reason there was a pause in between using the struct,
  65. /// this resets the internal state of both the values recorded to the
  66. /// `Histogram` and the value of when it last sent a `Histogram` onto
  67. /// the writing thread.
  68. ///
  69. pub fn reset(&mut self) {
  70. self.hist.clear();
  71. self.last_sent = Instant::now();
  72. }
  73. fn send(&mut self, loop_time: Instant) {
  74. let end = SystemTime::now();
  75. let start = end - (loop_time - self.last_sent);
  76. assert!(end > start, "end <= start!");
  77. let mut next = Histogram::new_from(&self.hist);
  78. mem::swap(&mut self.hist, &mut next);
  79. self.tx.send(Some(Entry { tag: self.tag, start, end, hist: next })).expect("sending entry failed");
  80. self.last_sent = loop_time;
  81. }
  82. pub fn check_send(&mut self, loop_time: Instant) {
  83. //let since = loop_time - self.last_sent;
  84. if loop_time > self.last_sent && loop_time - self.last_sent >= self.freq {
  85. // send sets self.last_sent to loop_time fyi
  86. self.send(loop_time);
  87. }
  88. }
  89. fn scribe(
  90. series : &'static str,
  91. rx : Receiver<Option<Entry>>,
  92. dir : PathBuf,
  93. ) -> JoinHandle<()> {
  94. let mut ser = V2DeflateSerializer::new();
  95. let start_time = SystemTime::now();
  96. let seconds = start_time.duration_since(UNIX_EPOCH).unwrap().as_secs();
  97. let path = dir.join(&format!("{}-interval-log-{}.v2z", series, seconds));
  98. let file = fs::File::create(&path).unwrap();
  99. thread::Builder::new().name(format!("mm:hist:{}", series)).spawn(move || {
  100. let mut buf = io::LineWriter::new(file);
  101. let mut wtr =
  102. IntervalLogWriterBuilder::new()
  103. .with_base_time(UNIX_EPOCH)
  104. .with_start_time(start_time)
  105. .begin_log_with(&mut buf, &mut ser)
  106. .unwrap();
  107. loop {
  108. match rx.recv() { //.recv_timeout(Duration::from_millis(1)) {
  109. //match rx.recv_timeout(Duration::new(1, 0)) {
  110. Ok(Some(Entry { tag, start, end, hist })) => {
  111. wtr.write_histogram(&hist, start.duration_since(UNIX_EPOCH).unwrap(),
  112. end.duration_since(start).unwrap(), Tag::new(tag))
  113. .ok();
  114. //.map_err(|e| { println!("{:?}", e); e }).ok();
  115. }
  116. // `None` used as terminate signal from `Drop`
  117. Ok(None) => break,
  118. _ => {
  119. thread::sleep(Duration::new(0, 0));
  120. }
  121. }
  122. }
  123. }).unwrap()
  124. }
  125. }
  126. impl Drop for HistLog {
  127. fn drop(&mut self) {
  128. if !self.hist.is_empty() { self.send(Instant::now()) }
  129. if let Some(arc) = self.thread.take() {
  130. //println!("in Drop, strong count is {}", Arc::strong_count(&arc));
  131. if let Ok(thread) = Arc::try_unwrap(arc) {
  132. let _ = self.tx.send(None);
  133. let _ = thread.join();
  134. }
  135. }
  136. }
  137. }
  138. // pub fn save_hist<T: Counter>(thread: &'static str, ticker: Ticker, hist: Histogram<T>) {
  139. // env::home_dir().and_then(|mut path| {
  140. // path.push(&format!("src/market-maker/var/hist/{}/", ticker.to_str()));
  141. // let _ = fs::create_dir_all(&path);
  142. // path.push(&format!("mm-v{}-{}-{}-1h-{}.v2", crate_version!(), thread, ticker.to_string(), Utc::now().to_rfc3339()));
  143. // fs::File::create(&path).ok()
  144. // }).map(|mut file| {
  145. // let mut ser = V2DeflateSerializer::new();
  146. // ser.serialize(&hist, &mut file)
  147. // .map_err(|e| {
  148. // let _ = write!(&mut file, "\n\n{:?}", e);
  149. // e
  150. // }).ok();
  151. // });
  152. // }