1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
use crate::attributes::{Attributes, Buffered, MetricId, OnFlush, Prefixed, WithAttributes};
use crate::input::InputKind;
use crate::input::{Input, InputMetric, InputScope};
use crate::metrics;
use crate::name::MetricName;
use crate::output::socket::RetrySocket;
use crate::{CachedInput, QueuedInput};
use crate::{Flush, MetricValue};
use std::net::ToSocketAddrs;
use std::fmt::Debug;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
use std::sync::Arc;
#[cfg(not(feature = "parking_lot"))]
use std::sync::{RwLock, RwLockWriteGuard};
#[cfg(feature = "parking_lot")]
use parking_lot::{RwLock, RwLockWriteGuard};
use std::io;
#[derive(Clone, Debug)]
pub struct Graphite {
attributes: Attributes,
socket: Arc<RwLock<RetrySocket>>,
}
impl Input for Graphite {
type SCOPE = GraphiteScope;
fn metrics(&self) -> Self::SCOPE {
GraphiteScope {
attributes: self.attributes.clone(),
buffer: Arc::new(RwLock::new(String::new())),
socket: self.socket.clone(),
}
}
}
impl Graphite {
pub fn send_to<A: ToSocketAddrs + Debug + Clone>(address: A) -> io::Result<Graphite> {
debug!("Connecting to graphite {:?}", address);
let socket = Arc::new(RwLock::new(RetrySocket::new(address)?));
Ok(Graphite {
attributes: Attributes::default(),
socket,
})
}
}
impl WithAttributes for Graphite {
fn get_attributes(&self) -> &Attributes {
&self.attributes
}
fn mut_attributes(&mut self) -> &mut Attributes {
&mut self.attributes
}
}
impl Buffered for Graphite {}
#[derive(Debug, Clone)]
pub struct GraphiteScope {
attributes: Attributes,
buffer: Arc<RwLock<String>>,
socket: Arc<RwLock<RetrySocket>>,
}
impl InputScope for GraphiteScope {
fn new_metric(&self, name: MetricName, kind: InputKind) -> InputMetric {
let mut prefix = self.prefix_prepend(name.clone()).join(".");
prefix.push(' ');
let scale = match kind {
InputKind::Timer => 1000,
_ => 1,
};
let cloned = self.clone();
let metric = GraphiteMetric { prefix, scale };
let metric_id = MetricId::forge("graphite", name);
InputMetric::new(metric_id, move |value, _labels| {
cloned.print(&metric, value);
})
}
}
impl Flush for GraphiteScope {
fn flush(&self) -> io::Result<()> {
self.notify_flush_listeners();
let buf = write_lock!(self.buffer);
self.flush_inner(buf)
}
}
impl GraphiteScope {
fn print(&self, metric: &GraphiteMetric, value: MetricValue) {
let scaled_value = value / metric.scale;
let value_str = scaled_value.to_string();
let start = SystemTime::now();
let mut buffer = write_lock!(self.buffer);
match start.duration_since(UNIX_EPOCH) {
Ok(timestamp) => {
buffer.push_str(&metric.prefix);
buffer.push_str(&value_str);
buffer.push(' ');
buffer.push_str(×tamp.as_secs().to_string());
buffer.push('\n');
if buffer.len() > BUFFER_FLUSH_THRESHOLD {
metrics::GRAPHITE_OVERFLOW.mark();
warn!("Graphite Buffer Size Exceeded: {}", BUFFER_FLUSH_THRESHOLD);
let _ = self.flush_inner(buffer);
buffer = write_lock!(self.buffer);
}
}
Err(e) => {
warn!("Could not compute epoch timestamp. {}", e);
}
};
if self.is_buffered() {
if let Err(e) = self.flush_inner(buffer) {
debug!("Could not send to graphite {}", e)
}
}
}
fn flush_inner(&self, mut buf: RwLockWriteGuard<String>) -> io::Result<()> {
if buf.is_empty() {
return Ok(());
}
let mut sock = write_lock!(self.socket);
match sock.write_all(buf.as_bytes()) {
Ok(()) => {
metrics::GRAPHITE_SENT_BYTES.count(buf.len());
trace!("Sent {} bytes to graphite", buf.len());
buf.clear();
Ok(())
}
Err(e) => {
metrics::GRAPHITE_SEND_ERR.mark();
debug!("Failed to send buffer to graphite: {}", e);
Err(e)
}
}
}
}
impl WithAttributes for GraphiteScope {
fn get_attributes(&self) -> &Attributes {
&self.attributes
}
fn mut_attributes(&mut self) -> &mut Attributes {
&mut self.attributes
}
}
impl Buffered for GraphiteScope {}
impl QueuedInput for Graphite {}
impl CachedInput for Graphite {}
const BUFFER_FLUSH_THRESHOLD: usize = 65_536;
#[derive(Debug, Clone)]
pub struct GraphiteMetric {
prefix: String,
scale: isize,
}
impl Drop for GraphiteScope {
fn drop(&mut self) {
if let Err(err) = self.flush() {
warn!("Could not flush graphite metrics upon Drop: {}", err)
}
}
}
#[cfg(feature = "bench")]
mod bench {
use super::*;
use crate::attributes::*;
use crate::input::*;
#[bench]
pub fn immediate_graphite(b: &mut test::Bencher) {
let sd = Graphite::send_to("localhost:2003").unwrap().metrics();
let timer = sd.new_metric("timer".into(), InputKind::Timer);
b.iter(|| test::black_box(timer.write(2000, labels![])));
}
#[bench]
pub fn buffering_graphite(b: &mut test::Bencher) {
let sd = Graphite::send_to("localhost:2003")
.unwrap()
.buffered(Buffering::BufferSize(65465))
.metrics();
let timer = sd.new_metric("timer".into(), InputKind::Timer);
b.iter(|| test::black_box(timer.write(2000, labels![])));
}
}