|
| 1 | +/// A mirrored PostgreSQL client. |
| 2 | +/// Packets arrive to us through a channel from the main client and we send them to the server. |
| 3 | +use bb8::Pool; |
| 4 | +use bytes::{Bytes, BytesMut}; |
| 5 | + |
| 6 | +use crate::config::{get_config, Address, Role, User}; |
| 7 | +use crate::pool::{ClientServerMap, ServerPool}; |
| 8 | +use crate::stats::get_reporter; |
| 9 | +use log::{error, info, trace, warn}; |
| 10 | +use tokio::sync::mpsc::{channel, Receiver, Sender}; |
| 11 | + |
| 12 | +pub struct MirroredClient { |
| 13 | + address: Address, |
| 14 | + user: User, |
| 15 | + database: String, |
| 16 | + bytes_rx: Receiver<Bytes>, |
| 17 | + disconnect_rx: Receiver<()>, |
| 18 | +} |
| 19 | + |
| 20 | +impl MirroredClient { |
| 21 | + async fn create_pool(&self) -> Pool<ServerPool> { |
| 22 | + let config = get_config(); |
| 23 | + let default = std::time::Duration::from_millis(10_000).as_millis() as u64; |
| 24 | + let (connection_timeout, idle_timeout) = match config.pools.get(&self.address.pool_name) { |
| 25 | + Some(cfg) => ( |
| 26 | + cfg.connect_timeout.unwrap_or(default), |
| 27 | + cfg.idle_timeout.unwrap_or(default), |
| 28 | + ), |
| 29 | + None => (default, default), |
| 30 | + }; |
| 31 | + |
| 32 | + let manager = ServerPool::new( |
| 33 | + self.address.clone(), |
| 34 | + self.user.clone(), |
| 35 | + self.database.as_str(), |
| 36 | + ClientServerMap::default(), |
| 37 | + get_reporter(), |
| 38 | + ); |
| 39 | + |
| 40 | + Pool::builder() |
| 41 | + .max_size(1) |
| 42 | + .connection_timeout(std::time::Duration::from_millis(connection_timeout)) |
| 43 | + .idle_timeout(Some(std::time::Duration::from_millis(idle_timeout))) |
| 44 | + .test_on_check_out(false) |
| 45 | + .build(manager) |
| 46 | + .await |
| 47 | + .unwrap() |
| 48 | + } |
| 49 | + |
| 50 | + pub fn start(mut self) { |
| 51 | + tokio::spawn(async move { |
| 52 | + let pool = self.create_pool().await; |
| 53 | + let address = self.address.clone(); |
| 54 | + loop { |
| 55 | + let mut server = match pool.get().await { |
| 56 | + Ok(server) => server, |
| 57 | + Err(err) => { |
| 58 | + error!( |
| 59 | + "Failed to get connection from pool, Discarding message {:?}, {:?}", |
| 60 | + err, |
| 61 | + address.clone() |
| 62 | + ); |
| 63 | + continue; |
| 64 | + } |
| 65 | + }; |
| 66 | + |
| 67 | + tokio::select! { |
| 68 | + // Exit channel events |
| 69 | + _ = self.disconnect_rx.recv() => { |
| 70 | + info!("Got mirror exit signal, exiting {:?}", address.clone()); |
| 71 | + break; |
| 72 | + } |
| 73 | + |
| 74 | + // Incoming data from server (we read to clear the socket buffer and discard the data) |
| 75 | + recv_result = server.recv() => { |
| 76 | + match recv_result { |
| 77 | + Ok(message) => trace!("Received from mirror: {} {:?}", String::from_utf8_lossy(&message[..]), address.clone()), |
| 78 | + Err(err) => { |
| 79 | + server.mark_bad(); |
| 80 | + error!("Failed to receive from mirror {:?} {:?}", err, address.clone()); |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + // Messages to send to the server |
| 86 | + message = self.bytes_rx.recv() => { |
| 87 | + match message { |
| 88 | + Some(bytes) => { |
| 89 | + match server.send(&BytesMut::from(&bytes[..])).await { |
| 90 | + Ok(_) => trace!("Sent to mirror: {} {:?}", String::from_utf8_lossy(&bytes[..]), address.clone()), |
| 91 | + Err(err) => { |
| 92 | + server.mark_bad(); |
| 93 | + error!("Failed to send to mirror, Discarding message {:?}, {:?}", err, address.clone()) |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + None => { |
| 98 | + info!("Mirror channel closed, exiting {:?}", address.clone()); |
| 99 | + break; |
| 100 | + }, |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + } |
| 105 | + }); |
| 106 | + } |
| 107 | +} |
| 108 | +pub struct MirroringManager { |
| 109 | + pub byte_senders: Vec<Sender<Bytes>>, |
| 110 | + pub disconnect_senders: Vec<Sender<()>>, |
| 111 | +} |
| 112 | +impl MirroringManager { |
| 113 | + pub fn from_addresses( |
| 114 | + user: User, |
| 115 | + database: String, |
| 116 | + addresses: Vec<Address>, |
| 117 | + ) -> MirroringManager { |
| 118 | + let mut byte_senders: Vec<Sender<Bytes>> = vec![]; |
| 119 | + let mut exit_senders: Vec<Sender<()>> = vec![]; |
| 120 | + |
| 121 | + addresses.iter().for_each(|mirror| { |
| 122 | + let (bytes_tx, bytes_rx) = channel::<Bytes>(500); |
| 123 | + let (exit_tx, exit_rx) = channel::<()>(1); |
| 124 | + let mut addr = mirror.clone(); |
| 125 | + addr.role = Role::Mirror; |
| 126 | + let client = MirroredClient { |
| 127 | + user: user.clone(), |
| 128 | + database: database.to_owned(), |
| 129 | + address: addr, |
| 130 | + bytes_rx, |
| 131 | + disconnect_rx: exit_rx, |
| 132 | + }; |
| 133 | + exit_senders.push(exit_tx.clone()); |
| 134 | + byte_senders.push(bytes_tx.clone()); |
| 135 | + client.start(); |
| 136 | + }); |
| 137 | + |
| 138 | + Self { |
| 139 | + byte_senders: byte_senders, |
| 140 | + disconnect_senders: exit_senders, |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + pub fn send(self: &mut Self, bytes: &BytesMut) { |
| 145 | + let cpy = bytes.clone().freeze(); |
| 146 | + self.byte_senders |
| 147 | + .iter_mut() |
| 148 | + .for_each(|sender| match sender.try_send(cpy.clone()) { |
| 149 | + Ok(_) => {} |
| 150 | + Err(err) => { |
| 151 | + warn!("Failed to send bytes to a mirror channel {}", err); |
| 152 | + } |
| 153 | + }); |
| 154 | + } |
| 155 | + |
| 156 | + pub fn disconnect(self: &mut Self) { |
| 157 | + self.disconnect_senders |
| 158 | + .iter_mut() |
| 159 | + .for_each(|sender| match sender.try_send(()) { |
| 160 | + Ok(_) => {} |
| 161 | + Err(err) => { |
| 162 | + warn!( |
| 163 | + "Failed to send disconnect signal to a mirror channel {}", |
| 164 | + err |
| 165 | + ); |
| 166 | + } |
| 167 | + }); |
| 168 | + } |
| 169 | +} |
0 commit comments