-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathpostgrespool.rs
376 lines (324 loc) · 12.6 KB
/
postgrespool.rs
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use std::{collections::HashMap, path::PathBuf, str::FromStr, sync::Arc};
use crate::util::{self, ns_lookup::verify_ns_lookup_and_tcp_connect};
use async_trait::async_trait;
use bb8::ErrorSink;
use bb8_postgres::{
tokio_postgres::{config::Host, types::ToSql, Config},
PostgresConnectionManager,
};
use native_tls::{Certificate, TlsConnector};
use postgres_native_tls::MakeTlsConnector;
use secrecy::{ExposeSecret, Secret, SecretString};
use snafu::{prelude::*, ResultExt};
use tokio_postgres;
use super::DbConnectionPool;
use crate::sql::db_connection_pool::{
dbconnection::{postgresconn::PostgresConnection, AsyncDbConnection, DbConnection},
JoinPushDown,
};
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("ConnectionPoolError: {source}"))]
ConnectionPoolError {
source: bb8_postgres::tokio_postgres::Error,
},
#[snafu(display("ConnectionPoolRunError: {source}"))]
ConnectionPoolRunError {
source: bb8::RunError<bb8_postgres::tokio_postgres::Error>,
},
#[snafu(display("Invalid parameter: {parameter_name}"))]
InvalidParameterError { parameter_name: String },
#[snafu(display("Could not parse {parameter_name} into a valid integer"))]
InvalidIntegerParameterError {
parameter_name: String,
source: std::num::ParseIntError,
},
#[snafu(display("Cannot connect to PostgreSQL on {host}:{port}. Ensure that the host and port are correctly configured, and that the host is reachable."))]
InvalidHostOrPortError {
source: crate::util::ns_lookup::Error,
host: String,
port: u16,
},
#[snafu(display("Invalid root cert path: {path}"))]
InvalidRootCertPathError { path: String },
#[snafu(display("Failed to read cert : {source}"))]
FailedToReadCertError { source: std::io::Error },
#[snafu(display("Failed to load cert : {source}"))]
FailedToLoadCertError { source: native_tls::Error },
#[snafu(display("Failed to build tls connector : {source}"))]
FailedToBuildTlsConnectorError { source: native_tls::Error },
#[snafu(display("Postgres connection error: {source}"))]
PostgresConnectionError { source: tokio_postgres::Error },
#[snafu(display(
"Authentication failed. Ensure that the username and password are correctly configured."
))]
InvalidUsernameOrPassword { source: tokio_postgres::Error },
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug)]
pub struct PostgresConnectionPool {
pool: Arc<bb8::Pool<PostgresConnectionManager<MakeTlsConnector>>>,
join_push_down: JoinPushDown,
}
impl PostgresConnectionPool {
/// Creates a new instance of `PostgresConnectionPool`.
///
/// # Errors
///
/// Returns an error if there is a problem creating the connection pool.
pub async fn new(params: HashMap<String, SecretString>) -> Result<Self> {
// Remove the "pg_" prefix from the keys to keep backward compatibility
let params = util::remove_prefix_from_hashmap_keys(params, "pg_");
let mut connection_string = String::new();
let mut ssl_mode = "verify-full".to_string();
let mut ssl_rootcert_path: Option<PathBuf> = None;
if let Some(pg_connection_string) =
params.get("connection_string").map(Secret::expose_secret)
{
let (str, mode, cert_path) = parse_connection_string(pg_connection_string.as_str());
connection_string = str;
ssl_mode = mode;
if let Some(cert_path) = cert_path {
let sslrootcert = cert_path.as_str();
ensure!(
std::path::Path::new(sslrootcert).exists(),
InvalidRootCertPathSnafu { path: cert_path }
);
ssl_rootcert_path = Some(PathBuf::from(sslrootcert));
}
} else {
if let Some(pg_host) = params.get("host").map(Secret::expose_secret) {
connection_string.push_str(format!("host={pg_host} ").as_str());
}
if let Some(pg_user) = params.get("user").map(Secret::expose_secret) {
connection_string.push_str(format!("user={pg_user} ").as_str());
}
if let Some(pg_db) = params.get("db").map(Secret::expose_secret) {
connection_string.push_str(format!("dbname={pg_db} ").as_str());
}
if let Some(pg_pass) = params.get("pass").map(Secret::expose_secret) {
connection_string.push_str(format!("password={pg_pass} ").as_str());
}
if let Some(pg_port) = params.get("port").map(Secret::expose_secret) {
connection_string.push_str(format!("port={pg_port} ").as_str());
}
}
if let Some(pg_sslmode) = params.get("sslmode").map(Secret::expose_secret) {
match pg_sslmode.to_lowercase().as_str() {
"disable" | "require" | "prefer" | "verify-ca" | "verify-full" => {
ssl_mode = pg_sslmode.to_string();
}
_ => {
InvalidParameterSnafu {
parameter_name: "sslmode".to_string(),
}
.fail()?;
}
}
}
if let Some(pg_sslrootcert) = params.get("sslrootcert").map(Secret::expose_secret) {
ensure!(
std::path::Path::new(pg_sslrootcert).exists(),
InvalidRootCertPathSnafu {
path: pg_sslrootcert,
}
);
ssl_rootcert_path = Some(PathBuf::from(pg_sslrootcert));
}
let mode = match ssl_mode.as_str() {
"disable" => "disable",
"prefer" => "prefer",
// tokio_postgres supports only disable, require and prefer
_ => "require",
};
connection_string.push_str(format!("sslmode={mode} ").as_str());
let config = Config::from_str(connection_string.as_str()).context(ConnectionPoolSnafu)?;
verify_postgres_config(&config).await?;
let mut certs: Option<Vec<Certificate>> = None;
if let Some(path) = ssl_rootcert_path {
let buf = tokio::fs::read(path).await.context(FailedToReadCertSnafu)?;
certs = Some(parse_certs(&buf)?);
}
let tls_connector = get_tls_connector(ssl_mode.as_str(), certs)?;
let connector = MakeTlsConnector::new(tls_connector);
test_postgres_connection(connection_string.as_str(), connector.clone()).await?;
let join_push_down = get_join_context(&config);
let manager = PostgresConnectionManager::new(config, connector);
let error_sink = PostgresErrorSink::new();
let mut connection_pool_size = 10; // The BB8 default is 10
if let Some(pg_pool_size) = params
.get("connection_pool_size")
.map(Secret::expose_secret)
{
connection_pool_size = pg_pool_size.parse().context(InvalidIntegerParameterSnafu {
parameter_name: "pool_size".to_string(),
})?;
}
let pool = bb8::Pool::builder()
.max_size(connection_pool_size)
.error_sink(Box::new(error_sink))
.build(manager)
.await
.context(ConnectionPoolSnafu)?;
// Test the connection
let conn = pool.get().await.context(ConnectionPoolRunSnafu)?;
conn.execute("SELECT 1", &[])
.await
.context(ConnectionPoolSnafu)?;
Ok(PostgresConnectionPool {
pool: Arc::new(pool.clone()),
join_push_down,
})
}
/// Returns a direct connection to the underlying database.
///
/// # Errors
///
/// Returns an error if there is a problem creating the connection pool.
pub async fn connect_direct(&self) -> super::Result<PostgresConnection> {
let pool = Arc::clone(&self.pool);
let conn = pool.get_owned().await.context(ConnectionPoolRunSnafu)?;
Ok(PostgresConnection::new(conn))
}
}
fn parse_connection_string(pg_connection_string: &str) -> (String, String, Option<String>) {
let mut connection_string = String::new();
let mut ssl_mode = "verify-full".to_string();
let mut ssl_rootcert_path: Option<String> = None;
let str = pg_connection_string;
let str_params: Vec<&str> = str.split_whitespace().collect();
for param in str_params {
let param = param.split('=').collect::<Vec<&str>>();
if let (Some(&name), Some(&value)) = (param.first(), param.get(1)) {
match name {
"sslmode" => {
ssl_mode = value.to_string();
}
"sslrootcert" => {
ssl_rootcert_path = Some(value.to_string());
}
_ => {
connection_string.push_str(format!("{name}={value} ").as_str());
}
}
}
}
(connection_string, ssl_mode, ssl_rootcert_path)
}
fn get_join_context(config: &Config) -> JoinPushDown {
let mut join_push_context_str = String::new();
for host in config.get_hosts() {
join_push_context_str.push_str(&format!("host={host:?},"));
}
if !config.get_ports().is_empty() {
join_push_context_str.push_str(&format!("port={port},", port = config.get_ports()[0]));
}
if let Some(dbname) = config.get_dbname() {
join_push_context_str.push_str(&format!("db={dbname},"));
}
if let Some(user) = config.get_user() {
join_push_context_str.push_str(&format!("user={user},"));
}
JoinPushDown::AllowedFor(join_push_context_str)
}
async fn test_postgres_connection(
connection_string: &str,
connector: MakeTlsConnector,
) -> Result<()> {
match tokio_postgres::connect(connection_string, connector).await {
Ok(_) => Ok(()),
Err(err) => {
if let Some(code) = err.code() {
if *code == tokio_postgres::error::SqlState::INVALID_PASSWORD {
return Err(Error::InvalidUsernameOrPassword { source: err });
}
}
Err(Error::PostgresConnectionError { source: err })
}
}
}
async fn verify_postgres_config(config: &Config) -> Result<()> {
for host in config.get_hosts() {
for port in config.get_ports() {
if let Host::Tcp(host) = host {
verify_ns_lookup_and_tcp_connect(host, *port)
.await
.context(InvalidHostOrPortSnafu { host, port: *port })?;
}
}
}
Ok(())
}
fn get_tls_connector(ssl_mode: &str, rootcerts: Option<Vec<Certificate>>) -> Result<TlsConnector> {
let mut builder = TlsConnector::builder();
if ssl_mode == "disable" {
return builder.build().context(FailedToBuildTlsConnectorSnafu);
}
if let Some(certs) = rootcerts {
for cert in certs {
builder.add_root_certificate(cert);
}
}
builder
.danger_accept_invalid_hostnames(ssl_mode != "verify-full")
.danger_accept_invalid_certs(ssl_mode != "verify-full" && ssl_mode != "verify-ca")
.build()
.context(FailedToBuildTlsConnectorSnafu)
}
fn parse_certs(buf: &[u8]) -> Result<Vec<Certificate>> {
Certificate::from_der(buf)
.map(|x| vec![x])
.or_else(|_| {
pem::parse_many(buf)
.unwrap_or_default()
.iter()
.map(pem::encode)
.map(|s| Certificate::from_pem(s.as_bytes()))
.collect()
})
.context(FailedToLoadCertSnafu)
}
#[derive(Debug, Clone, Copy)]
struct PostgresErrorSink {}
impl PostgresErrorSink {
pub fn new() -> Self {
PostgresErrorSink {}
}
}
impl<E> ErrorSink<E> for PostgresErrorSink
where
E: std::fmt::Debug,
E: std::fmt::Display,
{
fn sink(&self, error: E) {
tracing::error!("Postgres Connection Error: {:?}", error);
}
fn boxed_clone(&self) -> Box<dyn ErrorSink<E>> {
Box::new(*self)
}
}
#[async_trait]
impl
DbConnectionPool<
bb8::PooledConnection<'static, PostgresConnectionManager<MakeTlsConnector>>,
&'static (dyn ToSql + Sync),
> for PostgresConnectionPool
{
async fn connect(
&self,
) -> super::Result<
Box<
dyn DbConnection<
bb8::PooledConnection<'static, PostgresConnectionManager<MakeTlsConnector>>,
&'static (dyn ToSql + Sync),
>,
>,
> {
let pool = Arc::clone(&self.pool);
let conn = pool.get_owned().await.context(ConnectionPoolRunSnafu)?;
Ok(Box::new(PostgresConnection::new(conn)))
}
fn join_push_down(&self) -> JoinPushDown {
self.join_push_down.clone()
}
}