run cargo fmt

This commit is contained in:
Yan Ka, Chiu
2023-07-01 13:16:29 +08:00
parent a116386ff0
commit e4e26a3762
10 changed files with 76 additions and 72 deletions

View File

@@ -40,7 +40,7 @@ extern "C" {
pub type Notify = tokio::sync::Notify;
/// Notify like construct but backed by non-blocking eventfd(2). The fd is than closed when this
/// struct dropped.
/// struct dropped.
///
/// There are few reason to use this instead of tokio::sync::Notify, one being since this is
/// eventfd based, it can be send across processes. It can also use synchronously by calling

View File

@@ -57,10 +57,7 @@ pub(crate) fn use_image_action(
config,
} => {
use std::os::fd::AsRawFd;
let config_file = std::fs::OpenOptions::new()
.read(true)
.open(config)
.unwrap();
let config_file = std::fs::OpenOptions::new().read(true).open(config).unwrap();
let config: xc::models::jail_image::JailConfig =
serde_json::from_reader(config_file).unwrap();
let file = std::fs::OpenOptions::new().read(true).open(path).unwrap();

View File

@@ -299,7 +299,7 @@ fn main() -> Result<(), ActionError> {
} => {
let req = PushImageRequest {
image_reference: image_reference.clone(),
remote_reference: new_image_reference.clone()
remote_reference: new_image_reference.clone(),
};
if let Ok(_res) = do_push_image(&mut conn, req)? {
let mut lines_count = 0;
@@ -311,7 +311,7 @@ fn main() -> Result<(), ActionError> {
let reqt = UploadStat {
image_reference: image_reference.clone(),
remote_reference: new_image_reference.clone()
remote_reference: new_image_reference.clone(),
};
let res = do_upload_stat(&mut conn, reqt)?.unwrap();
if let Some(error) = res.fault {
@@ -330,30 +330,33 @@ fn main() -> Result<(), ActionError> {
match i.cmp(&x) {
Ordering::Less => eprintln!("{digest} ... done"),
Ordering::Equal => {
let speed = res.duration_secs
.and_then(|secs|
res.bytes.map(|bytes| (bytes * 8) as f64/secs as f64));
let uploaded = res.bytes.map(|bytes| {
let bytes = bytes as f64;
if bytes > 1000000000.0 {
format!("{:.2} GB", bytes / 1000000000.0)
} else if bytes > 1000000.0 {
format!("{:.2} MB", bytes / 1000000.0)
} else if bytes > 1000.0 {
format!("{:.2} KB", bytes / 1000.0)
} else {
format!("{:.2} B", bytes)
}
}).unwrap_or_else(|| "".to_string());
let speed = res.duration_secs.and_then(|secs| {
res.bytes.map(|bytes| (bytes * 8) as f64 / secs as f64)
});
let uploaded = res
.bytes
.map(|bytes| {
let bytes = bytes as f64;
if bytes > 1000000000.0 {
format!("{:.2} GB", bytes / 1000000000.0)
} else if bytes > 1000000.0 {
format!("{:.2} MB", bytes / 1000000.0)
} else if bytes > 1000.0 {
format!("{:.2} KB", bytes / 1000.0)
} else {
format!("{:.2} B", bytes)
}
})
.unwrap_or_else(|| "".to_string());
let label = match speed {
None => "".to_string(),
Some(speed) => {
if speed > 1000000000.0 {
format!("{:.2} gbps", speed/1000000000.0)
format!("{:.2} gbps", speed / 1000000000.0)
} else if speed > 1000000.0 {
format!("{:.2} mbps", speed/1000000.0)
format!("{:.2} mbps", speed / 1000000.0)
} else if speed > 1000.0 {
format!("{:.2} kbps", speed/1000.0)
format!("{:.2} kbps", speed / 1000.0)
} else {
format!("{:.2} bps", speed)
}
@@ -598,7 +601,14 @@ impl<'a> TableSource for PrintManifest<'a> {
if self.0.ip_alloc.is_empty() {
None
} else {
Some(self.0.ip_alloc.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(","))
Some(
self.0
.ip_alloc
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(","),
)
}
}
_ => None,

View File

@@ -253,9 +253,7 @@ impl ProcessRunner {
let log_path = format!("/var/log/xc.{}.{}.log", self.container.id, id);
spawn_process_pty(cmd, &log_path, &socket_path)?
}
StdioMode::Files { stdout, stderr } => {
spawn_process_files(&mut cmd, stdout, stderr)?
}
StdioMode::Files { stdout, stderr } => spawn_process_files(&mut cmd, stdout, stderr)?,
StdioMode::Inherit => {
let out_path = format!("/var/log/xc.{}.{}.out.log", self.container.id, id);
let err_path = format!("/var/log/xc.{}.{}.err.log", self.container.id, id);
@@ -400,7 +398,8 @@ impl ProcessRunner {
if inits.queue_processes_check_if_drain(
stat.id(),
&mut next_processes,
) && !self.container.main_norun {
) && !self.container.main_norun
{
self.should_run_main = true;
}

View File

@@ -81,7 +81,7 @@ impl std::fmt::Display for PortNum {
pub enum NetProto {
Tcp,
Udp,
Sctp
Sctp,
}
impl std::fmt::Display for NetProto {
@@ -89,7 +89,7 @@ impl std::fmt::Display for NetProto {
match self {
Self::Tcp => write!(formatter, "tcp"),
Self::Udp => write!(formatter, "udp"),
Self::Sctp => write!(formatter, "sctp")
Self::Sctp => write!(formatter, "sctp"),
}
}
}
@@ -99,7 +99,7 @@ impl AsRef<str> for NetProto {
match self {
Self::Tcp => "tcp",
Self::Udp => "udp",
Self::Sctp => "sctp"
Self::Sctp => "sctp",
}
}
}

View File

@@ -195,7 +195,7 @@ pub fn exists_exec(
pub enum CompressionFormat {
Other,
Zstd,
Gzip
Gzip,
}
pub trait CompressionFormatExt {
@@ -210,7 +210,7 @@ impl CompressionFormatExt for std::fs::File {
if unsafe { freebsd::libc::pread(fd, magic.as_mut_ptr().cast(), 4, 0) } == -1 {
Err(std::io::Error::last_os_error())
} else if magic[..2] == [0x1f, 0x8b] {
Ok(CompressionFormat::Gzip)
Ok(CompressionFormat::Gzip)
} else if magic == [0x28, 0xb5, 0x2f, 0xfd] {
Ok(CompressionFormat::Zstd)
} else {

View File

@@ -410,13 +410,13 @@ impl ServerContext {
pub(crate) async fn push_image(
&self,
reference: ImageReference,
remote_reference: ImageReference
remote_reference: ImageReference,
) -> Result<(), crate::image::PushImageError> {
_ = ImageManager::push_image(
self.image_manager.clone(),
&self.config_manager.config().layers_dir,
reference,
remote_reference
remote_reference,
)
.await?;
Ok(())

View File

@@ -432,14 +432,13 @@ impl ImageManager {
pub async fn push_image(
this: Arc<RwLock<Self>>,
layers_dir: &str,
// registry: &str,
// registry: &str,
reference: ImageReference,
remote_reference: ImageReference,
// name: &str,
// tag: &str,
// name: &str,
// tag: &str,
) -> Result<Receiver<Task<String, PushImageStatus>>, PushImageError> {
// let id = reference.to_string();
// let id = reference.to_string();
let id = format!("{reference}->{remote_reference}");
let name = remote_reference.name;
let tag = remote_reference.tag.to_string();
@@ -454,7 +453,8 @@ impl ImageManager {
.await
.map_err(|_| PushImageError::NoSuchLocalReference)?;
let registry = remote_reference.hostname
let registry = remote_reference
.hostname
.and_then(|registry| reg.get_registry_by_name(&registry))
.ok_or(PushImageError::RegistryNotFound)?;
@@ -478,7 +478,7 @@ impl ImageManager {
let mut session = registry.new_session(name.to_string());
let layers = record.manifest.layers().clone();
let mut selections = Vec::new();
// let (tx, upload_status) = tokio::sync::watch::channel(UploadStat::default());
// let (tx, upload_status) = tokio::sync::watch::channel(UploadStat::default());
'layer_loop: for layer in layers.iter() {
let maps = {
@@ -528,7 +528,7 @@ impl ImageManager {
let path = std::path::Path::new(&path);
let file = std::fs::OpenOptions::new().read(true).open(path)?;
// let dedup_check = Ok::<bool, std::io::Error>(false);
// let dedup_check = Ok::<bool, std::io::Error>(false);
let dedup_check = session.exists_digest(&map.archive_digest).await;
_ = emitter.use_try(|state| {
@@ -629,7 +629,9 @@ impl ImageManager {
let reg = this.context.registries.lock().await;
match reference.hostname {
None => reg.default_registry().expect("no default registry found"),
Some(name) => reg.get_registry_by_name(&name).expect("no such registry"),
Some(name) => reg
.get_registry_by_name(&name)
.unwrap_or_else(|| Registry::new(name, None)),
}
};
@@ -850,7 +852,7 @@ pub struct PushImageStatusDesc {
pub fault: Option<String>,
pub bytes: Option<usize>,
pub duration_secs: Option<u64>
pub duration_secs: Option<u64>,
}
#[derive(Clone, Default)]
@@ -862,23 +864,19 @@ pub struct PushImageStatus {
pub push_manifest: bool,
pub done: bool,
pub fault: Option<String>,
pub upload_status: Option<Receiver<UploadStat>>
pub upload_status: Option<Receiver<UploadStat>>,
}
impl PushImageStatus {
fn to_desc(&self) -> PushImageStatusDesc {
let (bytes, duration_secs) = match &self.upload_status {
None => {
(None, None)
},
None => (None, None),
Some(receiver) => {
let stat = receiver.borrow();
if let Some((bytes, elapsed)) = stat.started_at.and_then(|started_at| {
stat.uploaded.map(|bytes| {
(bytes, started_at.elapsed().unwrap().as_secs())
})
})
{
stat.uploaded
.map(|bytes| (bytes, started_at.elapsed().unwrap().as_secs()))
}) {
(Some(bytes), Some(elapsed))
} else {
(None, None)
@@ -892,7 +890,8 @@ impl PushImageStatus {
push_manifest: self.push_manifest,
done: self.done,
fault: self.fault.clone(),
bytes, duration_secs
bytes,
duration_secs,
}
}
}

View File

@@ -44,7 +44,7 @@ use xc::container::request::{MountReq, NetworkAllocRequest};
use xc::models::jail_image::JailConfig;
use xc::models::network::{DnsSetting, IpAssign, PortRedirection};
use xc::res::network::Network;
use xc::util::{gen_id, CompressionFormatExt, CompressionFormat};
use xc::util::{gen_id, CompressionFormat, CompressionFormatExt};
#[derive(FromPacket, Debug)]
pub struct CreateChannelRequest {
@@ -242,7 +242,7 @@ async fn instantiate(
#[derive(Serialize, Deserialize, Debug)]
pub struct UploadStat {
pub image_reference: ImageReference,
pub remote_reference: ImageReference
pub remote_reference: ImageReference,
}
#[ipc_method(method = "upload_stat")]
@@ -251,7 +251,7 @@ async fn upload_stat(
local_context: &mut ConnectionContext<Variables>,
request: UploadStat,
) -> GenericResult<crate::image::PushImageStatusDesc> {
// let id = request.image_reference.to_string();
// let id = request.image_reference.to_string();
let id = format!("{}->{}", request.image_reference, request.remote_reference);
let state = context
.read()
@@ -595,7 +595,7 @@ async fn fd_import(
let content_type = match file.compression_format().expect("cannot read magic") {
CompressionFormat::Gzip => "gzip",
CompressionFormat::Zstd => "zstd",
CompressionFormat::Other => "plain"
CompressionFormat::Other => "plain",
};
info!("import: content_type is {content_type}");
@@ -771,16 +771,13 @@ async fn push_image(
request: PushImageRequest,
) -> Result<PushImageResponse, ipc::proto::ErrResponse<crate::image::PushImageError>> {
let ctx = context.read().await;
ctx.push_image(
request.image_reference,
request.remote_reference
)
.await
.map(|_| PushImageResponse {})
.map_err(|err| ipc::proto::ErrResponse {
value: err,
errno: 1,
})
ctx.push_image(request.image_reference, request.remote_reference)
.await
.map(|_| PushImageResponse {})
.map_err(|err| ipc::proto::ErrResponse {
value: err,
errno: 1,
})
}
#[allow(non_upper_case_globals)]

View File

@@ -44,7 +44,9 @@ pub async fn xmain() -> Result<(), anyhow::Error> {
let config_path = "/usr/local/etc/xc.conf";
info!("loading configuration from {config_path}");
match ConfigManager::load_from_path(config_path) {
Err(error) => { error!("{error:#?}"); },
Err(error) => {
error!("{error:#?}");
}
Ok(config_manager) => {
let xc_config = config_manager.config();
let path = xc_config.socket_path.to_string();