Generalize disk file creation logic
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2025-05-29 08:03:42 +02:00
parent 7451f1b7b4
commit 20de618568
6 changed files with 103 additions and 58 deletions

View File

@ -2,21 +2,19 @@ use crate::app_config::AppConfig;
use crate::constants;
use crate::libvirt_lib_structures::XMLUuid;
use crate::utils::file_disks_utils::{DiskFileFormat, DiskFileInfo};
use crate::utils::file_size_utils::FileSize;
use crate::utils::files_utils;
use lazy_regex::regex;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(thiserror::Error, Debug)]
enum VMDisksError {
#[error("DiskConfigError: {0}")]
Config(&'static str),
#[error("DiskCreateError")]
Create,
}
/// Type of disk allocation
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize)]
#[derive(Copy, Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
pub enum VMDiskAllocType {
Fixed,
Sparse,
@ -38,7 +36,7 @@ pub struct VMFileDisk {
/// Disk name
pub name: String,
/// Disk size, in bytes
pub size: usize,
pub size: FileSize,
/// Disk format
#[serde(flatten)]
pub format: VMDiskFormat,
@ -129,51 +127,20 @@ impl VMFileDisk {
return Ok(());
}
// Prepare command to create file
let res = match self.format {
VMDiskFormat::Raw { alloc_type } => {
let mut cmd = Command::new("/usr/bin/dd");
cmd.arg("if=/dev/zero")
.arg(format!("of={}", file.to_string_lossy()))
.arg("bs=1M");
match alloc_type {
VMDiskAllocType::Fixed => cmd.arg(format!("count={}", self.size_mb())),
VMDiskAllocType::Sparse => {
cmd.arg(format!("seek={}", self.size_mb())).arg("count=0")
}
};
cmd.output()?
}
VMDiskFormat::QCow2 => {
let mut cmd = Command::new(constants::QEMU_IMAGE_PROGRAM);
cmd.arg("create")
.arg("-f")
.arg("qcow2")
.arg(file)
.arg(format!("{}M", self.size_mb()));
cmd.output()?
}
};
// Execute Linux command
if !res.status.success() {
log::error!(
"Failed to create disk! stderr={} stdout={}",
String::from_utf8_lossy(&res.stderr),
String::from_utf8_lossy(&res.stdout)
);
return Err(VMDisksError::Create.into());
}
// Create disk file
DiskFileInfo::create(
&file,
match self.format {
VMDiskFormat::Raw { alloc_type } => DiskFileFormat::Raw {
is_sparse: alloc_type == VMDiskAllocType::Sparse,
},
VMDiskFormat::QCow2 => DiskFileFormat::QCow2 {
virtual_size: self.size,
},
},
self.size,
)?;
Ok(())
}
/// Get the size of file disk in megabytes
pub fn size_mb(&self) -> usize {
self.size / (1000 * 1000)
}
}