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.

1624 lines
64KB

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