use std::io::{Read as _, Write as _};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use printobserver_types::serde::Deserialize;
const LAUNCH_FILE: &str = "launch.json";
const LOG_FILE: &str = "launcher.log";
const ANSWERED: &str = "200";
#[derive(Clone, Copy)]
enum Report {
Started,
Exited,
CompactionStarted,
CompactionExited,
CheckStarted,
CheckExited,
}
impl Report {
const fn path(self) -> &'static str {
match self {
Self::Started => "/started",
Self::Exited => "/exited",
Self::CompactionStarted => "/compaction-started",
Self::CompactionExited => "/compaction-exited",
Self::CheckStarted => "/check-started",
Self::CheckExited => "/check-exited",
}
}
}
const COMPACT_PROMPT: &str = "/compact";
const STATUS_COMMAND: &str = "auth";
const TEXT_INPUT: [&str; 2] = ["--input-format", "text"];
fn text_prompt(arguments: &[String]) -> Result<Option<Vec<u8>>, String> {
if !arguments.windows(2).any(|pair| pair == TEXT_INPUT) {
return Ok(None);
}
let mut prompt = Vec::new();
std::io::stdin()
.read_to_end(&mut prompt)
.map_err(|error| format!("the prompt could not be read: {error}"))?;
Ok(Some(prompt))
}
fn tell(control: SocketAddr, report: Report) -> Result<String, String> {
let failed = |error: std::io::Error| format!("{control} did not answer: {error}");
let mut stream = TcpStream::connect(control).map_err(failed)?;
let path = report.path();
stream
.write_all(
format!(
"POST {path} HTTP/1.1\r\nHost: {control}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
)
.as_bytes(),
)
.map_err(failed)?;
let mut answer = String::new();
stream.read_to_string(&mut answer).map_err(failed)?;
let (head, body) = answer
.split_once("\r\n\r\n")
.ok_or_else(|| format!("{control} answered {path} with no whole response"))?;
if head.split_whitespace().nth(1) != Some(ANSWERED) {
return Err(format!("{control} refused {path}: {head}"));
}
let declared = head.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse::<usize>().ok())?
});
if declared != Some(body.len()) {
return Err(format!("{control} answered {path} with no whole response"));
}
Ok(body.to_owned())
}
#[derive(Deserialize)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
struct Launch {
control: SocketAddr,
program: PathBuf,
#[serde(default)]
arguments: Vec<String>,
}
fn launch() -> Result<Launch, String> {
let beside = std::env::current_exe()
.map_err(|error| format!("this program cannot find itself: {error}"))?
.with_file_name(LAUNCH_FILE);
let text = std::fs::read_to_string(&beside)
.map_err(|error| format!("{} is unreadable: {error}", beside.display()))?;
serde_json::from_str(&text)
.map_err(|error| format!("{} is no launch file: {error}", beside.display()))
}
fn passed_through(launch: &Launch) -> Result<ExitCode, String> {
let program = launch.program.display();
let status = Command::new(&launch.program)
.args(&launch.arguments)
.args(std::env::args_os().skip(1))
.status()
.map_err(|error| format!("{program} could not be started: {error}"))?;
Ok(status
.code()
.and_then(|code| u8::try_from(code).ok())
.map_or(ExitCode::FAILURE, ExitCode::from))
}
fn run(launch: &Launch, record: &Path, prompt: Option<Vec<u8>>) -> Result<ExitCode, String> {
let program = launch.program.display();
let mut kept = std::fs::File::create(record)
.map_err(|error| format!("{} could not be created: {error}", record.display()))?;
let mut child = Command::new(&launch.program)
.args(&launch.arguments)
.args(std::env::args_os().skip(1))
.stdin(if prompt.is_some() {
Stdio::piped()
} else {
Stdio::inherit()
})
.stderr(Stdio::inherit())
.stdout(Stdio::piped())
.spawn()
.map_err(|error| format!("{program} could not be started: {error}"))?;
let feeding = prompt
.zip(child.stdin.take())
.map(|(prompt, mut to_child)| {
std::thread::spawn(move || to_child.write_all(&prompt))
});
let mut from_child = child
.stdout
.take()
.ok_or_else(|| format!("{program} was started with no output to read"))?;
let mut to_caller = std::io::stdout();
let mut piece = [0_u8; 8192];
loop {
let count = from_child
.read(&mut piece)
.map_err(|error| format!("{program}'s output could not be read: {error}"))?;
let Some(read) = piece.get(..count).filter(|read| !read.is_empty()) else {
break;
};
to_caller
.write_all(read)
.and_then(|()| to_caller.flush())
.map_err(|error| format!("the output could not be passed on: {error}"))?;
kept.write_all(read)
.map_err(|error| format!("{} could not be written: {error}", record.display()))?;
}
let status = child
.wait()
.map_err(|error| format!("{program} could not be waited for: {error}"))?;
if let Some(feeding) = feeding {
let _ = feeding.join();
}
Ok(status
.code()
.and_then(|code| u8::try_from(code).ok())
.map_or(ExitCode::FAILURE, ExitCode::from))
}
fn launched() -> Result<ExitCode, String> {
let launch = launch()?;
let arguments: Vec<String> = std::env::args().skip(1).collect();
if arguments.first().map(String::as_str) == Some(STATUS_COMMAND) {
return passed_through(&launch);
}
let prompt = text_prompt(&arguments)?;
let checking = prompt.as_deref().is_some_and(|prompt| {
String::from_utf8_lossy(prompt).trim() == printobserver_server::readiness::check_prompt()
});
let (started, exited) = if arguments.iter().any(|argument| argument == COMPACT_PROMPT) {
(Report::CompactionStarted, Report::CompactionExited)
} else if checking {
(Report::CheckStarted, Report::CheckExited)
} else {
(Report::Started, Report::Exited)
};
let record = tell(launch.control, started)?;
let status = run(&launch, Path::new(record.trim()), prompt)?;
tell(launch.control, exited)?;
Ok(status)
}
fn keep_the_reason(why: &str) {
let Ok(program) = std::env::current_exe() else {
return;
};
if let Ok(mut log) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(program.with_file_name(LOG_FILE))
{
let _ = writeln!(log, "{why}");
}
}
fn main() -> ExitCode {
launched().unwrap_or_else(|why| {
eprintln!("printobserver-server-turn-launcher: {why}");
keep_the_reason(&why);
ExitCode::FAILURE
})
}