kmip_protocol/net/sync_pool.rs
1//! KMIP connection pool
2//!
3//! Used to:
4//! - Avoid repeated TCP connection setup and TLS session establishment
5//! for mutiple KMIP requests made close together in time.
6//! - Handle loss of connectivity by re-creating the connection when an
7//! existing connection is considered to be "broken" at the network
8//! level.
9use core::fmt::Display;
10use core::ops::{Deref, DerefMut};
11use std::string::String;
12use std::{sync::Arc, time::Duration};
13
14use crate::net::ConnectionSettings;
15use crate::net::common::error::{NetError, NetResult};
16
17use log::error;
18use r2d2::PooledConnection;
19
20cfg_if::cfg_if! {
21 if #[cfg(any(feature = "tls-with-openssl", feature = "tls-with-openssl-vendored"))] {
22 use crate::net::tls::openssl::{Client, connect};
23 } else if #[cfg(feature = "tls-with-rustls")] {
24 use crate::net::tls::rustls::{Client, connect};
25 } else {
26 pub type Client = crate::net::client::Client<std::net::TcpStream>;
27 }
28}
29
30//------------ KmipConnError -------------------------------------------------
31
32#[derive(Clone, Debug)]
33pub struct KmipConnError(String);
34
35impl From<r2d2::Error> for KmipConnError {
36 fn from(err: r2d2::Error) -> Self {
37 Self(format!("{err}"))
38 }
39}
40
41impl Display for KmipConnError {
42 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
43 write!(f, "{}", self.0)
44 }
45}
46
47//------------ KmipConn ------------------------------------------------------
48
49/// A KMIP connection pool connection.
50pub struct KmipConn {
51 conn: PooledConnection<ConnectionManager>,
52}
53
54impl KmipConn {
55 fn new(conn: PooledConnection<ConnectionManager>) -> Self {
56 Self { conn }
57 }
58}
59
60impl Deref for KmipConn {
61 type Target = Client;
62
63 fn deref(&self) -> &Self::Target {
64 self.conn.deref()
65 }
66}
67
68impl DerefMut for KmipConn {
69 fn deref_mut(&mut self) -> &mut Self::Target {
70 self.conn.deref_mut()
71 }
72}
73
74/// A pool of KMIP clients.
75///
76/// Connections are re-used until timed out or the connection is lost, and are
77/// re-created as necessary.
78#[derive(Clone, Debug)]
79pub struct ConnPool {
80 server_id: String,
81 conn_settings: Arc<ConnectionSettings>,
82 pool: r2d2::Pool<ConnectionManager>,
83}
84
85impl ConnPool {
86 pub fn new(
87 server_id: String,
88 conn_settings: Arc<ConnectionSettings>,
89 max_conncurrent_connections: u32,
90 max_life_time: Option<Duration>,
91 max_idle_time: Option<Duration>,
92 ) -> Result<ConnPool, KmipConnError> {
93 let pool = r2d2::Pool::builder()
94 // Don't pre-create idle connections to the KMIP server
95 .min_idle(Some(0))
96 // Create at most this many concurrent connections to the KMIP
97 // server
98 .max_size(max_conncurrent_connections)
99 // Don't verify that a connection is usable when fetching it from
100 // the pool (as doing so requires sending a request to the server
101 // and we might as well just try the actual request that we want
102 // the connection for)
103 .test_on_check_out(false)
104 // Don't use the default logging behaviour as `[ERROR] [r2d2]
105 // Server error: ...` is a bit confusing for end users who
106 // shouldn't know or care that we use the r2d2 crate.
107 .error_handler(Box::new(ErrorLoggingHandler))
108 // Don't keep using the same connection for longer than around N
109 // minutes (unless in use in which case it will wait until the
110 // connection is returned to the pool before closing it) - maybe
111 // long held connections would run into problems with some
112 // firewalls.
113 .max_lifetime(max_life_time)
114 // Don't keep connections open that were not used in the last N
115 // minutes.
116 .idle_timeout(max_idle_time)
117 // Don't wait longer than N seconds for a new connection to be
118 // established, instead try again to connect.
119 .connection_timeout(conn_settings.connect_timeout.unwrap_or(Duration::from_secs(30)))
120 // Use our connection manager to create connections in the pool
121 // and to verify their health
122 .build(ConnectionManager {
123 conn_settings: conn_settings.clone(),
124 })?;
125
126 Ok(Self {
127 server_id,
128 conn_settings,
129 pool,
130 })
131 }
132
133 pub fn server_id(&self) -> &str {
134 &self.server_id
135 }
136
137 pub fn conn_settings(&self) -> &ConnectionSettings {
138 &self.conn_settings
139 }
140
141 pub fn get(&self) -> Result<KmipConn, KmipConnError> {
142 Ok(KmipConn::new(self.pool.get()?))
143 }
144}
145
146/// Manages KMIP TCP + TLS connection creation.
147///
148/// Uses the [r2d2] crate to manage a pool of connections.
149///
150/// [r2d2]: https://crates.io/crates/r2d2/
151#[derive(Debug)]
152pub struct ConnectionManager {
153 conn_settings: Arc<ConnectionSettings>,
154}
155
156impl ConnectionManager
157where
158 Self: r2d2::ManageConnection,
159{
160 /// Create a pool of up-to N TCP + TLS connections to the KMIP server.
161 #[rustfmt::skip]
162 pub fn create_connection_pool(
163 server_id: String,
164 conn_settings: Arc<ConnectionSettings>,
165 max_conncurrent_connections: u32,
166 max_life_time: Option<Duration>,
167 max_idle_time: Option<Duration>,
168 ) -> Result<ConnPool, KmipConnError> {
169 ConnPool::new(
170 server_id,
171 conn_settings,
172 max_conncurrent_connections,
173 max_life_time,
174 max_idle_time,
175 )
176 }
177
178 /// Connect using the given connection settings to a KMIP server.
179 ///
180 /// This function creates a new connection to the server. The connection
181 /// is NOT taken from the connection pool.
182 pub fn connect_one_off(settings: &ConnectionSettings) -> NetResult<Client> {
183 connect(settings)
184 }
185}
186
187impl r2d2::ManageConnection for ConnectionManager {
188 type Connection = Client;
189
190 type Error = NetError;
191
192 /// Establishes a KMIP server connection which will be added to the
193 /// connection pool.
194 fn connect(&self) -> Result<Self::Connection, Self::Error> {
195 Self::connect_one_off(&self.conn_settings)
196 }
197
198 /// This function is never used because the [r2d2] `test_on_check_out`
199 /// flag is set to false when the connection pool is created.
200 ///
201 /// [r2d2]: https://crates.io/crates/r2d2/
202 fn is_valid(&self, _conn: &mut Self::Connection) -> Result<(), Self::Error> {
203 unreachable!()
204 }
205
206 /// Quickly verify if an existing connection is broken.
207 ///
208 /// Used to discard and re-create connections that encounter multiple
209 /// connection related errors.
210 fn has_broken(&self, conn: &mut Self::Connection) -> bool {
211 conn.connection_error_count() > 1
212 }
213}
214
215/// Logs connection pool related connection error messages using the format
216/// `"[<LEVEL>] Pool error: ..."` instead of
217/// the default [r2d2] `"[ERROR] [r2d2] Server error: ..."` format. Assumes
218/// that the logging framework will include the logging module context in the
219/// logged message, i.e. `xxx::kmip::xxx` and thus we don't need to mention
220/// KMIP in the logged message content.
221///
222/// Rationale:
223/// - The use of the [r2d2] crate is an internal detail which of no use to
224/// end users consulting the logs and which we may change at any time.
225/// - Krill should be the one to determine the appropriate level to log a
226/// connection issue at, not [r2d2].
227#[derive(Debug)]
228struct ErrorLoggingHandler;
229
230impl<E> r2d2::HandleError<E> for ErrorLoggingHandler
231where
232 E: std::fmt::Display,
233{
234 fn handle_error(&self, err: E) {
235 error!("Pool error: {}", err)
236 }
237}