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.

1553 lines
61KB

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