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.

195 lines
6.5KB

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