2022-06-24 14:52:38 -07:00
|
|
|
// Copyright (c) 2022 Lev Kokotov <hi@levthe.dev>
|
2022-02-08 14:59:10 -08:00
|
|
|
|
2022-02-20 13:49:30 -08:00
|
|
|
// Permission is hereby granted, free of charge, to any person obtaining
|
|
|
|
|
// a copy of this software and associated documentation files (the
|
|
|
|
|
// "Software"), to deal in the Software without restriction, including
|
|
|
|
|
// without limitation the rights to use, copy, modify, merge, publish,
|
|
|
|
|
// distribute, sublicense, and/or sell copies of the Software, and to
|
|
|
|
|
// permit persons to whom the Software is furnished to do so, subject to
|
|
|
|
|
// the following conditions:
|
2022-02-08 14:59:10 -08:00
|
|
|
|
2022-02-20 13:49:30 -08:00
|
|
|
// The above copyright notice and this permission notice shall be
|
|
|
|
|
// included in all copies or substantial portions of the Software.
|
|
|
|
|
|
|
|
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
|
|
|
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
|
|
|
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
|
|
|
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
|
|
|
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
|
|
|
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
|
|
|
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
2022-02-08 14:59:10 -08:00
|
|
|
|
2022-02-19 13:57:35 -08:00
|
|
|
extern crate arc_swap;
|
2022-02-03 17:06:19 -08:00
|
|
|
extern crate async_trait;
|
|
|
|
|
extern crate bb8;
|
2022-02-03 13:35:40 -08:00
|
|
|
extern crate bytes;
|
2022-02-20 22:47:08 -08:00
|
|
|
extern crate env_logger;
|
2022-08-25 20:56:18 -05:00
|
|
|
extern crate exitcode;
|
2022-02-18 07:10:18 -08:00
|
|
|
extern crate log;
|
2022-02-03 15:17:04 -08:00
|
|
|
extern crate md5;
|
2022-02-10 17:05:20 -08:00
|
|
|
extern crate num_cpus;
|
|
|
|
|
extern crate once_cell;
|
2022-06-27 15:52:01 -07:00
|
|
|
extern crate rustls_pemfile;
|
2022-02-08 09:25:59 -08:00
|
|
|
extern crate serde;
|
|
|
|
|
extern crate serde_derive;
|
2022-02-18 07:10:18 -08:00
|
|
|
extern crate sqlparser;
|
2022-02-03 13:35:40 -08:00
|
|
|
extern crate tokio;
|
2022-06-27 09:46:33 -07:00
|
|
|
extern crate tokio_rustls;
|
2022-06-27 15:52:01 -07:00
|
|
|
extern crate toml;
|
2022-02-03 13:35:40 -08:00
|
|
|
|
2022-06-24 14:52:38 -07:00
|
|
|
use log::{debug, error, info};
|
2022-02-24 08:44:41 -08:00
|
|
|
use parking_lot::Mutex;
|
2022-02-03 17:06:19 -08:00
|
|
|
use tokio::net::TcpListener;
|
2022-02-19 13:57:35 -08:00
|
|
|
use tokio::{
|
|
|
|
|
signal::unix::{signal as unix_signal, SignalKind},
|
2022-02-20 22:47:08 -08:00
|
|
|
sync::mpsc,
|
2022-02-19 13:57:35 -08:00
|
|
|
};
|
2022-02-03 13:35:40 -08:00
|
|
|
|
2022-02-04 09:28:52 -08:00
|
|
|
use std::collections::HashMap;
|
2022-08-09 15:19:11 -04:00
|
|
|
use std::net::SocketAddr;
|
|
|
|
|
use std::str::FromStr;
|
2022-02-24 08:44:41 -08:00
|
|
|
use std::sync::Arc;
|
2022-08-08 19:01:24 -04:00
|
|
|
use tokio::sync::broadcast;
|
2022-02-04 09:28:52 -08:00
|
|
|
|
2022-02-25 18:20:15 -08:00
|
|
|
mod admin;
|
2022-02-03 15:17:04 -08:00
|
|
|
mod client;
|
2022-02-05 10:02:13 -08:00
|
|
|
mod config;
|
2022-02-15 22:45:45 -08:00
|
|
|
mod constants;
|
2022-02-03 13:35:40 -08:00
|
|
|
mod errors;
|
|
|
|
|
mod messages;
|
2022-02-03 16:25:05 -08:00
|
|
|
mod pool;
|
2022-08-09 15:19:11 -04:00
|
|
|
mod prometheus;
|
2022-02-16 22:52:11 -08:00
|
|
|
mod query_router;
|
2022-06-18 18:36:00 -07:00
|
|
|
mod scram;
|
2022-02-03 17:06:19 -08:00
|
|
|
mod server;
|
2022-02-05 19:43:48 -08:00
|
|
|
mod sharding;
|
2022-02-14 10:00:55 -08:00
|
|
|
mod stats;
|
2022-06-27 16:45:41 -07:00
|
|
|
mod tls;
|
2022-02-03 13:35:40 -08:00
|
|
|
|
2022-08-09 15:19:11 -04:00
|
|
|
use crate::config::{get_config, reload_config, VERSION};
|
2022-08-25 06:40:56 -07:00
|
|
|
use crate::errors::Error;
|
2022-08-09 15:19:11 -04:00
|
|
|
use crate::pool::{ClientServerMap, ConnectionPool};
|
|
|
|
|
use crate::prometheus::start_metric_server;
|
|
|
|
|
use crate::stats::{Collector, Reporter, REPORTER};
|
2022-07-27 21:47:55 -05:00
|
|
|
|
2022-02-10 13:48:56 -08:00
|
|
|
#[tokio::main(worker_threads = 4)]
|
2022-02-03 13:35:40 -08:00
|
|
|
async fn main() {
|
2022-02-20 22:47:08 -08:00
|
|
|
env_logger::init();
|
2022-07-27 21:47:55 -05:00
|
|
|
info!("Welcome to PgCat! Meow. (Version {})", VERSION);
|
2022-02-03 13:35:40 -08:00
|
|
|
|
2022-02-16 22:52:11 -08:00
|
|
|
if !query_router::QueryRouter::setup() {
|
2022-02-20 22:47:08 -08:00
|
|
|
error!("Could not setup query router");
|
2022-08-25 20:56:18 -05:00
|
|
|
std::process::exit(exitcode::CONFIG);
|
2022-02-16 22:52:11 -08:00
|
|
|
}
|
2022-02-10 17:05:20 -08:00
|
|
|
|
2022-02-21 20:41:32 -08:00
|
|
|
let args = std::env::args().collect::<Vec<String>>();
|
|
|
|
|
|
|
|
|
|
let config_file = if args.len() == 2 {
|
|
|
|
|
args[1].to_string()
|
|
|
|
|
} else {
|
|
|
|
|
String::from("pgcat.toml")
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
match config::parse(&config_file).await {
|
2022-02-19 13:57:35 -08:00
|
|
|
Ok(_) => (),
|
2022-02-08 09:25:59 -08:00
|
|
|
Err(err) => {
|
2022-02-20 22:47:08 -08:00
|
|
|
error!("Config parse error: {:?}", err);
|
2022-08-25 20:56:18 -05:00
|
|
|
std::process::exit(exitcode::CONFIG);
|
2022-02-08 09:25:59 -08:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2022-02-19 13:57:35 -08:00
|
|
|
let config = get_config();
|
2022-08-09 15:19:11 -04:00
|
|
|
|
|
|
|
|
if let Some(true) = config.general.enable_prometheus_exporter {
|
2022-08-14 01:25:14 +08:00
|
|
|
let http_addr_str = format!(
|
|
|
|
|
"{}:{}",
|
|
|
|
|
config.general.host, config.general.prometheus_exporter_port
|
|
|
|
|
);
|
2022-08-09 15:19:11 -04:00
|
|
|
let http_addr = match SocketAddr::from_str(&http_addr_str) {
|
|
|
|
|
Ok(addr) => addr,
|
|
|
|
|
Err(err) => {
|
|
|
|
|
error!("Invalid http address: {}", err);
|
2022-08-25 20:56:18 -05:00
|
|
|
std::process::exit(exitcode::CONFIG);
|
2022-08-09 15:19:11 -04:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
tokio::task::spawn(async move {
|
|
|
|
|
start_metric_server(http_addr).await;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-08 09:25:59 -08:00
|
|
|
let addr = format!("{}:{}", config.general.host, config.general.port);
|
2022-03-10 01:33:29 -08:00
|
|
|
|
2022-02-08 09:25:59 -08:00
|
|
|
let listener = match TcpListener::bind(&addr).await {
|
2022-02-03 13:35:40 -08:00
|
|
|
Ok(sock) => sock,
|
|
|
|
|
Err(err) => {
|
2022-02-20 22:47:08 -08:00
|
|
|
error!("Listener socket error: {:?}", err);
|
2022-08-25 20:56:18 -05:00
|
|
|
std::process::exit(exitcode::CONFIG);
|
2022-02-03 13:35:40 -08:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2022-02-20 22:47:08 -08:00
|
|
|
info!("Running on {}", addr);
|
2022-03-10 01:33:29 -08:00
|
|
|
|
2022-02-19 13:57:35 -08:00
|
|
|
config.show();
|
2022-02-05 10:02:13 -08:00
|
|
|
|
2022-02-08 09:25:59 -08:00
|
|
|
// Tracks which client is connected to which server for query cancellation.
|
2022-02-04 16:01:35 -08:00
|
|
|
let client_server_map: ClientServerMap = Arc::new(Mutex::new(HashMap::new()));
|
2022-02-05 10:02:13 -08:00
|
|
|
|
2022-03-10 01:33:29 -08:00
|
|
|
// Statistics reporting.
|
2022-08-25 06:40:56 -07:00
|
|
|
let (stats_tx, stats_rx) = mpsc::channel(100_000);
|
|
|
|
|
REPORTER.store(Arc::new(Reporter::new(stats_tx.clone())));
|
2022-03-04 17:04:27 -08:00
|
|
|
|
2022-03-10 01:33:29 -08:00
|
|
|
// Connection pool that allows to query all shards and replicas.
|
2022-06-24 14:52:38 -07:00
|
|
|
match ConnectionPool::from_config(client_server_map.clone()).await {
|
|
|
|
|
Ok(_) => (),
|
|
|
|
|
Err(err) => {
|
|
|
|
|
error!("Pool error: {:?}", err);
|
2022-08-25 20:56:18 -05:00
|
|
|
std::process::exit(exitcode::CONFIG);
|
2022-06-24 14:52:38 -07:00
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2022-02-14 10:00:55 -08:00
|
|
|
tokio::task::spawn(async move {
|
2022-08-25 06:40:56 -07:00
|
|
|
let mut stats_collector = Collector::new(stats_rx, stats_tx.clone());
|
2022-06-25 12:22:46 -07:00
|
|
|
stats_collector.collect().await;
|
2022-02-14 10:00:55 -08:00
|
|
|
});
|
|
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
info!("Config autoreloader: {}", config.general.autoreload);
|
|
|
|
|
|
|
|
|
|
let mut term_signal = unix_signal(SignalKind::terminate()).unwrap();
|
|
|
|
|
let mut interrupt_signal = unix_signal(SignalKind::interrupt()).unwrap();
|
|
|
|
|
let mut sighup_signal = unix_signal(SignalKind::hangup()).unwrap();
|
|
|
|
|
let mut autoreload_interval = tokio::time::interval(tokio::time::Duration::from_millis(15_000));
|
|
|
|
|
let (shutdown_tx, _) = broadcast::channel::<()>(1);
|
|
|
|
|
let (drain_tx, mut drain_rx) = mpsc::channel::<i8>(2048);
|
|
|
|
|
let (exit_tx, mut exit_rx) = mpsc::channel::<()>(1);
|
|
|
|
|
|
2022-02-20 22:47:08 -08:00
|
|
|
info!("Waiting for clients");
|
2022-02-03 16:25:05 -08:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
let mut admin_only = false;
|
|
|
|
|
let mut total_clients = 0;
|
2022-08-08 19:01:24 -04:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
loop {
|
|
|
|
|
tokio::select! {
|
|
|
|
|
// Reload config:
|
|
|
|
|
// kill -SIGHUP $(pgrep pgcat)
|
|
|
|
|
_ = sighup_signal.recv() => {
|
|
|
|
|
info!("Reloading config");
|
2022-08-08 19:01:24 -04:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
match reload_config(client_server_map.clone()).await {
|
|
|
|
|
Ok(_) => (),
|
|
|
|
|
Err(_) => (),
|
|
|
|
|
};
|
2022-08-08 19:01:24 -04:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
get_config().show();
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
_ = autoreload_interval.tick() => {
|
|
|
|
|
if config.general.autoreload {
|
|
|
|
|
info!("Automatically reloading config");
|
|
|
|
|
|
|
|
|
|
match reload_config(client_server_map.clone()).await {
|
|
|
|
|
Ok(changed) => {
|
|
|
|
|
if changed {
|
|
|
|
|
get_config().show()
|
|
|
|
|
}
|
2022-08-08 19:01:24 -04:00
|
|
|
}
|
2022-08-25 06:40:56 -07:00
|
|
|
Err(_) => (),
|
|
|
|
|
};
|
2022-02-03 13:35:40 -08:00
|
|
|
}
|
2022-08-25 06:40:56 -07:00
|
|
|
},
|
2022-06-27 16:45:41 -07:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
// Initiate graceful shutdown sequence on sig int
|
|
|
|
|
_ = interrupt_signal.recv() => {
|
|
|
|
|
info!("Got SIGINT, waiting for client connection drain now");
|
|
|
|
|
admin_only = true;
|
2022-02-12 10:16:05 -08:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
// Broadcast that client tasks need to finish
|
|
|
|
|
let _ = shutdown_tx.send(());
|
|
|
|
|
let exit_tx = exit_tx.clone();
|
|
|
|
|
let _ = drain_tx.send(0).await;
|
2022-02-19 13:57:35 -08:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
tokio::task::spawn(async move {
|
|
|
|
|
let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(config.general.shutdown_timeout));
|
2022-06-24 14:52:38 -07:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
// First tick fires immediately.
|
|
|
|
|
interval.tick().await;
|
2022-06-24 14:52:38 -07:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
// Second one in the interval time.
|
|
|
|
|
interval.tick().await;
|
2022-06-24 14:52:38 -07:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
// We're done waiting.
|
|
|
|
|
error!("Timed out waiting for clients");
|
2022-02-19 13:57:35 -08:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
let _ = exit_tx.send(()).await;
|
|
|
|
|
});
|
|
|
|
|
},
|
2022-06-25 11:46:20 -07:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
_ = term_signal.recv() => break,
|
|
|
|
|
|
|
|
|
|
new_client = listener.accept() => {
|
|
|
|
|
let (socket, addr) = match new_client {
|
|
|
|
|
Ok((socket, addr)) => (socket, addr),
|
|
|
|
|
Err(err) => {
|
|
|
|
|
error!("{:?}", err);
|
|
|
|
|
continue;
|
2022-06-25 11:46:20 -07:00
|
|
|
}
|
|
|
|
|
};
|
2022-08-25 06:40:56 -07:00
|
|
|
|
|
|
|
|
let shutdown_rx = shutdown_tx.subscribe();
|
|
|
|
|
let drain_tx = drain_tx.clone();
|
|
|
|
|
let client_server_map = client_server_map.clone();
|
|
|
|
|
|
|
|
|
|
tokio::task::spawn(async move {
|
|
|
|
|
let start = chrono::offset::Utc::now().naive_utc();
|
|
|
|
|
|
|
|
|
|
match client::client_entrypoint(
|
|
|
|
|
socket,
|
|
|
|
|
client_server_map,
|
|
|
|
|
shutdown_rx,
|
|
|
|
|
drain_tx,
|
|
|
|
|
admin_only,
|
|
|
|
|
)
|
|
|
|
|
.await
|
|
|
|
|
{
|
|
|
|
|
Ok(()) => {
|
|
|
|
|
|
|
|
|
|
let duration = chrono::offset::Utc::now().naive_utc() - start;
|
|
|
|
|
|
|
|
|
|
info!(
|
|
|
|
|
"Client {:?} disconnected, session duration: {}",
|
|
|
|
|
addr,
|
|
|
|
|
format_duration(&duration)
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Err(err) => {
|
|
|
|
|
match err {
|
|
|
|
|
// Don't count the clients we rejected.
|
|
|
|
|
Error::ShuttingDown => (),
|
|
|
|
|
_ => {
|
|
|
|
|
// drain_tx.send(-1).await.unwrap();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
debug!("Client disconnected with error {:?}", err);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
});
|
2022-06-25 11:46:20 -07:00
|
|
|
}
|
|
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
_ = exit_rx.recv() => {
|
|
|
|
|
break;
|
|
|
|
|
}
|
2022-02-14 10:00:55 -08:00
|
|
|
|
2022-08-25 06:40:56 -07:00
|
|
|
client_ping = drain_rx.recv() => {
|
|
|
|
|
let client_ping = client_ping.unwrap();
|
|
|
|
|
total_clients += client_ping;
|
|
|
|
|
|
|
|
|
|
if total_clients == 0 && admin_only {
|
|
|
|
|
let _ = exit_tx.send(()).await;
|
2022-08-08 19:01:24 -04:00
|
|
|
}
|
|
|
|
|
}
|
2022-08-25 06:40:56 -07:00
|
|
|
}
|
2022-08-08 19:01:24 -04:00
|
|
|
}
|
2022-03-08 17:18:48 -08:00
|
|
|
|
|
|
|
|
info!("Shutting down...");
|
2022-02-03 13:35:40 -08:00
|
|
|
}
|
2022-02-12 09:24:24 -08:00
|
|
|
|
|
|
|
|
/// Format chrono::Duration to be more human-friendly.
|
|
|
|
|
///
|
|
|
|
|
/// # Arguments
|
|
|
|
|
///
|
|
|
|
|
/// * `duration` - A duration of time
|
|
|
|
|
fn format_duration(duration: &chrono::Duration) -> String {
|
|
|
|
|
let seconds = {
|
|
|
|
|
let seconds = duration.num_seconds() % 60;
|
|
|
|
|
if seconds < 10 {
|
|
|
|
|
format!("0{}", seconds)
|
|
|
|
|
} else {
|
|
|
|
|
format!("{}", seconds)
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let minutes = {
|
|
|
|
|
let minutes = duration.num_minutes() % 60;
|
|
|
|
|
if minutes < 10 {
|
|
|
|
|
format!("0{}", minutes)
|
|
|
|
|
} else {
|
|
|
|
|
format!("{}", minutes)
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let hours = {
|
|
|
|
|
let hours = duration.num_hours() % 24;
|
|
|
|
|
if hours < 10 {
|
|
|
|
|
format!("0{}", hours)
|
|
|
|
|
} else {
|
|
|
|
|
format!("{}", hours)
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let days = duration.num_days().to_string();
|
|
|
|
|
|
|
|
|
|
format!("{}d {}:{}:{}", days, hours, minutes, seconds)
|
|
|
|
|
}
|