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.

1038 lines
34KB

  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::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. 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 super::{nanos, file_logger, LOG_LEVEL};
  26. #[cfg(feature = "warnings")]
  27. use warnings::Warning;
  28. pub use super::{dur_nanos, dt_nanos};
  29. pub type Map<K, V> = OrderMap<K, V, BuildHasherDefault<FnvHasher>>;
  30. pub fn new_map<K, V>(capacity: usize) -> Map<K, V> {
  31. Map::with_capacity_and_hasher(capacity, Default::default())
  32. }
  33. /// Provides flexible and ergonomic use of `Sender<OwnedMeasurement>`.
  34. ///
  35. /// The macro both creates an `OwnedMeasurement` from the supplied tags and
  36. /// values, as well as sends it with the `Sender`.
  37. ///
  38. /// Benchmarks show around 600ns for a small measurement and 1u for a medium-sized
  39. /// measurement (see `tests` mod).
  40. ///
  41. /// # Examples
  42. ///
  43. /// ```
  44. /// #[macro_use] extern crate logging;
  45. /// extern crate decimal;
  46. ///
  47. /// use std::sync::mpsc::channel;
  48. /// use decimal::d128;
  49. /// use logging::influx::*;
  50. ///
  51. /// fn main() {
  52. /// let (tx, rx) = channel();
  53. ///
  54. /// // "shorthand" syntax
  55. ///
  56. /// measure!(tx, test, tag[color;"red"], int[n;1]);
  57. ///
  58. /// let meas: OwnedMeasurement = rx.recv().unwrap();
  59. ///
  60. /// assert_eq!(meas.key, "test");
  61. /// assert_eq!(meas.get_tag("color"), Some("red"));
  62. /// assert_eq!(meas.get_field("n"), Some(&OwnedValue::Integer(1)));
  63. ///
  64. /// // alternate syntax ...
  65. ///
  66. /// measure!(tx, test,
  67. /// tag [ one => "a" ],
  68. /// tag [ two => "b" ],
  69. /// int [ three => 2 ],
  70. /// float [ four => 1.2345 ],
  71. /// string [ five => String::from("d") ],
  72. /// bool [ six => true ],
  73. /// int [ seven => { 1 + 2 } ],
  74. /// time [ 1 ]
  75. /// );
  76. ///
  77. /// let meas: OwnedMeasurement = rx.recv().unwrap();
  78. ///
  79. /// assert_eq!(meas.key, "test");
  80. /// assert_eq!(meas.get_tag("one"), Some("a"));
  81. /// assert_eq!(meas.get_tag("two"), Some("b"));
  82. /// assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  83. /// assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  84. /// assert_eq!(meas.timestamp, Some(1));
  85. ///
  86. /// // use the @make_meas flag to skip sending a measurement, instead merely
  87. /// // creating it.
  88. ///
  89. /// let meas: OwnedMeasurement = measure!(@make_meas meas_only, tag[color; "red"], int[n; 1]);
  90. ///
  91. /// // each variant also has shorthand aliases
  92. ///
  93. /// let meas: OwnedMeasurement =
  94. /// measure!(@make_meas abcd, t[color; "red"], i[n; 1], d[price; d128::zero()]);
  95. /// }
  96. /// ```
  97. ///
  98. #[macro_export]
  99. macro_rules! measure {
  100. (@kv $t:tt, $meas:ident, $k:tt => $v:expr) => { measure!(@ea $t, $meas, stringify!($k), $v) };
  101. (@kv $t:tt, $meas:ident, $k:tt; $v:expr) => { measure!(@ea $t, $meas, stringify!($k), $v) };
  102. (@kv $t:tt, $meas:ident, $k:tt, $v:expr) => { measure!(@ea $t, $meas, stringify!($k), $v) };
  103. (@kv time, $meas:ident, $tm:expr) => { $meas = $meas.set_timestamp($tm as i64) };
  104. (@kv tm, $meas:ident, $tm:expr) => { $meas = $meas.set_timestamp($tm as i64) };
  105. (@kv $t:tt, $meas:ident, $k:tt) => { measure!(@ea $t, $meas, stringify!($k), measure!(@as_expr $k)) };
  106. (@ea tag, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_tag($k, $v); };
  107. (@ea t, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_tag($k, $v); };
  108. (@ea int, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Integer($v as i64)) };
  109. (@ea i, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Integer($v as i64)) };
  110. (@ea float, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Float($v as f64)) };
  111. (@ea f, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Float($v as f64)) };
  112. (@ea string, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::String($v)) };
  113. (@ea s, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::String($v)) };
  114. (@ea d128, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::D128($v)) };
  115. (@ea d, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::D128($v)) };
  116. (@ea uuid, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Uuid($v)) };
  117. (@ea u, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Uuid($v)) };
  118. (@ea bool, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Boolean($v as bool)) };
  119. (@ea b, $meas:ident, $k:expr, $v:expr) => { $meas = $meas.add_field($k, $crate::influx::OwnedValue::Boolean($v as bool)) };
  120. (@as_expr $e:expr) => {$e};
  121. (@count_tags) => {0usize};
  122. (@count_tags tag $($tail:tt)*) => {1usize + measure!(@count_tags $($tail)*)};
  123. (@count_tags $t:tt $($tail:tt)*) => {0usize + measure!(@count_tags $($tail)*)};
  124. (@count_fields) => {0usize};
  125. (@count_fields tag $($tail:tt)*) => {0usize + measure!(@count_fields $($tail)*)};
  126. (@count_fields time $($tail:tt)*) => {0usize + measure!(@count_fields $($tail)*)};
  127. (@count_fields $t:tt $($tail:tt)*) => {1usize + measure!(@count_fields $($tail)*)};
  128. (@make_meas $name:tt, $( $t:tt ( $($tail:tt)* ) ),+ $(,)*) => {
  129. measure!(@make_meas $name, $( $t [ $($tail)* ] ),*)
  130. };
  131. (@make_meas $name:tt, $( $t:tt [ $($tail:tt)* ] ),+ $(,)*) => {{
  132. let n_tags = measure!(@count_tags $($t)*);
  133. let n_fields = measure!(@count_fields $($t)*);
  134. let mut meas =
  135. $crate::influx::OwnedMeasurement::with_capacity(stringify!($name), n_tags, n_fields);
  136. $(
  137. measure!(@kv $t, meas, $($tail)*);
  138. )*
  139. meas
  140. }};
  141. ($m:expr, $name:tt, $( $t:tt ( $($tail:tt)* ) ),+ $(,)*) => {
  142. measure!($m, $name, $($t [ $($tail)* ] ),+)
  143. };
  144. ($m:tt, $name:tt, $( $t:tt [ $($tail:tt)* ] ),+ $(,)*) => {{
  145. let measurement = measure!(@make_meas $name, $( $t [ $($tail)* ] ),*);
  146. let _ = $m.send(measurement);
  147. }};
  148. }
  149. /// Holds a thread (and provides an interface to it) that serializes `OwnedMeasurement`s
  150. /// it receives (over a SPSC channel) and inserts to influxdb via http when `BUFFER_SIZE`
  151. /// measurements have accumulated.
  152. ///
  153. #[derive(Debug)]
  154. pub struct InfluxWriter {
  155. host: String,
  156. db: String,
  157. tx: Sender<Option<OwnedMeasurement>>,
  158. thread: Option<Arc<thread::JoinHandle<()>>>,
  159. }
  160. impl Default for InfluxWriter {
  161. fn default() -> Self {
  162. //if cfg!(any(test, feature = "test")) {
  163. // InfluxWriter::new("localhost", "test", "/home/jstrong/src/logging/var/log/influx-test.log", 0)
  164. //} else {
  165. InfluxWriter::new("localhost", "test", "/home/jstrong/src/logging/var/log/influx-test.log", 4000)
  166. //}
  167. }
  168. }
  169. impl Clone for InfluxWriter {
  170. fn clone(&self) -> Self {
  171. debug_assert!(self.thread.is_some());
  172. let thread = self.thread.as_ref().map(|x| Arc::clone(x));
  173. InfluxWriter {
  174. host: self.host.to_string(),
  175. db: self.db.to_string(),
  176. tx: self.tx.clone(),
  177. thread,
  178. }
  179. }
  180. }
  181. impl InfluxWriter {
  182. /// Sends the `OwnedMeasurement` to the serialization thread.
  183. ///
  184. pub fn send(&self, m: OwnedMeasurement) -> Result<(), SendError<Option<OwnedMeasurement>>> {
  185. self.tx.send(Some(m))
  186. }
  187. pub fn nanos(&self, d: DateTime<Utc>) -> i64 { nanos(d) as i64 }
  188. pub fn dur_nanos(&self, d: Duration) -> i64 { dur_nanos(d) as i64 }
  189. pub fn dur_nanos_u64(&self, d: Duration) -> u64 { dur_nanos(d).max(0) as u64 }
  190. pub fn tx(&self) -> Sender<Option<OwnedMeasurement>> {
  191. self.tx.clone()
  192. }
  193. pub fn new(host: &str, db: &str, log_path: &str, buffer_size: u16) -> Self {
  194. let logger = file_logger(log_path, LOG_LEVEL); // this needs to be outside the thread
  195. Self::with_logger(host, db, buffer_size, logger)
  196. }
  197. #[allow(unused_assignments)]
  198. pub fn with_logger(host: &str, db: &str, buffer_size: u16, logger: Logger) -> Self {
  199. let (tx, rx): (Sender<Option<OwnedMeasurement>>, Receiver<Option<OwnedMeasurement>>) = channel();
  200. #[cfg(feature = "no-influx-buffer")]
  201. let buffer_size = 0u16;
  202. debug!(logger, "initializing url"; "host" => host, "db" => db, "buffer_size" => buffer_size);
  203. let url =
  204. Url::parse_with_params(&format!("http://{}:8086/write", host),
  205. &[("db", db), ("precision", "ns")])
  206. .expect("influx writer url should parse");
  207. let thread = thread::Builder::new().name(format!("mm:inflx:{}", db)).spawn(move || {
  208. let client = Client::new();
  209. debug!(logger, "initializing buffers");
  210. let mut buf = String::with_capacity(32 * 32 * 32);
  211. let mut count = 0;
  212. let send = |buf: &str| {
  213. let resp = client.post(url.clone())
  214. .body(buf)
  215. .send();
  216. match resp {
  217. Ok(Response { status, .. }) if status == StatusCode::NoContent => {
  218. debug!(logger, "server responded ok: 204 NoContent");
  219. }
  220. Ok(mut resp) => {
  221. let mut server_resp = String::with_capacity(1024);
  222. let _ = resp.read_to_string(&mut server_resp); //.unwrap_or(0);
  223. error!(logger, "influx server error";
  224. "status" => resp.status.to_string(),
  225. "body" => server_resp);
  226. }
  227. Err(why) => {
  228. error!(logger, "http request failed: {:?}", why);
  229. }
  230. }
  231. };
  232. let next = |prev: u16, m: &OwnedMeasurement, buf: &mut String| -> u16 {
  233. match prev {
  234. 0 if buffer_size > 0 => {
  235. serialize_owned(m, buf);
  236. 1
  237. }
  238. n if n < buffer_size => {
  239. buf.push_str("\n");
  240. serialize_owned(m, buf);
  241. n + 1
  242. }
  243. n => {
  244. buf.push_str("\n");
  245. serialize_owned(m, buf);
  246. debug!(logger, "sending buffer to influx"; "len" => n);
  247. send(buf);
  248. buf.clear();
  249. 0
  250. }
  251. }
  252. };
  253. loop {
  254. match rx.recv() {
  255. Ok(Some(mut meas)) => {
  256. if meas.timestamp.is_none() { meas.timestamp = Some(now()) }
  257. //#[cfg(feature = "trace")] { if count % 10 == 0 { trace!(logger, "rcvd new measurement"; "count" => count, "key" => meas.key); } }
  258. count = next(count, &meas, &mut buf);
  259. }
  260. Ok(None) => {
  261. if buf.len() > 0 {
  262. debug!(logger, "sending buffer to influx"; "len" => count);
  263. send(&buf)
  264. }
  265. break
  266. }
  267. _ => {
  268. thread::sleep(Duration::new(0, 1))
  269. }
  270. }
  271. }
  272. }).unwrap();
  273. InfluxWriter {
  274. host: host.to_string(),
  275. db: db.to_string(),
  276. tx,
  277. thread: Some(Arc::new(thread))
  278. }
  279. }
  280. }
  281. impl Drop for InfluxWriter {
  282. fn drop(&mut self) {
  283. if let Some(arc) = self.thread.take() {
  284. if let Ok(thread) = Arc::try_unwrap(arc) {
  285. let _ = self.tx.send(None);
  286. let _ = thread.join();
  287. }
  288. }
  289. }
  290. }
  291. const WRITER_ADDR: &'static str = "ipc:///tmp/mm/influx";
  292. pub fn pull(ctx: &zmq::Context) -> Result<zmq::Socket, zmq::Error> {
  293. let socket = ctx.socket(zmq::PULL)?;
  294. socket.bind(WRITER_ADDR)?;
  295. socket.set_rcvhwm(0)?;
  296. Ok(socket)
  297. }
  298. pub fn push(ctx: &zmq::Context) -> Result<zmq::Socket, zmq::Error> {
  299. let socket = ctx.socket(zmq::PUSH)?;
  300. socket.connect(WRITER_ADDR)?;
  301. socket.set_sndhwm(0)?;
  302. Ok(socket)
  303. }
  304. /// This removes offending things rather than escaping them.
  305. ///
  306. fn escape_tag(s: &str) -> String {
  307. s.replace(" ", "")
  308. .replace(",", "")
  309. .replace("\"", "")
  310. }
  311. fn escape(s: &str) -> String {
  312. s.replace(" ", "\\ ")
  313. .replace(",", "\\,")
  314. }
  315. fn as_string(s: &str) -> String {
  316. // the second replace removes double escapes
  317. //
  318. format!("\"{}\"", s.replace("\"", "\\\"")
  319. .replace(r#"\\""#, r#"\""#))
  320. }
  321. #[test]
  322. fn it_checks_as_string_does_not_double_escape() {
  323. let raw = "this is \\\"an escaped string\\\" so it's problematic";
  324. let escaped = as_string(&raw);
  325. assert_eq!(escaped, format!("\"{}\"", raw).as_ref());
  326. }
  327. fn as_integer(i: &i64) -> String {
  328. format!("{}i", i)
  329. }
  330. fn as_float(f: &f64) -> String {
  331. f.to_string()
  332. }
  333. fn as_boolean(b: &bool) -> &str {
  334. if *b { "t" } else { "f" }
  335. }
  336. pub fn now() -> i64 {
  337. nanos(Utc::now()) as i64
  338. }
  339. /// Serialize the measurement into influx line protocol
  340. /// and append to the buffer.
  341. ///
  342. /// # Examples
  343. ///
  344. /// ```
  345. /// extern crate influent;
  346. /// extern crate logging;
  347. ///
  348. /// use influent::measurement::{Measurement, Value};
  349. /// use std::string::String;
  350. /// use logging::influx::serialize;
  351. ///
  352. /// fn main() {
  353. /// let mut buf = String::new();
  354. /// let mut m = Measurement::new("test");
  355. /// m.add_field("x", Value::Integer(1));
  356. /// serialize(&m, &mut buf);
  357. /// }
  358. ///
  359. /// ```
  360. ///
  361. pub fn serialize(measurement: &Measurement, line: &mut String) {
  362. line.push_str(&escape(measurement.key));
  363. for (tag, value) in measurement.tags.iter() {
  364. line.push_str(",");
  365. line.push_str(&escape(tag));
  366. line.push_str("=");
  367. line.push_str(&escape(value));
  368. }
  369. let mut was_spaced = false;
  370. for (field, value) in measurement.fields.iter() {
  371. line.push_str({if !was_spaced { was_spaced = true; " " } else { "," }});
  372. line.push_str(&escape(field));
  373. line.push_str("=");
  374. match value {
  375. &Value::String(ref s) => line.push_str(&as_string(s)),
  376. &Value::Integer(ref i) => line.push_str(&as_integer(i)),
  377. &Value::Float(ref f) => line.push_str(&as_float(f)),
  378. &Value::Boolean(ref b) => line.push_str(as_boolean(b))
  379. };
  380. }
  381. match measurement.timestamp {
  382. Some(t) => {
  383. line.push_str(" ");
  384. line.push_str(&t.to_string());
  385. }
  386. _ => {}
  387. }
  388. }
  389. /// Serializes an `&OwnedMeasurement` as influx line protocol into `line`.
  390. ///
  391. /// The serialized measurement is appended to the end of the string without
  392. /// any regard for what exited in it previously.
  393. ///
  394. pub fn serialize_owned(measurement: &OwnedMeasurement, line: &mut String) {
  395. line.push_str(&escape_tag(measurement.key));
  396. let add_tag = |line: &mut String, key: &str, value: &str| {
  397. line.push_str(",");
  398. line.push_str(&escape_tag(key));
  399. line.push_str("=");
  400. line.push_str(&escape(value));
  401. };
  402. for &(key, value) in measurement.tags.iter() {
  403. add_tag(line, key, value);
  404. }
  405. let add_field = |line: &mut String, key: &str, value: &OwnedValue, is_first: bool| {
  406. if is_first { line.push_str(" "); } else { line.push_str(","); }
  407. line.push_str(&escape_tag(key));
  408. line.push_str("=");
  409. match *value {
  410. OwnedValue::String(ref s) => line.push_str(&as_string(s)),
  411. OwnedValue::Integer(ref i) => line.push_str(&format!("{}i", i)),
  412. OwnedValue::Float(ref f) => line.push_str(&format!("{}", f)),
  413. OwnedValue::Boolean(ref b) => line.push_str(as_boolean(b)),
  414. OwnedValue::D128(ref d) => line.push_str(&format!("{}", d)),
  415. #[cfg(not(feature = "disable-short-uuid"))]
  416. OwnedValue::Uuid(ref u) => line.push_str(&format!("\"{}\"", &u.to_string()[..8])),
  417. #[cfg(feature = "disable-short-uuid")]
  418. OwnedValue::Uuid(ref u) => line.push_str(&format!("\"{}\"", u)),
  419. };
  420. };
  421. let mut fields = measurement.fields.iter();
  422. // first time separate from tags with space
  423. //
  424. fields.next().map(|kv| {
  425. add_field(line, &kv.0, &kv.1, true);
  426. });
  427. // then seperate the rest w/ comma
  428. //
  429. for kv in fields {
  430. add_field(line, kv.0, &kv.1, false);
  431. }
  432. if let Some(t) = measurement.timestamp {
  433. line.push_str(" ");
  434. line.push_str(&t.to_string());
  435. }
  436. }
  437. #[cfg(feature = "warnings")]
  438. #[deprecated(since="0.4", note="Replace with InfluxWriter")]
  439. pub fn writer(warnings: Sender<Warning>) -> thread::JoinHandle<()> {
  440. assert!(false);
  441. thread::Builder::new().name("mm:inflx-wtr".into()).spawn(move || {
  442. const DB_HOST: &'static str = "http://127.0.0.1:8086/write";
  443. let _ = fs::create_dir("/tmp/mm");
  444. let ctx = zmq::Context::new();
  445. let socket = pull(&ctx).expect("influx::writer failed to create pull socket");
  446. let url = Url::parse_with_params(DB_HOST, &[("db", DB_NAME), ("precision", "ns")]).expect("influx writer url should parse");
  447. let client = Client::new();
  448. let mut buf = String::with_capacity(4096);
  449. let mut server_resp = String::with_capacity(4096);
  450. let mut count = 0;
  451. loop {
  452. if let Ok(bytes) = socket.recv_bytes(0) {
  453. if let Ok(msg) = String::from_utf8(bytes) {
  454. count = match count {
  455. 0 => {
  456. buf.push_str(&msg);
  457. 1
  458. }
  459. n @ 1...40 => {
  460. buf.push_str("\n");
  461. buf.push_str(&msg);
  462. n + 1
  463. }
  464. _ => {
  465. buf.push_str("\n");
  466. buf.push_str(&msg);
  467. match client.post(url.clone())
  468. .body(&buf)
  469. .send() {
  470. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  471. Ok(mut resp) => {
  472. let _ = resp.read_to_string(&mut server_resp); //.unwrap_or(0);
  473. let _ = warnings.send(
  474. Warning::Error(
  475. format!("Influx server: {}", server_resp)));
  476. server_resp.clear();
  477. }
  478. Err(why) => {
  479. let _ = warnings.send(
  480. Warning::Error(
  481. format!("Influx write error: {}", why)));
  482. }
  483. }
  484. buf.clear();
  485. 0
  486. }
  487. }
  488. }
  489. }
  490. }
  491. }).unwrap()
  492. }
  493. #[derive(Debug, Clone, PartialEq)]
  494. pub enum OwnedValue {
  495. String(String),
  496. Float(f64),
  497. Integer(i64),
  498. Boolean(bool),
  499. D128(d128),
  500. Uuid(Uuid),
  501. }
  502. /// Holds data meant for an influxdb measurement in transit to the
  503. /// writing thread.
  504. ///
  505. /// TODO: convert `Map` to `SmallVec`?
  506. ///
  507. #[derive(Clone, Debug)]
  508. pub struct OwnedMeasurement {
  509. pub key: &'static str,
  510. pub timestamp: Option<i64>,
  511. //pub fields: Map<&'static str, OwnedValue>,
  512. //pub tags: Map<&'static str, &'static str>,
  513. pub fields: SmallVec<[(&'static str, OwnedValue); 8]>,
  514. pub tags: SmallVec<[(&'static str, &'static str); 8]>,
  515. }
  516. impl OwnedMeasurement {
  517. pub fn with_capacity(key: &'static str, n_tags: usize, n_fields: usize) -> Self {
  518. OwnedMeasurement {
  519. key,
  520. timestamp: None,
  521. tags: SmallVec::with_capacity(n_tags),
  522. fields: SmallVec::with_capacity(n_fields),
  523. }
  524. }
  525. pub fn new(key: &'static str) -> Self {
  526. OwnedMeasurement {
  527. key,
  528. timestamp: None,
  529. tags: SmallVec::new(),
  530. fields: SmallVec::new(),
  531. }
  532. }
  533. pub fn add_tag(mut self, key: &'static str, value: &'static str) -> Self {
  534. self.tags.push((key, value));
  535. self
  536. }
  537. pub fn add_field(mut self, key: &'static str, value: OwnedValue) -> Self {
  538. self.fields.push((key, value));
  539. self
  540. }
  541. pub fn set_timestamp(mut self, timestamp: i64) -> Self {
  542. self.timestamp = Some(timestamp);
  543. self
  544. }
  545. pub fn set_tag(mut self, key: &'static str, value: &'static str) -> Self {
  546. match self.tags.iter().position(|kv| kv.0 == key) {
  547. Some(i) => {
  548. self.tags.get_mut(i)
  549. .map(|x| {
  550. x.0 = value;
  551. });
  552. self
  553. }
  554. None => {
  555. self.add_tag(key, value)
  556. }
  557. }
  558. }
  559. pub fn get_field(&self, key: &'static str) -> Option<&OwnedValue> {
  560. self.fields.iter()
  561. .find(|kv| kv.0 == key)
  562. .map(|kv| &kv.1)
  563. }
  564. pub fn get_tag(&self, key: &'static str) -> Option<&'static str> {
  565. self.tags.iter()
  566. .find(|kv| kv.0 == key)
  567. .map(|kv| kv.1)
  568. }
  569. }
  570. #[allow(unused_imports, unused_variables)]
  571. #[cfg(test)]
  572. mod tests {
  573. use super::*;
  574. use test::{black_box, Bencher};
  575. #[test]
  576. fn it_uses_the_new_tag_k_only_shortcut() {
  577. let tag_value = "one";
  578. let color = "red";
  579. let time = now();
  580. let m = measure!(@make_meas test, t(color), t(tag_value), tm(time));
  581. assert_eq!(m.get_tag("color"), Some("red"));
  582. assert_eq!(m.get_tag("tag_value"), Some("one"));
  583. assert_eq!(m.timestamp, Some(time));
  584. }
  585. #[test]
  586. fn it_uses_measure_macro_parenthesis_syntax() {
  587. let m = measure!(@make_meas test, t(a,"b"), i(n,1), f(x,1.1), tm(1));
  588. assert_eq!(m.key, "test");
  589. assert_eq!(m.get_tag("a"), Some("b"));
  590. assert_eq!(m.get_field("n"), Some(&OwnedValue::Integer(1)));
  591. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  592. assert_eq!(m.timestamp, Some(1));
  593. }
  594. #[test]
  595. fn it_uses_measure_macro_on_a_self_attribute() {
  596. struct A {
  597. pub influx: InfluxWriter,
  598. }
  599. impl A {
  600. fn f(&self) {
  601. measure!(self.influx, test, t(color, "red"), i(n, 1));
  602. }
  603. }
  604. let a = A { influx: InfluxWriter::default() };
  605. a.f();
  606. }
  607. #[test]
  608. fn it_clones_an_influx_writer_to_check_both_drop() {
  609. let influx = InfluxWriter::default();
  610. measure!(influx, drop_test, i(a, 1), i(b, 2));
  611. {
  612. let influx = influx.clone();
  613. thread::spawn(move || {
  614. measure!(influx, drop_test, i(a, 3), i(b, 4));
  615. });
  616. }
  617. }
  618. #[bench]
  619. fn influx_writer_send_basic(b: &mut Bencher) {
  620. let m = InfluxWriter::new("localhost", "test", "var/log/influx-test.log", 4000);
  621. b.iter(|| {
  622. measure!(m, test, tag[color; "red"], int[n; 1]); //, float[p; 1.234]);
  623. });
  624. }
  625. #[bench]
  626. fn influx_writer_send_price(b: &mut Bencher) {
  627. let m = InfluxWriter::new("localhost", "test", "var/log/influx-test.log", 4000);
  628. b.iter(|| {
  629. measure!(m, test,
  630. t(ticker, t!(xmr-btc).as_str()),
  631. t(exchange, "plnx"),
  632. d(bid, d128::zero()),
  633. d(ask, d128::zero()),
  634. );
  635. });
  636. }
  637. #[test]
  638. fn it_checks_color_tag_error_in_non_doctest() {
  639. let (tx, rx) = channel();
  640. measure!(tx, test, tag[color;"red"], int[n;1]);
  641. let meas: OwnedMeasurement = rx.recv().unwrap();
  642. assert_eq!(meas.get_tag("color"), Some("red"), "meas = \n {:?} \n", meas);
  643. }
  644. #[test]
  645. fn it_uses_the_make_meas_pattern_of_the_measure_macro() {
  646. let meas = measure!(@make_meas test_measurement,
  647. tag [ one => "a" ],
  648. tag [ two => "b" ],
  649. int [ three => 2 ],
  650. float [ four => 1.2345 ],
  651. string [ five => String::from("d") ],
  652. bool [ six => true ],
  653. int [ seven => { 1 + 2 } ],
  654. time [ 1 ]
  655. );
  656. assert_eq!(meas.key, "test_measurement");
  657. assert_eq!(meas.get_tag("one"), Some("a"));
  658. assert_eq!(meas.get_tag("two"), Some("b"));
  659. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  660. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  661. assert_eq!(meas.timestamp, Some(1));
  662. }
  663. #[test]
  664. fn it_uses_the_measure_macro() {
  665. let (tx, rx) = channel();
  666. measure!(tx, test_measurement,
  667. tag [ one => "a" ],
  668. tag [ two => "b" ],
  669. int [ three => 2 ],
  670. float [ four => 1.2345 ],
  671. string [ five => String::from("d") ],
  672. bool [ six => true ],
  673. int [ seven => { 1 + 2 } ],
  674. time [ 1 ]
  675. );
  676. thread::sleep(Duration::from_millis(10));
  677. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  678. assert_eq!(meas.key, "test_measurement");
  679. assert_eq!(meas.get_tag("one"), Some("a"));
  680. assert_eq!(meas.get_tag("two"), Some("b"));
  681. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  682. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  683. assert_eq!(meas.timestamp, Some(1));
  684. }
  685. #[test]
  686. fn it_uses_measure_macro_for_d128_and_uuid() {
  687. let (tx, rx) = channel();
  688. let u = Uuid::new_v4();
  689. let d = d128::zero();
  690. let t = now();
  691. measure!(tx, test_measurement,
  692. tag[one; "a"],
  693. d128[two; d],
  694. uuid[three; u],
  695. time[t]
  696. );
  697. thread::sleep(Duration::from_millis(10));
  698. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  699. assert_eq!(meas.key, "test_measurement");
  700. assert_eq!(meas.get_tag("one"), Some("a"));
  701. assert_eq!(meas.get_field("two"), Some(&OwnedValue::D128(d128::zero())));
  702. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Uuid(u)));
  703. assert_eq!(meas.timestamp, Some(t));
  704. }
  705. #[test]
  706. fn it_uses_the_measure_macro_alt_syntax() {
  707. let (tx, rx) = channel();
  708. measure!(tx, test_measurement,
  709. tag[one; "a"],
  710. tag[two; "b"],
  711. int[three; 2],
  712. float[four; 1.2345],
  713. string[five; String::from("d")],
  714. bool [ six => true ],
  715. int[seven; { 1 + 2 }],
  716. time[1]
  717. );
  718. thread::sleep(Duration::from_millis(10));
  719. let meas: OwnedMeasurement = rx.try_recv().unwrap();
  720. assert_eq!(meas.key, "test_measurement");
  721. assert_eq!(meas.get_tag("one"), Some("a"));
  722. assert_eq!(meas.get_tag("two"), Some("b"));
  723. assert_eq!(meas.get_field("three"), Some(&OwnedValue::Integer(2)));
  724. assert_eq!(meas.get_field("seven"), Some(&OwnedValue::Integer(3)));
  725. assert_eq!(meas.timestamp, Some(1));
  726. }
  727. #[test]
  728. fn it_checks_that_fields_are_separated_correctly() {
  729. let m = measure!(@make_meas test, t[a; "one"], t[b; "two"], f[x; 1.1], f[y; -1.1]);
  730. assert_eq!(m.key, "test");
  731. assert_eq!(m.get_tag("a"), Some("one"));
  732. assert_eq!(m.get_field("x"), Some(&OwnedValue::Float(1.1)));
  733. let mut buf = String::new();
  734. serialize_owned(&m, &mut buf);
  735. assert!(buf.contains("b=two x=1.1,y=-1.1"), "buf = {}", buf);
  736. }
  737. #[test]
  738. fn try_to_break_measure_macro() {
  739. let (tx, _) = channel();
  740. measure!(tx, one, tag[x=>"y"], int[n;1]);
  741. measure!(tx, one, tag[x;"y"], int[n;1],);
  742. struct A {
  743. pub one: i32,
  744. pub two: i32,
  745. }
  746. struct B {
  747. pub a: A
  748. }
  749. let b = B { a: A { one: 1, two: 2 } };
  750. let m = measure!(@make_meas test, t(name, "a"), i(a, b.a.one));
  751. assert_eq!(m.get_field("a"), Some(&OwnedValue::Integer(1)));
  752. }
  753. #[bench]
  754. fn measure_macro_small(b: &mut Bencher) {
  755. let (tx, rx) = channel();
  756. let listener = thread::spawn(move || {
  757. loop { if rx.recv().is_err() { break } }
  758. });
  759. b.iter(|| {
  760. measure!(tx, test, tag[color; "red"], int[n; 1], time[now()]);
  761. });
  762. }
  763. #[bench]
  764. fn measure_macro_medium(b: &mut Bencher) {
  765. let (tx, rx) = channel();
  766. let listener = thread::spawn(move || {
  767. loop { if rx.recv().is_err() { break } }
  768. });
  769. b.iter(|| {
  770. measure!(tx, test,
  771. tag[color; "red"],
  772. tag[mood => "playful"],
  773. tag [ ticker => "xmr_btc" ],
  774. float[ price => 1.2345 ],
  775. float[ amount => 56.323],
  776. int[n; 1],
  777. time[now()]
  778. );
  779. });
  780. }
  781. #[cfg(feature = "warnings")]
  782. #[test]
  783. #[ignore]
  784. fn it_spawns_a_writer_thread_and_sends_dummy_measurement_to_influxdb() {
  785. let ctx = zmq::Context::new();
  786. let socket = push(&ctx).unwrap();
  787. let (tx, rx) = channel();
  788. let w = writer(tx.clone());
  789. let mut buf = String::with_capacity(4096);
  790. let mut meas = Measurement::new("rust_test");
  791. meas.add_tag("a", "t");
  792. meas.add_field("c", Value::Float(1.23456));
  793. let now = now();
  794. meas.set_timestamp(now);
  795. serialize(&meas, &mut buf);
  796. socket.send_str(&buf, 0).unwrap();
  797. drop(w);
  798. }
  799. #[test]
  800. fn it_serializes_a_measurement_in_place() {
  801. let mut buf = String::with_capacity(4096);
  802. let mut meas = Measurement::new("rust_test");
  803. meas.add_tag("a", "b");
  804. meas.add_field("c", Value::Float(1.0));
  805. let now = now();
  806. meas.set_timestamp(now);
  807. serialize(&meas, &mut buf);
  808. let ans = format!("rust_test,a=b c=1 {}", now);
  809. assert_eq!(buf, ans);
  810. }
  811. #[test]
  812. fn it_serializes_a_hard_to_serialize_message() {
  813. let raw = r#"error encountered trying to send krkn order: Other("Failed to send http request: Other("Resource temporarily unavailable (os error 11)")")"#;
  814. let mut buf = String::new();
  815. let mut server_resp = String::new();
  816. let mut m = Measurement::new("rust_test");
  817. m.add_field("s", Value::String(&raw));
  818. let now = now();
  819. m.set_timestamp(now);
  820. serialize(&m, &mut buf);
  821. println!("{}", buf);
  822. buf.push_str("\n");
  823. let buf_copy = buf.clone();
  824. buf.push_str(&buf_copy);
  825. println!("{}", buf);
  826. let url = Url::parse_with_params("http://localhost:8086/write", &[("db", "test"), ("precision", "ns")]).expect("influx writer url should parse");
  827. let client = Client::new();
  828. match client.post(url.clone())
  829. .body(&buf)
  830. .send() {
  831. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  832. Ok(mut resp) => {
  833. resp.read_to_string(&mut server_resp).unwrap();
  834. panic!("{}", server_resp);
  835. }
  836. Err(why) => {
  837. panic!(why)
  838. }
  839. }
  840. }
  841. #[bench]
  842. fn serialize_owned_longer(b: &mut Bencher) {
  843. let mut buf = String::with_capacity(1024);
  844. let m =
  845. OwnedMeasurement::new("test")
  846. .add_tag("one", "a")
  847. .add_tag("two", "b")
  848. .add_tag("ticker", "xmr_btc")
  849. .add_tag("exchange", "plnx")
  850. .add_tag("side", "bid")
  851. .add_field("three", OwnedValue::Float(1.2345))
  852. .add_field("four", OwnedValue::Integer(57))
  853. .add_field("five", OwnedValue::Boolean(true))
  854. .add_field("six", OwnedValue::String(String::from("abcdefghijklmnopqrstuvwxyz")))
  855. .set_timestamp(now());
  856. b.iter(|| {
  857. serialize_owned(&m, &mut buf);
  858. buf.clear()
  859. });
  860. }
  861. #[bench]
  862. fn serialize_owned_simple(b: &mut Bencher) {
  863. let mut buf = String::with_capacity(1024);
  864. let m =
  865. OwnedMeasurement::new("test")
  866. .add_tag("one", "a")
  867. .add_tag("two", "b")
  868. .add_field("three", OwnedValue::Float(1.2345))
  869. .add_field("four", OwnedValue::Integer(57))
  870. .set_timestamp(now());
  871. b.iter(|| {
  872. serialize_owned(&m, &mut buf);
  873. buf.clear()
  874. });
  875. }
  876. #[test]
  877. fn it_serializes_a_hard_to_serialize_message_from_owned() {
  878. let raw = r#"error encountered trying to send krkn order: Other("Failed to send http request: Other("Resource temporarily unavailable (os error 11)")")"#;
  879. let mut buf = String::new();
  880. let mut server_resp = String::new();
  881. let m = OwnedMeasurement::new("rust_test")
  882. .add_field("s", OwnedValue::String(raw.to_string()))
  883. .set_timestamp(now());
  884. serialize_owned(&m, &mut buf);
  885. println!("{}", buf);
  886. buf.push_str("\n");
  887. let buf_copy = buf.clone();
  888. buf.push_str(&buf_copy);
  889. println!("{}", buf);
  890. let url = Url::parse_with_params("http://localhost:8086/write", &[("db", "test"), ("precision", "ns")]).expect("influx writer url should parse");
  891. let client = Client::new();
  892. match client.post(url.clone())
  893. .body(&buf)
  894. .send() {
  895. Ok(Response { status, .. }) if status == StatusCode::NoContent => {}
  896. Ok(mut resp) => {
  897. resp.read_to_string(&mut server_resp).unwrap();
  898. panic!("{}", server_resp);
  899. }
  900. Err(why) => {
  901. panic!(why)
  902. }
  903. }
  904. }
  905. }