Skip to content

Commit 2d95f84

Browse files
committed
Add performance counters gated by metrics feature
1 parent c5f620e commit 2d95f84

16 files changed

+285
-14
lines changed

Cargo.toml

+3-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ once_cell = "1.7.2"
2828
pem = "3.0"
2929
percent-encoding = "2.1.0"
3030
pin-project = "1.0.2"
31-
serde = "1"
31+
serde = { version = "1", features = ["derive", "rc"] }
3232
serde_json = "1"
3333
socket2 = "0.5.2"
3434
thiserror = "1.0.4"
@@ -78,6 +78,7 @@ rand = "0.8.0"
7878

7979
[features]
8080
default = [
81+
"metrics",
8182
"flate2/zlib",
8283
"mysql_common/bigdecimal",
8384
"mysql_common/rust_decimal",
@@ -95,6 +96,7 @@ default-rustls = [
9596
"derive",
9697
"rustls-tls",
9798
]
99+
metrics = []
98100
minimal = ["flate2/zlib"]
99101
native-tls-tls = ["native-tls", "tokio-native-tls"]
100102
rustls-tls = [

src/buffer_pool.rs

+22-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
// option. All files in the project carrying such notice may not be copied,
77
// modified, or distributed except according to those terms.
88

9+
use crate::metrics::BufferPoolMetrics;
910
use crossbeam::queue::ArrayQueue;
1011
use std::{mem::replace, ops::Deref, sync::Arc};
1112

@@ -14,6 +15,7 @@ pub struct BufferPool {
1415
buffer_size_cap: usize,
1516
buffer_init_cap: usize,
1617
pool: ArrayQueue<Vec<u8>>,
18+
metrics: BufferPoolMetrics,
1719
}
1820

1921
impl BufferPool {
@@ -37,14 +39,21 @@ impl BufferPool {
3739
pool: ArrayQueue::new(pool_cap),
3840
buffer_size_cap,
3941
buffer_init_cap,
42+
metrics: Default::default(),
4043
}
4144
}
4245

4346
pub fn get(self: &Arc<Self>) -> PooledBuf {
44-
let buf = self
45-
.pool
46-
.pop()
47-
.unwrap_or_else(|| Vec::with_capacity(self.buffer_init_cap));
47+
let buf = match self.pool.pop() {
48+
Some(buf) => {
49+
self.metrics.reuses.incr();
50+
buf
51+
}
52+
None => {
53+
self.metrics.creations.incr();
54+
Vec::with_capacity(self.buffer_init_cap)
55+
}
56+
};
4857
debug_assert_eq!(buf.len(), 0);
4958
PooledBuf(buf, self.clone())
5059
}
@@ -64,7 +73,15 @@ impl BufferPool {
6473
buf.shrink_to(self.buffer_size_cap);
6574

6675
// ArrayQueue will make sure to drop the buffer if capacity is exceeded
67-
let _ = self.pool.push(buf);
76+
match self.pool.push(buf) {
77+
Ok(()) => self.metrics.returns.incr(),
78+
Err(_buf) => self.metrics.discards.incr(),
79+
};
80+
}
81+
82+
#[cfg(feature = "metrics")]
83+
pub(crate) fn snapshot_metrics(&self) -> BufferPoolMetrics {
84+
self.metrics.clone()
6885
}
6986
}
7087

src/conn/mod.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ use crate::{
3939
consts::{CapabilityFlags, Command, StatusFlags},
4040
error::*,
4141
io::Stream,
42+
metrics::ConnMetrics,
4243
opts::Opts,
4344
queryable::{
4445
query_result::{QueryResult, ResultSetMeta},
@@ -59,6 +60,8 @@ const DEFAULT_WAIT_TIMEOUT: usize = 28800;
5960

6061
/// Helper that asynchronously disconnects the givent connection on the default tokio executor.
6162
fn disconnect(mut conn: Conn) {
63+
conn.metrics().disconnects.incr();
64+
6265
let disconnected = conn.inner.disconnected;
6366

6467
// Mark conn as disconnected.
@@ -119,6 +122,7 @@ struct ConnInner {
119122
/// One-time connection-level infile handler.
120123
infile_handler:
121124
Option<Pin<Box<dyn Future<Output = crate::Result<InfileData>> + Send + Sync + 'static>>>,
125+
conn_metrics: Arc<ConnMetrics>,
122126
}
123127

124128
impl fmt::Debug for ConnInner {
@@ -140,6 +144,7 @@ impl fmt::Debug for ConnInner {
140144
impl ConnInner {
141145
/// Constructs an empty connection.
142146
fn empty(opts: Opts) -> ConnInner {
147+
let conn_metrics: Arc<ConnMetrics> = Default::default();
143148
ConnInner {
144149
capabilities: opts.get_capabilities(),
145150
status: StatusFlags::empty(),
@@ -154,7 +159,7 @@ impl ConnInner {
154159
tx_status: TxStatus::None,
155160
last_io: Instant::now(),
156161
wait_timeout: Duration::from_secs(0),
157-
stmt_cache: StmtCache::new(opts.stmt_cache_size()),
162+
stmt_cache: StmtCache::new(opts.stmt_cache_size(), conn_metrics.clone()),
158163
socket: opts.socket().map(Into::into),
159164
opts,
160165
nonce: Vec::default(),
@@ -164,6 +169,7 @@ impl ConnInner {
164169
server_key: None,
165170
infile_handler: None,
166171
reset_upon_returning_to_a_pool: false,
172+
conn_metrics,
167173
}
168174
}
169175

@@ -175,6 +181,18 @@ impl ConnInner {
175181
.as_mut()
176182
.ok_or_else(|| DriverError::ConnectionClosed.into())
177183
}
184+
185+
fn set_pool(&mut self, pool: Option<Pool>) {
186+
let conn_metrics = if let Some(ref pool) = pool {
187+
Arc::clone(&pool.inner.metrics.conn)
188+
} else {
189+
Default::default()
190+
};
191+
self.conn_metrics = Arc::clone(&conn_metrics);
192+
self.stmt_cache.conn_metrics = conn_metrics;
193+
194+
self.pool = pool;
195+
}
178196
}
179197

180198
/// MySql server connection.
@@ -926,6 +944,8 @@ impl Conn {
926944
conn.run_init_commands().await?;
927945
conn.run_setup_commands().await?;
928946

947+
conn.metrics().connects.incr();
948+
929949
Ok(conn)
930950
}
931951
.boxed()
@@ -1162,6 +1182,10 @@ impl Conn {
11621182
self.inner.stmt_cache.clear();
11631183
self.inner.infile_handler = None;
11641184
self.run_setup_commands().await?;
1185+
// self.inner.set_pool(pool);
1186+
1187+
// TODO: clear some metrics?
1188+
11651189
Ok(())
11661190
}
11671191

@@ -1276,6 +1300,10 @@ impl Conn {
12761300

12771301
Ok(BinlogStream::new(self))
12781302
}
1303+
1304+
pub(crate) fn metrics(&self) -> &ConnMetrics {
1305+
&self.inner.conn_metrics
1306+
}
12791307
}
12801308

12811309
#[cfg(test)]

src/conn/pool/futures/get_conn.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,10 @@ impl Future for GetConn {
142142

143143
return match result {
144144
Ok(mut c) => {
145-
c.inner.pool = Some(pool);
145+
c.inner.set_pool(Some(pool));
146146
c.inner.reset_upon_returning_to_a_pool =
147147
self.reset_upon_returning_to_a_pool;
148+
c.metrics().connects.incr();
148149
Poll::Ready(Ok(c))
149150
}
150151
Err(e) => {
@@ -160,7 +161,8 @@ impl Future for GetConn {
160161
self.inner = GetConnInner::Done;
161162

162163
let pool = self.pool_take();
163-
c.inner.pool = Some(pool);
164+
pool.inner.metrics.reuses.incr();
165+
c.inner.set_pool(Some(pool));
164166
c.inner.reset_upon_returning_to_a_pool =
165167
self.reset_upon_returning_to_a_pool;
166168
return Poll::Ready(Ok(c));

src/conn/pool/mod.rs

+29-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use std::{
2525
use crate::{
2626
conn::{pool::futures::*, Conn},
2727
error::*,
28+
metrics::PoolMetrics,
2829
opts::{Opts, PoolOpts},
2930
queryable::transaction::{Transaction, TxOpts},
3031
};
@@ -121,6 +122,10 @@ impl Waitlist {
121122
self.queue.remove(&tmp);
122123
}
123124

125+
fn len(&self) -> usize {
126+
self.queue.len()
127+
}
128+
124129
fn is_empty(&self) -> bool {
125130
self.queue.is_empty()
126131
}
@@ -177,6 +182,7 @@ pub struct Inner {
177182
close: atomic::AtomicBool,
178183
closed: atomic::AtomicBool,
179184
exchange: Mutex<Exchange>,
185+
pub(crate) metrics: PoolMetrics,
180186
}
181187

182188
/// Asynchronous pool of MySql connections.
@@ -190,7 +196,7 @@ pub struct Inner {
190196
#[derive(Debug, Clone)]
191197
pub struct Pool {
192198
opts: Opts,
193-
inner: Arc<Inner>,
199+
pub(super) inner: Arc<Inner>,
194200
drop: mpsc::UnboundedSender<Option<Conn>>,
195201
}
196202

@@ -219,6 +225,7 @@ impl Pool {
219225
exist: 0,
220226
recycler: Some((rx, pool_opts)),
221227
}),
228+
metrics: Default::default(),
222229
}),
223230
drop: tx,
224231
}
@@ -232,6 +239,7 @@ impl Pool {
232239

233240
/// Async function that resolves to `Conn`.
234241
pub fn get_conn(&self) -> GetConn {
242+
self.inner.metrics.gets.incr();
235243
let reset_connection = self.opts.pool_opts().reset_connection();
236244
GetConn::new(self, reset_connection)
237245
}
@@ -250,6 +258,11 @@ impl Pool {
250258
DisconnectPool::new(self)
251259
}
252260

261+
#[cfg(feature = "metrics")]
262+
pub fn snapshot_metrics(&self) -> PoolMetrics {
263+
self.inner.metrics.clone()
264+
}
265+
253266
/// A way to return connection taken from a pool.
254267
fn return_conn(&mut self, conn: Conn) {
255268
// NOTE: we're not in async context here, so we can't block or return NotReady
@@ -258,6 +271,8 @@ impl Pool {
258271
}
259272

260273
fn send_to_recycler(&self, conn: Conn) {
274+
self.inner.metrics.recycler.recycles.incr();
275+
261276
if let Err(conn) = self.drop.send(Some(conn)) {
262277
let conn = conn.0.unwrap();
263278

@@ -354,6 +369,19 @@ impl Pool {
354369
let mut exchange = self.inner.exchange.lock().unwrap();
355370
exchange.waiting.remove(queue_id);
356371
}
372+
373+
/// Returns the number of
374+
/// - open connections,
375+
/// - idling connections in the pool and
376+
/// - tasks waiting for a connection.
377+
pub fn queue_stats(&self) -> (usize, usize, usize) {
378+
let exchange = self.inner.exchange.lock().unwrap();
379+
(
380+
exchange.exist,
381+
exchange.available.len(),
382+
exchange.waiting.len(),
383+
)
384+
}
357385
}
358386

359387
impl Drop for Conn {

src/conn/pool/recycler.rs

+5
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,10 @@ impl Future for Recycler {
6767
let mut exchange = $self.inner.exchange.lock().unwrap();
6868
if $pool_is_closed || exchange.available.len() >= $self.pool_opts.active_bound() {
6969
drop(exchange);
70+
$self.inner.metrics.recycler.discards.incr();
7071
$self.discard.push($conn.close_conn().boxed());
7172
} else {
73+
$self.inner.metrics.recycler.recycled_returnals.incr();
7274
exchange.available.push_back($conn.into());
7375
if let Some(w) = exchange.waiting.pop() {
7476
w.wake();
@@ -80,11 +82,14 @@ impl Future for Recycler {
8082
macro_rules! conn_decision {
8183
($self:ident, $conn:ident) => {
8284
if $conn.inner.stream.is_none() || $conn.inner.disconnected {
85+
$self.inner.metrics.recycler.discards.incr();
8386
// drop unestablished connection
8487
$self.discard.push(futures_util::future::ok(()).boxed());
8588
} else if $conn.inner.tx_status != TxStatus::None || $conn.has_pending_result() {
89+
$self.inner.metrics.recycler.cleans.incr();
8690
$self.cleaning.push($conn.cleanup_for_pool().boxed());
8791
} else if $conn.expired() || close {
92+
$self.inner.metrics.recycler.discards.incr();
8893
$self.discard.push($conn.close_conn().boxed());
8994
} else if $conn.inner.reset_upon_returning_to_a_pool {
9095
$self.reset.push($conn.reset_for_pool().boxed());

src/conn/routines/change_user.rs

+2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ pub struct ChangeUser;
1717

1818
impl Routine<()> for ChangeUser {
1919
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
20+
conn.metrics().routines.change_user.incr();
21+
2022
#[cfg(feature = "tracing")]
2123
let span = debug_span!(
2224
"mysql_async::change_user",

src/conn/routines/exec.rs

+2
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ impl<'a> ExecRoutine<'a> {
2525

2626
impl Routine<()> for ExecRoutine<'_> {
2727
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
28+
conn.metrics().routines.execs.incr();
29+
2830
#[cfg(feature = "tracing")]
2931
let span = info_span!(
3032
"mysql_async::exec",

src/conn/routines/next_set.rs

+2
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ where
2424
P: Protocol,
2525
{
2626
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
27+
conn.metrics().routines.next_sets.incr();
28+
2729
#[cfg(feature = "tracing")]
2830
let span = debug_span!(
2931
"mysql_async::next_set",

src/conn/routines/ping.rs

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ pub struct PingRoutine;
1414

1515
impl Routine<()> for PingRoutine {
1616
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
17+
conn.metrics().routines.pings.incr();
18+
1719
#[cfg(feature = "tracing")]
1820
let span = debug_span!("mysql_async::ping", mysql_async.connection.id = conn.id());
1921

src/conn/routines/prepare.rs

+2
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ impl PrepareRoutine {
2626

2727
impl Routine<Arc<StmtInner>> for PrepareRoutine {
2828
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<Arc<StmtInner>>> {
29+
conn.metrics().routines.prepares.incr();
30+
2931
#[cfg(feature = "tracing")]
3032
let span = info_span!(
3133
"mysql_async::prepare",

src/conn/routines/query.rs

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ impl<'a, L: TracingLevel> QueryRoutine<'a, L> {
2929

3030
impl<L: TracingLevel> Routine<()> for QueryRoutine<'_, L> {
3131
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
32+
conn.metrics().routines.queries.incr();
33+
3234
#[cfg(feature = "tracing")]
3335
let span = create_span!(
3436
L::LEVEL,

src/conn/routines/reset.rs

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ pub struct ResetRoutine;
1414

1515
impl Routine<()> for ResetRoutine {
1616
fn call<'a>(&'a mut self, conn: &'a mut Conn) -> BoxFuture<'a, crate::Result<()>> {
17+
conn.metrics().routines.resets.incr();
18+
1719
#[cfg(feature = "tracing")]
1820
let span = debug_span!("mysql_async::reset", mysql_async.connection.id = conn.id());
1921

0 commit comments

Comments
 (0)