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.

latency.rs 18KB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. use std::thread::{self, JoinHandle};
  2. use std::sync::{Arc, Mutex, RwLock};
  3. use std::sync::mpsc::{self, Sender, Receiver, channel};
  4. use std::collections::VecDeque;
  5. use std::fmt::{self, Display, Write};
  6. use std::time::{Instant, Duration};
  7. use chrono::{self, DateTime, Utc, TimeZone};
  8. use pub_sub::PubSub;
  9. use zmq;
  10. use influent::measurement::{Measurement, Value};
  11. use sloggers::types::Severity;
  12. //use chashmap::CHashMap;
  13. use windows::{DurationWindow, Incremental, Window};
  14. use money::{Ticker, Side, ByExchange, Exchange};
  15. use super::file_logger;
  16. use influx::{self, OwnedMeasurement, OwnedValue};
  17. pub type Nanos = u64;
  18. pub const SECOND: u64 = 1e9 as u64;
  19. pub const MINUTE: u64 = SECOND * 60;
  20. pub const HOUR: u64 = MINUTE * 60;
  21. pub const MILLISECOND: u64 = SECOND / 1000;
  22. pub const MICROSECOND: u64 = MILLISECOND / 1000;
  23. pub fn nanos(d: Duration) -> Nanos {
  24. d.as_secs() * 1_000_000_000 + (d.subsec_nanos() as u64)
  25. }
  26. pub fn dt_nanos(t: DateTime<Utc>) -> i64 {
  27. (t.timestamp() as i64) * 1_000_000_000_i64 + (t.timestamp_subsec_nanos() as i64)
  28. }
  29. pub fn now() -> i64 { dt_nanos(Utc::now()) }
  30. pub fn tfmt(ns: Nanos) -> String {
  31. let mut f = String::new();
  32. match ns {
  33. t if t <= MICROSECOND => {
  34. write!(f, "{}ns", t);
  35. }
  36. t if t > MICROSECOND && t < MILLISECOND => {
  37. write!(f, "{}u", t / MICROSECOND);
  38. }
  39. t if t > MILLISECOND && t < SECOND => {
  40. write!(f, "{}ms", t / MILLISECOND);
  41. }
  42. t => {
  43. write!(f, "{}.{}sec", t / SECOND, t / MILLISECOND);
  44. }
  45. }
  46. f
  47. }
  48. pub fn tfmt_dur(d: Duration) -> String {
  49. tfmt(nanos(d))
  50. }
  51. pub fn tfmt_dt(dt: DateTime<Utc>) -> String {
  52. Utc::now().signed_duration_since(dt)
  53. .to_std()
  54. .map(|dur| {
  55. tfmt_dur(dur)
  56. }).unwrap_or("?".into())
  57. }
  58. pub fn tfmt_write(ns: Nanos, f: &mut fmt::Formatter) {
  59. match ns {
  60. t if t <= MICROSECOND => {
  61. write!(f, "{}ns", t);
  62. }
  63. t if t > MICROSECOND && t < MILLISECOND => {
  64. write!(f, "{}u", t / MICROSECOND);
  65. }
  66. t if t > MILLISECOND && t < SECOND => {
  67. write!(f, "{}ms", t / MILLISECOND);
  68. }
  69. t => {
  70. write!(f, "{}.{}sec", t / SECOND, t / MILLISECOND);
  71. }
  72. }
  73. }
  74. #[derive(Debug)]
  75. pub enum Latency {
  76. Ws(Exchange, Ticker, Duration),
  77. Http(Exchange, Duration),
  78. Trade(Exchange, Ticker, Duration),
  79. Terminate
  80. }
  81. #[derive(Debug)]
  82. pub enum ExperiencedLatency {
  83. GdaxWebsocket(Duration),
  84. //GdaxWebsocketNoLock(Duration),
  85. GdaxHttpPublic(Duration),
  86. GdaxHttpPrivate(Duration),
  87. PlnxHttpPublic(Duration),
  88. PlnxHttpPrivate(Duration),
  89. PlnxOrderBook(Duration),
  90. ExmoHttpPublic(Duration),
  91. KrknHttpPublic(Duration),
  92. KrknHttpPrivate(Duration),
  93. KrknTrade(Duration, &'static str, Option<Ticker>, Option<Side>),
  94. EventLoop(Duration),
  95. PlnxWs(Ticker),
  96. Terminate
  97. }
  98. // impl Message for ExperiencedLatency {
  99. // fn kill_switch() -> Self {
  100. // ExperiencedLatency::Terminate
  101. // }
  102. // }
  103. /// represents over what period of time
  104. /// the latency measurements were taken
  105. pub trait MeasurementWindow {
  106. fn duration(&self) -> Duration;
  107. }
  108. #[derive(Debug, Clone, Copy)]
  109. pub struct WThirty;
  110. impl Default for WThirty {
  111. fn default() -> Self { WThirty {} }
  112. }
  113. impl MeasurementWindow for WThirty {
  114. fn duration(&self) -> Duration { Duration::from_secs(30) }
  115. }
  116. #[derive(Debug, Clone, Copy)]
  117. pub struct WTen;
  118. impl Default for WTen {
  119. fn default() -> Self { WTen {} }
  120. }
  121. impl MeasurementWindow for WTen {
  122. fn duration(&self) -> Duration { Duration::from_secs(10) }
  123. }
  124. #[derive(Debug, Clone)]
  125. pub struct Update {
  126. pub gdax_ws: Nanos,
  127. pub gdax_trade: Nanos,
  128. pub gdax_last: DateTime<Utc>
  129. }
  130. impl Default for Update {
  131. fn default() -> Self {
  132. Update {
  133. gdax_ws: 0,
  134. gdax_trade: 0,
  135. gdax_last: Utc::now(),
  136. }
  137. }
  138. }
  139. #[derive(Debug, Clone)]
  140. pub struct LatencyUpdate<W>
  141. where W: MeasurementWindow
  142. {
  143. pub gdax_ws: Nanos,
  144. pub krkn_pub: Nanos,
  145. pub krkn_priv: Nanos,
  146. pub plnx_pub: Nanos,
  147. pub plnx_priv: Nanos,
  148. pub plnx_order: Nanos,
  149. pub krkn_trade_30_mean: Nanos,
  150. pub krkn_trade_30_max: Nanos,
  151. pub krkn_trade_300_mean: Nanos,
  152. pub krkn_trade_300_max: Nanos,
  153. pub plnx_last: DateTime<Utc>,
  154. pub krkn_last: DateTime<Utc>,
  155. pub plnx_ws_count: u64,
  156. //pub event_loop: Nanos,
  157. pub size: W,
  158. }
  159. impl<W> Default for LatencyUpdate<W>
  160. where W: MeasurementWindow + Default
  161. {
  162. fn default() -> Self {
  163. LatencyUpdate {
  164. gdax_ws: Nanos::default(),
  165. krkn_pub: Nanos::default(),
  166. krkn_priv: Nanos::default(),
  167. plnx_pub: Nanos::default(),
  168. plnx_priv: Nanos::default(),
  169. plnx_order: Nanos::default(),
  170. krkn_trade_30_mean: Nanos::default(),
  171. krkn_trade_30_max: Nanos::default(),
  172. krkn_trade_300_mean: Nanos::default(),
  173. krkn_trade_300_max: Nanos::default(),
  174. plnx_ws_count: 0,
  175. plnx_last: Utc::now(),
  176. krkn_last: Utc::now(),
  177. size: W::default()
  178. }
  179. }
  180. }
  181. impl<W> Display for LatencyUpdate<W>
  182. where W: MeasurementWindow
  183. {
  184. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  185. write!(f, " gdax ws: ");
  186. tfmt_write(self.gdax_ws, f);
  187. write!(f, "\n krkn pub: ");
  188. tfmt_write(self.krkn_pub, f);
  189. write!(f, "\n krkn priv: ");
  190. tfmt_write(self.krkn_priv, f);
  191. write!(f, "\n krkn trade 30 mean: ");
  192. tfmt_write(self.krkn_trade_30_mean, f);
  193. write!(f, "\n krkn trade 30 max: ");
  194. tfmt_write(self.krkn_trade_30_max, f);
  195. write!(f, "\n krkn trade 300 mean: ");
  196. tfmt_write(self.krkn_trade_300_mean, f);
  197. write!(f, "\n krkn trade 300 max: ");
  198. tfmt_write(self.krkn_trade_300_max, f);
  199. write!(f, "\n plnx pub: ");
  200. tfmt_write(self.plnx_pub, f);
  201. write!(f, "\n plnx priv: ");
  202. tfmt_write(self.plnx_priv, f);
  203. write!(f, "\n plnx orderbook loop: ");
  204. tfmt_write(self.plnx_order, f);
  205. //write!(f, "\n gdax ws nolock: ");
  206. //tfmt_write(self.gdax_ws_nolock, f);
  207. //write!(f, "\n event loop: ");
  208. //tfmt(self.event_loop, f);
  209. write!(f,"")
  210. }
  211. }
  212. impl<W: MeasurementWindow> LatencyUpdate<W> {
  213. pub fn measurement_window(&self) -> Duration {
  214. self.size.duration()
  215. }
  216. }
  217. pub struct Manager {
  218. pub tx: Sender<Latency>,
  219. pub channel: PubSub<Update>,
  220. thread: Option<JoinHandle<()>>,
  221. }
  222. pub struct LatencyManager<W>
  223. where W: MeasurementWindow + Clone + Send + Sync
  224. {
  225. pub tx: Sender<ExperiencedLatency>,
  226. pub channel: PubSub<LatencyUpdate<W>>,
  227. thread: Option<JoinHandle<()>>,
  228. }
  229. /// returns a DateTime equal to now - `dur`
  230. ///
  231. pub fn dt_from_dur(dur: Duration) -> DateTime<Utc> {
  232. let old_dur = chrono::Duration::nanoseconds(nanos(dur) as i64);
  233. Utc::now() - old_dur
  234. }
  235. struct Last {
  236. broadcast: Instant,
  237. plnx: Instant,
  238. krkn: Instant,
  239. gdax: Instant,
  240. }
  241. impl Default for Last {
  242. fn default() -> Self {
  243. Last {
  244. broadcast: Instant::now(),
  245. plnx: Instant::now(),
  246. krkn: Instant::now(),
  247. gdax: Instant::now(),
  248. }
  249. }
  250. }
  251. impl Manager {
  252. pub fn new(window: Duration,
  253. log_path: &'static str,
  254. measurements: Sender<OwnedMeasurement>) -> Self {
  255. let (tx, rx) = channel();
  256. let tx_copy = tx.clone();
  257. let channel = PubSub::new();
  258. let channel_copy = channel.clone();
  259. let logger = file_logger(log_path, Severity::Info);
  260. info!(logger, "initializing");
  261. let mut gdax_ws = DurationWindow::new(window);
  262. let mut gdax_trade = DurationWindow::new(window);
  263. let mut last = Last::default();
  264. info!(logger, "entering loop");
  265. let mut terminate = false;
  266. let thread = Some(thread::spawn(move || {
  267. loop {
  268. let loop_time = Instant::now();
  269. rx.try_recv().map(|msg| {
  270. debug!(logger, "rcvd {:?}", msg);
  271. match msg {
  272. Latency::Ws(exch, ticker, dur) => {
  273. // shortcut
  274. gdax_ws.update(loop_time, dur);
  275. last.gdax = loop_time;
  276. }
  277. Latency::Trade(exch, ticker, dur) => {
  278. //shorcut
  279. gdax_trade.update(loop_time, dur);
  280. last.gdax = loop_time;
  281. let nanos = DurationWindow::nanos(dur);
  282. measurements.send(
  283. OwnedMeasurement::new("gdax_trade_api")
  284. .add_string_tag("ticker", ticker.to_string())
  285. .add_field("nanos", OwnedValue::Integer(nanos as i64))
  286. .set_timestamp(influx::now()));
  287. }
  288. Latency::Terminate => {
  289. crit!(logger, "rcvd Terminate order");
  290. terminate = true;
  291. }
  292. _ => {}
  293. }
  294. });
  295. if loop_time - last.broadcast > Duration::from_millis(100) {
  296. debug!(logger, "initalizing broadcast");
  297. let update = Update {
  298. gdax_ws: gdax_ws.refresh(&loop_time).mean_nanos(),
  299. gdax_trade: gdax_trade.refresh(&loop_time).mean_nanos(),
  300. gdax_last: dt_from_dur(loop_time - last.gdax)
  301. };
  302. channel.send(update);
  303. last.broadcast = loop_time;
  304. debug!(logger, "sent broadcast");
  305. } else {
  306. #[cfg(feature = "no-thrash")]
  307. thread::sleep(Duration::new(0, 1000));
  308. }
  309. if terminate { break }
  310. }
  311. crit!(logger, "goodbye");
  312. }));
  313. Manager {
  314. tx,
  315. channel: channel_copy,
  316. thread,
  317. }
  318. }
  319. }
  320. impl Drop for Manager {
  321. fn drop(&mut self) {
  322. self.tx.send(Latency::Terminate);
  323. if let Some(thread) = self.thread.take() {
  324. let _ = thread.join();
  325. }
  326. }
  327. }
  328. //impl<W: MeasurementWindow + Clone + Send + Sync> LatencyManager<W> {
  329. impl LatencyManager<WTen> {
  330. pub fn new(w: WTen) -> Self {
  331. let (tx, rx) = channel();
  332. let tx_copy = tx.clone();
  333. let channel = PubSub::new();
  334. let channel_copy = channel.clone();
  335. let w = w.clone();
  336. let thread = Some(thread::spawn(move || {
  337. let logger = file_logger("var/log/latency-manager.log", Severity::Info);
  338. info!(logger, "initializing zmq");
  339. let ctx = zmq::Context::new();
  340. let socket = influx::push(&ctx).unwrap();
  341. let mut buf = String::with_capacity(4096);
  342. info!(logger, "initializing DurationWindows");
  343. let mut gdax_ws = DurationWindow::new(w.duration());
  344. let mut gdax_priv = DurationWindow::new(w.duration());
  345. let mut krkn_pub = DurationWindow::new(w.duration());
  346. let mut krkn_priv = DurationWindow::new(w.duration());
  347. let mut plnx_pub = DurationWindow::new(w.duration());
  348. let mut plnx_priv = DurationWindow::new(w.duration());
  349. let mut plnx_order = DurationWindow::new(w.duration());
  350. let mut plnx_ws_count: Window<u32> = Window::new(w.duration());
  351. // yes I am intentionally breaking from the hard-typed duration
  352. // window ... that was a stupid idea
  353. //
  354. let mut krkn_trade_30 = DurationWindow::new(Duration::from_secs(30));
  355. let mut krkn_trade_300 = DurationWindow::new(Duration::from_secs(300));
  356. //let mut gdax_ws_nolock = DurationWindow::new(w.duration());
  357. //let mut event_loop = DurationWindow::new(w.duration());
  358. let mut last = Last::default();
  359. thread::sleep_ms(1);
  360. info!(logger, "entering loop");
  361. loop {
  362. let loop_time = Instant::now();
  363. if let Ok(msg) = rx.recv() {
  364. debug!(logger, "new msg: {:?}", msg);
  365. match msg {
  366. ExperiencedLatency::Terminate => {
  367. crit!(logger, "terminating");
  368. break;
  369. }
  370. ExperiencedLatency::GdaxWebsocket(d) => gdax_ws.update(loop_time, d),
  371. //ExperiencedLatency::GdaxWebsocketNoLock(d) => gdax_ws_nolock.update(loop_time, d),
  372. ExperiencedLatency::GdaxHttpPrivate(d) => gdax_priv.update(loop_time, d),
  373. ExperiencedLatency::KrknHttpPublic(d) => {
  374. last.krkn = loop_time;
  375. krkn_pub.update(loop_time, d)
  376. }
  377. ExperiencedLatency::KrknHttpPrivate(d) => {
  378. last.krkn = loop_time;
  379. krkn_priv.update(loop_time, d)
  380. }
  381. ExperiencedLatency::PlnxHttpPublic(d) => {
  382. last.plnx = loop_time;
  383. plnx_pub.update(loop_time, d)
  384. }
  385. ExperiencedLatency::PlnxHttpPrivate(d) => {
  386. last.plnx = loop_time;
  387. plnx_priv.update(loop_time, d)
  388. }
  389. ExperiencedLatency::PlnxOrderBook(d) => {
  390. last.plnx = loop_time;
  391. plnx_order.update(loop_time, d)
  392. }
  393. ExperiencedLatency::PlnxWs(_) => {
  394. last.plnx = loop_time;
  395. plnx_ws_count.update(loop_time, 1_u32);
  396. }
  397. ExperiencedLatency::KrknTrade(d, cmd, ticker, side) => {
  398. debug!(logger, "new KrknTrade";
  399. "cmd" => cmd);
  400. last.krkn = loop_time;
  401. let n = DurationWindow::nanos(d);
  402. krkn_trade_30.update(loop_time, d);
  403. krkn_trade_300.update(loop_time, d);
  404. let ticker_s = ticker.map(|t| t.to_string()).unwrap_or("".into());
  405. let side_s = side.map(|s| s.to_string()).unwrap_or("".into());
  406. let mut m = Measurement::new("krkn_trade_api");
  407. m.add_field("nanos", Value::Integer(n as i64));
  408. m.add_tag("cmd", cmd);
  409. if ticker.is_some() {
  410. m.add_tag("ticker", &ticker_s);
  411. }
  412. if side.is_some() {
  413. m.add_tag("side", &side_s);
  414. }
  415. m.set_timestamp(now());
  416. influx::serialize(&m, &mut buf);
  417. socket.send_str(&buf, 0);
  418. buf.clear();
  419. }
  420. //ExperiencedLatency::EventLoop(d) => event_loop.update(Instant::now(), d),
  421. other => {
  422. warn!(logger, "unexpected msg: {:?}", other);
  423. }
  424. }
  425. }
  426. if loop_time - last.broadcast > Duration::from_millis(100) {
  427. debug!(logger, "initalizing broadcast");
  428. // note - because we mutated the Window instances
  429. // above, we need a fresh Instant to avoid less than other
  430. // panic
  431. //
  432. krkn_trade_30.refresh(&loop_time);
  433. krkn_trade_300.refresh(&loop_time);
  434. let update = LatencyUpdate {
  435. gdax_ws: gdax_ws.refresh(&loop_time).mean_nanos(),
  436. //gdax_ws_nolock: gdax_ws_nolock.refresh(&loop_time).mean_nanos(),
  437. krkn_pub: krkn_pub.refresh(&loop_time).mean_nanos(),
  438. krkn_priv: krkn_priv.refresh(&loop_time).mean_nanos(),
  439. plnx_pub: plnx_pub.refresh(&loop_time).mean_nanos(),
  440. plnx_priv: plnx_priv.refresh(&loop_time).mean_nanos(),
  441. plnx_order: plnx_order.refresh(&loop_time).mean_nanos(),
  442. krkn_trade_30_mean: krkn_trade_30.mean_nanos(),
  443. krkn_trade_30_max: krkn_trade_30.max_nanos().unwrap_or(0),
  444. krkn_trade_300_mean: krkn_trade_300.mean_nanos(),
  445. krkn_trade_300_max: krkn_trade_300.max_nanos().unwrap_or(0),
  446. plnx_last: dt_from_dur(loop_time - last.plnx),
  447. krkn_last: dt_from_dur(loop_time - last.krkn),
  448. plnx_ws_count: plnx_ws_count.refresh(&loop_time).count() as u64,
  449. //event_loop: event_loop.refresh(&now).mean_nanos(),
  450. size: w.clone(),
  451. };
  452. channel.send(update);
  453. last.broadcast = loop_time;
  454. debug!(logger, "sent broadcast");
  455. }
  456. }
  457. crit!(logger, "goodbye");
  458. }));
  459. LatencyManager {
  460. tx: tx_copy,
  461. channel: channel_copy,
  462. thread
  463. }
  464. }
  465. }