1
0
Fork 0
mirror of https://codeberg.org/icewind/haze.git synced 2026-06-03 17:14:08 +02:00
This commit is contained in:
Robin Appelman 2022-01-11 17:22:51 +01:00
commit 701d3b2a82
20 changed files with 303 additions and 172 deletions

View file

@ -1,6 +1,6 @@
use crate::cloud::CloudOptions;
use crate::service::{Service, ServiceTrait};
use color_eyre::{Report, Result};
use miette::{IntoDiagnostic, Report, Result};
use parse_display::Display;
use std::fmt::Display;
use std::str::FromStr;
@ -178,7 +178,11 @@ impl HazeArgs {
Ok(HazeArgs::Logs {
filter,
service,
count: args.next().map(|arg| arg.as_ref().parse()).transpose()?,
count: args
.next()
.map(|arg| arg.as_ref().parse())
.transpose()
.into_diagnostic()?,
})
}
HazeCommand::Open => Ok(HazeArgs::Open { filter }),

View file

@ -10,9 +10,9 @@ use bollard::models::ContainerState;
use bollard::network::CreateNetworkOptions;
use bollard::Docker;
use camino::Utf8PathBuf;
use color_eyre::{eyre::WrapErr, Report, Result};
use flate2::read::GzDecoder;
use futures_util::future::try_join_all;
use miette::{IntoDiagnostic, Report, Result, WrapErr};
use petname::petname;
use std::collections::HashMap;
use std::fmt::Display;
@ -167,6 +167,7 @@ impl Cloud {
if !options.app_packages.is_empty() {
create_dir_all(&app_package_dir)
.await
.into_diagnostic()
.wrap_err("Failed to create directory for app packages")?;
}
@ -178,13 +179,15 @@ impl Cloud {
let app_dir = app_package_dir.join(app_name);
let app_package_file = fs::File::open(&app_package)
.into_diagnostic()
.wrap_err_with(|| format!("Failed to open app bundle {}", app_package))?;
if app_package.metadata()?.len() > 1024 * 1024 {
if app_package.metadata().into_diagnostic()?.len() > 1024 * 1024 {
println!("Extracting app archive for {}...", app_name);
}
let gz = GzDecoder::new(app_package_file);
tar::Archive::new(gz)
.unpack(&app_package_dir)
.into_diagnostic()
.wrap_err_with(|| format!("Failed to extract app bundle {}", app_package))?;
Ok(HazeVolumeConfig {
@ -214,12 +217,16 @@ impl Cloud {
name: id.as_str(),
..Default::default()
})
.await?
.await
.into_diagnostic()?
.id
.ok_or(Report::msg("No network id in response"))
.wrap_err("Failed to create network")?;
let network_info = docker.inspect_network::<String>(&network, None).await?;
let network_info = docker
.inspect_network::<String>(&network, None)
.await
.into_diagnostic()?;
let gateway = network_info
.ipam
.as_ref()
@ -234,7 +241,7 @@ impl Cloud {
let mut containers = Vec::new();
let sources_meta = fs::metadata(&config.sources_root)?;
let sources_meta = fs::metadata(&config.sources_root).into_diagnostic()?;
let uid = sources_meta.uid();
let gid = sources_meta.gid();
@ -293,7 +300,10 @@ impl Cloud {
let mut tries = 0;
let ip = loop {
let info = docker.inspect_container(&container, None).await?;
let info = docker
.inspect_container(&container, None)
.await
.into_diagnostic()?;
if matches!(
info.state,
Some(ContainerState {
@ -375,15 +385,18 @@ impl Cloud {
}),
)
.await
.into_diagnostic()
.wrap_err("Failed to remove container")?;
}
docker
.remove_network(&self.network)
.await
.into_diagnostic()
.wrap_err("Failed to remove network")?;
if self.workdir.exists() {
if let Err(e) = remove_dir_all(self.workdir)
.await
.into_diagnostic()
.wrap_err("Failed to remove work directory")
{
eprintln!("{}", e);
@ -435,7 +448,8 @@ impl Cloud {
all: true,
..Default::default()
}))
.await?;
.await
.into_diagnostic()?;
let mut containers_by_id: HashMap<String, (Option<_>, Vec<_>)> = HashMap::new();
for container in containers {
let labels = container.labels.clone().unwrap_or_default();

View file

@ -1,6 +1,6 @@
use camino::Utf8PathBuf;
use color_eyre::{eyre::WrapErr, Report, Result};
use directories_next::ProjectDirs;
use miette::{IntoDiagnostic, Report, Result, WrapErr};
use serde::Deserialize;
use std::fs::read;
@ -66,7 +66,11 @@ impl HazeConfig {
file.to_string_lossy()
)));
}
let content = read(&file).wrap_err("Failed to read config file")?;
toml::from_slice(&content).wrap_err("Failed to parse config file")
let content = read(&file)
.into_diagnostic()
.wrap_err("Failed to read config file")?;
toml::from_slice(&content)
.into_diagnostic()
.wrap_err("Failed to parse config file")
}
}

View file

@ -3,8 +3,8 @@ use crate::image::pull_image;
use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{EndpointSettings, HostConfig};
use bollard::Docker;
use color_eyre::{eyre::WrapErr, Report, Result};
use maplit::hashmap;
use miette::{IntoDiagnostic, Report, Result, WrapErr};
use std::io::{stdout, Stdout};
use std::str::FromStr;
use std::time::Duration;
@ -208,8 +208,15 @@ impl Database {
},
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(Some(id))
}
@ -280,6 +287,7 @@ impl Database {
Ok(())
})
.await
.into_diagnostic()
.wrap_err("Timeout after 15 seconds")?
}
@ -297,7 +305,7 @@ impl Database {
Some(&mut output),
)
.await?;
let output = String::from_utf8(output)?;
let output = String::from_utf8(output).into_diagnostic()?;
Ok(!output.contains("ERROR"))
}
DatabaseFamily::Postgres => {

View file

@ -1,8 +1,8 @@
use bollard::container::LogsOptions;
use bollard::exec::{CreateExecOptions, ResizeExecOptions, StartExecResults};
use bollard::Docker;
use color_eyre::{eyre::WrapErr, Report, Result};
use futures_util::StreamExt;
use miette::{IntoDiagnostic, Report, Result, WrapErr};
use std::io::{stdout, Read, Write};
use std::time::Duration;
use termion::raw::IntoRawMode;
@ -24,7 +24,7 @@ pub async fn exec_tty<S1: AsRef<str>, S2: Into<String>>(
return exec(docker, container, user, cmd, env, Some(stdout)).await;
}
let tty_size = terminal_size()?;
let tty_size = terminal_size().into_diagnostic()?;
let cmd = cmd.into_iter().map(S2::into).collect();
let env = env.into_iter().map(String::from).collect();
let config = CreateExecOptions {
@ -40,6 +40,7 @@ pub async fn exec_tty<S1: AsRef<str>, S2: Into<String>>(
let message = docker
.create_exec(container.as_ref(), config)
.await
.into_diagnostic()
.wrap_err("Failed to setup exec")?;
if let StartExecResults::Attached {
mut output,
@ -47,6 +48,7 @@ pub async fn exec_tty<S1: AsRef<str>, S2: Into<String>>(
} = docker
.start_exec(&message.id, None)
.await
.into_diagnostic()
.wrap_err("Failed to start exec")?
{
docker
@ -73,12 +75,14 @@ pub async fn exec_tty<S1: AsRef<str>, S2: Into<String>>(
});
// set stdout in raw mode so we can do tty stuff
let mut stdout = stdout.lock().into_raw_mode()?;
let mut stdout = stdout.lock().into_raw_mode().into_diagnostic()?;
// pipe docker exec output into stdout
while let Some(Ok(output)) = output.next().await {
stdout.write(output.into_bytes().as_ref())?;
stdout.flush()?;
stdout
.write(output.into_bytes().as_ref())
.into_diagnostic()?;
stdout.flush().into_diagnostic()?;
}
} else {
unreachable!();
@ -86,7 +90,8 @@ pub async fn exec_tty<S1: AsRef<str>, S2: Into<String>>(
Ok(docker
.inspect_exec(&message.id)
.await?
.await
.into_diagnostic()?
.exit_code
.unwrap_or_default()
.into())
@ -114,15 +119,17 @@ pub async fn exec<S1: AsRef<str>, S2: Into<String>>(
let message = docker
.create_exec(container.as_ref(), config)
.await
.into_diagnostic()
.wrap_err("Failed to setup exec")?;
if let StartExecResults::Attached { mut output, .. } = docker
.start_exec(&message.id, None)
.await
.into_diagnostic()
.wrap_err("Failed to start exec")?
{
while let Some(Ok(line)) = output.next().await {
if let Some(std_out) = &mut std_out {
write!(std_out, "{}", line)?;
write!(std_out, "{}", line).into_diagnostic()?;
}
}
} else {
@ -131,7 +138,8 @@ pub async fn exec<S1: AsRef<str>, S2: Into<String>>(
Ok(docker
.inspect_exec(&message.id)
.await?
.await
.into_diagnostic()?
.exit_code
.unwrap_or_default()
.into())
@ -149,7 +157,7 @@ pub async fn container_logs(docker: &Docker, container: &str, count: usize) -> R
}),
);
while let Some(line) = stream.next().await {
logs.push(line?.to_string());
logs.push(line.into_diagnostic()?.to_string());
}
Ok(logs)
}

View file

@ -1,8 +1,8 @@
use bollard::image::CreateImageOptions;
use bollard::models::CreateImageInfo;
use bollard::Docker;
use color_eyre::Result;
use futures_util::StreamExt;
use miette::{IntoDiagnostic, Result};
use std::collections::HashMap;
use std::io::stdout;
use std::io::Write;
@ -29,7 +29,7 @@ pub async fn pull_image(docker: &Docker, image: &str) -> Result<()> {
let mut stdout = stdout();
while let Some(info) = info_stream.next().await {
let info: CreateImageInfo = info?;
let info: CreateImageInfo = info.into_diagnostic()?;
// dbg!(&info);
if let (Some(id), Some(status), Some(progress)) = (info.id, info.status, info.progress)
{
@ -45,14 +45,16 @@ pub async fn pull_image(docker: &Docker, image: &str) -> Result<()> {
status,
progress,
cursor::Restore
)?;
)
.into_diagnostic()?;
}
None => {
writeln!(stdout, "{} - {:12} {}", id, status, progress)?;
writeln!(stdout, "{} - {:12} {}", id, status, progress)
.into_diagnostic()?;
bars.insert(id, bars.len() as u16);
}
}
stdout.flush()?;
stdout.flush().into_diagnostic()?;
}
}
}

View file

@ -7,7 +7,7 @@ use crate::php::PhpVersion;
use crate::service::Service;
use crate::service::ServiceTrait;
use bollard::Docker;
use color_eyre::{eyre::WrapErr, Result};
use miette::{IntoDiagnostic, Result, WrapErr};
mod args;
mod cloud;
@ -22,8 +22,11 @@ mod service;
#[tokio::main]
async fn main() -> Result<()> {
let mut docker =
Docker::connect_with_local_defaults().wrap_err("Failed to connect to docker")?;
miette::set_panic_hook();
let mut docker = Docker::connect_with_local_defaults()
.into_diagnostic()
.wrap_err("Failed to connect to docker")?;
let config = HazeConfig::load().wrap_err("Failed to load config")?;
let args = HazeArgs::parse(std::env::args())?;
@ -212,7 +215,7 @@ async fn main() -> Result<()> {
HazeArgs::Open { filter } => {
let cloud = Cloud::get_by_filter(&mut docker, filter, &config).await?;
match cloud.ip {
Some(ip) => opener::open(format!("http://{}", ip))?,
Some(ip) => opener::open(format!("http://{}", ip)).into_diagnostic()?,
None => eprintln!("{} is not running", cloud.id),
}
}

View file

@ -1,6 +1,6 @@
use crate::config::{HazeConfig, HazeVolumeConfig};
use camino::Utf8Path;
use color_eyre::Result;
use miette::{IntoDiagnostic, Result};
use tokio::fs::{create_dir_all, write};
#[derive(Debug)]
@ -71,8 +71,8 @@ impl<'a> Mapping<'a> {
MappingSourceType::Absolute => self.source.into(),
};
match self.mapping_type {
MappingType::Folder => create_dir_all(source).await?,
MappingType::File => write(source, "").await?,
MappingType::Folder => create_dir_all(source).await.into_diagnostic()?,
MappingType::File => write(source, "").await.into_diagnostic()?,
}
Ok(())
@ -151,6 +151,7 @@ pub fn default_mappings<'a>() -> impl IntoIterator<Item = Mapping<'a>> {
Mapping::new(Sources, ".htaccess", "/var/www/html/.htaccess")
.file()
.read_only(),
Mapping::new(Absolute, "/var/run/docker.sock", "/var/run/docker.sock"),
];
IntoIterator::into_iter(mappings)
}

View file

@ -1,11 +1,12 @@
use bollard::network::CreateNetworkOptions;
use bollard::Docker;
use color_eyre::{eyre::WrapErr, Result};
use miette::{IntoDiagnostic, Result, WrapErr};
pub async fn clear_networks(docker: &Docker) -> Result<()> {
let networks = docker
.list_networks::<&str>(None)
.await
.into_diagnostic()
.wrap_err("Failed to list docker networks")?;
for network in networks {
match network.name.as_deref() {
@ -13,6 +14,7 @@ pub async fn clear_networks(docker: &Docker) -> Result<()> {
docker
.remove_network(name)
.await
.into_diagnostic()
.wrap_err("Failed to remove docker network")?;
}
_ => {}
@ -25,6 +27,7 @@ async fn get_network_id(docker: &Docker, name: &str) -> Result<Option<String>> {
let networks = docker
.list_networks::<&str>(None)
.await
.into_diagnostic()
.wrap_err("Failed to list docker networks")?;
Ok(networks.into_iter().find_map(|network| {
if network.name.as_deref() == Some(name) {
@ -45,7 +48,8 @@ pub async fn ensure_network_exists(docker: &Docker, name: &str) -> Result<String
check_duplicate: true,
..Default::default()
})
.await?
.await
.into_diagnostic()?
.id
.unwrap())
}

View file

@ -5,8 +5,8 @@ use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{EndpointSettings, HostConfig};
use bollard::network::ConnectNetworkOptions;
use bollard::Docker;
use color_eyre::{eyre::WrapErr, Report, Result};
use maplit::hashmap;
use miette::{IntoDiagnostic, Report, Result, WrapErr};
use reqwest::{Client, Url};
use std::net::IpAddr;
use std::str::FromStr;
@ -103,8 +103,15 @@ impl PhpVersion {
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
docker
.connect_network(
@ -117,7 +124,8 @@ impl PhpVersion {
},
},
)
.await?;
.await
.into_diagnostic()?;
Ok(id)
}
@ -127,13 +135,15 @@ impl PhpVersion {
let url = Url::parse(&format!(
"http://{}/status.php",
ip.ok_or(Report::msg("Container not running"))?
))?;
))
.into_diagnostic()?;
timeout(Duration::from_secs(5), async {
while !client.get(url.clone()).send().await.is_ok() {
sleep(Duration::from_millis(100)).await
}
})
.await
.into_diagnostic()
.wrap_err("Timeout after 5 seconds")
}
}

View file

@ -14,8 +14,8 @@ pub use crate::service::push::NotifyPush;
use crate::service::smb::Smb;
use bollard::models::ContainerState;
use bollard::Docker;
use color_eyre::{eyre::WrapErr, Result};
use enum_dispatch::enum_dispatch;
use miette::{IntoDiagnostic, Result, WrapErr};
use std::time::Duration;
use tokio::time::{sleep, timeout};
@ -39,7 +39,8 @@ pub trait ServiceTrait {
async fn is_healthy(&self, docker: &Docker, cloud_id: &str) -> Result<bool> {
let info = docker
.inspect_container(&self.container_name(cloud_id), None)
.await?;
.await
.into_diagnostic()?;
Ok(matches!(
info.state,
Some(ContainerState {
@ -98,6 +99,7 @@ impl Service {
Ok(())
})
.await
.into_diagnostic()
.wrap_err("Timeout after 30 seconds")?
}
}

View file

@ -6,8 +6,8 @@ use crate::Result;
use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{EndpointSettings, HostConfig};
use bollard::Docker;
use color_eyre::eyre::eyre;
use maplit::hashmap;
use miette::{bail, IntoDiagnostic};
use std::io::Stdout;
#[derive(Debug, Clone, Eq, PartialEq)]
@ -32,7 +32,7 @@ impl ServiceTrait for Kaspersky {
) -> Result<String> {
let image = "kaspersky";
if !image_exists(docker, image).await {
eyre!("You need to manually create the 'kaspersky' image");
bail!("You need to manually create the 'kaspersky' image");
}
pull_image(docker, image).await?;
let options = Some(CreateContainerOptions {
@ -58,8 +58,15 @@ impl ServiceTrait for Kaspersky {
}),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(id)
}

View file

@ -5,8 +5,8 @@ use crate::Result;
use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{ContainerState, EndpointSettings, HostConfig};
use bollard::Docker;
use color_eyre::Report;
use maplit::hashmap;
use miette::{IntoDiagnostic, Report};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct LDAP;
@ -55,8 +55,15 @@ impl ServiceTrait for LDAP {
cmd: Some(vec!["--copy-service"]),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(id)
}
@ -116,8 +123,15 @@ impl ServiceTrait for LDAPAdmin {
cmd: Some(vec!["--copy-service"]),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(id)
}
@ -128,7 +142,8 @@ impl ServiceTrait for LDAPAdmin {
async fn start_message(&self, docker: &Docker, cloud_id: &str) -> Result<Option<String>> {
let info = docker
.inspect_container(&self.container_name(cloud_id), None)
.await?;
.await
.into_diagnostic()?;
let ip = if matches!(
info.state,
Some(ContainerState {

View file

@ -7,6 +7,7 @@ use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{EndpointSettings, HostConfig};
use bollard::Docker;
use maplit::hashmap;
use miette::IntoDiagnostic;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ObjectStore {
@ -84,8 +85,15 @@ impl ServiceTrait for ObjectStore {
}),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(id)
}
@ -100,7 +108,7 @@ impl ServiceTrait for ObjectStore {
Some(&mut output),
)
.await?;
let output = String::from_utf8(output)?;
let output = String::from_utf8(output).into_diagnostic()?;
Ok(output.contains(r#""s3": "running""#))
}

View file

@ -5,8 +5,8 @@ use crate::Result;
use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{ContainerState, EndpointSettings, HostConfig};
use bollard::Docker;
use color_eyre::Report;
use maplit::hashmap;
use miette::{IntoDiagnostic, Report};
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct OnlyOffice;
@ -53,8 +53,15 @@ impl ServiceTrait for OnlyOffice {
}),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(id)
}
@ -69,7 +76,8 @@ impl ServiceTrait for OnlyOffice {
async fn post_setup(&self, docker: &Docker, cloud_id: &str) -> Result<Vec<String>> {
let info = docker
.inspect_container(&self.container_name(cloud_id), None)
.await?;
.await
.into_diagnostic()?;
let ip = if matches!(
info.state,
Some(ContainerState {

View file

@ -1,13 +1,11 @@
use crate::config::HazeConfig;
use crate::image::pull_image;
use crate::service::ServiceTrait;
use crate::Result;
use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{ContainerState, EndpointSettings, HostConfig};
use bollard::Docker;
use color_eyre::eyre::WrapErr;
use color_eyre::Report;
use maplit::hashmap;
use miette::{IntoDiagnostic, Report, Result, WrapErr};
use std::time::Duration;
use tokio::time::{sleep, timeout};
@ -66,7 +64,11 @@ impl ServiceTrait for NotifyPush {
cmd: Some(vec!["/notify_push", "/config/config.php"]),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
Ok(id)
}
@ -85,14 +87,16 @@ impl ServiceTrait for NotifyPush {
async fn post_setup(&self, docker: &Docker, cloud_id: &str) -> Result<Vec<String>> {
docker
.start_container::<String>(&self.container_name(cloud_id), None)
.await?;
.await
.into_diagnostic()?;
self.wait_for_push(docker, cloud_id).await?;
sleep(Duration::from_millis(100)).await;
let info = docker
.inspect_container(&self.container_name(cloud_id), None)
.await?;
.await
.into_diagnostic()?;
let ip = if matches!(
info.state,
Some(ContainerState {
@ -124,7 +128,8 @@ impl NotifyPush {
async fn is_push_running(&self, docker: &Docker, cloud_id: &str) -> Result<bool> {
let info = docker
.inspect_container(&self.container_name(cloud_id), None)
.await?;
.await
.into_diagnostic()?;
Ok(matches!(
info.state,
Some(ContainerState {
@ -142,6 +147,7 @@ impl NotifyPush {
Ok(())
})
.await
.into_diagnostic()
.wrap_err("Timeout after 30 seconds")?
}
}

View file

@ -6,6 +6,7 @@ use bollard::container::{Config, CreateContainerOptions, NetworkingConfig};
use bollard::models::{EndpointSettings, HostConfig};
use bollard::Docker;
use maplit::hashmap;
use miette::IntoDiagnostic;
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Smb;
@ -57,8 +58,15 @@ impl ServiceTrait for Smb {
}),
..Default::default()
};
let id = docker.create_container(options, config).await?.id;
docker.start_container::<String>(&id, None).await?;
let id = docker
.create_container(options, config)
.await
.into_diagnostic()?
.id;
docker
.start_container::<String>(&id, None)
.await
.into_diagnostic()?;
Ok(id)
}