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.

1541 lines
61KB

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