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.

1147 lines
39KB

  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;
  7. #[cfg(feature = "warnings")]
  8. use std::fs;
  9. use std::time::{Instant, Duration};
  10. use std::hash::BuildHasherDefault;
  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 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. /// Holds a thread (and provides an interface to it) that serializes `OwnedMeasurement`s
  189. /// it receives (over a SPSC channel) and inserts to influxdb via http when `BUFFER_SIZE`
  190. /// measurements have accumulated.
  191. ///
  192. #[derive(Debug)]
  193. pub struct InfluxWriter {
  194. host: String,
  195. db: String,
  196. tx: Sender<Option<OwnedMeasurement>>,
  197. thread: Option<Arc<thread::JoinHandle<()>>>,
  198. }
  199. impl Default for InfluxWriter {
  200. fn default() -> Self {
  201. //if cfg!(any(test, feature = "test")) {
  202. // InfluxWriter::new("localhost", "test", "/home/jstrong/src/logging/var/log/influx-test.log", 0)
  203. //} else {
  204. InfluxWriter::new("localhost", "test", "/tmp/influx-test.log", 4096)
  205. //}
  206. }
  207. }
  208. impl Clone for InfluxWriter {
  209. fn clone(&self) -> Self {
  210. debug_assert!(self.thread.is_some());
  211. let thread = self.thread.as_ref().map(|x| Arc::clone(x));
  212. InfluxWriter {
  213. host: self.host.to_string(),
  214. db: self.db.to_string(),
  215. tx: self.tx.clone(),
  216. thread,
  217. }
  218. }
  219. }
  220. impl InfluxWriter {
  221. /// Sends the `OwnedMeasurement` to the serialization thread.
  222. ///
  223. #[cfg_attr(feature = "inlines", inline)]
  224. pub fn send(&self, m: OwnedMeasurement) -> Result<(), SendError<Option<OwnedMeasurement>>> {
  225. self.tx.send(Some(m))
  226. }
  227. #[cfg_attr(feature = "inlines", inline)]
  228. pub fn nanos(&self, d: DateTime<Utc>) -> i64 { nanos(d) as i64 }
  229. #[cfg_attr(feature = "inlines", inline)]
  230. pub fn dur_nanos(&self, d: Duration) -> i64 { dur_nanos(d) as i64 }
  231. #[cfg_attr(feature = "inlines", inline)]
  232. pub fn dur_nanos_u64(&self, d: Duration) -> u64 { dur_nanos(d).max(0) as u64 }
  233. #[cfg_attr(feature = "inlines", inline)]
  234. pub fn secs(&self, d: Duration) -> f64 {
  235. ((d.as_secs() as f64 + (d.subsec_nanos() as f64 / 1_000_000_000_f64))
  236. * 1000.0)
  237. .round()
  238. / 1000.0
  239. }
  240. pub fn tx(&self) -> Sender<Option<OwnedMeasurement>> {
  241. self.tx.clone()
  242. }
  243. pub fn new(host: &str, db: &str, log_path: &str, buffer_size: u16) -> Self {
  244. let logger = file_logger(log_path, LOG_LEVEL); // this needs to be outside the thread
  245. Self::with_logger(host, db, buffer_size, logger)
  246. }
  247. #[allow(unused_assignments)]
  248. pub fn with_logger(host: &str, db: &str, _buffer_size: u16, logger: Logger) -> Self {
  249. let (tx, rx): (Sender<Option<OwnedMeasurement>>, Receiver<Option<OwnedMeasurement>>) = channel();
  250. let buffer_size = INFLUX_WRITER_MAX_BUFFER;
  251. #[cfg(feature = "no-influx-buffer")]
  252. let buffer_size = 0usize;
  253. debug!(logger, "initializing url"; "host" => host, "db" => db, "buffer_size" => buffer_size);
  254. let url =
  255. Url::parse_with_params(&format!("http://{}:8086/write", host),
  256. &[("db", db), ("precision", "ns")])
  257. .expect("influx writer url should parse");
  258. let thread = thread::Builder::new().name(format!("mm:inflx:{}", db)).spawn(move || {
  259. let client = Client::new();
  260. debug!(logger, "initializing buffers");
  261. let mut buf = String::with_capacity(32 * 32 * 32);
  262. let mut count = 0;
  263. let mut last = Instant::now();
  264. let mut loop_time = Instant::now();
  265. let send = |buf: &str| {
  266. let resp = client.post(url.clone())
  267. .body(buf)
  268. .send();
  269. match resp {
  270. Ok(Response { status, .. }) if status == StatusCode::NoContent => {
  271. debug!(logger, "server responded ok: 204 NoContent");
  272. }
  273. Ok(mut resp) => {
  274. let mut server_resp = String::with_capacity(32 * 1024); // need to allocate here bc will be
  275. // sent to logging thread
  276. let _ = resp.read_to_string(&mut server_resp); //.unwrap_or(0);
  277. error!(logger, "influx server error";
  278. "status" => resp.status.to_string(),
  279. "body" => server_resp);
  280. }
  281. Err(why) => {
  282. error!(logger, "http request failed: {:?}", why);
  283. }
  284. }
  285. };
  286. let next = |prev: usize, m: &OwnedMeasurement, buf: &mut String, loop_time: &Instant, last: &mut Instant| -> usize {
  287. match prev {
  288. 0 if buffer_size > 0 => {
  289. serialize_owned(m, buf);
  290. 1
  291. }
  292. n if n < buffer_size && *loop_time - *last < Duration::from_secs(2) => {
  293. buf.push_str("\n");
  294. serialize_owned(m, buf);
  295. n + 1
  296. }
  297. n => {
  298. buf.push_str("\n");
  299. serialize_owned(m, buf);
  300. debug!(logger, "sending buffer to influx"; "len" => n);
  301. send(buf);
  302. *last = *loop_time;
  303. buf.clear();
  304. 0
  305. }
  306. }
  307. };
  308. loop {
  309. loop_time = Instant::now();
  310. match rx.recv() {
  311. Ok(Some(mut meas)) => {
  312. if meas.timestamp.is_none() { meas.timestamp = Some(now()) }
  313. if meas.fields.is_empty() {
  314. meas.fields.push(("n", OwnedValue::Integer(1)));
  315. }
  316. //#[cfg(feature = "trace")] { if count % 10 == 0 { trace!(logger, "rcvd new measurement"; "count" => count, "key" => meas.key); } }
  317. count = next(count, &meas, &mut buf, &loop_time, &mut last);
  318. }
  319. Ok(None) => {
  320. if buf.len() > 0 {
  321. debug!(logger, "sending buffer to influx"; "len" => count);
  322. send(&buf)
  323. }
  324. break
  325. }
  326. _ => {
  327. thread::sleep(Duration::new(0, 1))
  328. }
  329. }
  330. }
  331. }).unwrap();
  332. InfluxWriter {
  333. host: host.to_string(),
  334. db: db.to_string(),
  335. tx,
  336. thread: Some(Arc::new(thread))
  337. }
  338. }
  339. }
  340. impl Drop for InfluxWriter {
  341. fn drop(&mut self) {
  342. if let Some(arc) = self.thread.take() {
  343. if let Ok(thread) = Arc::try_unwrap(arc) {
  344. let _ = self.tx.send(None);
  345. let _ = thread.join();
  346. }
  347. }
  348. }
  349. }
  350. #[cfg(feature = "zmq")]
  351. const WRITER_ADDR: &'static str = "ipc:///tmp/mm/influx";
  352. #[cfg(feature = "zmq")]
  353. pub fn pull(ctx: &zmq::Context) -> Result<zmq::Socket, zmq::Error> {
  354. let socket = ctx.socket(zmq::PULL)?;
  355. socket.bind(WRITER_ADDR)?;
  356. socket.set_rcvhwm(0)?;
  357. Ok(socket)
  358. }
  359. #[cfg(feature = "zmq")]
  360. pub fn push(ctx: &zmq::Context) -> Result<zmq::Socket, zmq::Error> {
  361. let socket = ctx.socket(zmq::PUSH)?;
  362. socket.connect(WRITER_ADDR)?;
  363. socket.set_sndhwm(0)?;
  364. Ok(socket)
  365. }
  366. /// This removes offending things rather than escaping them.
  367. ///
  368. fn escape_tag(s: &str) -> String {
  369. s.replace(" ", "")
  370. .replace(",", "")
  371. .replace("\"", "")
  372. }
  373. fn escape(s: &str) -> String {
  374. s.replace(" ", "\\ ")
  375. .replace(",", "\\,")
  376. }
  377. fn as_string(s: &str) -> String {
  378. // the second replace removes double escapes
  379. //
  380. format!("\"{}\"", s.replace("\"", "\\\"")
  381. .replace(r#"\\""#, r#"\""#))
  382. }
  383. #[test]
  384. fn it_checks_as_string_does_not_double_escape() {
  385. let raw = "this is \\\"an escaped string\\\" so it's problematic";
  386. let escaped = as_string(&raw);
  387. assert_eq!(escaped, format!("\"{}\"", raw).as_ref());
  388. }
  389. fn as_integer(i: &i64) -> String {
  390. format!("{}i", i)
  391. }
  392. fn as_float(f: &f64) -> String {
  393. f.to_string()
  394. }
  395. fn as_boolean(b: &bool) -> &str {
  396. if *b { "t" } else { "f" }
  397. }
  398. pub fn now() -> i64 {
  399. nanos(Utc::now()) as i64
  400. }
  401. /// Serialize the measurement into influx line protocol
  402. /// and append to the buffer.
  403. ///
  404. /// # Examples
  405. ///
  406. /// ```
  407. /// extern crate influent;
  408. /// extern crate logging;
  409. ///
  410. /// use influent::measurement::{Measurement, Value};
  411. /// use std::string::String;
  412. /// use logging::influx::serialize;
  413. ///
  414. /// fn main() {
  415. /// let mut buf = String::new();
  416. /// let mut m = Measurement::new("test");
  417. /// m.add_field("x", Value::Integer(1));
  418. /// serialize(&m, &mut buf);
  419. /// }
  420. ///
  421. /// ```
  422. ///
  423. pub fn serialize(measurement: &Measurement, line: &mut String) {
  424. line.push_str(&escape(measurement.key));
  425. for (tag, value) in measurement.tags.iter() {
  426. line.push_str(",");
  427. line.push_str(&escape(tag));
  428. line.push_str("=");
  429. line.push_str(&escape(value));
  430. }
  431. let mut was_spaced = false;
  432. for (field, value) in measurement.fields.iter() {
  433. line.push_str({if !was_spaced { was_spaced = true; " " } else { "," }});
  434. line.push_str(&escape(field));
  435. line.push_str("=");
  436. match value {
  437. &Value::String(ref s) => line.push_str(&as_string(s)),
  438. &Value::Integer(ref i) => line.push_str(&as_integer(i)),
  439. &Value::Float(ref f) => line.push_str(&as_float(f)),
  440. &Value::Boolean(ref b) => line.push_str(as_boolean(b))
  441. };
  442. }
  443. match measurement.timestamp {
  444. Some(t) => {
  445. line.push_str(" ");
  446. line.push_str(&t.to_string());
  447. }
  448. _ => {}
  449. }
  450. }
  451. /// Serializes an `&OwnedMeasurement` as influx line protocol into `line`.
  452. ///
  453. /// The serialized measurement is appended to the end of the string without
  454. /// any regard for what exited in it previously.
  455. ///
  456. pub fn serialize_owned(measurement: &OwnedMeasurement, line: &mut String) {
  457. line.push_str(&escape_tag(measurement.key));
  458. let add_tag = |line: &mut String, key: &str, value: &str| {
  459. line.push_str(",");
  460. line.push_str(&escape_tag(key));
  461. line.push_str("=");
  462. line.push_str(&escape(value));
  463. };
  464. for &(key, value) in measurement.tags.iter() {
  465. add_tag(line, key, value);
  466. }
  467. let add_field = |line: &mut String, key: &str, value: &OwnedValue, is_first: bool| {
  468. if is_first { line.push_str(" "); } else { line.push_str(","); }
  469. line.push_str(&escape_tag(key));
  470. line.push_str("=");
  471. match *value {
  472. OwnedValue::String(ref s) => line.push_str(&as_string(s)),
  473. OwnedValue::Integer(ref i) => line.push_str(&format!("{}i", i)),
  474. OwnedValue::Boolean(ref b) => line.push_str(as_boolean(b)),
  475. OwnedValue::D128(ref d) => {
  476. if d.is_finite() {
  477. line.push_str(&format!("{}", d));
  478. } else {
  479. line.push_str("0.0");
  480. }
  481. }
  482. OwnedValue::Float(ref f) => {
  483. if f.is_finite() {
  484. line.push_str(&format!("{}", f));
  485. } else {
  486. line.push_str("0.0");
  487. }
  488. }
  489. OwnedValue::Uuid(ref u) => line.push_str(&format!("\"{}\"", u)),
  490. };
  491. };
  492. let mut fields = measurement.fields.iter();
  493. // first time separate from tags with space
  494. //
  495. fields.next().map(|kv| {
  496. add_field(line, &kv.0, &kv.1, true);
  497. });
  498. // then seperate the rest w/ comma
  499. //
  500. for kv in fields {
  501. add_field(line, kv.0, &kv.1, false);
  502. }
  503. if let Some(t) = measurement.timestamp {
  504. line.push_str(" ");
  505. line.push_str(&t.to_string());
  506. }
  507. }
  508. #[cfg(feature = "warnings")]
  509. #[deprecated(since="0.4", note="Replace with InfluxWriter")]
  510. #[cfg(feature = "zmq")]
  511. pub fn writer(warnings: Sender<Warning>) -> thread::JoinHandle<()> {
  512. assert!(false);
  513. thread::Builder::new().name("mm:inflx-wtr".into()).spawn(move || {
  514. const DB_HOST: &'static str = "http://127.0.0.1:8086/write";
  515. let _ = fs::create_dir("/tmp/mm");
  516. let ctx = zmq::Context::new();
  517. let socket = pull(&ctx).expect("influx::writer failed to create pull socket");
  518. let url = Url::parse_with_params(DB_HOST, &[("db", DB_NAME), ("precision", "ns")]).expect("influx writer url should parse");
  519. let client = Client::new();
  520. let mut buf = String::with_capacity(4096);
  521. let mut server_resp = String::with_capacity(4096);
  522. let mut count = 0;
  523. loop {
  524. if let Ok(bytes) = socket.recv_bytes(0) {
  525. if let Ok(msg) = String::from_utf8(bytes) {
  526. count = match count {
  527. 0 => {
  528. buf.push_str(&msg);
  529. 1
  530. }
  531. n @ 1...40 => {
  532. buf.push_str("\n");
  533. buf.push_str(&msg);
  534. n + 1
  535. }
  536. _ => {
  537. buf.push_str("\n");
  538. buf.push_str(&msg);
  539. match client.post(url.clone())
  540. .body(&buf)
  541. .send() {
  542. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  543. Ok(mut resp) => {
  544. let _ = resp.read_to_string(&mut server_resp); //.unwrap_or(0);
  545. let _ = warnings.send(
  546. Warning::Error(
  547. format!("Influx server: {}", server_resp)));
  548. server_resp.clear();
  549. }
  550. Err(why) => {
  551. let _ = warnings.send(
  552. Warning::Error(
  553. format!("Influx write error: {}", why)));
  554. }
  555. }
  556. buf.clear();
  557. 0
  558. }
  559. }
  560. }
  561. }
  562. }
  563. }).unwrap()
  564. }
  565. #[derive(Debug, Clone, PartialEq)]
  566. pub enum OwnedValue {
  567. String(String),
  568. Float(f64),
  569. Integer(i64),
  570. Boolean(bool),
  571. D128(d128),
  572. Uuid(Uuid),
  573. }
  574. /// Holds data meant for an influxdb measurement in transit to the
  575. /// writing thread.
  576. ///
  577. /// TODO: convert `Map` to `SmallVec`?
  578. ///
  579. #[derive(Clone, Debug)]
  580. pub struct OwnedMeasurement {
  581. pub key: &'static str,
  582. pub timestamp: Option<i64>,
  583. //pub fields: Map<&'static str, OwnedValue>,
  584. //pub tags: Map<&'static str, &'static str>,
  585. pub fields: SmallVec<[(&'static str, OwnedValue); 8]>,
  586. pub tags: SmallVec<[(&'static str, &'static str); 8]>,
  587. }
  588. impl OwnedMeasurement {
  589. pub fn with_capacity(key: &'static str, n_tags: usize, n_fields: usize) -> Self {
  590. OwnedMeasurement {
  591. key,
  592. timestamp: None,
  593. tags: SmallVec::with_capacity(n_tags),
  594. fields: SmallVec::with_capacity(n_fields),
  595. }
  596. }
  597. pub fn new(key: &'static str) -> Self {
  598. OwnedMeasurement {
  599. key,
  600. timestamp: None,
  601. tags: SmallVec::new(),
  602. fields: SmallVec::new(),
  603. }
  604. }
  605. /// Unusual consuming `self` signature because primarily used by
  606. /// the `measure!` macro.
  607. pub fn add_tag(mut self, key: &'static str, value: &'static str) -> Self {
  608. self.tags.push((key, value));
  609. self
  610. }
  611. /// Unusual consuming `self` signature because primarily used by
  612. /// the `measure!` macro.
  613. pub fn add_field(mut self, key: &'static str, value: OwnedValue) -> Self {
  614. self.fields.push((key, value));
  615. self
  616. }
  617. pub fn set_timestamp(mut self, timestamp: i64) -> Self {
  618. self.timestamp = Some(timestamp);
  619. self
  620. }
  621. pub fn set_tag(mut self, key: &'static str, value: &'static str) -> Self {
  622. match self.tags.iter().position(|kv| kv.0 == key) {
  623. Some(i) => {
  624. self.tags.get_mut(i)
  625. .map(|x| {
  626. x.0 = value;
  627. });
  628. self
  629. }
  630. None => {
  631. self.add_tag(key, value)
  632. }
  633. }
  634. }
  635. pub fn get_field(&self, key: &'static str) -> Option<&OwnedValue> {
  636. self.fields.iter()
  637. .find(|kv| kv.0 == key)
  638. .map(|kv| &kv.1)
  639. }
  640. pub fn get_tag(&self, key: &'static str) -> Option<&'static str> {
  641. self.tags.iter()
  642. .find(|kv| kv.0 == key)
  643. .map(|kv| kv.1)
  644. }
  645. }
  646. #[allow(unused_imports, unused_variables)]
  647. #[cfg(test)]
  648. mod tests {
  649. use super::*;
  650. use test::{black_box, Bencher};
  651. #[test]
  652. fn it_uses_the_utc_shortcut_to_convert_a_datetime_utc() {
  653. const VERSION: &str = "0.3.90";
  654. let tag_value = "one";
  655. let color = "red";
  656. let time = Utc::now();
  657. let m = measure!(@make_meas test, i(n, 1), t(color), v(VERSION), utc(time));
  658. assert_eq!(m.get_tag("color"), Some("red"));
  659. assert_eq!(m.get_tag("version"), Some(VERSION));
  660. assert_eq!(m.timestamp, Some(nanos(time) as i64));
  661. }
  662. #[test]
  663. fn it_uses_the_v_for_version_shortcut() {
  664. const VERSION: &str = "0.3.90";
  665. let tag_value = "one";
  666. let color = "red";
  667. let time = now();
  668. let m = measure!(@make_meas test, i(n, 1), t(color), v(VERSION), tm(time));
  669. assert_eq!(m.get_tag("color"), Some("red"));
  670. assert_eq!(m.get_tag("version"), Some(VERSION));
  671. assert_eq!(m.timestamp, Some(time));
  672. }
  673. #[test]
  674. fn it_uses_the_new_tag_k_only_shortcut() {
  675. let tag_value = "one";
  676. let color = "red";
  677. let time = now();
  678. let m = measure!(@make_meas test, t(color), t(tag_value), tm(time));
  679. assert_eq!(m.get_tag("color"), Some("red"));
  680. assert_eq!(m.get_tag("tag_value"), Some("one"));
  681. assert_eq!(m.timestamp, Some(time));
  682. }
  683. #[test]
  684. fn it_uses_measure_macro_parenthesis_syntax() {
  685. let m = measure!(@make_meas test, t(a,"b"), i(n,1), f(x,1.1), tm(1));
  686. assert_eq!(m.key, "test");
  687. assert_eq!(m.get_tag("a"), Some("b"));
  688. assert_eq!(m.get_field("n"), Some(&OwnedValue::Integer(1)));
  689. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  690. assert_eq!(m.timestamp, Some(1));
  691. }
  692. #[test]
  693. fn it_uses_measure_macro_on_a_self_attribute() {
  694. struct A {
  695. pub influx: InfluxWriter,
  696. }
  697. impl A {
  698. fn f(&self) {
  699. measure!(self.influx, test, t(color, "red"), i(n, 1));
  700. }
  701. }
  702. let a = A { influx: InfluxWriter::default() };
  703. a.f();
  704. }
  705. #[test]
  706. fn it_clones_an_influx_writer_to_check_both_drop() {
  707. let influx = InfluxWriter::default();
  708. measure!(influx, drop_test, i(a, 1), i(b, 2));
  709. {
  710. let influx = influx.clone();
  711. thread::spawn(move || {
  712. measure!(influx, drop_test, i(a, 3), i(b, 4));
  713. });
  714. }
  715. }
  716. #[bench]
  717. fn influx_writer_send_basic(b: &mut Bencher) {
  718. let m = InfluxWriter::new("localhost", "test", "var/log/influx-test.log", 4000);
  719. b.iter(|| {
  720. measure!(m, test, tag[color; "red"], int[n; 1]); //, float[p; 1.234]);
  721. });
  722. }
  723. #[bench]
  724. fn influx_writer_send_price(b: &mut Bencher) {
  725. let m = InfluxWriter::new("localhost", "test", "var/log/influx-test.log", 4000);
  726. b.iter(|| {
  727. measure!(m, test,
  728. t(ticker, t!(xmr-btc).as_str()),
  729. t(exchange, "plnx"),
  730. d(bid, d128::zero()),
  731. d(ask, d128::zero()),
  732. );
  733. });
  734. }
  735. #[test]
  736. fn it_checks_color_tag_error_in_non_doctest() {
  737. let (tx, rx) = channel();
  738. measure!(tx, test, tag[color;"red"], int[n;1]);
  739. let meas: OwnedMeasurement = rx.recv().unwrap();
  740. assert_eq!(meas.get_tag("color"), Some("red"), "meas = \n {:?} \n", meas);
  741. }
  742. #[test]
  743. fn it_uses_the_make_meas_pattern_of_the_measure_macro() {
  744. let meas = measure!(@make_meas test_measurement,
  745. tag [ one => "a" ],
  746. tag [ two => "b" ],
  747. int [ three => 2 ],
  748. float [ four => 1.2345 ],
  749. string [ five => String::from("d") ],
  750. bool [ six => true ],
  751. int [ seven => { 1 + 2 } ],
  752. time [ 1 ]
  753. );
  754. assert_eq!(meas.key, "test_measurement");
  755. assert_eq!(meas.get_tag("one"), Some("a"));
  756. assert_eq!(meas.get_tag("two"), Some("b"));
  757. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  758. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  759. assert_eq!(meas.timestamp, Some(1));
  760. }
  761. #[test]
  762. fn it_uses_the_measure_macro() {
  763. let (tx, rx) = channel();
  764. measure!(tx, test_measurement,
  765. tag [ one => "a" ],
  766. tag [ two => "b" ],
  767. int [ three => 2 ],
  768. float [ four => 1.2345 ],
  769. string [ five => String::from("d") ],
  770. bool [ six => true ],
  771. int [ seven => { 1 + 2 } ],
  772. time [ 1 ]
  773. );
  774. thread::sleep(Duration::from_millis(10));
  775. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  776. assert_eq!(meas.key, "test_measurement");
  777. assert_eq!(meas.get_tag("one"), Some("a"));
  778. assert_eq!(meas.get_tag("two"), Some("b"));
  779. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  780. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  781. assert_eq!(meas.timestamp, Some(1));
  782. }
  783. #[test]
  784. fn it_uses_measure_macro_for_d128_and_uuid() {
  785. let (tx, rx) = channel();
  786. let u = Uuid::new_v4();
  787. let d = d128::zero();
  788. let t = now();
  789. measure!(tx, test_measurement,
  790. tag[one; "a"],
  791. d128[two; d],
  792. uuid[three; u],
  793. time[t]
  794. );
  795. thread::sleep(Duration::from_millis(10));
  796. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  797. assert_eq!(meas.key, "test_measurement");
  798. assert_eq!(meas.get_tag("one"), Some("a"));
  799. assert_eq!(meas.get_field("two"), Some(&OwnedValue::D128(d128::zero())));
  800. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Uuid(u)));
  801. assert_eq!(meas.timestamp, Some(t));
  802. }
  803. #[test]
  804. fn it_uses_the_measure_macro_alt_syntax() {
  805. let (tx, rx) = channel();
  806. measure!(tx, test_measurement,
  807. tag[one; "a"],
  808. tag[two; "b"],
  809. int[three; 2],
  810. float[four; 1.2345],
  811. string[five; String::from("d")],
  812. bool [ six => true ],
  813. int[seven; { 1 + 2 }],
  814. time[1]
  815. );
  816. thread::sleep(Duration::from_millis(10));
  817. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  818. assert_eq!(meas.key, "test_measurement");
  819. assert_eq!(meas.get_tag("one"), Some("a"));
  820. assert_eq!(meas.get_tag("two"), Some("b"));
  821. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  822. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  823. assert_eq!(meas.timestamp, Some(1));
  824. }
  825. #[test]
  826. fn it_checks_that_fields_are_separated_correctly() {
  827. let m = measure!(@make_meas test, t[a; "one"], t[b; "two"], f[x; 1.1], f[y; -1.1]);
  828. assert_eq!(m.key, "test");
  829. assert_eq!(m.get_tag("a"), Some("one"));
  830. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  831. let mut buf = String::new();
  832. serialize_owned(&m, &mut buf);
  833. assert!(buf.contains("b=two x=1.1,y=-1.1"), "buf = {}", buf);
  834. }
  835. #[test]
  836. fn try_to_break_measure_macro() {
  837. let (tx, _) = channel();
  838. measure!(tx, one, tag[x=>"y"], int[n;1]);
  839. measure!(tx, one, tag[x;"y"], int[n;1],);
  840. struct A {
  841. pub one: i32,
  842. pub two: i32,
  843. }
  844. struct B {
  845. pub a: A
  846. }
  847. let b = B { a: A { one: 1, two: 2 } };
  848. let m = measure!(@make_meas test, t(name, "a"), i(a, b.a.one));
  849. assert_eq!(m.get_field("a"), Some(&OwnedValue::Integer(1)));
  850. }
  851. #[bench]
  852. fn measure_macro_small(b: &mut Bencher) {
  853. let (tx, rx) = channel();
  854. let listener = thread::spawn(move || {
  855. loop { if rx.recv().is_err() { break } }
  856. });
  857. b.iter(|| {
  858. measure!(tx, test, tag[color; "red"], int[n; 1], time[now()]);
  859. });
  860. }
  861. #[bench]
  862. fn measure_macro_medium(b: &mut Bencher) {
  863. let (tx, rx) = channel();
  864. let listener = thread::spawn(move || {
  865. loop { if rx.recv().is_err() { break } }
  866. });
  867. b.iter(|| {
  868. measure!(tx, test,
  869. tag[color; "red"],
  870. tag[mood => "playful"],
  871. tag [ ticker => "xmr_btc" ],
  872. float[ price => 1.2345 ],
  873. float[ amount => 56.323],
  874. int[n; 1],
  875. time[now()]
  876. );
  877. });
  878. }
  879. #[cfg(feature = "zmq")]
  880. #[cfg(feature = "warnings")]
  881. #[test]
  882. #[ignore]
  883. fn it_spawns_a_writer_thread_and_sends_dummy_measurement_to_influxdb() {
  884. let ctx = zmq::Context::new();
  885. let socket = push(&ctx).unwrap();
  886. let (tx, rx) = channel();
  887. let w = writer(tx.clone());
  888. let mut buf = String::with_capacity(4096);
  889. let mut meas = Measurement::new("rust_test");
  890. meas.add_tag("a", "t");
  891. meas.add_field("c", Value::Float(1.23456));
  892. let now = now();
  893. meas.set_timestamp(now);
  894. serialize(&meas, &mut buf);
  895. socket.send_str(&buf, 0).unwrap();
  896. drop(w);
  897. }
  898. #[test]
  899. fn it_serializes_a_measurement_in_place() {
  900. let mut buf = String::with_capacity(4096);
  901. let mut meas = Measurement::new("rust_test");
  902. meas.add_tag("a", "b");
  903. meas.add_field("c", Value::Float(1.0));
  904. let now = now();
  905. meas.set_timestamp(now);
  906. serialize(&meas, &mut buf);
  907. let ans = format!("rust_test,a=b c=1 {}", now);
  908. assert_eq!(buf, ans);
  909. }
  910. #[test]
  911. fn it_serializes_a_hard_to_serialize_message() {
  912. let raw = r#"error encountered trying to send krkn order: Other("Failed to send http request: Other("Resource temporarily unavailable (os error 11)")")"#;
  913. let mut buf = String::new();
  914. let mut server_resp = String::new();
  915. let mut m = Measurement::new("rust_test");
  916. m.add_field("s", Value::String(&raw));
  917. let now = now();
  918. m.set_timestamp(now);
  919. serialize(&m, &mut buf);
  920. println!("{}", buf);
  921. buf.push_str("\n");
  922. let buf_copy = buf.clone();
  923. buf.push_str(&buf_copy);
  924. println!("{}", buf);
  925. let url = Url::parse_with_params("http://localhost:8086/write", &[("db", "test"), ("precision", "ns")]).expect("influx writer url should parse");
  926. let client = Client::new();
  927. match client.post(url.clone())
  928. .body(&buf)
  929. .send() {
  930. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  931. Ok(mut resp) => {
  932. resp.read_to_string(&mut server_resp).unwrap();
  933. panic!("{}", server_resp);
  934. }
  935. Err(why) => {
  936. panic!(why)
  937. }
  938. }
  939. }
  940. #[bench]
  941. fn serialize_owned_longer(b: &mut Bencher) {
  942. let mut buf = String::with_capacity(1024);
  943. let m =
  944. OwnedMeasurement::new("test")
  945. .add_tag("one", "a")
  946. .add_tag("two", "b")
  947. .add_tag("ticker", "xmr_btc")
  948. .add_tag("exchange", "plnx")
  949. .add_tag("side", "bid")
  950. .add_field("three", OwnedValue::Float(1.2345))
  951. .add_field("four", OwnedValue::Integer(57))
  952. .add_field("five", OwnedValue::Boolean(true))
  953. .add_field("six", OwnedValue::String(String::from("abcdefghijklmnopqrstuvwxyz")))
  954. .set_timestamp(now());
  955. b.iter(|| {
  956. serialize_owned(&m, &mut buf);
  957. buf.clear()
  958. });
  959. }
  960. #[bench]
  961. fn serialize_owned_simple(b: &mut Bencher) {
  962. let mut buf = String::with_capacity(1024);
  963. let m =
  964. OwnedMeasurement::new("test")
  965. .add_tag("one", "a")
  966. .add_tag("two", "b")
  967. .add_field("three", OwnedValue::Float(1.2345))
  968. .add_field("four", OwnedValue::Integer(57))
  969. .set_timestamp(now());
  970. b.iter(|| {
  971. serialize_owned(&m, &mut buf);
  972. buf.clear()
  973. });
  974. }
  975. #[test]
  976. fn it_serializes_a_hard_to_serialize_message_from_owned() {
  977. let raw = r#"error encountered trying to send krkn order: Other("Failed to send http request: Other("Resource temporarily unavailable (os error 11)")")"#;
  978. let mut buf = String::new();
  979. let mut server_resp = String::new();
  980. let m = OwnedMeasurement::new("rust_test")
  981. .add_field("s", OwnedValue::String(raw.to_string()))
  982. .set_timestamp(now());
  983. serialize_owned(&m, &mut buf);
  984. println!("{}", buf);
  985. buf.push_str("\n");
  986. let buf_copy = buf.clone();
  987. buf.push_str(&buf_copy);
  988. println!("{}", buf);
  989. let url = Url::parse_with_params("http://localhost:8086/write", &[("db", "test"), ("precision", "ns")]).expect("influx writer url should parse");
  990. let client = Client::new();
  991. match client.post(url.clone())
  992. .body(&buf)
  993. .send() {
  994. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  995. Ok(mut resp) => {
  996. resp.read_to_string(&mut server_resp).unwrap();
  997. panic!("{}", server_resp);
  998. }
  999. Err(why) => {
  1000. panic!(why)
  1001. }
  1002. }
  1003. }
  1004. }