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.

1564 lines
62KB

  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 n_pts: u64 = 0;
  403. let mut in_flight_buffer_bytes = 0;
  404. let mut last = Instant::now();
  405. let mut active: bool;
  406. let mut last_clear = Instant::now();
  407. let mut last_memory_check = Instant::now();
  408. let mut loop_time: Instant;
  409. let n_out = |s: &VecDeque<String>, b: &VecDeque<String>, extras: usize| -> usize {
  410. INITIAL_BACKLOG + extras - s.len() - b.len() - 1
  411. };
  412. assert_eq!(n_out(&spares, &backlog, extras), 0);
  413. let count_allocated_memory = |spares: &VecDeque<String>, backlog: &VecDeque<String>, in_flight_buffer_bytes: &usize| -> usize {
  414. spares.iter().map(|x| x.capacity()).sum::<usize>()
  415. + backlog.iter().map(|x| x.capacity()).sum::<usize>()
  416. + (*in_flight_buffer_bytes)
  417. };
  418. let send = |mut buf: String, backlog: &mut VecDeque<String>, n_outstanding: usize, in_flight_buffer_bytes: &mut usize| {
  419. if n_outstanding >= MAX_OUTSTANDING_HTTP {
  420. backlog.push_back(buf);
  421. return
  422. }
  423. let url = url.clone(); // Arc would be faster, but `hyper::Client::post` consumes url
  424. let tx = http_tx.clone();
  425. 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
  426. let client = Arc::clone(&client);
  427. let creds = Arc::clone(&creds);
  428. *in_flight_buffer_bytes = *in_flight_buffer_bytes + buf.capacity();
  429. debug!(logger, "launching http thread");
  430. let thread_res = thread::Builder::new().name(format!("inflx-http{}", n_outstanding)).spawn(move || {
  431. let logger = thread_logger;
  432. debug!(logger, "preparing to send http request to influx"; "buf.len()" => buf.len());
  433. let start = Instant::now();
  434. for n_req in 0..N_HTTP_ATTEMPTS {
  435. let throttle = Duration::from_secs(2) * n_req * n_req;
  436. if n_req > 0 {
  437. warn!(logger, "InfluxWriter http thread: pausing before next request";
  438. "n_req" => n_req,
  439. "throttle" => %format_args!("{:?}", throttle),
  440. "elapsed" => %format_args!("{:?}", Instant::now() - start));
  441. thread::sleep(throttle); // 0, 2, 8, 16, 32
  442. }
  443. let sent = Instant::now();
  444. let req = Self::http_req(&client, url.clone(), buf.as_str(), &creds);
  445. let resp = req.send();
  446. let rcvd = Instant::now();
  447. let took = rcvd - sent;
  448. let mut n_tx = 0u32;
  449. match resp {
  450. Ok(Response { status, .. }) if status == StatusCode::NoContent => {
  451. debug!(logger, "server responded ok: 204 NoContent");
  452. buf.clear();
  453. let mut resp = Some(Ok(Resp { buf, took }));
  454. loop {
  455. n_tx += 1;
  456. match tx.try_send(resp.take().unwrap()) {
  457. Ok(_) => {
  458. if n_req > 0 {
  459. info!(logger, "successfully recovered from failed request with retry";
  460. "n_req" => n_req,
  461. "n_tx" => n_tx,
  462. "elapsed" => %format_args!("{:?}", Instant::now() - start));
  463. }
  464. return
  465. }
  466. Err(chan::TrySendError::Full(r)) => {
  467. let throttle = Duration::from_millis(1000) * n_tx;
  468. warn!(logger, "channel full: InfluxWriter http thread failed to return buf";
  469. "n_tx" => n_tx, "n_req" => n_req, "until next" => %format_args!("{:?}", throttle));
  470. resp = Some(r);
  471. thread::sleep(throttle);
  472. }
  473. Err(chan::TrySendError::Disconnected(_)) => {
  474. warn!(logger, "InfluxWriter http thread: channel disconnected, aborting buffer return";
  475. "n_tx" => n_tx, "n_req" => n_req);
  476. return
  477. }
  478. }
  479. }
  480. }
  481. Ok(mut resp) => {
  482. let mut server_resp = String::new();
  483. let _ = resp.read_to_string(&mut server_resp); //.unwrap_or(0);
  484. error!(logger, "influx server error (request took {:?})", took;
  485. "status" => %resp.status,
  486. "body" => server_resp);
  487. }
  488. Err(e) => {
  489. error!(logger, "http request failed: {:?} (request took {:?})", e, took; "err" => %e);
  490. }
  491. }
  492. }
  493. let took = Instant::now() - start;
  494. warn!(logger, "InfluxWriter http thread: aborting http req, returning buffer";
  495. "took" => %format_args!("{:?}", took));
  496. let buflen = buf.len();
  497. let n_lines = buf.lines().count();
  498. if let Err(e) = tx.send(Err(Resp { buf, took })) {
  499. crit!(logger, "failed to send Err(Resp {{ .. }}) back on abort: {:?}", e;
  500. "err" => %e, "buf.len()" => buflen, "n_lines" => n_lines);
  501. }
  502. });
  503. if let Err(e) = thread_res {
  504. crit!(logger, "failed to spawn thread: {}", e);
  505. }
  506. };
  507. let next = |prev: usize, m: &OwnedMeasurement, buf: &mut String, loop_time: Instant, last: Instant| -> Result<usize, usize> {
  508. match prev {
  509. 0 if N_BUFFER_LINES > 0 => {
  510. serialize_owned(m, buf);
  511. Ok(1)
  512. }
  513. n if n < N_BUFFER_LINES && loop_time - last < MAX_PENDING => {
  514. buf.push_str("\n");
  515. serialize_owned(m, buf);
  516. Ok(n + 1)
  517. }
  518. n => {
  519. buf.push_str("\n");
  520. serialize_owned(m, buf);
  521. Err(n + 1)
  522. }
  523. }
  524. };
  525. 'event: loop {
  526. loop_time = Instant::now();
  527. active = false;
  528. if loop_time - last_memory_check > Duration::from_secs(300) {
  529. let allocated_bytes = count_allocated_memory(&spares, &backlog, &in_flight_buffer_bytes);
  530. let allocated_mb = allocated_bytes as f64 / 1024.0 / 1024.0;
  531. info!(logger, "InfluxWriter: allocated memory: {:.1}MB", allocated_mb;
  532. "allocated bytes" => allocated_bytes,
  533. "in flight buffer bytes" => in_flight_buffer_bytes,
  534. "spares.len()" => spares.len(),
  535. "backlog.len()" => backlog.len(),
  536. );
  537. last_memory_check = loop_time;
  538. }
  539. match rx.recv() {
  540. Ok(Some(mut meas)) => {
  541. n_rcvd += 1;
  542. n_pts += meas.fields.len() as u64;
  543. active = true;
  544. if n_rcvd % INFO_HB_EVERY == 0 {
  545. let n_outstanding = n_out(&spares, &backlog, extras);
  546. let allocated_bytes = count_allocated_memory(&spares, &backlog, &in_flight_buffer_bytes);
  547. let allocated_mb = allocated_bytes as f64 / 1024.0 / 1024.0;
  548. info!(logger, "InfluxWriter: rcvd {} measurements", n_rcvd.thousands_sep();
  549. "total pts written" => n_pts.thousands_sep(),
  550. "n_outstanding" => n_outstanding,
  551. "spares.len()" => spares.len(),
  552. "n_rcvd" => n_rcvd,
  553. "n_active_buf" => count,
  554. "db_health" => %format_args!("{:?}", db_health.mean),
  555. "allocated buffer memory" => %format_args!("{:.1}MB", allocated_mb),
  556. "backlog.len()" => backlog.len());
  557. } else if n_rcvd % DEBUG_HB_EVERY == 0 {
  558. let n_outstanding = n_out(&spares, &backlog, extras);
  559. let allocated_bytes = count_allocated_memory(&spares, &backlog, &in_flight_buffer_bytes);
  560. let allocated_mb = allocated_bytes as f64 / 1024.0 / 1024.0;
  561. debug!(logger, "InfluxWriter: rcvd {} measurements", n_rcvd.thousands_sep();
  562. "n_outstanding" => n_outstanding,
  563. "spares.len()" => spares.len(),
  564. "n_rcvd" => n_rcvd,
  565. "n_active_buf" => count,
  566. "db_health" => %format_args!("{:?}", db_health.mean),
  567. "allocated buffer memory" => %format_args!("{:.1}MB", allocated_mb),
  568. "backlog.len()" => backlog.len());
  569. }
  570. if meas.timestamp.is_none() { meas.timestamp = Some(now()) }
  571. if meas.fields.is_empty() {
  572. meas.fields.push(("n", OwnedValue::Integer(1)));
  573. }
  574. //#[cfg(feature = "trace")] { if count % 10 == 0 { trace!(logger, "rcvd new measurement"; "count" => count, "key" => meas.key); } }
  575. count = match next(count, &meas, &mut buf, loop_time, last) {
  576. Ok(n) => n,
  577. Err(_n) => {
  578. let mut count = 0;
  579. let mut next: String = match spares.pop_front() {
  580. Some(x) => x,
  581. None => {
  582. let n_outstanding = n_out(&spares, &backlog, extras);
  583. if n_outstanding > MAX_BACKLOG {
  584. warn!(logger, "InfluxWriter: no available buffers in `spares`, pulling from backlog";
  585. "total pts written" => n_pts.thousands_sep(),
  586. "n_outstanding" => n_outstanding,
  587. "spares.len()" => spares.len(),
  588. "n_rcvd" => n_rcvd,
  589. "backlog.len()" => backlog.len());
  590. match backlog.pop_front() {
  591. // Note: this does not clear the backlog buffer,
  592. // instead we will just write more and more until
  593. // we are out of memory. I expect that will never
  594. // happen.
  595. //
  596. Some(x) => {
  597. count = 1; // otherwise, no '\n' added in `next(..)` - we are
  598. // sending a "full" buffer to be extended
  599. x
  600. }
  601. None => {
  602. extras += 1;
  603. crit!(logger, "InfluxWriter: failed to pull from backlog, too!! WTF #!(*#(* ... creating new String";
  604. "total pts written" => n_pts.thousands_sep(),
  605. "n_outstanding" => n_outstanding,
  606. "spares.len()" => spares.len(),
  607. "backlog.len()" => backlog.len(),
  608. "n_rcvd" => n_rcvd,
  609. "extras" => extras);
  610. String::new()
  611. }
  612. }
  613. } else {
  614. extras += 1;
  615. let allocated_bytes = count_allocated_memory(&spares, &backlog, &in_flight_buffer_bytes) + INITIAL_BUFFER_CAPACITY;
  616. let allocated_mb = allocated_bytes as f64 / 1024.0 / 1024.0;
  617. info!(logger, "InfluxWriter: allocating new buffer: zero spares avail";
  618. "total pts written" => n_pts.thousands_sep(),
  619. "allocated buffer memory" => %format_args!("{:.1}MB", allocated_mb),
  620. "n_outstanding" => n_outstanding,
  621. "extras" => extras,
  622. );
  623. String::with_capacity(INITIAL_BUFFER_CAPACITY)
  624. }
  625. }
  626. };
  627. // after swap, buf in next, so want to send next
  628. //
  629. mem::swap(&mut buf, &mut next);
  630. let n_outstanding = n_out(&spares, &backlog, extras);
  631. send(next, &mut backlog, n_outstanding, &mut in_flight_buffer_bytes);
  632. last = loop_time;
  633. count
  634. }
  635. };
  636. }
  637. Ok(None) => {
  638. let start = Instant::now();
  639. let mut hb = Instant::now();
  640. warn!(logger, "terminate signal rcvd"; "count" => count);
  641. if buf.len() > 0 {
  642. info!(logger, "InfluxWriter: sending remaining buffer to influx on terminate"; "count" => count);
  643. let meas = OwnedMeasurement::new("influx_writer").add_field("n", OwnedValue::Integer(1));
  644. let _ = next(N_BUFFER_LINES, &meas, &mut buf, loop_time, last);
  645. let n_outstanding = n_out(&spares, &backlog, extras);
  646. let mut placeholder = spares.pop_front().unwrap_or_else(String::new);
  647. mem::swap(&mut buf, &mut placeholder);
  648. send(placeholder, &mut backlog, n_outstanding, &mut in_flight_buffer_bytes);
  649. }
  650. let mut n_ok = 0;
  651. let mut n_err = 0;
  652. loop {
  653. loop_time = Instant::now();
  654. let n_outstanding = n_out(&spares, &backlog, extras);
  655. if backlog.is_empty() && n_outstanding < 1 {
  656. info!(logger, "InfluxWriter: cleared any remaining backlog";
  657. "total pts written" => n_pts.thousands_sep(),
  658. "n_outstanding" => n_outstanding,
  659. "spares.len()" => spares.len(),
  660. "backlog.len()" => backlog.len(),
  661. "n_cleared_ok" => n_ok,
  662. "n_cleared_err" => n_err,
  663. "n_rcvd" => n_rcvd,
  664. "extras" => extras,
  665. "elapsed" => %format_args!("{:?}", loop_time - start));
  666. break 'event
  667. }
  668. if loop_time.saturating_duration_since(start) > DROP_DEADLINE {
  669. crit!(logger, "drop deadline exceeded! commencing dirty exit :( ";
  670. "total pts written" => n_pts.thousands_sep(),
  671. "elapsed" => ?(loop_time.saturating_duration_since(start)),
  672. "n outstanding" => n_outstanding,
  673. "backlog.len()" => backlog.len(),
  674. );
  675. break 'event
  676. }
  677. if loop_time - hb > Duration::from_secs(5) {
  678. info!(logger, "InfluxWriter still clearing backlog ..";
  679. "total pts written" => n_pts.thousands_sep(),
  680. "n_outstanding" => n_outstanding,
  681. "spares.len()" => spares.len(),
  682. "backlog.len()" => backlog.len(),
  683. "n_cleared_ok" => n_ok,
  684. "n_cleared_err" => n_err,
  685. "extras" => extras,
  686. "n_rcvd" => n_rcvd,
  687. "elapsed" => %format_args!("{:?}", loop_time - start));
  688. hb = loop_time;
  689. }
  690. if let Some(buf) = backlog.pop_front() {
  691. let n_outstanding = n_out(&spares, &backlog, extras);
  692. debug!(logger, "InfluxWriter: resending queued buffer from backlog";
  693. "backlog.len()" => backlog.len(),
  694. "spares.len()" => spares.len(),
  695. "n_rcvd" => n_rcvd,
  696. "n_outstanding" => n_outstanding);
  697. send(buf, &mut backlog, n_outstanding, &mut in_flight_buffer_bytes);
  698. }
  699. 'rx: loop {
  700. match http_rx.try_recv() {
  701. Ok(Ok(Resp { buf, .. })) => {
  702. n_ok += 1;
  703. in_flight_buffer_bytes = in_flight_buffer_bytes.saturating_sub(buf.capacity());
  704. if spares.len() <= INITIAL_BACKLOG {
  705. spares.push_back(buf); // needed so `n_outstanding` count remains accurate
  706. } else {
  707. extras = extras.saturating_sub(1);
  708. }
  709. }
  710. Ok(Err(Resp { buf, .. })) => {
  711. warn!(logger, "InfluxWriter: requeueing failed request"; "buf.len()" => buf.len());
  712. n_err += 1;
  713. in_flight_buffer_bytes = in_flight_buffer_bytes.saturating_sub(buf.capacity());
  714. backlog.push_front(buf);
  715. }
  716. Err(chan::TryRecvError::Disconnected) => {
  717. crit!(logger, "InfluxWriter: trying to clear backlog, but http_rx disconnected! aborting";
  718. "total pts written" => n_pts.thousands_sep(),
  719. "n_outstanding" => n_outstanding,
  720. "backlog.len()" => backlog.len(),
  721. "n_cleared_ok" => n_ok,
  722. "n_cleared_err" => n_err,
  723. "extras" => extras,
  724. "n_rcvd" => n_rcvd,
  725. "elapsed" => %format_args!("{:?}", loop_time - start));
  726. break 'event
  727. }
  728. Err(_) => break 'rx
  729. }
  730. }
  731. thread::sleep(Duration::from_millis(1));
  732. }
  733. }
  734. _ => {}
  735. }
  736. db_health.refresh(loop_time);
  737. let n_outstanding = n_out(&spares, &backlog, extras);
  738. let healthy = db_health.count == 0 || db_health.mean < Duration::from_secs(200);
  739. if (n_outstanding < MAX_OUTSTANDING_HTTP
  740. || loop_time.saturating_duration_since(last_clear) > Duration::from_secs(60))
  741. && healthy {
  742. if let Some(queued) = backlog.pop_front() {
  743. let n_outstanding = n_out(&spares, &backlog, extras);
  744. send(queued, &mut backlog, n_outstanding, &mut in_flight_buffer_bytes);
  745. active = true;
  746. }
  747. last_clear = loop_time;
  748. }
  749. loop {
  750. match http_rx.try_recv() {
  751. Ok(Ok(Resp { buf, took })) => {
  752. db_health.add(loop_time, took);
  753. let in_flight_before = in_flight_buffer_bytes.clone();
  754. in_flight_buffer_bytes = in_flight_buffer_bytes.saturating_sub(buf.capacity());
  755. if spares.len() <= INITIAL_BACKLOG {
  756. spares.push_back(buf);
  757. } else {
  758. extras = extras.saturating_sub(1);
  759. debug!(logger, "InfluxWriter: dropping buffer to reduce memory back to INITIAL_BACKLOG size";
  760. "spares.len()" => spares.len(),
  761. "extras" => extras,
  762. "in flight before" => in_flight_before,
  763. "in in_flight_buffer_bytes" => in_flight_buffer_bytes,
  764. );
  765. }
  766. //spares.push_back(buf);
  767. active = true;
  768. }
  769. Ok(Err(Resp { buf, took })) => {
  770. db_health.add(loop_time, took);
  771. in_flight_buffer_bytes = in_flight_buffer_bytes.saturating_sub(buf.capacity());
  772. backlog.push_front(buf);
  773. active = true;
  774. }
  775. Err(chan::TryRecvError::Disconnected) => {
  776. crit!(logger, "InfluxWriter: trying to recover buffers, but http_rx disconnected! aborting";
  777. "total pts written" => n_pts.thousands_sep(),
  778. "n_outstanding" => n_outstanding,
  779. "backlog.len()" => backlog.len(),
  780. "n_rcvd" => n_rcvd,
  781. "extras" => extras);
  782. break 'event
  783. }
  784. Err(_) => break
  785. }
  786. }
  787. if !active {
  788. thread::sleep(Duration::new(0, 1))
  789. }
  790. }
  791. thread::sleep(Duration::from_millis(10));
  792. }).unwrap();
  793. InfluxWriter {
  794. host: host.to_string(),
  795. db: db.to_string(),
  796. tx,
  797. thread: Some(Arc::new(thread))
  798. }
  799. }
  800. }
  801. impl Drop for InfluxWriter {
  802. fn drop(&mut self) {
  803. if let Some(arc) = self.thread.take() {
  804. if let Ok(thread) = Arc::try_unwrap(arc) {
  805. let _ = self.tx.send(None);
  806. let _ = thread.join();
  807. }
  808. }
  809. }
  810. }
  811. /// This removes offending things rather than escaping them.
  812. ///
  813. fn escape_tag(s: &str) -> String {
  814. s.replace(" ", "")
  815. .replace(",", "")
  816. .replace("\"", "")
  817. }
  818. fn escape(s: &str) -> String {
  819. s.replace(" ", "\\ ")
  820. .replace(",", "\\,")
  821. }
  822. fn as_string(s: &str) -> String {
  823. // the second replace removes double escapes
  824. //
  825. format!("\"{}\"", s.replace("\"", "\\\"")
  826. .replace(r#"\\""#, r#"\""#))
  827. }
  828. #[test]
  829. fn it_checks_as_string_does_not_double_escape() {
  830. let raw = "this is \\\"an escaped string\\\" so it's problematic";
  831. let escaped = as_string(&raw);
  832. assert_eq!(escaped, format!("\"{}\"", raw).as_ref());
  833. }
  834. fn as_boolean(b: &bool) -> &str {
  835. if *b { "t" } else { "f" }
  836. }
  837. pub fn now() -> i64 {
  838. nanos(Utc::now()) as i64
  839. }
  840. /// Serializes an `&OwnedMeasurement` as influx line protocol into `line`.
  841. ///
  842. /// The serialized measurement is appended to the end of the string without
  843. /// any regard for what exited in it previously.
  844. ///
  845. pub fn serialize_owned(measurement: &OwnedMeasurement, line: &mut String) {
  846. line.push_str(&escape_tag(measurement.key));
  847. let add_tag = |line: &mut String, key: &str, value: &str| {
  848. line.push_str(",");
  849. line.push_str(&escape_tag(key));
  850. line.push_str("=");
  851. line.push_str(&escape(value));
  852. };
  853. for (key, value) in measurement.tags.iter() {
  854. #[cfg(not(feature = "string-tags"))]
  855. add_tag(line, key, value);
  856. #[cfg(feature = "string-tags")]
  857. add_tag(line, key, value.as_str());
  858. }
  859. let add_field = |line: &mut String, key: &str, value: &OwnedValue, is_first: bool| -> bool {
  860. if SKIP_NAN_VALUES && ! value.is_finite() { return false }
  861. if is_first { line.push_str(" "); } else { line.push_str(","); }
  862. line.push_str(&escape_tag(key));
  863. line.push_str("=");
  864. match *value {
  865. OwnedValue::String(ref s) => line.push_str(&as_string(s)),
  866. OwnedValue::Integer(ref i) => line.push_str(&format!("{}i", i)),
  867. OwnedValue::Boolean(ref b) => line.push_str(as_boolean(b)),
  868. OwnedValue::D128(ref d) => {
  869. if d.is_finite() {
  870. line.push_str(&format!("{}", d));
  871. } else {
  872. line.push_str("-999.0");
  873. }
  874. }
  875. OwnedValue::Float(ref f) => {
  876. if f.is_finite() {
  877. line.push_str(&format!("{}", f));
  878. } else {
  879. line.push_str("-999.0");
  880. }
  881. }
  882. OwnedValue::Uuid(ref u) => line.push_str(&format!("\"{}\"", u)),
  883. };
  884. true
  885. };
  886. // use this counter to ensure that at least one field was
  887. // serialized. since NaN values may be skipped, the serialization
  888. // would be wrong if no fields ended up being serialized. instead,
  889. // track it, and if there are none serialized, add a n=1 to make
  890. // the measurement serialize properly
  891. //
  892. // this also controls what value is passed to the `is_first` argument
  893. // of `add_field`
  894. let mut n_fields_serialized = 0;
  895. for kv in measurement.fields.iter() {
  896. if add_field(line, kv.0, &kv.1, n_fields_serialized == 0) {
  897. n_fields_serialized += 1;
  898. }
  899. }
  900. // supply a minimum of one field (n=1)
  901. //
  902. // TODO: could potentially clobber a "n" tag? do we care?
  903. //
  904. if n_fields_serialized == 0 { add_field(line, "n", &OwnedValue::Integer(1), true); }
  905. if let Some(t) = measurement.timestamp {
  906. line.push_str(" ");
  907. line.push_str(&t.to_string());
  908. }
  909. }
  910. #[derive(Debug, Clone, PartialEq)]
  911. pub enum OwnedValue {
  912. String(String),
  913. Float(f64),
  914. Integer(i64),
  915. Boolean(bool),
  916. D128(d128),
  917. Uuid(Uuid),
  918. }
  919. impl OwnedValue {
  920. /// if `self` is a `Float` or `D128` variant, checks
  921. /// whether the contained value is finite
  922. ///
  923. /// # Examples
  924. ///
  925. /// ```
  926. /// use std::str::FromStr;
  927. /// use influx_writer::OwnedValue;
  928. ///
  929. /// let v1 = OwnedValue::Float(f64::NAN);
  930. /// assert!( ! v1.is_finite());
  931. /// let v2 = OwnedValue::Float(1.234f64);
  932. /// assert!(v2.is_finite());
  933. ///
  934. /// let v3 = OwnedValue::D128(decimal::d128::from_str("NaN").unwrap());
  935. /// assert!( ! v3.is_finite());
  936. /// let v4 = OwnedValue::D128(decimal::d128::from_str("42.42").unwrap());
  937. /// assert!(v4.is_finite());
  938. ///
  939. /// // other variants are always "finite"
  940. /// assert!(OwnedValue::String("NaN".into()).is_finite());
  941. /// ```
  942. pub fn is_finite(&self) -> bool {
  943. match self {
  944. OwnedValue::Float(x) => x.is_finite(),
  945. OwnedValue::D128(x) => x.is_finite(),
  946. _ => true,
  947. }
  948. }
  949. }
  950. /// Holds data meant for an influxdb measurement in transit to the
  951. /// writing thread.
  952. ///
  953. #[derive(Clone, Debug)]
  954. pub struct OwnedMeasurement {
  955. pub key: &'static str,
  956. pub timestamp: Option<i64>,
  957. //pub fields: Map<&'static str, OwnedValue>,
  958. //pub tags: Map<&'static str, &'static str>,
  959. pub fields: SmallVec<[(&'static str, OwnedValue); 8]>,
  960. #[cfg(not(feature = "string-tags"))]
  961. pub tags: SmallVec<[(&'static str, &'static str); 8]>,
  962. #[cfg(feature = "string-tags")]
  963. pub tags: SmallVec<[(&'static str, String); 8]>,
  964. }
  965. impl OwnedMeasurement {
  966. pub fn with_capacity(key: &'static str, n_tags: usize, n_fields: usize) -> Self {
  967. OwnedMeasurement {
  968. key,
  969. timestamp: None,
  970. tags: SmallVec::with_capacity(n_tags),
  971. fields: SmallVec::with_capacity(n_fields),
  972. }
  973. }
  974. pub fn new(key: &'static str) -> Self {
  975. OwnedMeasurement {
  976. key,
  977. timestamp: None,
  978. tags: SmallVec::new(),
  979. fields: SmallVec::new(),
  980. }
  981. }
  982. /// Unusual consuming `self` signature because primarily used by
  983. /// the `measure!` macro.
  984. #[cfg(not(feature = "string-tags"))]
  985. pub fn add_tag(mut self, key: &'static str, value: &'static str) -> Self {
  986. self.tags.push((key, value));
  987. self
  988. }
  989. #[cfg(feature = "string-tags")]
  990. pub fn add_tag<S: ToString>(mut self, key: &'static str, value: S) -> Self {
  991. self.tags.push((key, value.to_string()));
  992. self
  993. }
  994. /// Unusual consuming `self` signature because primarily used by
  995. /// the `measure!` macro.
  996. pub fn add_field(mut self, key: &'static str, value: OwnedValue) -> Self {
  997. self.fields.push((key, value));
  998. self
  999. }
  1000. pub fn set_timestamp(mut self, timestamp: i64) -> Self {
  1001. self.timestamp = Some(timestamp);
  1002. self
  1003. }
  1004. #[cfg(not(feature = "string-tags"))]
  1005. pub fn set_tag(mut self, key: &'static str, value: &'static str) -> Self {
  1006. match self.tags.iter().position(|kv| kv.0 == key) {
  1007. Some(i) => {
  1008. self.tags.get_mut(i)
  1009. .map(|x| {
  1010. x.0 = value;
  1011. });
  1012. self
  1013. }
  1014. None => {
  1015. self.add_tag(key, value)
  1016. }
  1017. }
  1018. }
  1019. pub fn get_field(&self, key: &'static str) -> Option<&OwnedValue> {
  1020. self.fields.iter()
  1021. .find(|kv| kv.0 == key)
  1022. .map(|kv| &kv.1)
  1023. }
  1024. #[cfg(feature = "string-tags")]
  1025. pub fn get_tag(&self, key: &'static str) -> Option<&str> {
  1026. self.tags.iter()
  1027. .find(|kv| kv.0 == key)
  1028. .map(|kv| kv.1.as_str())
  1029. }
  1030. #[cfg(not(feature = "string-tags"))]
  1031. pub fn get_tag(&self, key: &'static str) -> Option<&'static str> {
  1032. self.tags.iter()
  1033. .find(|kv| kv.0 == key)
  1034. .map(|kv| kv.1)
  1035. }
  1036. }
  1037. #[allow(unused)]
  1038. #[cfg(test)]
  1039. mod tests {
  1040. use std::str::FromStr;
  1041. use super::*;
  1042. #[cfg(feature = "unstable")]
  1043. use test::{black_box, Bencher};
  1044. #[ignore]
  1045. #[cfg(feature = "unstable")]
  1046. #[bench]
  1047. fn measure_ten(b: &mut Bencher) {
  1048. let influx = InfluxWriter::new("localhost", "test");
  1049. let mut n = 0;
  1050. b.iter(|| {
  1051. for _ in 0..10 {
  1052. let time = influx.nanos(Utc::now());
  1053. n += 1;
  1054. measure!(influx, million, i(n), tm(time));
  1055. }
  1056. });
  1057. }
  1058. #[test]
  1059. fn it_uses_the_utc_shortcut_to_convert_a_datetime_utc() {
  1060. const VERSION: &str = "0.3.90";
  1061. let tag_value = "one";
  1062. let color = "red";
  1063. let time = Utc::now();
  1064. let m = measure!(@make_meas test, i(n, 1), t(color), v(VERSION), utc(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(nanos(time) as i64));
  1068. }
  1069. #[test]
  1070. fn it_uses_the_v_for_version_shortcut() {
  1071. const VERSION: &str = "0.3.90";
  1072. let tag_value = "one";
  1073. let color = "red";
  1074. let time = now();
  1075. let m = measure!(@make_meas test, i(n, 1), t(color), v(VERSION), tm(time));
  1076. assert_eq!(m.get_tag("color"), Some("red"));
  1077. assert_eq!(m.get_tag("version"), Some(VERSION));
  1078. assert_eq!(m.timestamp, Some(time));
  1079. }
  1080. #[test]
  1081. fn it_uses_the_new_tag_k_only_shortcut() {
  1082. let tag_value = "one";
  1083. let color = "red";
  1084. let time = now();
  1085. let m = measure!(@make_meas test, t(color), t(tag_value), tm(time));
  1086. assert_eq!(m.get_tag("color"), Some("red"));
  1087. assert_eq!(m.get_tag("tag_value"), Some("one"));
  1088. assert_eq!(m.timestamp, Some(time));
  1089. }
  1090. #[test]
  1091. fn it_uses_measure_macro_parenthesis_syntax() {
  1092. let m = measure!(@make_meas test, t(a,"b"), i(n,1), f(x,1.1), tm(1));
  1093. assert_eq!(m.key, "test");
  1094. assert_eq!(m.get_tag("a"), Some("b"));
  1095. assert_eq!(m.get_field("n"), Some(&OwnedValue::Integer(1)));
  1096. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  1097. assert_eq!(m.timestamp, Some(1));
  1098. }
  1099. #[test]
  1100. fn it_uses_measure_macro_on_a_self_attribute() {
  1101. struct A {
  1102. pub influx: InfluxWriter,
  1103. }
  1104. impl A {
  1105. fn f(&self) {
  1106. measure!(self.influx, test, t(color, "red"), i(n, 1));
  1107. }
  1108. }
  1109. let a = A { influx: InfluxWriter::default() };
  1110. a.f();
  1111. }
  1112. #[test]
  1113. fn it_clones_an_influx_writer_to_check_both_drop() {
  1114. let influx = InfluxWriter::default();
  1115. measure!(influx, drop_test, i(a, 1), i(b, 2));
  1116. {
  1117. let influx = influx.clone();
  1118. thread::spawn(move || {
  1119. measure!(influx, drop_test, i(a, 3), i(b, 4));
  1120. });
  1121. }
  1122. }
  1123. #[cfg(feature = "unstable")]
  1124. #[bench]
  1125. fn influx_writer_send_basic(b: &mut Bencher) {
  1126. let m = InfluxWriter::new("localhost", "test");
  1127. b.iter(|| {
  1128. measure!(m, test, t(color; "red"), i(n, 1)); //, float[p; 1.234]);
  1129. });
  1130. }
  1131. #[cfg(feature = "unstable")]
  1132. #[bench]
  1133. fn influx_writer_send_price(b: &mut Bencher) {
  1134. let m = InfluxWriter::new("localhost", "test");
  1135. b.iter(|| {
  1136. measure!(m, test,
  1137. t(ticker, "xmr_btc"),
  1138. t(exchange, "plnx"),
  1139. d(bid, d128::zero()),
  1140. d(ask, d128::zero()),
  1141. );
  1142. });
  1143. }
  1144. #[test]
  1145. fn it_checks_color_tag_error_in_non_doctest() {
  1146. let (tx, rx) = bounded(1024);
  1147. measure!(tx, test, t(color,"red"), i(n,1));
  1148. let meas: OwnedMeasurement = rx.recv().unwrap();
  1149. assert_eq!(meas.get_tag("color"), Some("red"), "meas = \n {:?} \n", meas);
  1150. }
  1151. #[test]
  1152. fn it_uses_the_make_meas_pattern_of_the_measure_macro() {
  1153. let meas = measure!(@make_meas test_measurement,
  1154. t(one, "a"), t(two, "b"), i(three, 2),
  1155. f(four, 1.2345), s(five, String::from("d")),
  1156. b(six, true), i(seven, 1 + 2),
  1157. tm(1)
  1158. );
  1159. assert_eq!(meas.key, "test_measurement");
  1160. assert_eq!(meas.get_tag("one"), Some("a"));
  1161. assert_eq!(meas.get_tag("two"), Some("b"));
  1162. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  1163. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  1164. assert_eq!(meas.timestamp, Some(1));
  1165. }
  1166. #[test]
  1167. fn it_uses_measure_macro_for_d128_and_uuid() {
  1168. let (tx, rx) = bounded(1024);
  1169. let one = "a";
  1170. let two = d128::zero();
  1171. let three = Uuid::new_v4();
  1172. let time = now();
  1173. measure!(tx, test_measurement, t(one), d(two), u(three), tm(time));
  1174. thread::sleep(Duration::from_millis(10));
  1175. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  1176. assert_eq!(meas.key, "test_measurement");
  1177. assert_eq!(meas.get_tag("one"), Some("a"));
  1178. assert_eq!(meas.get_field("two"), Some(&OwnedValue::D128(d128::zero())));
  1179. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Uuid(three)));
  1180. assert_eq!(meas.timestamp, Some(time));
  1181. }
  1182. #[test]
  1183. fn it_uses_the_measure_macro_alt_syntax() {
  1184. let (tx, rx) = bounded(1024);
  1185. measure!(tx, test_measurement,
  1186. t(one, "a"), t(two, "b"), i(three, 2),
  1187. f(four, 1.2345), s(five, String::from("d")),
  1188. b(six, true), i(seven, 1 + 2),
  1189. tm(1)
  1190. );
  1191. thread::sleep(Duration::from_millis(10));
  1192. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  1193. assert_eq!(meas.key, "test_measurement");
  1194. assert_eq!(meas.get_tag("one"), Some("a"));
  1195. assert_eq!(meas.get_tag("two"), Some("b"));
  1196. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  1197. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  1198. assert_eq!(meas.timestamp, Some(1));
  1199. }
  1200. #[test]
  1201. fn it_checks_that_fields_are_separated_correctly() {
  1202. let m = measure!(@make_meas test, t[a; "one"], t[b; "two"], f[x; 1.1], f[y; -1.1]);
  1203. assert_eq!(m.key, "test");
  1204. assert_eq!(m.get_tag("a"), Some("one"));
  1205. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  1206. let mut buf = String::new();
  1207. serialize_owned(&m, &mut buf);
  1208. assert!(buf.contains("b=two x=1.1,y=-1.1"), "buf = {}", buf);
  1209. }
  1210. #[test]
  1211. fn try_to_break_measure_macro() {
  1212. let (tx, _) = bounded(1024);
  1213. measure!(tx, one, t(x,"y"), i(n,1));
  1214. measure!(tx, one, t(x,"y"), i(n,1),);
  1215. struct A {
  1216. pub one: i32,
  1217. pub two: i32,
  1218. }
  1219. struct B {
  1220. pub a: A
  1221. }
  1222. let b = B { a: A { one: 1, two: 2 } };
  1223. let m = measure!(@make_meas test, t(name, "a"), i(a, b.a.one));
  1224. assert_eq!(m.get_field("a"), Some(&OwnedValue::Integer(1)));
  1225. }
  1226. #[cfg(feature = "unstable")]
  1227. #[bench]
  1228. fn measure_macro_small(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"), i(n, 1), tm(now()));
  1235. });
  1236. }
  1237. #[cfg(feature = "unstable")]
  1238. #[bench]
  1239. fn measure_macro_medium(b: &mut Bencher) {
  1240. let (tx, rx) = bounded(1024);
  1241. let listener = thread::spawn(move || {
  1242. loop { if rx.recv().is_err() { break } }
  1243. });
  1244. b.iter(|| {
  1245. measure!(tx, test, t(color, "red"), t(mood, "playful"),
  1246. t(ticker, "xmr_btc"), f(price, 1.2345), f(amount, 56.322),
  1247. i(n, 1), tm(now()));
  1248. });
  1249. }
  1250. #[cfg(feature = "unstable")]
  1251. #[bench]
  1252. fn serialize_owned_longer(b: &mut Bencher) {
  1253. let mut buf = String::with_capacity(1024);
  1254. let m =
  1255. OwnedMeasurement::new("test")
  1256. .add_tag("one", "a")
  1257. .add_tag("two", "b")
  1258. .add_tag("ticker", "xmr_btc")
  1259. .add_tag("exchange", "plnx")
  1260. .add_tag("side", "bid")
  1261. .add_field("three", OwnedValue::Float(1.2345))
  1262. .add_field("four", OwnedValue::Integer(57))
  1263. .add_field("five", OwnedValue::Boolean(true))
  1264. .add_field("six", OwnedValue::String(String::from("abcdefghijklmnopqrstuvwxyz")))
  1265. .set_timestamp(now());
  1266. b.iter(|| {
  1267. serialize_owned(&m, &mut buf);
  1268. buf.clear()
  1269. });
  1270. }
  1271. #[cfg(feature = "unstable")]
  1272. #[bench]
  1273. fn serialize_owned_simple(b: &mut Bencher) {
  1274. let mut buf = String::with_capacity(1024);
  1275. let m =
  1276. OwnedMeasurement::new("test")
  1277. .add_tag("one", "a")
  1278. .add_tag("two", "b")
  1279. .add_field("three", OwnedValue::Float(1.2345))
  1280. .add_field("four", OwnedValue::Integer(57))
  1281. .set_timestamp(now());
  1282. b.iter(|| {
  1283. serialize_owned(&m, &mut buf);
  1284. buf.clear()
  1285. });
  1286. }
  1287. #[cfg(feature = "unstable")]
  1288. #[bench]
  1289. fn clone_url_for_thread(b: &mut Bencher) {
  1290. let host = "ahmes";
  1291. let db = "mlp";
  1292. let url =
  1293. Url::parse_with_params(&format!("http://{}:8086/write", host),
  1294. &[("db", db), ("precision", "ns")]).unwrap();
  1295. b.iter(|| {
  1296. url.clone()
  1297. })
  1298. }
  1299. #[cfg(feature = "unstable")]
  1300. #[bench]
  1301. fn clone_arc_url_for_thread(b: &mut Bencher) {
  1302. let host = "ahmes";
  1303. let db = "mlp";
  1304. let url =
  1305. Url::parse_with_params(&format!("http://{}:8086/write", host),
  1306. &[("db", db), ("precision", "ns")]).unwrap();
  1307. let url = Arc::new(url);
  1308. b.iter(|| {
  1309. Arc::clone(&url)
  1310. })
  1311. }
  1312. #[test]
  1313. fn it_serializes_a_hard_to_serialize_message_from_owned() {
  1314. let raw = r#"error encountered trying to send krkn order: Other("Failed to send http request: Other("Resource temporarily unavailable (os error 11)")")"#;
  1315. let mut buf = String::new();
  1316. let mut server_resp = String::new();
  1317. let m = OwnedMeasurement::new("rust_test")
  1318. .add_field("s", OwnedValue::String(raw.to_string()))
  1319. .set_timestamp(now());
  1320. serialize_owned(&m, &mut buf);
  1321. println!("{}", buf);
  1322. buf.push_str("\n");
  1323. let buf_copy = buf.clone();
  1324. buf.push_str(&buf_copy);
  1325. println!("{}", buf);
  1326. let url = Url::parse_with_params("http://localhost:8086/write", &[("db", "test"), ("precision", "ns")]).expect("influx writer url should parse");
  1327. let client = Client::new();
  1328. let req = InfluxWriter::http_req(&client, url.clone(), &buf, &None);
  1329. match req.send() {
  1330. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  1331. Ok(mut resp) => {
  1332. resp.read_to_string(&mut server_resp).unwrap();
  1333. panic!("{}", server_resp);
  1334. }
  1335. Err(why) => {
  1336. panic!("{}", why)
  1337. }
  1338. }
  1339. }
  1340. #[cfg(feature = "auth-tests")]
  1341. #[test]
  1342. fn it_sends_authenticated_measurements() {
  1343. let creds = InfluxWriter::get_credentials("auth_test_user".into(), Some("hot dog".into()));
  1344. let noop_logger = slog::Logger::root(slog::Discard.fuse(), o!());
  1345. //let decorator = slog_term::TermDecorator::new().stdout().force_color().build();
  1346. //let drain = slog_term::FullFormat::new(decorator).use_utc_timestamp().build().fuse();
  1347. //let drain = slog_async::Async::new(drain).chan_size(1024 * 64).thread_name("recv".into()).build().fuse();
  1348. //let root = slog::Logger::root(drain, o!("version" => "0.1"));
  1349. //let influx = InfluxWriter::with_logger_and_opt_creds("localhost", "auth_test", Some(creds), &root);
  1350. measure!(influx, auth_test_meas, i(n, 1));
  1351. drop(influx);
  1352. }
  1353. #[test]
  1354. fn it_skips_nan_values() {
  1355. assert!(SKIP_NAN_VALUES, "otherwise this test is worthless");
  1356. let m = OwnedMeasurement::new("rust_test")
  1357. .add_field("hello", OwnedValue::Integer(1234))
  1358. .add_field("finite_float", OwnedValue::Float(1.234))
  1359. .add_field("nan_float", OwnedValue::Float(f64::NAN))
  1360. .add_field("inf_float", OwnedValue::Float(f64::INFINITY))
  1361. .add_field("neg_inf_float", OwnedValue::Float(f64::NEG_INFINITY))
  1362. .add_field("finite_d128", OwnedValue::D128(d128::from_str("3.456").unwrap()))
  1363. .add_field("nan_d128", OwnedValue::D128(d128::from_str("NaN").unwrap()))
  1364. .set_timestamp(now());
  1365. let mut buf = String::new();
  1366. serialize_owned(&m, &mut buf);
  1367. dbg!(&buf);
  1368. assert!(buf.contains("hello=1234"));
  1369. assert!(buf.contains("finite_float=1.234"));
  1370. assert!( ! buf.contains("nan_float="));
  1371. assert!( ! buf.contains("inf_float="));
  1372. assert!( ! buf.contains("neg_inf_float="));
  1373. assert!(buf.contains("finite_d128=3.456"));
  1374. assert!( ! buf.contains("nan_d128="));
  1375. }
  1376. #[test]
  1377. fn it_supplies_a_field_if_every_field_is_skipped_because_nan() {
  1378. assert!(SKIP_NAN_VALUES, "otherwise this test is worthless");
  1379. let m = OwnedMeasurement::new("rust_test")
  1380. .add_field("nan_float", OwnedValue::Float(f64::NAN));
  1381. let mut buf = String::new();
  1382. serialize_owned(&m, &mut buf);
  1383. dbg!(&buf);
  1384. assert!(buf.contains("n=1i"));
  1385. }
  1386. }