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.

196 lines
6.4KB

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