obnam_benchmark/
client.rs

1use log::debug;
2use serde::Serialize;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5use tempfile::{tempdir, TempDir};
6
7#[derive(Debug, thiserror::Error)]
8pub enum ObnamClientError {
9    #[error("failed to create temporary directory for server: {0}")]
10    TempDir(std::io::Error),
11
12    #[error("failed to write client configuration to {0}: {1}")]
13    WriteConfig(PathBuf, std::io::Error),
14
15    #[error("failed to run obnam: {0}")]
16    Run(std::io::Error),
17}
18
19#[derive(Debug)]
20pub struct ObnamClient {
21    binary: PathBuf,
22    #[allow(dead_code)]
23    tempdir: TempDir,
24    #[allow(dead_code)]
25    config: PathBuf,
26}
27
28impl ObnamClient {
29    pub fn new(
30        client_binary: &Path,
31        server_url: String,
32        root: PathBuf,
33    ) -> Result<Self, ObnamClientError> {
34        debug!("creating ObnamClient");
35        let tempdir = tempdir().map_err(ObnamClientError::TempDir)?;
36        let config_filename = tempdir.path().join("client.yaml");
37
38        let config = ClientConfig::new(server_url, root);
39        config.write(&config_filename)?;
40
41        Ok(Self {
42            binary: client_binary.to_path_buf(),
43            tempdir,
44            config: config_filename,
45        })
46    }
47
48    pub fn run(&self, args: &[&str]) -> Result<String, ObnamClientError> {
49        let output = Command::new(&self.binary)
50            .arg("--config")
51            .arg(&self.config)
52            .args(args)
53            .output()
54            .map_err(ObnamClientError::Run)?;
55        if output.status.code() != Some(0) {
56            eprintln!("{}", String::from_utf8_lossy(&output.stdout));
57            eprintln!("{}", String::from_utf8_lossy(&output.stderr));
58            std::process::exit(1);
59        }
60
61        Ok(String::from_utf8_lossy(&output.stdout)
62            .to_owned()
63            .to_string())
64    }
65}
66
67#[derive(Debug, Serialize)]
68pub struct ClientConfig {
69    server_url: String,
70    verify_tls_cert: bool,
71    roots: Vec<PathBuf>,
72    log: PathBuf,
73}
74
75impl ClientConfig {
76    fn new(server_url: String, root: PathBuf) -> Self {
77        Self {
78            server_url,
79            verify_tls_cert: false,
80            roots: vec![root],
81            log: PathBuf::from("obnam.log"),
82        }
83    }
84
85    fn write(&self, filename: &Path) -> Result<(), ObnamClientError> {
86        std::fs::write(filename, serde_yaml::to_string(self).unwrap())
87            .map_err(|err| ObnamClientError::WriteConfig(filename.to_path_buf(), err))?;
88        Ok(())
89    }
90}