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.

1552 lines
58KB

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