refactor(controller): use state to find available port range
This commit is contained in:
@@ -122,7 +122,7 @@ impl Controller {
|
|||||||
let config = PGDConfig {
|
let config = PGDConfig {
|
||||||
version: *latest_version,
|
version: *latest_version,
|
||||||
password: utils::generate_password(),
|
password: utils::generate_password(),
|
||||||
port: utils::find_available_port()?,
|
port: utils::find_available_port(&self.ctx.state)?,
|
||||||
};
|
};
|
||||||
let project = Project::new(config)?;
|
let project = Project::new(config)?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,18 @@
|
|||||||
use miette::Result;
|
use miette::Result;
|
||||||
use rand::{Rng, distr::Alphanumeric};
|
use rand::{Rng, distr::Alphanumeric};
|
||||||
|
|
||||||
|
use crate::state::StateManager;
|
||||||
const DEFAULT_POSTGRES_PORT: u16 = 5432;
|
const DEFAULT_POSTGRES_PORT: u16 = 5432;
|
||||||
const PORT_SEARCH_RANGE: u16 = 100;
|
const PORT_SEARCH_RANGE: u16 = 100;
|
||||||
|
|
||||||
pub fn find_available_port() -> Result<u16> {
|
pub fn find_available_port(state: &StateManager) -> Result<u16> {
|
||||||
use std::net::TcpListener;
|
use std::net::TcpListener;
|
||||||
|
|
||||||
for port in DEFAULT_POSTGRES_PORT..(DEFAULT_POSTGRES_PORT + PORT_SEARCH_RANGE) {
|
let starting_port = state
|
||||||
|
.get_highest_used_port()
|
||||||
|
.unwrap_or(DEFAULT_POSTGRES_PORT);
|
||||||
|
|
||||||
|
for port in starting_port..(starting_port + PORT_SEARCH_RANGE) {
|
||||||
if TcpListener::bind(("127.0.0.1", port)).is_ok() {
|
if TcpListener::bind(("127.0.0.1", port)).is_ok() {
|
||||||
return Ok(port);
|
return Ok(port);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -88,8 +88,8 @@ impl StateManager {
|
|||||||
self.0.borrow_mut().instances.insert(project_name, state);
|
self.0.borrow_mut().instances.insert(project_name, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove(&self, project_name: &str) -> Option<InstanceState> {
|
pub fn get_highest_used_port(&self) -> Option<u16> {
|
||||||
self.0.borrow_mut().instances.remove(project_name)
|
self.0.borrow().instances.values().map(|i| i.port).max()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user