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.

1613 lines
63KB

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