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.

1338 lines
50KB

  1. //! Utilities to efficiently send data to influx
  2. //!
  3. #![cfg_attr(all(test, feature = "unstable"), feature(test))]
  4. #![cfg(all(test, feature = "unstable"))]
  5. extern crate test;
  6. #[macro_use]
  7. extern crate slog;
  8. use std::io::Read;
  9. use std::sync::Arc;
  10. use crossbeam_channel::{Sender, Receiver, bounded, SendError};
  11. use std::{thread, mem};
  12. use std::time::*;
  13. use std::collections::VecDeque;
  14. use hyper::status::StatusCode;
  15. use hyper::client::response::Response;
  16. use hyper::Url;
  17. use hyper::client::Client;
  18. use slog::Drain;
  19. use chrono::prelude::*;
  20. use decimal::d128;
  21. use uuid::Uuid;
  22. use smallvec::SmallVec;
  23. use slog::Logger;
  24. use pretty_toa::ThousandsSep;
  25. /// Created this so I know what types can be passed through the
  26. /// `measure!` macro, which used to convert with `as i64` and
  27. /// `as f64` until I accidentally passed a function name, and it
  28. /// still compiled, but with garbage numbers.
  29. pub trait AsI64 {
  30. fn as_i64(x: Self) -> i64;
  31. }
  32. impl AsI64 for i64 { fn as_i64(x: Self) -> i64 { x } }
  33. impl AsI64 for i32 { fn as_i64(x: Self) -> i64 { x as i64 } }
  34. impl AsI64 for u32 { fn as_i64(x: Self) -> i64 { x as i64 } }
  35. impl AsI64 for u64 { fn as_i64(x: Self) -> i64 { x as i64 } }
  36. impl AsI64 for usize { fn as_i64(x: Self) -> i64 { x as i64 } }
  37. impl AsI64 for f64 { fn as_i64(x: Self) -> i64 { x as i64 } }
  38. impl AsI64 for f32 { fn as_i64(x: Self) -> i64 { x as i64 } }
  39. impl AsI64 for u16 { fn as_i64(x: Self) -> i64 { x as i64 } }
  40. impl AsI64 for i16 { fn as_i64(x: Self) -> i64 { x as i64 } }
  41. impl AsI64 for u8 { fn as_i64(x: Self) -> i64 { x as i64 } }
  42. impl AsI64 for i8 { fn as_i64(x: Self) -> i64 { x as i64 } }
  43. /// Created this so I know what types can be passed through the
  44. /// `measure!` macro, which used to convert with `as i64` and
  45. /// `as f64` until I accidentally passed a function name, and it
  46. /// still compiled, but with garbage numbers.
  47. pub trait AsF64 {
  48. fn as_f64(x: Self) -> f64;
  49. }
  50. impl AsF64 for f64 { fn as_f64(x: Self) -> f64 { x } }
  51. impl AsF64 for i64 { fn as_f64(x: Self) -> f64 { x as f64 } }
  52. impl AsF64 for i32 { fn as_f64(x: Self) -> f64 { x as f64 } }
  53. impl AsF64 for u32 { fn as_f64(x: Self) -> f64 { x as f64 } }
  54. impl AsF64 for u64 { fn as_f64(x: Self) -> f64 { x as f64 } }
  55. impl AsF64 for usize { fn as_f64(x: Self) -> f64 { x as f64 } }
  56. impl AsF64 for f32 { fn as_f64(x: Self) -> f64 { x as f64 } }
  57. /// Provides flexible and ergonomic use of `Sender<OwnedMeasurement>`.
  58. ///
  59. /// The macro both creates an `OwnedMeasurement` from the supplied tags and
  60. /// values, as well as sends it with the `Sender`.
  61. ///
  62. /// Benchmarks show around 600ns for a small measurement and 1u for a medium-sized
  63. /// measurement (see `tests` mod).
  64. ///
  65. /// # Examples
  66. ///
  67. /// ```
  68. /// #![feature(try_from)]
  69. /// #[macro_use] extern crate influx_writer;
  70. /// extern crate decimal;
  71. ///
  72. /// use std::sync::mpsc::channel;
  73. /// use decimal::d128;
  74. ///
  75. /// fn main() {
  76. /// let (tx, rx) = crossbeam_channel::bounded(1024);
  77. ///
  78. /// // "shorthand" syntax
  79. ///
  80. /// measure!(tx, test, tag[color;"red"], int[n;1]);
  81. ///
  82. /// let meas: OwnedMeasurement = rx.recv().unwrap();
  83. ///
  84. /// assert_eq!(meas.key, "test");
  85. /// assert_eq!(meas.get_tag("color"), Some("red"));
  86. /// assert_eq!(meas.get_field("n"), Some(&OwnedValue::Integer(1)));
  87. ///
  88. /// // alternate syntax ...
  89. ///
  90. /// measure!(tx, test,
  91. /// tag [ one => "a" ],
  92. /// tag [ two => "b" ],
  93. /// int [ three => 2 ],
  94. /// float [ four => 1.2345 ],
  95. /// string [ five => String::from("d") ],
  96. /// bool [ six => true ],
  97. /// int [ seven => { 1 + 2 } ],
  98. /// time [ 1 ]
  99. /// );
  100. ///
  101. /// let meas: OwnedMeasurement = rx.recv().unwrap();
  102. ///
  103. /// assert_eq!(meas.key, "test");
  104. /// assert_eq!(meas.get_tag("one"), Some("a"));
  105. /// assert_eq!(meas.get_tag("two"), Some("b"));
  106. /// assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  107. /// assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  108. /// assert_eq!(meas.timestamp, Some(1));
  109. ///
  110. /// // use the @make_meas flag to skip sending a measurement, instead merely
  111. /// // creating it.
  112. ///
  113. /// let meas: OwnedMeasurement = measure!(@make_meas meas_only, tag[color; "red"], int[n; 1]);
  114. ///
  115. /// // each variant also has shorthand aliases
  116. ///
  117. /// let meas: OwnedMeasurement =
  118. /// measure!(@make_meas abcd, t[color; "red"], i[n; 1], d[price; d128::zero()]);
  119. /// }
  120. /// ```
  121. ///
  122. #[macro_export]
  123. macro_rules! measure {
  124. (@kv $t:tt, $meas:ident, $k:tt => $v:expr) => { measure!(@ea $t, $meas, stringify!($k), $v) };
  125. (@kv $t:tt, $meas:ident, $k:tt; $v:expr) => { measure!(@ea $t, $meas, stringify!($k), $v) };
  126. (@kv $t:tt, $meas:ident, $k:tt, $v:expr) => { measure!(@ea $t, $meas, stringify!($k), $v) };
  127. //(@kv time, $meas:ident, $tm:expr) => { $meas = $meas.set_timestamp(AsI64::as_i64($tm)) };
  128. (@kv tm, $meas:ident, $tm:expr) => { $meas = $meas.set_timestamp(AsI64::as_i64($tm)) };
  129. (@kv utc, $meas:ident, $tm:expr) => { $meas = $meas.set_timestamp(AsI64::as_i64($crate::nanos($tm))) };
  130. (@kv v, $meas:ident, $k:expr) => { measure!(@ea t, $meas, "version", $k) };
  131. (@kv $t:tt, $meas:ident, $k:tt) => { measure!(@ea $t, $meas, stringify!($k), measure!(@as_expr $k)) };
  132. (@ea t, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_tag($k, $v); };
  133. (@ea i, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::OwnedValue::Integer(AsI64::as_i64($v))) };
  134. (@ea f, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::OwnedValue::Float(AsF64::as_f64($v))) };
  135. (@ea s, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::OwnedValue::String($v)) };
  136. (@ea d, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::OwnedValue::D128($v)) };
  137. (@ea u, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::OwnedValue::Uuid($v)) };
  138. (@ea b, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::OwnedValue::Boolean(bool::from($v))) };
  139. (@as_expr $e:expr) => {$e};
  140. (@count_tags) => {0usize};
  141. (@count_tags tag $($tail:tt)*) => {1usize + measure!(@count_tags $($tail)*)};
  142. (@count_tags $t:tt $($tail:tt)*) => {0usize + measure!(@count_tags $($tail)*)};
  143. (@count_fields) => {0usize};
  144. (@count_fields tag $($tail:tt)*) => {0usize + measure!(@count_fields $($tail)*)};
  145. (@count_fields time $($tail:tt)*) => {0usize + measure!(@count_fields $($tail)*)};
  146. (@count_fields $t:tt $($tail:tt)*) => {1usize + measure!(@count_fields $($tail)*)};
  147. (@make_meas $name:tt, $( $t:tt ( $($tail:tt)* ) ),+ $(,)*) => {
  148. measure!(@make_meas $name, $( $t [ $($tail)* ] ),*)
  149. };
  150. (@make_meas $name:tt, $( $t:tt [ $($tail:tt)* ] ),+ $(,)*) => {{
  151. let n_tags = measure!(@count_tags $($t)*);
  152. let n_fields = measure!(@count_fields $($t)*);
  153. let mut meas =
  154. $crate::OwnedMeasurement::with_capacity(stringify!($name), n_tags, n_fields);
  155. $(
  156. measure!(@kv $t, meas, $($tail)*);
  157. )*
  158. meas
  159. }};
  160. ($m:expr, $name:tt, $( $t:tt ( $($tail:tt)* ) ),+ $(,)*) => {
  161. measure!($m, $name, $($t [ $($tail)* ] ),+)
  162. };
  163. ($m:tt, $name:tt, $( $t:tt [ $($tail:tt)* ] ),+ $(,)*) => {{
  164. #[allow(unused_imports)]
  165. use $crate::{AsI64, AsF64};
  166. let measurement = measure!(@make_meas $name, $( $t [ $($tail)* ] ),*);
  167. let _ = $m.send(measurement);
  168. }};
  169. }
  170. /// converts a chrono::DateTime to an integer timestamp (ns)
  171. ///
  172. #[inline]
  173. pub fn nanos(t: DateTime<Utc>) -> u64 {
  174. (t.timestamp() as u64) * 1_000_000_000_u64 + (t.timestamp_subsec_nanos() as u64)
  175. }
  176. #[inline]
  177. pub fn secs(d: Duration) -> f64 {
  178. d.as_secs() as f64 + d.subsec_nanos() as f64 / 1_000_000_000_f64
  179. }
  180. #[inline]
  181. pub fn inanos(t: DateTime<Utc>) -> i64 {
  182. t.timestamp() * 1_000_000_000i64 + t.timestamp_subsec_nanos() as i64
  183. }
  184. //#[deprecated(since="0.4.3", note="Use `nanos(DateTime<Utc>) -> u64` instead")]
  185. pub fn dt_nanos(t: DateTime<Utc>) -> i64 {
  186. (t.timestamp() as i64) * 1_000_000_000_i64 + (t.timestamp_subsec_nanos() as i64)
  187. }
  188. #[inline]
  189. pub fn dur_nanos(d: ::std::time::Duration) -> i64 {
  190. (d.as_secs() * 1_000_000_000_u64 + (d.subsec_nanos() as u64)) as i64
  191. }
  192. #[inline]
  193. pub fn nanos_utc(t: i64) -> DateTime<Utc> {
  194. Utc.timestamp(t / 1_000_000_000, (t % 1_000_000_000) as u32)
  195. }
  196. #[derive(Clone, Debug)]
  197. pub struct Point<T, V> {
  198. pub time: T,
  199. pub value: V
  200. }
  201. pub struct DurationWindow {
  202. pub size: Duration,
  203. pub mean: Duration,
  204. pub sum: Duration,
  205. pub count: u32,
  206. pub items: VecDeque<Point<Instant, Duration>>
  207. }
  208. impl DurationWindow {
  209. #[inline]
  210. pub fn update(&mut self, time: Instant, value: Duration) {
  211. self.add(time, value);
  212. self.refresh(time);
  213. }
  214. #[inline]
  215. pub fn refresh(&mut self, t: Instant) -> &Self {
  216. if !self.items.is_empty() {
  217. let (n_remove, sum, count) =
  218. self.items.iter()
  219. .take_while(|x| t - x.time > self.size)
  220. .fold((0, self.sum, self.count), |(n_remove, sum, count), x| {
  221. (n_remove + 1, sum - x.value, count - 1)
  222. });
  223. self.sum = sum;
  224. self.count = count;
  225. for _ in 0..n_remove {
  226. self.items.pop_front();
  227. }
  228. }
  229. if self.count > 0 {
  230. self.mean = self.sum / self.count.into();
  231. }
  232. self
  233. }
  234. #[inline]
  235. pub fn add(&mut self, time: Instant, value: Duration) {
  236. let p = Point { time, value };
  237. self.sum += p.value;
  238. self.count += 1;
  239. self.items.push_back(p);
  240. }
  241. }
  242. /// Holds a thread (and provides an interface to it) that serializes `OwnedMeasurement`s
  243. /// it receives (over a SPSC channel) and inserts to influxdb via http when `BUFFER_SIZE`
  244. /// measurements have accumulated.
  245. ///
  246. #[derive(Debug)]
  247. pub struct InfluxWriter {
  248. host: String,
  249. db: String,
  250. tx: Sender<Option<OwnedMeasurement>>,
  251. thread: Option<Arc<thread::JoinHandle<()>>>,
  252. }
  253. impl Default for InfluxWriter {
  254. fn default() -> Self {
  255. InfluxWriter::new("localhost", "test")
  256. }
  257. }
  258. impl Clone for InfluxWriter {
  259. fn clone(&self) -> Self {
  260. debug_assert!(self.thread.is_some());
  261. let thread = self.thread.as_ref().map(|x| Arc::clone(x));
  262. InfluxWriter {
  263. host: self.host.to_string(),
  264. db: self.db.to_string(),
  265. tx: self.tx.clone(),
  266. thread,
  267. }
  268. }
  269. }
  270. impl InfluxWriter {
  271. pub fn host(&self) -> &str { self.host.as_str() }
  272. pub fn db(&self) -> &str { self.db.as_str() }
  273. /// Sends the `OwnedMeasurement` to the serialization thread.
  274. ///
  275. #[inline]
  276. pub fn send(&self, m: OwnedMeasurement) -> Result<(), SendError<Option<OwnedMeasurement>>> {
  277. self.tx.send(Some(m))
  278. }
  279. #[inline]
  280. pub fn nanos(&self, d: DateTime<Utc>) -> i64 { nanos(d) as i64 }
  281. #[inline]
  282. pub fn dur_nanos(&self, d: Duration) -> i64 { dur_nanos(d) as i64 }
  283. #[inline]
  284. pub fn dur_nanos_u64(&self, d: Duration) -> u64 { dur_nanos(d).max(0) as u64 }
  285. #[inline]
  286. pub fn rsecs(&self, d: Duration) -> f64 {
  287. ((d.as_secs() as f64 + (d.subsec_nanos() as f64 / 1_000_000_000_f64))
  288. * 1000.0)
  289. .round()
  290. / 1000.0
  291. }
  292. #[inline]
  293. pub fn secs(&self, d: Duration) -> f64 {
  294. d.as_secs() as f64 + d.subsec_nanos() as f64 / 1_000_000_000_f64
  295. }
  296. pub fn tx(&self) -> Sender<Option<OwnedMeasurement>> {
  297. self.tx.clone()
  298. }
  299. #[inline]
  300. pub fn is_full(&self) -> bool { self.tx.is_full() }
  301. pub fn placeholder() -> Self {
  302. let (tx, _) = bounded(1024);
  303. Self {
  304. host: String::new(),
  305. db: String::new(),
  306. tx,
  307. thread: None,
  308. }
  309. }
  310. pub fn new(host: &str, db: &str) -> Self {
  311. let noop_logger = slog::Logger::root(slog::Discard.fuse(), o!());
  312. Self::with_logger(host, db, &noop_logger)
  313. }
  314. #[allow(unused_assignments)]
  315. pub fn with_logger(host: &str, db: &str, logger: &Logger) -> Self {
  316. let logger = logger.new(o!(
  317. "host" => host.to_string(),
  318. "db" => db.to_string()));
  319. let (tx, rx): (Sender<Option<OwnedMeasurement>>, Receiver<Option<OwnedMeasurement>>) = bounded(4096);
  320. let url =
  321. Url::parse_with_params(&format!("http://{}:8086/write", host),
  322. &[("db", db), ("precision", "ns")])
  323. .expect("influx writer url should parse");
  324. let thread = thread::Builder::new().name(format!("mm:inflx:{}", db)).spawn(move || {
  325. use std::time::*;
  326. use crossbeam_channel as chan;
  327. #[cfg(feature = "no-influx-buffer")]
  328. const N_BUFFER_LINES: usize = 0;
  329. const N_BUFFER_LINES: usize = 1024;
  330. const MAX_PENDING: Duration = Duration::from_secs(3);
  331. const INITIAL_BUFFER_CAPACITY: usize = 4096;
  332. const MAX_BACKLOG: usize = 128;
  333. const MAX_OUTSTANDING_HTTP: usize = 64;
  334. const HB_EVERY: usize = 100_000;
  335. const N_HTTP_ATTEMPTS: u32 = 15;
  336. let client = Arc::new(Client::new());
  337. info!(logger, "initializing InfluxWriter ...";
  338. "N_BUFFER_LINES" => N_BUFFER_LINES,
  339. "MAX_PENDING" => %format_args!("{:?}", MAX_PENDING),
  340. "MAX_OUTSTANDING_HTTP" => MAX_OUTSTANDING_HTTP,
  341. "INITIAL_BUFFER_CAPACITY" => INITIAL_BUFFER_CAPACITY,
  342. "MAX_BACKLOG" => MAX_BACKLOG);
  343. // pre-allocated buffers ready for use if the active one is stasheed
  344. // during an outage
  345. let mut spares: VecDeque<String> = VecDeque::with_capacity(MAX_BACKLOG);
  346. // queue failed sends here until problem resolved, then send again. in worst
  347. // case scenario, loop back around on buffers queued in `backlog`, writing
  348. // over the oldest first.
  349. //
  350. let mut backlog: VecDeque<String> = VecDeque::with_capacity(MAX_BACKLOG);
  351. for _ in 0..MAX_BACKLOG {
  352. spares.push_back(String::with_capacity(1024));
  353. }
  354. struct Resp {
  355. pub buf: String,
  356. pub took: Duration,
  357. }
  358. let mut db_health = DurationWindow {
  359. size: Duration::from_secs(120),
  360. mean: Duration::new(10, 0),
  361. sum: Duration::new(0, 0),
  362. count: 0,
  363. items: VecDeque::with_capacity(MAX_OUTSTANDING_HTTP),
  364. };
  365. let (http_tx, http_rx) = chan::bounded(32);
  366. let mut buf = spares.pop_front().unwrap();
  367. let mut count = 0;
  368. let mut extras = 0; // any new Strings we intro to the system
  369. let mut n_rcvd = 0;
  370. let mut last = Instant::now();
  371. let mut active: bool;
  372. let mut last_clear = Instant::now();
  373. let mut loop_time = Instant::now();
  374. let n_out = |s: &VecDeque<String>, b: &VecDeque<String>, extras: usize| -> usize {
  375. MAX_BACKLOG + extras - s.len() - b.len() - 1
  376. };
  377. assert_eq!(n_out(&spares, &backlog, extras), 0);
  378. let send = |mut buf: String, backlog: &mut VecDeque<String>, n_outstanding: usize| {
  379. if n_outstanding >= MAX_OUTSTANDING_HTTP {
  380. backlog.push_back(buf);
  381. return
  382. }
  383. let url = url.clone(); // Arc would be faster, but `hyper::Client::post` consumes url
  384. let tx = http_tx.clone();
  385. let thread_logger = logger.new(o!("thread" => "InfluxWriter:http", "n_outstanding" => n_outstanding)); // re `thread_logger` name: disambiguating for `logger` after thread closure
  386. let client = Arc::clone(&client);
  387. debug!(logger, "launching http thread");
  388. let thread_res = thread::Builder::new().name(format!("inflx-http{}", n_outstanding)).spawn(move || {
  389. let logger = thread_logger;
  390. debug!(logger, "preparing to send http request to influx"; "buf.len()" => buf.len());
  391. let start = Instant::now();
  392. for n_req in 0..N_HTTP_ATTEMPTS {
  393. let throttle = Duration::from_secs(2) * n_req * n_req;
  394. if n_req > 0 {
  395. warn!(logger, "InfluxWriter http thread: pausing before next request";
  396. "n_req" => n_req,
  397. "throttle" => %format_args!("{:?}", throttle),
  398. "elapsed" => %format_args!("{:?}", Instant::now() - start));
  399. thread::sleep(throttle); // 0, 2, 8, 16, 32
  400. }
  401. let sent = Instant::now();
  402. let resp = client.post(url.clone())
  403. .body(buf.as_str())
  404. .send();
  405. let rcvd = Instant::now();
  406. let took = rcvd - sent;
  407. let mut n_tx = 0u32;
  408. match resp {
  409. Ok(Response { status, .. }) if status == StatusCode::NoContent => {
  410. debug!(logger, "server responded ok: 204 NoContent");
  411. buf.clear();
  412. let mut resp = Some(Ok(Resp { buf, took }));
  413. loop {
  414. n_tx += 1;
  415. match tx.try_send(resp.take().unwrap()) {
  416. Ok(_) => {
  417. if n_req > 0 {
  418. info!(logger, "successfully recovered from failed request with retry";
  419. "n_req" => n_req,
  420. "n_tx" => n_tx,
  421. "elapsed" => %format_args!("{:?}", Instant::now() - start));
  422. }
  423. return
  424. }
  425. Err(chan::TrySendError::Full(r)) => {
  426. let throttle = Duration::from_millis(1000) * n_tx;
  427. warn!(logger, "channel full: InfluxWriter http thread failed to return buf";
  428. "n_tx" => n_tx, "n_req" => n_req, "until next" => %format_args!("{:?}", throttle));
  429. resp = Some(r);
  430. thread::sleep(throttle);
  431. }
  432. Err(chan::TrySendError::Disconnected(_)) => {
  433. warn!(logger, "InfluxWriter http thread: channel disconnected, aborting buffer return";
  434. "n_tx" => n_tx, "n_req" => n_req);
  435. return
  436. }
  437. }
  438. }
  439. }
  440. Ok(mut resp) => {
  441. let mut server_resp = String::new();
  442. let _ = resp.read_to_string(&mut server_resp); //.unwrap_or(0);
  443. error!(logger, "influx server error (request took {:?})", took;
  444. "status" => %resp.status,
  445. "body" => server_resp);
  446. }
  447. Err(e) => {
  448. error!(logger, "http request failed: {:?} (request took {:?})", e, took; "err" => %e);
  449. }
  450. }
  451. }
  452. let took = Instant::now() - start;
  453. warn!(logger, "InfluxWriter http thread: aborting http req, returning buffer";
  454. "took" => %format_args!("{:?}", took));
  455. let buflen = buf.len();
  456. let n_lines = buf.lines().count();
  457. if let Err(e) = tx.send(Err(Resp { buf, took })) {
  458. crit!(logger, "failed to send Err(Resp {{ .. }}) back on abort: {:?}", e;
  459. "err" => %e, "buf.len()" => buflen, "n_lines" => n_lines);
  460. }
  461. });
  462. if let Err(e) = thread_res {
  463. crit!(logger, "failed to spawn thread: {}", e);
  464. }
  465. };
  466. let next = |prev: usize, m: &OwnedMeasurement, buf: &mut String, loop_time: Instant, last: Instant| -> Result<usize, usize> {
  467. match prev {
  468. 0 if N_BUFFER_LINES > 0 => {
  469. serialize_owned(m, buf);
  470. Ok(1)
  471. }
  472. n if n < N_BUFFER_LINES && loop_time - last < MAX_PENDING => {
  473. buf.push_str("\n");
  474. serialize_owned(m, buf);
  475. Ok(n + 1)
  476. }
  477. n => {
  478. buf.push_str("\n");
  479. serialize_owned(m, buf);
  480. Err(n + 1)
  481. }
  482. }
  483. };
  484. 'event: loop {
  485. loop_time = Instant::now();
  486. active = false;
  487. match rx.recv() {
  488. Ok(Some(mut meas)) => {
  489. n_rcvd += 1;
  490. active = true;
  491. if n_rcvd % HB_EVERY == 0 {
  492. let n_outstanding = n_out(&spares, &backlog, extras);
  493. info!(logger, "rcvd {} measurements", n_rcvd.thousands_sep();
  494. "n_outstanding" => n_outstanding,
  495. "spares.len()" => spares.len(),
  496. "n_rcvd" => n_rcvd,
  497. "n_active_buf" => count,
  498. "db_health" => %format_args!("{:?}", db_health.mean),
  499. "backlog.len()" => backlog.len());
  500. }
  501. if meas.timestamp.is_none() { meas.timestamp = Some(now()) }
  502. if meas.fields.is_empty() {
  503. meas.fields.push(("n", OwnedValue::Integer(1)));
  504. }
  505. //#[cfg(feature = "trace")] { if count % 10 == 0 { trace!(logger, "rcvd new measurement"; "count" => count, "key" => meas.key); } }
  506. count = match next(count, &meas, &mut buf, loop_time, last) {
  507. Ok(n) => n,
  508. Err(_n) => {
  509. let mut count = 0;
  510. let mut next: String = match spares.pop_front() {
  511. Some(x) => x,
  512. None => {
  513. let n_outstanding = n_out(&spares, &backlog, extras);
  514. crit!(logger, "no available buffers in `spares`, pulling from backlog";
  515. "n_outstanding" => n_outstanding,
  516. "spares.len()" => spares.len(),
  517. "n_rcvd" => n_rcvd,
  518. "backlog.len()" => backlog.len());
  519. match backlog.pop_front() {
  520. // Note: this does not clear the backlog buffer,
  521. // instead we will just write more and more until
  522. // we are out of memory. I expect that will never
  523. // happen.
  524. //
  525. Some(x) => {
  526. count = 1; // otherwise, no '\n' added in `next(..)` - we are
  527. // sending a "full" buffer to be extended
  528. x
  529. }
  530. None => {
  531. extras += 1;
  532. crit!(logger, "failed to pull from backlog, too!! WTF #!(*#(* ... creating new String";
  533. "n_outstanding" => n_outstanding,
  534. "spares.len()" => spares.len(),
  535. "backlog.len()" => backlog.len(),
  536. "n_rcvd" => n_rcvd,
  537. "extras" => extras);
  538. String::new()
  539. }
  540. }
  541. }
  542. };
  543. // after swap, buf in next, so want to send next
  544. //
  545. mem::swap(&mut buf, &mut next);
  546. let n_outstanding = n_out(&spares, &backlog, extras);
  547. send(next, &mut backlog, n_outstanding);
  548. last = loop_time;
  549. count
  550. }
  551. };
  552. }
  553. Ok(None) => {
  554. let start = Instant::now();
  555. let mut hb = Instant::now();
  556. warn!(logger, "terminate signal rcvd"; "count" => count);
  557. if buf.len() > 0 {
  558. info!(logger, "sending remaining buffer to influx on terminate"; "count" => count);
  559. let meas = OwnedMeasurement::new("wtrterm").add_field("n", OwnedValue::Integer(1));
  560. let _ = next(N_BUFFER_LINES, &meas, &mut buf, loop_time, last);
  561. let n_outstanding = n_out(&spares, &backlog, extras);
  562. let mut placeholder = spares.pop_front().unwrap_or_else(String::new);
  563. mem::swap(&mut buf, &mut placeholder);
  564. send(placeholder, &mut backlog, n_outstanding);
  565. }
  566. let mut n_ok = 0;
  567. let mut n_err = 0;
  568. loop {
  569. loop_time = Instant::now();
  570. let n_outstanding = n_out(&spares, &backlog, extras);
  571. if backlog.is_empty() && n_outstanding < 1 {
  572. info!(logger, "cleared any remaining backlog";
  573. "n_outstanding" => n_outstanding,
  574. "spares.len()" => spares.len(),
  575. "backlog.len()" => backlog.len(),
  576. "n_cleared_ok" => n_ok,
  577. "n_cleared_err" => n_err,
  578. "n_rcvd" => n_rcvd,
  579. "extras" => extras,
  580. "elapsed" => %format_args!("{:?}", loop_time - start));
  581. break 'event
  582. }
  583. if loop_time - hb > Duration::from_secs(5) {
  584. info!(logger, "InfluxWriter still clearing backlog ..";
  585. "n_outstanding" => n_outstanding,
  586. "spares.len()" => spares.len(),
  587. "backlog.len()" => backlog.len(),
  588. "n_cleared_ok" => n_ok,
  589. "n_cleared_err" => n_err,
  590. "extras" => extras,
  591. "n_rcvd" => n_rcvd,
  592. "elapsed" => %format_args!("{:?}", loop_time - start));
  593. hb = loop_time;
  594. }
  595. if let Some(buf) = backlog.pop_front() {
  596. let n_outstanding = n_out(&spares, &backlog, extras);
  597. debug!(logger, "resending queued buffer from backlog";
  598. "backlog.len()" => backlog.len(),
  599. "spares.len()" => spares.len(),
  600. "n_rcvd" => n_rcvd,
  601. "n_outstanding" => n_outstanding);
  602. send(buf, &mut backlog, n_outstanding);
  603. last_clear = loop_time;
  604. }
  605. 'rx: loop {
  606. match http_rx.try_recv() {
  607. Ok(Ok(Resp { buf, .. })) => {
  608. n_ok += 1;
  609. spares.push_back(buf); // needed so `n_outstanding` count remains accurate
  610. }
  611. Ok(Err(Resp { buf, .. })) => {
  612. warn!(logger, "requeueing failed request"; "buf.len()" => buf.len());
  613. n_err += 1;
  614. backlog.push_front(buf);
  615. }
  616. Err(chan::TryRecvError::Disconnected) => {
  617. crit!(logger, "trying to clear backlog, but http_rx disconnected! aborting";
  618. "n_outstanding" => n_outstanding,
  619. "backlog.len()" => backlog.len(),
  620. "n_cleared_ok" => n_ok,
  621. "n_cleared_err" => n_err,
  622. "extras" => extras,
  623. "n_rcvd" => n_rcvd,
  624. "elapsed" => %format_args!("{:?}", loop_time - start));
  625. break 'event
  626. }
  627. Err(_) => break 'rx
  628. }
  629. }
  630. thread::sleep(Duration::from_millis(1));
  631. }
  632. }
  633. _ => {}
  634. }
  635. db_health.refresh(loop_time);
  636. let n_outstanding = n_out(&spares, &backlog, extras);
  637. let healthy = db_health.count == 0 || db_health.mean < Duration::from_secs(200);
  638. if (n_outstanding < MAX_OUTSTANDING_HTTP || loop_time - last_clear > Duration::from_secs(60)) && healthy {
  639. if let Some(queued) = backlog.pop_front() {
  640. let n_outstanding = n_out(&spares, &backlog, extras);
  641. send(queued, &mut backlog, n_outstanding);
  642. active = true;
  643. }
  644. }
  645. loop {
  646. match http_rx.try_recv() {
  647. Ok(Ok(Resp { buf, took })) => {
  648. db_health.add(loop_time, took);
  649. spares.push_back(buf);
  650. active = true;
  651. }
  652. Ok(Err(Resp { buf, took })) => {
  653. db_health.add(loop_time, took);
  654. backlog.push_front(buf);
  655. active = true;
  656. }
  657. Err(chan::TryRecvError::Disconnected) => {
  658. crit!(logger, "trying to recover buffers, but http_rx disconnected! aborting";
  659. "n_outstanding" => n_outstanding,
  660. "backlog.len()" => backlog.len(),
  661. "n_rcvd" => n_rcvd,
  662. "extras" => extras);
  663. break 'event
  664. }
  665. Err(_) => break
  666. }
  667. }
  668. if !active {
  669. thread::sleep(Duration::new(0, 1))
  670. }
  671. }
  672. info!(logger, "waiting 1s before exiting thread");
  673. thread::sleep(Duration::from_secs(1));
  674. }).unwrap();
  675. InfluxWriter {
  676. host: host.to_string(),
  677. db: db.to_string(),
  678. tx,
  679. thread: Some(Arc::new(thread))
  680. }
  681. }
  682. }
  683. impl Drop for InfluxWriter {
  684. fn drop(&mut self) {
  685. if let Some(arc) = self.thread.take() {
  686. if let Ok(thread) = Arc::try_unwrap(arc) {
  687. let _ = self.tx.send(None);
  688. let _ = thread.join();
  689. }
  690. }
  691. }
  692. }
  693. /// This removes offending things rather than escaping them.
  694. ///
  695. fn escape_tag(s: &str) -> String {
  696. s.replace(" ", "")
  697. .replace(",", "")
  698. .replace("\"", "")
  699. }
  700. fn escape(s: &str) -> String {
  701. s.replace(" ", "\\ ")
  702. .replace(",", "\\,")
  703. }
  704. fn as_string(s: &str) -> String {
  705. // the second replace removes double escapes
  706. //
  707. format!("\"{}\"", s.replace("\"", "\\\"")
  708. .replace(r#"\\""#, r#"\""#))
  709. }
  710. #[test]
  711. fn it_checks_as_string_does_not_double_escape() {
  712. let raw = "this is \\\"an escaped string\\\" so it's problematic";
  713. let escaped = as_string(&raw);
  714. assert_eq!(escaped, format!("\"{}\"", raw).as_ref());
  715. }
  716. fn as_boolean(b: &bool) -> &str {
  717. if *b { "t" } else { "f" }
  718. }
  719. pub fn now() -> i64 {
  720. nanos(Utc::now()) as i64
  721. }
  722. /// Serializes an `&OwnedMeasurement` as influx line protocol into `line`.
  723. ///
  724. /// The serialized measurement is appended to the end of the string without
  725. /// any regard for what exited in it previously.
  726. ///
  727. pub fn serialize_owned(measurement: &OwnedMeasurement, line: &mut String) {
  728. line.push_str(&escape_tag(measurement.key));
  729. let add_tag = |line: &mut String, key: &str, value: &str| {
  730. line.push_str(",");
  731. line.push_str(&escape_tag(key));
  732. line.push_str("=");
  733. line.push_str(&escape(value));
  734. };
  735. for (key, value) in measurement.tags.iter() {
  736. #[cfg(not(feature = "string-tags"))]
  737. add_tag(line, key, value);
  738. #[cfg(feature = "string-tags")]
  739. add_tag(line, key, value.as_str());
  740. }
  741. let add_field = |line: &mut String, key: &str, value: &OwnedValue, is_first: bool| {
  742. if is_first { line.push_str(" "); } else { line.push_str(","); }
  743. line.push_str(&escape_tag(key));
  744. line.push_str("=");
  745. match *value {
  746. OwnedValue::String(ref s) => line.push_str(&as_string(s)),
  747. OwnedValue::Integer(ref i) => line.push_str(&format!("{}i", i)),
  748. OwnedValue::Boolean(ref b) => line.push_str(as_boolean(b)),
  749. OwnedValue::D128(ref d) => {
  750. if d.is_finite() {
  751. line.push_str(&format!("{}", d));
  752. } else {
  753. line.push_str("0.0");
  754. }
  755. }
  756. OwnedValue::Float(ref f) => {
  757. if f.is_finite() {
  758. line.push_str(&format!("{}", f));
  759. } else {
  760. line.push_str("-999.0");
  761. }
  762. }
  763. OwnedValue::Uuid(ref u) => line.push_str(&format!("\"{}\"", u)),
  764. };
  765. };
  766. let mut fields = measurement.fields.iter();
  767. // first time separate from tags with space
  768. //
  769. fields.next().map(|kv| {
  770. add_field(line, &kv.0, &kv.1, true);
  771. });
  772. // then seperate the rest w/ comma
  773. //
  774. for kv in fields {
  775. add_field(line, kv.0, &kv.1, false);
  776. }
  777. if let Some(t) = measurement.timestamp {
  778. line.push_str(" ");
  779. line.push_str(&t.to_string());
  780. }
  781. }
  782. #[derive(Debug, Clone, PartialEq)]
  783. pub enum OwnedValue {
  784. String(String),
  785. Float(f64),
  786. Integer(i64),
  787. Boolean(bool),
  788. D128(d128),
  789. Uuid(Uuid),
  790. }
  791. /// Holds data meant for an influxdb measurement in transit to the
  792. /// writing thread.
  793. ///
  794. #[derive(Clone, Debug)]
  795. pub struct OwnedMeasurement {
  796. pub key: &'static str,
  797. pub timestamp: Option<i64>,
  798. //pub fields: Map<&'static str, OwnedValue>,
  799. //pub tags: Map<&'static str, &'static str>,
  800. pub fields: SmallVec<[(&'static str, OwnedValue); 8]>,
  801. #[cfg(not(feature = "string-tags"))]
  802. pub tags: SmallVec<[(&'static str, &'static str); 8]>,
  803. #[cfg(feature = "string-tags")]
  804. pub tags: SmallVec<[(&'static str, String); 8]>,
  805. }
  806. impl OwnedMeasurement {
  807. pub fn with_capacity(key: &'static str, n_tags: usize, n_fields: usize) -> Self {
  808. OwnedMeasurement {
  809. key,
  810. timestamp: None,
  811. tags: SmallVec::with_capacity(n_tags),
  812. fields: SmallVec::with_capacity(n_fields),
  813. }
  814. }
  815. pub fn new(key: &'static str) -> Self {
  816. OwnedMeasurement {
  817. key,
  818. timestamp: None,
  819. tags: SmallVec::new(),
  820. fields: SmallVec::new(),
  821. }
  822. }
  823. /// Unusual consuming `self` signature because primarily used by
  824. /// the `measure!` macro.
  825. #[cfg(not(feature = "string-tags"))]
  826. pub fn add_tag(mut self, key: &'static str, value: &'static str) -> Self {
  827. self.tags.push((key, value));
  828. self
  829. }
  830. #[cfg(feature = "string-tags")]
  831. pub fn add_tag<S: ToString>(mut self, key: &'static str, value: S) -> Self {
  832. self.tags.push((key, value.to_string()));
  833. self
  834. }
  835. /// Unusual consuming `self` signature because primarily used by
  836. /// the `measure!` macro.
  837. pub fn add_field(mut self, key: &'static str, value: OwnedValue) -> Self {
  838. self.fields.push((key, value));
  839. self
  840. }
  841. pub fn set_timestamp(mut self, timestamp: i64) -> Self {
  842. self.timestamp = Some(timestamp);
  843. self
  844. }
  845. #[cfg(not(feature = "string-tags"))]
  846. pub fn set_tag(mut self, key: &'static str, value: &'static str) -> Self {
  847. match self.tags.iter().position(|kv| kv.0 == key) {
  848. Some(i) => {
  849. self.tags.get_mut(i)
  850. .map(|x| {
  851. x.0 = value;
  852. });
  853. self
  854. }
  855. None => {
  856. self.add_tag(key, value)
  857. }
  858. }
  859. }
  860. pub fn get_field(&self, key: &'static str) -> Option<&OwnedValue> {
  861. self.fields.iter()
  862. .find(|kv| kv.0 == key)
  863. .map(|kv| &kv.1)
  864. }
  865. #[cfg(feature = "string-tags")]
  866. pub fn get_tag(&self, key: &'static str) -> Option<&str> {
  867. self.tags.iter()
  868. .find(|kv| kv.0 == key)
  869. .map(|kv| kv.1.as_str())
  870. }
  871. #[cfg(not(feature = "string-tags"))]
  872. pub fn get_tag(&self, key: &'static str) -> Option<&'static str> {
  873. self.tags.iter()
  874. .find(|kv| kv.0 == key)
  875. .map(|kv| kv.1)
  876. }
  877. }
  878. #[allow(unused)]
  879. #[cfg(test)]
  880. mod tests {
  881. use super::*;
  882. #[cfg(feature = "unstable")]
  883. use test::{black_box, Bencher};
  884. #[ignore]
  885. #[cfg(feature = "unstable")]
  886. #[bench]
  887. fn measure_ten(b: &mut Bencher) {
  888. let influx = InfluxWriter::new("localhost", "test");
  889. let mut n = 0;
  890. b.iter(|| {
  891. for _ in 0..10 {
  892. let time = influx.nanos(Utc::now());
  893. n += 1;
  894. measure!(influx, million, i(n), tm(time));
  895. }
  896. });
  897. }
  898. #[test]
  899. fn it_uses_the_utc_shortcut_to_convert_a_datetime_utc() {
  900. const VERSION: &str = "0.3.90";
  901. let tag_value = "one";
  902. let color = "red";
  903. let time = Utc::now();
  904. let m = measure!(@make_meas test, i(n, 1), t(color), v(VERSION), utc(time));
  905. assert_eq!(m.get_tag("color"), Some("red"));
  906. assert_eq!(m.get_tag("version"), Some(VERSION));
  907. assert_eq!(m.timestamp, Some(nanos(time) as i64));
  908. }
  909. #[test]
  910. fn it_uses_the_v_for_version_shortcut() {
  911. const VERSION: &str = "0.3.90";
  912. let tag_value = "one";
  913. let color = "red";
  914. let time = now();
  915. let m = measure!(@make_meas test, i(n, 1), t(color), v(VERSION), tm(time));
  916. assert_eq!(m.get_tag("color"), Some("red"));
  917. assert_eq!(m.get_tag("version"), Some(VERSION));
  918. assert_eq!(m.timestamp, Some(time));
  919. }
  920. #[test]
  921. fn it_uses_the_new_tag_k_only_shortcut() {
  922. let tag_value = "one";
  923. let color = "red";
  924. let time = now();
  925. let m = measure!(@make_meas test, t(color), t(tag_value), tm(time));
  926. assert_eq!(m.get_tag("color"), Some("red"));
  927. assert_eq!(m.get_tag("tag_value"), Some("one"));
  928. assert_eq!(m.timestamp, Some(time));
  929. }
  930. #[test]
  931. fn it_uses_measure_macro_parenthesis_syntax() {
  932. let m = measure!(@make_meas test, t(a,"b"), i(n,1), f(x,1.1), tm(1));
  933. assert_eq!(m.key, "test");
  934. assert_eq!(m.get_tag("a"), Some("b"));
  935. assert_eq!(m.get_field("n"), Some(&OwnedValue::Integer(1)));
  936. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  937. assert_eq!(m.timestamp, Some(1));
  938. }
  939. #[test]
  940. fn it_uses_measure_macro_on_a_self_attribute() {
  941. struct A {
  942. pub influx: InfluxWriter,
  943. }
  944. impl A {
  945. fn f(&self) {
  946. measure!(self.influx, test, t(color, "red"), i(n, 1));
  947. }
  948. }
  949. let a = A { influx: InfluxWriter::default() };
  950. a.f();
  951. }
  952. #[test]
  953. fn it_clones_an_influx_writer_to_check_both_drop() {
  954. let influx = InfluxWriter::default();
  955. measure!(influx, drop_test, i(a, 1), i(b, 2));
  956. {
  957. let influx = influx.clone();
  958. thread::spawn(move || {
  959. measure!(influx, drop_test, i(a, 3), i(b, 4));
  960. });
  961. }
  962. }
  963. #[cfg(feature = "unstable")]
  964. #[bench]
  965. fn influx_writer_send_basic(b: &mut Bencher) {
  966. let m = InfluxWriter::new("localhost", "test");
  967. b.iter(|| {
  968. measure!(m, test, t(color; "red"), i(n, 1)); //, float[p; 1.234]);
  969. });
  970. }
  971. #[cfg(feature = "unstable")]
  972. #[bench]
  973. fn influx_writer_send_price(b: &mut Bencher) {
  974. let m = InfluxWriter::new("localhost", "test");
  975. b.iter(|| {
  976. measure!(m, test,
  977. t(ticker, "xmr_btc"),
  978. t(exchange, "plnx"),
  979. d(bid, d128::zero()),
  980. d(ask, d128::zero()),
  981. );
  982. });
  983. }
  984. #[test]
  985. fn it_checks_color_tag_error_in_non_doctest() {
  986. let (tx, rx) = bounded(1024);
  987. measure!(tx, test, t(color,"red"), i(n,1));
  988. let meas: OwnedMeasurement = rx.recv().unwrap();
  989. assert_eq!(meas.get_tag("color"), Some("red"), "meas = \n {:?} \n", meas);
  990. }
  991. #[test]
  992. fn it_uses_the_make_meas_pattern_of_the_measure_macro() {
  993. let meas = measure!(@make_meas test_measurement,
  994. t(one, "a"), t(two, "b"), i(three, 2),
  995. f(four, 1.2345), s(five, String::from("d")),
  996. b(six, true), i(seven, 1 + 2),
  997. tm(1)
  998. );
  999. assert_eq!(meas.key, "test_measurement");
  1000. assert_eq!(meas.get_tag("one"), Some("a"));
  1001. assert_eq!(meas.get_tag("two"), Some("b"));
  1002. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  1003. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  1004. assert_eq!(meas.timestamp, Some(1));
  1005. }
  1006. #[test]
  1007. fn it_uses_measure_macro_for_d128_and_uuid() {
  1008. let (tx, rx) = bounded(1024);
  1009. let one = "a";
  1010. let two = d128::zero();
  1011. let three = Uuid::new_v4();
  1012. let time = now();
  1013. measure!(tx, test_measurement, t(one), d(two), u(three), tm(time));
  1014. thread::sleep(Duration::from_millis(10));
  1015. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  1016. assert_eq!(meas.key, "test_measurement");
  1017. assert_eq!(meas.get_tag("one"), Some("a"));
  1018. assert_eq!(meas.get_field("two"), Some(&OwnedValue::D128(d128::zero())));
  1019. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Uuid(three)));
  1020. assert_eq!(meas.timestamp, Some(time));
  1021. }
  1022. #[test]
  1023. fn it_uses_the_measure_macro_alt_syntax() {
  1024. let (tx, rx) = bounded(1024);
  1025. measure!(tx, test_measurement,
  1026. t(one, "a"), t(two, "b"), i(three, 2),
  1027. f(four, 1.2345), s(five, String::from("d")),
  1028. b(six, true), i(seven, 1 + 2),
  1029. tm(1)
  1030. );
  1031. thread::sleep(Duration::from_millis(10));
  1032. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  1033. assert_eq!(meas.key, "test_measurement");
  1034. assert_eq!(meas.get_tag("one"), Some("a"));
  1035. assert_eq!(meas.get_tag("two"), Some("b"));
  1036. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  1037. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  1038. assert_eq!(meas.timestamp, Some(1));
  1039. }
  1040. #[test]
  1041. fn it_checks_that_fields_are_separated_correctly() {
  1042. let m = measure!(@make_meas test, t[a; "one"], t[b; "two"], f[x; 1.1], f[y; -1.1]);
  1043. assert_eq!(m.key, "test");
  1044. assert_eq!(m.get_tag("a"), Some("one"));
  1045. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  1046. let mut buf = String::new();
  1047. serialize_owned(&m, &mut buf);
  1048. assert!(buf.contains("b=two x=1.1,y=-1.1"), "buf = {}", buf);
  1049. }
  1050. #[test]
  1051. fn try_to_break_measure_macro() {
  1052. let (tx, _) = bounded(1024);
  1053. measure!(tx, one, t(x,"y"), i(n,1));
  1054. measure!(tx, one, t(x,"y"), i(n,1),);
  1055. struct A {
  1056. pub one: i32,
  1057. pub two: i32,
  1058. }
  1059. struct B {
  1060. pub a: A
  1061. }
  1062. let b = B { a: A { one: 1, two: 2 } };
  1063. let m = measure!(@make_meas test, t(name, "a"), i(a, b.a.one));
  1064. assert_eq!(m.get_field("a"), Some(&OwnedValue::Integer(1)));
  1065. }
  1066. #[cfg(feature = "unstable")]
  1067. #[bench]
  1068. fn measure_macro_small(b: &mut Bencher) {
  1069. let (tx, rx) = bounded(1024);
  1070. let listener = thread::spawn(move || {
  1071. loop { if rx.recv().is_err() { break } }
  1072. });
  1073. b.iter(|| {
  1074. measure!(tx, test, t(color, "red"), i(n, 1), tm(now()));
  1075. });
  1076. }
  1077. #[cfg(feature = "unstable")]
  1078. #[bench]
  1079. fn measure_macro_medium(b: &mut Bencher) {
  1080. let (tx, rx) = bounded(1024);
  1081. let listener = thread::spawn(move || {
  1082. loop { if rx.recv().is_err() { break } }
  1083. });
  1084. b.iter(|| {
  1085. measure!(tx, test, t(color, "red"), t(mood, "playful"),
  1086. t(ticker, "xmr_btc"), f(price, 1.2345), f(amount, 56.322),
  1087. i(n, 1), tm(now()));
  1088. });
  1089. }
  1090. #[cfg(feature = "unstable")]
  1091. #[bench]
  1092. fn serialize_owned_longer(b: &mut Bencher) {
  1093. let mut buf = String::with_capacity(1024);
  1094. let m =
  1095. OwnedMeasurement::new("test")
  1096. .add_tag("one", "a")
  1097. .add_tag("two", "b")
  1098. .add_tag("ticker", "xmr_btc")
  1099. .add_tag("exchange", "plnx")
  1100. .add_tag("side", "bid")
  1101. .add_field("three", OwnedValue::Float(1.2345))
  1102. .add_field("four", OwnedValue::Integer(57))
  1103. .add_field("five", OwnedValue::Boolean(true))
  1104. .add_field("six", OwnedValue::String(String::from("abcdefghijklmnopqrstuvwxyz")))
  1105. .set_timestamp(now());
  1106. b.iter(|| {
  1107. serialize_owned(&m, &mut buf);
  1108. buf.clear()
  1109. });
  1110. }
  1111. #[cfg(feature = "unstable")]
  1112. #[bench]
  1113. fn serialize_owned_simple(b: &mut Bencher) {
  1114. let mut buf = String::with_capacity(1024);
  1115. let m =
  1116. OwnedMeasurement::new("test")
  1117. .add_tag("one", "a")
  1118. .add_tag("two", "b")
  1119. .add_field("three", OwnedValue::Float(1.2345))
  1120. .add_field("four", OwnedValue::Integer(57))
  1121. .set_timestamp(now());
  1122. b.iter(|| {
  1123. serialize_owned(&m, &mut buf);
  1124. buf.clear()
  1125. });
  1126. }
  1127. #[cfg(feature = "unstable")]
  1128. #[bench]
  1129. fn clone_url_for_thread(b: &mut Bencher) {
  1130. let host = "ahmes";
  1131. let db = "mlp";
  1132. let url =
  1133. Url::parse_with_params(&format!("http://{}:8086/write", host),
  1134. &[("db", db), ("precision", "ns")]).unwrap();
  1135. b.iter(|| {
  1136. url.clone()
  1137. })
  1138. }
  1139. #[cfg(feature = "unstable")]
  1140. #[bench]
  1141. fn clone_arc_url_for_thread(b: &mut Bencher) {
  1142. let host = "ahmes";
  1143. let db = "mlp";
  1144. let url =
  1145. Url::parse_with_params(&format!("http://{}:8086/write", host),
  1146. &[("db", db), ("precision", "ns")]).unwrap();
  1147. let url = Arc::new(url);
  1148. b.iter(|| {
  1149. Arc::clone(&url)
  1150. })
  1151. }
  1152. #[test]
  1153. fn it_serializes_a_hard_to_serialize_message_from_owned() {
  1154. let raw = r#"error encountered trying to send krkn order: Other("Failed to send http request: Other("Resource temporarily unavailable (os error 11)")")"#;
  1155. let mut buf = String::new();
  1156. let mut server_resp = String::new();
  1157. let m = OwnedMeasurement::new("rust_test")
  1158. .add_field("s", OwnedValue::String(raw.to_string()))
  1159. .set_timestamp(now());
  1160. serialize_owned(&m, &mut buf);
  1161. println!("{}", buf);
  1162. buf.push_str("\n");
  1163. let buf_copy = buf.clone();
  1164. buf.push_str(&buf_copy);
  1165. println!("{}", buf);
  1166. let url = Url::parse_with_params("http://localhost:8086/write", &[("db", "test"), ("precision", "ns")]).expect("influx writer url should parse");
  1167. let client = Client::new();
  1168. match client.post(url.clone())
  1169. .body(&buf)
  1170. .send() {
  1171. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  1172. Ok(mut resp) => {
  1173. resp.read_to_string(&mut server_resp).unwrap();
  1174. panic!("{}", server_resp);
  1175. }
  1176. Err(why) => {
  1177. panic!(why)
  1178. }
  1179. }
  1180. }
  1181. }