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.

1569 lines
59KB

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