Skip to content

Commit

Permalink
fix: Resolve path when saving state
Browse files Browse the repository at this point in the history
- Resolve absolute path from the cli
- Default to sozu working directory if a relative
path is provided to sozu
  • Loading branch information
hcaumeil committed Feb 25, 2025
1 parent e0017ba commit 29277c2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
26 changes: 22 additions & 4 deletions bin/src/command/requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::{
env,
fs::File,
io::{ErrorKind, Read},
path::PathBuf,
};

use mio::Token;
Expand Down Expand Up @@ -198,18 +199,35 @@ fn list_listeners(server: &mut Server, client: &mut ClientSession) {
}

fn save_state(server: &mut Server, client: &mut ClientSession, path: &str) {
debug!("saving state to file {}", path);
let mut file = match File::create(path) {
let mut path = PathBuf::from(path);
if path.is_relative() {
match std::env::current_dir() {
Ok(cwd) => path = cwd.join(path),
Err(error) => {
client.finish_failure(format!("Cannot get Sōzu working directory: {error}",));
return;
}
}
}

debug!("saving state to file {}", &path.display());
let mut file = match File::create(&path) {
Ok(file) => file,
Err(error) => {
client.finish_failure(format!("Cannot create file at path {path}: {error}"));
client.finish_failure(format!(
"Cannot create file at path {}: {error}",
path.display()
));
return;
}
};

match server.state.write_requests_to_file(&mut file) {
Ok(counter) => {
client.finish_ok(format!("Saved {counter} config messages to {path}"));
client.finish_ok(format!(
"Saved {counter} config messages to {}",
&path.display()
));
}
Err(error) => {
client.finish_failure(format!("Failed writing state to file: {error}"));
Expand Down
2 changes: 2 additions & 0 deletions bin/src/ctl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ pub enum CtlError {
WrongResponse(Response),
#[error("could not setup the logger: {0}")]
SetupLogging(LogError),
#[error("could not resolve path for {0} : {1}")]
ResolvePath(String, std::io::Error),
}

pub struct CommandManager {
Expand Down
8 changes: 7 additions & 1 deletion bin/src/ctl/request_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ impl CommandManager {
pub fn save_state(&mut self, path: String) -> Result<(), CtlError> {
debug!("Saving the state to file {}", path);

self.send_request(RequestType::SaveState(path).into())
let current_directory =
std::env::current_dir().map_err(|err| CtlError::ResolvePath(path.to_owned(), err))?;

let absolute_path = current_directory.join(&path);
self.send_request(
RequestType::SaveState(String::from(absolute_path.to_string_lossy())).into(),
)
}

pub fn load_state(&mut self, path: String) -> Result<(), CtlError> {
Expand Down

0 comments on commit 29277c2

Please sign in to comment.