-
Notifications
You must be signed in to change notification settings - Fork 226
Random instance selection #136
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
ecdaf44
wip
drdrsh 6ee6380
Merge branch 'main' of github.com:drdrsh/pgcat into mostafa_random-fa…
drdrsh 6c93dea
revert some'
drdrsh c9be159
revert more
drdrsh f4b3bf4
poor-man's integration test
drdrsh 1a07a7e
remove test
drdrsh 3159a47
fmt
drdrsh 6f9577c
--workspace
drdrsh 86355f0
fix build
drdrsh acd259a
fix integration test
drdrsh c8ea881
another stab
drdrsh d12b426
log
drdrsh 160b347
run after integration
drdrsh 38f325c
cargo test after integration
drdrsh 87d7bbf
revert
drdrsh 6608e14
revert more
drdrsh 13b3054
Refactor + clean up
drdrsh 18bc61c
more clean up
drdrsh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,8 @@ use chrono::naive::NaiveDateTime; | |
use log::{debug, error, info, warn}; | ||
use once_cell::sync::Lazy; | ||
use parking_lot::{Mutex, RwLock}; | ||
use rand::seq::SliceRandom; | ||
use rand::thread_rng; | ||
use std::collections::HashMap; | ||
use std::sync::Arc; | ||
use std::time::Instant; | ||
|
@@ -118,7 +120,7 @@ impl ConnectionPool { | |
host: server.0.clone(), | ||
port: server.1.to_string(), | ||
role: role, | ||
replica_number, | ||
instance_index: replica_number, | ||
shard: shard_idx.parse::<usize>().unwrap(), | ||
username: user_info.username.clone(), | ||
poolname: pool_name.clone(), | ||
|
@@ -201,42 +203,30 @@ impl ConnectionPool { | |
/// the pooler starts up. | ||
async fn validate(&mut self) -> Result<(), Error> { | ||
let mut server_infos = Vec::new(); | ||
let stats = self.stats.clone(); | ||
|
||
for shard in 0..self.shards() { | ||
let mut round_robin = 0; | ||
|
||
for _ in 0..self.servers(shard) { | ||
// To keep stats consistent. | ||
let fake_process_id = 0; | ||
|
||
let connection = match self.get(shard, None, fake_process_id, round_robin).await { | ||
for index in 0..self.servers(shard) { | ||
let connection = match self.databases[shard][index].get().await { | ||
Ok(conn) => conn, | ||
Err(err) => { | ||
error!("Shard {} down or misconfigured: {:?}", shard, err); | ||
continue; | ||
} | ||
}; | ||
|
||
let proxy = connection.0; | ||
let address = connection.1; | ||
let proxy = connection; | ||
let server = &*proxy; | ||
let server_info = server.server_info(); | ||
|
||
stats.client_disconnecting(fake_process_id, address.id); | ||
|
||
if server_infos.len() > 0 { | ||
// Compare against the last server checked. | ||
if server_info != server_infos[server_infos.len() - 1] { | ||
warn!( | ||
"{:?} has different server configuration than the last server", | ||
address | ||
proxy.address() | ||
); | ||
} | ||
} | ||
|
||
server_infos.push(server_info); | ||
round_robin += 1; | ||
} | ||
} | ||
|
||
|
@@ -254,70 +244,46 @@ impl ConnectionPool { | |
/// Get a connection from the pool. | ||
pub async fn get( | ||
&self, | ||
shard: usize, // shard number | ||
role: Option<Role>, // primary or replica | ||
process_id: i32, // client id | ||
mut round_robin: usize, // round robin offset | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. After randomization, this factor won't be needed. It is only used by the To simplify the logic for this method, I refactored |
||
shard: usize, // shard number | ||
role: Option<Role>, // primary or replica | ||
process_id: i32, // client id | ||
) -> Result<(PooledConnection<'_, ServerPool>, Address), Error> { | ||
let now = Instant::now(); | ||
let addresses = &self.addresses[shard]; | ||
|
||
let mut allowed_attempts = match role { | ||
// Primary-specific queries get one attempt, if the primary is down, | ||
// nothing we should do about it I think. It's dangerous to retry | ||
// write queries. | ||
Some(Role::Primary) => 1, | ||
let mut candidates: Vec<Address> = self.addresses[shard] | ||
.clone() | ||
.into_iter() | ||
.filter(|address| address.role == role) | ||
.collect(); | ||
|
||
// Replicas get to try as many times as there are replicas | ||
// and connections in the pool. | ||
_ => addresses.len(), | ||
}; | ||
|
||
debug!("Allowed attempts for {:?}: {}", role, allowed_attempts); | ||
|
||
let exists = match role { | ||
Some(role) => addresses.iter().filter(|addr| addr.role == role).count() > 0, | ||
None => true, | ||
}; | ||
|
||
if !exists { | ||
error!("Requested role {:?}, but none are configured", role); | ||
return Err(Error::BadConfig); | ||
} | ||
// Random load balancing | ||
candidates.shuffle(&mut thread_rng()); | ||
|
||
let healthcheck_timeout = get_config().general.healthcheck_timeout; | ||
let healthcheck_delay = get_config().general.healthcheck_delay as u128; | ||
|
||
while allowed_attempts > 0 { | ||
// Round-robin replicas. | ||
round_robin += 1; | ||
|
||
let index = round_robin % addresses.len(); | ||
let address = &addresses[index]; | ||
|
||
// Make sure you're getting a primary or a replica | ||
// as per request. If no specific role is requested, the first | ||
// available will be chosen. | ||
if address.role != role { | ||
continue; | ||
} | ||
|
||
allowed_attempts -= 1; | ||
while !candidates.is_empty() { | ||
// Get the next candidate | ||
let address = match candidates.pop() { | ||
Some(address) => address, | ||
None => break, | ||
}; | ||
|
||
// Don't attempt to connect to banned servers. | ||
if self.is_banned(address, shard, role) { | ||
if self.is_banned(&address, address.shard, role) { | ||
continue; | ||
} | ||
|
||
// Indicate we're waiting on a server connection from a pool. | ||
self.stats.client_waiting(process_id, address.id); | ||
|
||
// Check if we can connect | ||
let mut conn = match self.databases[shard][index].get().await { | ||
let mut conn = match self.databases[address.shard][address.instance_index] | ||
.get() | ||
.await | ||
{ | ||
Ok(conn) => conn, | ||
Err(err) => { | ||
error!("Banning replica {}, error: {:?}", index, err); | ||
self.ban(address, shard, process_id); | ||
error!("Banning instance {:?}, error: {:?}", address, err); | ||
self.ban(&address, address.shard, process_id); | ||
self.stats.client_disconnecting(process_id, address.id); | ||
self.stats | ||
.checkout_time(now.elapsed().as_micros(), process_id, address.id); | ||
|
@@ -359,29 +325,34 @@ impl ConnectionPool { | |
} | ||
|
||
// Health check failed. | ||
Err(_) => { | ||
error!("Banning replica {} because of failed health check", index); | ||
Err(err) => { | ||
error!( | ||
"Banning instance {:?} because of failed health check, {:?}", | ||
address, err | ||
); | ||
|
||
// Don't leave a bad connection in the pool. | ||
server.mark_bad(); | ||
|
||
self.ban(address, shard, process_id); | ||
self.ban(&address, address.shard, process_id); | ||
continue; | ||
} | ||
}, | ||
|
||
// Health check timed out. | ||
Err(_) => { | ||
error!("Banning replica {} because of health check timeout", index); | ||
Err(err) => { | ||
error!( | ||
"Banning instance {:?} because of health check timeout, {:?}", | ||
address, err | ||
); | ||
// Don't leave a bad connection in the pool. | ||
server.mark_bad(); | ||
|
||
self.ban(address, shard, process_id); | ||
self.ban(&address, address.shard, process_id); | ||
continue; | ||
} | ||
} | ||
} | ||
|
||
return Err(Error::AllServersDown); | ||
} | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Address
could point to a primary so using the termreplica
is misleading