Files
pgcat/src/client.rs

474 lines
19 KiB
Rust
Raw Normal View History

2022-02-04 09:28:52 -08:00
/// Implementation of the PostgreSQL client.
/// We are pretending to the server in this scenario,
/// and this module implements that.
use bytes::{Buf, BufMut, BytesMut};
2022-02-05 10:02:13 -08:00
use tokio::io::{AsyncReadExt, BufReader};
use tokio::net::{
tcp::{OwnedReadHalf, OwnedWriteHalf},
TcpStream,
};
2022-02-03 13:35:40 -08:00
2022-02-14 05:11:53 -08:00
use std::collections::HashMap;
use crate::config::get_config;
use crate::constants::*;
2022-02-03 13:35:40 -08:00
use crate::errors::Error;
use crate::messages::*;
2022-02-05 18:20:53 -08:00
use crate::pool::{ClientServerMap, ConnectionPool};
use crate::query_router::{Command, QueryRouter};
2022-02-04 16:01:35 -08:00
use crate::server::Server;
2022-02-14 10:00:55 -08:00
use crate::stats::Reporter;
2022-02-08 13:11:50 -08:00
/// The client state. One of these is created per client.
2022-02-03 13:35:40 -08:00
pub struct Client {
// The reads are buffered (8K by default).
2022-02-03 13:54:07 -08:00
read: BufReader<OwnedReadHalf>,
// We buffer the writes ourselves because we know the protocol
// better than a stock buffer.
2022-02-03 13:54:07 -08:00
write: OwnedWriteHalf,
// Internal buffer, where we place messages until we have to flush
// them to the backend.
2022-02-03 15:33:26 -08:00
buffer: BytesMut,
// The client was started with the sole reason to cancel another running query.
2022-02-04 09:28:52 -08:00
cancel_mode: bool,
// In transaction mode, the connection is released after each transaction.
// Session mode has slightly higher throughput per client, but lower capacity.
2022-02-05 15:23:21 -08:00
transaction_mode: bool,
// For query cancellation, the client is given a random process ID and secret on startup.
2022-02-04 09:28:52 -08:00
process_id: i32,
secret_key: i32,
// Clients are mapped to servers while they use them. This allows a client
// to connect and cancel a query.
2022-02-04 16:01:35 -08:00
client_server_map: ClientServerMap,
2022-02-11 11:19:40 -08:00
2022-02-14 05:11:53 -08:00
// Client parameters, e.g. user, client_encoding, etc.
#[allow(dead_code)]
2022-02-14 05:11:53 -08:00
parameters: HashMap<String, String>,
2022-02-14 10:00:55 -08:00
// Statistics
stats: Reporter,
2022-02-03 13:35:40 -08:00
}
impl Client {
2022-02-04 09:28:52 -08:00
/// Given a TCP socket, trick the client into thinking we are
/// the Postgres server. Perform the authentication and place
/// the client in query-ready mode.
2022-02-04 16:01:35 -08:00
pub async fn startup(
mut stream: TcpStream,
client_server_map: ClientServerMap,
server_info: BytesMut,
2022-02-14 10:00:55 -08:00
stats: Reporter,
2022-02-04 16:01:35 -08:00
) -> Result<Client, Error> {
let config = get_config();
let transaction_mode = config.general.pool_mode.starts_with("t");
drop(config);
2022-02-03 13:35:40 -08:00
loop {
// Could be StartupMessage or SSLRequest
// which makes this variable length.
let len = match stream.read_i32().await {
Ok(len) => len,
Err(_) => return Err(Error::ClientBadStartup),
};
// Read whatever is left.
let mut startup = vec![0u8; len as usize - 4];
match stream.read_exact(&mut startup).await {
Ok(_) => (),
Err(_) => return Err(Error::ClientBadStartup),
};
let mut bytes = BytesMut::from(&startup[..]);
let code = bytes.get_i32();
match code {
// Client wants SSL. We don't support it at the moment.
SSL_REQUEST_CODE => {
2022-02-03 13:35:40 -08:00
let mut no = BytesMut::with_capacity(1);
no.put_u8(b'N');
write_all(&mut stream, no).await?;
2022-02-03 15:17:04 -08:00
}
2022-02-03 13:35:40 -08:00
// Regular startup message.
PROTOCOL_VERSION_NUMBER => {
2022-02-03 13:35:40 -08:00
// TODO: perform actual auth.
2022-02-14 05:11:53 -08:00
let parameters = parse_startup(bytes.clone())?;
2022-02-04 09:28:52 -08:00
// Generate random backend ID and secret key
let process_id: i32 = rand::random();
let secret_key: i32 = rand::random();
2022-02-03 13:35:40 -08:00
auth_ok(&mut stream).await?;
write_all(&mut stream, server_info).await?;
2022-02-04 09:28:52 -08:00
backend_key_data(&mut stream, process_id, secret_key).await?;
2022-02-03 13:35:40 -08:00
ready_for_query(&mut stream).await?;
// Split the read and write streams
// so we can control buffering.
2022-02-03 13:54:07 -08:00
let (read, write) = stream.into_split();
2022-02-03 13:35:40 -08:00
return Ok(Client {
2022-02-03 13:54:07 -08:00
read: BufReader::new(read),
write: write,
2022-02-03 15:33:26 -08:00
buffer: BytesMut::with_capacity(8196),
2022-02-04 09:28:52 -08:00
cancel_mode: false,
2022-02-08 09:25:59 -08:00
transaction_mode: transaction_mode,
2022-02-04 09:28:52 -08:00
process_id: process_id,
secret_key: secret_key,
2022-02-04 16:01:35 -08:00
client_server_map: client_server_map,
2022-02-14 05:11:53 -08:00
parameters: parameters,
2022-02-14 10:00:55 -08:00
stats: stats,
2022-02-04 09:28:52 -08:00
});
}
// Query cancel request.
CANCEL_REQUEST_CODE => {
2022-02-04 09:28:52 -08:00
let (read, write) = stream.into_split();
let process_id = bytes.get_i32();
let secret_key = bytes.get_i32();
return Ok(Client {
read: BufReader::new(read),
write: write,
buffer: BytesMut::with_capacity(8196),
cancel_mode: true,
2022-02-08 09:25:59 -08:00
transaction_mode: transaction_mode,
2022-02-04 09:28:52 -08:00
process_id: process_id,
secret_key: secret_key,
2022-02-04 16:01:35 -08:00
client_server_map: client_server_map,
2022-02-14 05:11:53 -08:00
parameters: HashMap::new(),
2022-02-14 10:00:55 -08:00
stats: stats,
2022-02-03 13:35:40 -08:00
});
2022-02-03 15:17:04 -08:00
}
2022-02-03 13:35:40 -08:00
_ => {
return Err(Error::ProtocolSyncError);
}
};
}
}
2022-02-03 13:54:07 -08:00
2022-02-04 09:28:52 -08:00
/// Client loop. We handle all messages between the client and the database here.
pub async fn handle(&mut self, mut pool: ConnectionPool) -> Result<(), Error> {
// The client wants to cancel a query it has issued previously.
2022-02-04 09:28:52 -08:00
if self.cancel_mode {
2022-02-05 10:02:13 -08:00
let (process_id, secret_key, address, port) = {
2022-02-04 16:01:35 -08:00
let guard = self.client_server_map.lock().unwrap();
2022-02-04 16:01:35 -08:00
match guard.get(&(self.process_id, self.secret_key)) {
// Drop the mutex as soon as possible.
// We found the server the client is using for its query
// that it wants to cancel.
2022-02-05 10:02:13 -08:00
Some((process_id, secret_key, address, port)) => (
process_id.clone(),
secret_key.clone(),
address.clone(),
port.clone(),
),
// The client doesn't know / got the wrong server,
// we're closing the connection for security reasons.
2022-02-04 16:01:35 -08:00
None => return Ok(()),
}
};
// Opens a new separate connection to the server, sends the backend_id
// and secret_key and then closes it for security reasons. No other interactions
// take place.
2022-02-05 10:02:13 -08:00
return Ok(Server::cancel(&address, &port, process_id, secret_key).await?);
2022-02-04 09:28:52 -08:00
}
let mut query_router = QueryRouter::new();
// Our custom protocol loop.
// We expect the client to either start a transaction with regular queries
// or issue commands for our sharding and server selection protocols.
2022-02-03 13:54:07 -08:00
loop {
// Read a complete message from the client, which normally would be
// either a `Q` (query) or `P` (prepare, extended protocol).
// We can parse it here before grabbing a server from the pool,
// in case the client is sending some control messages, e.g.
2022-02-09 06:51:31 -08:00
// SET SHARDING KEY TO 'bigint';
let mut message = read_message(&mut self.read).await?;
// Handle all custom protocol commands here.
match query_router.try_execute_command(message.clone()) {
// Normal query
None => {
if query_router.query_parser_enabled() && query_router.role() == None {
query_router.infer_role(message.clone());
}
}
Some((Command::SetShard, _)) | Some((Command::SetShardingKey, _)) => {
custom_protocol_response_ok(&mut self.write, &format!("SET SHARD")).await?;
continue;
}
Some((Command::SetServerRole, _)) => {
custom_protocol_response_ok(&mut self.write, "SET SERVER ROLE").await?;
continue;
}
Some((Command::ShowServerRole, value)) => {
show_response(&mut self.write, "server role", &value).await?;
continue;
}
Some((Command::ShowShard, value)) => {
show_response(&mut self.write, "shard", &value).await?;
continue;
}
};
// Make sure we selected a valid shard.
if query_router.shard() >= pool.shards() {
error_response(
&mut self.write,
&format!(
"shard '{}' is more than configured '{}'",
query_router.shard(),
pool.shards()
),
)
.await?;
continue;
}
// Grab a server from the pool: the client issued a regular query.
let connection = match pool.get(query_router.shard(), query_router.role()).await {
2022-02-09 21:19:14 -08:00
Ok(conn) => conn,
Err(err) => {
println!(">> Could not get connection from pool: {:?}", err);
error_response(&mut self.write, "could not get connection from the pool")
.await?;
continue;
2022-02-09 21:19:14 -08:00
}
};
let mut reference = connection.0;
let _address = connection.1;
let server = &mut *reference;
2022-02-03 16:25:05 -08:00
2022-02-04 16:08:18 -08:00
// Claim this server as mine for query cancellation.
2022-02-04 16:01:35 -08:00
server.claim(self.process_id, self.secret_key);
// Transaction loop. Multiple queries can be issued by the client here.
// The connection belongs to the client until the transaction is over,
// or until the client disconnects if we are in session mode.
2022-02-03 16:25:05 -08:00
loop {
let mut message = if message.len() == 0 {
match read_message(&mut self.read).await {
Ok(message) => message,
Err(err) => {
// Client disconnected without warning.
if server.in_transaction() {
// Client left dirty server. Clean up and proceed
// without thrashing this connection.
server.query("ROLLBACK; DISCARD ALL;").await?;
2022-02-05 18:20:53 -08:00
}
return Err(err);
}
}
} else {
let msg = message.clone();
message.clear();
msg
};
// The message will be forwarded to the server intact. We still would like to
// parse it below to figure out what to do with it.
let original = message.clone();
2022-02-03 16:25:05 -08:00
let code = message.get_u8() as char;
let _len = message.get_i32() as usize;
match code {
// ReadyForQuery
2022-02-03 16:25:05 -08:00
'Q' => {
2022-02-09 21:19:14 -08:00
// TODO: implement retries here for read-only transactions.
2022-02-03 16:25:05 -08:00
server.send(original).await?;
2022-02-04 08:26:50 -08:00
// Read all data the server has to offer, which can be multiple messages
// buffered in 8196 bytes chunks.
2022-02-04 08:26:50 -08:00
loop {
2022-02-09 21:19:14 -08:00
// TODO: implement retries here for read-only transactions.
2022-02-04 08:26:50 -08:00
let response = server.recv().await?;
2022-02-09 21:19:14 -08:00
// Send server reply to the client.
2022-02-04 08:26:50 -08:00
match write_all_half(&mut self.write, response).await {
Ok(_) => (),
Err(err) => {
server.mark_bad();
return Err(err);
}
};
if !server.is_data_available() {
break;
}
2022-02-04 08:26:50 -08:00
}
2022-02-03 16:25:05 -08:00
// Report query executed statistics.
2022-02-14 10:00:55 -08:00
self.stats.query();
// The transaction is over, we can release the connection back to the pool.
2022-02-14 10:00:55 -08:00
if !server.in_transaction() {
// Report transaction executed statistics.
2022-02-14 10:00:55 -08:00
self.stats.transaction();
// Release server back to the pool if we are in transaction mode.
// If we are in session mode, we keep the server until the client disconnects.
2022-02-14 10:00:55 -08:00
if self.transaction_mode {
// Report this client as idle.
self.stats.client_idle();
2022-02-14 10:00:55 -08:00
break;
}
2022-02-03 16:25:05 -08:00
}
}
// Terminate
2022-02-03 16:25:05 -08:00
'X' => {
// Client closing. Rollback and clean up
// connection before releasing into the pool.
// Pgbouncer closes the connection which leads to
// connection thrashing when clients misbehave.
// This pool will protect the database. :salute:
2022-02-03 18:02:50 -08:00
if server.in_transaction() {
server.query("ROLLBACK; DISCARD ALL;").await?;
2022-02-03 18:02:50 -08:00
}
2022-02-03 16:25:05 -08:00
return Ok(());
}
// Parse
// The query with placeholders is here, e.g. `SELECT * FROM users WHERE email = $1 AND active = $2`.
2022-02-03 16:25:05 -08:00
'P' => {
self.buffer.put(&original[..]);
}
// Bind
// The placeholder's replacements are here, e.g. 'user@email.com' and 'true'
2022-02-03 16:25:05 -08:00
'B' => {
self.buffer.put(&original[..]);
}
// Describe
// Command a client can issue to describe a previously prepared named statement.
2022-02-03 16:25:05 -08:00
'D' => {
self.buffer.put(&original[..]);
}
// Execute
// Execute a prepared statement prepared in `P` and bound in `B`.
2022-02-03 16:25:05 -08:00
'E' => {
self.buffer.put(&original[..]);
}
// Sync
// Frontend (client) is asking for the query result now.
2022-02-03 16:25:05 -08:00
'S' => {
self.buffer.put(&original[..]);
2022-02-09 21:19:14 -08:00
// TODO: retries for read-only transactions.
2022-02-03 16:25:05 -08:00
server.send(self.buffer.clone()).await?;
2022-02-03 16:25:05 -08:00
self.buffer.clear();
// Read all data the server has to offer, which can be multiple messages
// buffered in 8196 bytes chunks.
2022-02-04 08:26:50 -08:00
loop {
2022-02-09 21:19:14 -08:00
// TODO: retries for read-only transactions
2022-02-04 08:26:50 -08:00
let response = server.recv().await?;
2022-02-04 08:26:50 -08:00
match write_all_half(&mut self.write, response).await {
Ok(_) => (),
Err(err) => {
server.mark_bad();
return Err(err);
}
};
if !server.is_data_available() {
break;
}
2022-02-04 08:26:50 -08:00
}
2022-02-03 16:25:05 -08:00
// Report query executed statistics.
2022-02-14 10:00:55 -08:00
self.stats.query();
// Release server back to the pool if we are in transaction mode.
// If we are in session mode, we keep the server until the client disconnects.
2022-02-14 10:00:55 -08:00
if !server.in_transaction() {
self.stats.transaction();
if self.transaction_mode {
self.stats.client_idle();
2022-02-14 10:00:55 -08:00
break;
}
2022-02-03 16:25:05 -08:00
}
}
2022-02-04 08:06:45 -08:00
// CopyData
'd' => {
// Forward the data to the server,
// don't buffer it since it can be rather large.
server.send(original).await?;
}
// CopyDone or CopyFail
// Copy is done, successfully or not.
2022-02-04 08:06:45 -08:00
'c' | 'f' => {
server.send(original).await?;
2022-02-04 08:06:45 -08:00
let response = server.recv().await?;
2022-02-04 08:06:45 -08:00
match write_all_half(&mut self.write, response).await {
Ok(_) => (),
Err(err) => {
server.mark_bad();
return Err(err);
}
};
2022-02-05 15:23:21 -08:00
// Release server back to the pool if we are in transaction mode.
// If we are in session mode, we keep the server until the client disconnects.
2022-02-14 10:00:55 -08:00
if !server.in_transaction() {
self.stats.transaction();
if self.transaction_mode {
self.stats.client_idle();
2022-02-14 10:00:55 -08:00
break;
}
2022-02-05 15:23:21 -08:00
}
2022-02-04 08:06:45 -08:00
}
// Some unexpected message. We either did not implement the protocol correctly
// or this is not a Postgres client we're talking to.
2022-02-03 16:25:05 -08:00
_ => {
println!(">>> Unexpected code: {}", code);
}
2022-02-03 15:17:04 -08:00
}
2022-02-03 13:54:07 -08:00
}
2022-02-04 16:01:35 -08:00
// The server is no longer bound to us, we can't cancel it's queries anymore.
2022-02-04 16:01:35 -08:00
self.release();
2022-02-03 13:54:07 -08:00
}
}
2022-02-04 16:01:35 -08:00
2022-02-04 16:08:18 -08:00
/// Release the server from being mine. I can't cancel its queries anymore.
2022-02-11 11:19:40 -08:00
pub fn release(&self) {
2022-02-04 16:01:35 -08:00
let mut guard = self.client_server_map.lock().unwrap();
guard.remove(&(self.process_id, self.secret_key));
}
2022-02-03 15:17:04 -08:00
}