GrammalecteClient/src/server.rs

180 lines
5.5 KiB
Rust
Raw Normal View History

use crate::server::utils::{get_free_port, wait_for_server};
2022-12-19 11:20:44 +00:00
use mktemp::Temp;
use std::io::{self, Cursor, Read};
use std::process::{Child, ExitStatus, Stdio};
use thiserror::Error;
use zip::{result::ZipError, ZipArchive};
#[derive(Debug, Error)]
pub enum Error {
#[error("Grammalecte-server failed to launch process")]
StartServerProcess(#[source] io::Error),
#[error("Get an available port failed")]
GetFreePort(#[source] io::Error),
#[error("Server exit with `{status}`")]
ServerExitWithStatus { status: ExitStatus },
#[error("Server exit with `{status}` :\n{msg}")]
ServerExitWithError { status: ExitStatus, msg: String },
#[error("Error append during check grammalecte-server status")]
ServerCheckStatus(#[source] io::Error),
#[error("Port {port} did not open in time!")]
WaitPortOpen { port: u16 },
#[error("Create temporary directory failed")]
CreateTempDir(#[source] io::Error),
#[error("Zip archive loading failed")]
ZipArchiveLoading(#[source] ZipError),
#[error("Access file by index failed")]
ZipFileIndex(#[source] ZipError),
#[error("Create directory for files from zip")]
CreateDirectoryForZipFile(#[source] io::Error),
#[error("Read file from zip archive")]
ZipFileReadToEnd(#[source] io::Error),
#[error("Write file from archive on disk")]
WriteFile(#[source] io::Error),
}
2022-12-19 11:20:44 +00:00
pub struct EmbeddedServer {
_srv_dir: Temp,
port: u16,
child: Child,
}
impl EmbeddedServer {
2023-05-23 12:46:45 +00:00
/// Start embedded Grammalecte server on a random free port
pub fn start() -> Result<Self, Error> {
Self::start_listen_on_port(get_free_port())
2023-05-23 12:46:45 +00:00
}
/// Start embedded Grammalecte server on a given port
pub fn start_listen_on_port(port: u16) -> Result<Self, Error> {
2022-12-19 11:20:44 +00:00
log::info!("Will start server");
// First, unpack server
let dest = mktemp::Temp::new_dir().map_err(Error::CreateTempDir)?;
2022-12-19 11:20:44 +00:00
let cursor = Cursor::new(include_bytes!("GrammalecteDist.zip"));
let mut zip = ZipArchive::new(cursor).map_err(Error::ZipArchiveLoading)?;
2022-12-19 11:20:44 +00:00
for i in 0..zip.len() {
let mut file = zip.by_index(i).map_err(Error::ZipFileIndex)?;
2022-12-19 11:20:44 +00:00
if file.is_dir() {
log::debug!("Create directory: {}", file.name());
std::fs::create_dir_all(dest.join(file.name()))
.map_err(Error::CreateDirectoryForZipFile)?;
2022-12-19 11:20:44 +00:00
} else {
log::debug!("Decompress file: {}", file.name());
let mut buff = Vec::with_capacity(file.size() as usize);
file.read_to_end(&mut buff)
.map_err(Error::ZipFileReadToEnd)?;
2022-12-19 11:20:44 +00:00
std::fs::write(dest.join(file.name()), buff).map_err(Error::WriteFile)?;
2022-12-19 11:20:44 +00:00
}
}
log::info!("Will start to listen on port {}", port);
let server_file = dest
.join("grammalecte/grammalecte-server.py")
.to_string_lossy()
.to_string();
log::info!("Will execute file {}", server_file);
// Start server
let mut child = std::process::Command::new("/usr/bin/python3")
2022-12-19 11:20:44 +00:00
.arg(server_file)
.arg("-p")
.arg(port.to_string())
2022-12-19 13:05:16 +00:00
.stdout(Stdio::null())
.stderr(Stdio::piped())
.spawn()
.map_err(Error::StartServerProcess)?;
2022-12-19 11:20:44 +00:00
wait_for_server(&mut child, port)?;
2022-12-19 11:20:44 +00:00
Ok(Self {
_srv_dir: dest,
port,
child,
})
}
/// Get embedde instance base URL
pub fn base_url(&self) -> String {
format!("http://localhost:{}", self.port)
}
}
impl Drop for EmbeddedServer {
fn drop(&mut self) {
let _ = self.child.kill();
}
}
mod utils {
use super::Error;
use std::fmt::Write;
use std::io::{BufRead, BufReader};
use std::process::Child;
use std::time::Duration;
2022-12-19 11:20:44 +00:00
/// Get a free port
pub fn get_free_port() -> u16 {
2022-12-19 11:20:44 +00:00
let mut port = 0;
while !(2000..=64000).contains(&port) {
port = rand::random::<u16>() % 64000;
}
while port_scanner::scan_port(port) {
port += 1;
}
port
2022-12-19 11:20:44 +00:00
}
pub fn wait_for_server(child: &mut Child, port: u16) -> Result<(), Error> {
2022-12-19 11:20:44 +00:00
for _ in 0..50 {
check_server(child)?;
2022-12-19 11:20:44 +00:00
if port_scanner::scan_port(port) {
return Ok(());
}
std::thread::sleep(Duration::from_millis(100));
}
Err(Error::WaitPortOpen { port })
2022-12-19 11:20:44 +00:00
}
fn check_server(child: &mut Child) -> Result<(), Error> {
match child.try_wait().map_err(Error::ServerCheckStatus)? {
None => Ok(()), // Continue
Some(status) => {
if let Some(err) = child.stderr.take() {
let mut msg = format!("grammalecte-server exit with `{status}`");
writeln!(&mut msg, " :").unwrap();
let err = BufReader::new(err);
err.lines().for_each(|line| match line {
Ok(line) => {
writeln!(&mut msg, "\t{}", line).unwrap();
}
Err(err) => {
writeln!(&mut msg, "__{err:?}").unwrap();
}
});
Err(Error::ServerExitWithError { status, msg })
} else {
Err(Error::ServerExitWithStatus { status })
}
}
}
}
2022-12-19 11:20:44 +00:00
}