From 236c78b13a79f290ba8851a4aa0e65ed810e8813 Mon Sep 17 00:00:00 2001 From: rorka900 Date: Fri, 27 Mar 2026 18:02:00 +0000 Subject: feat(rootfs): add parallel package downloads and atomic replace command --- src/config.rs | 20 ++- src/delete.rs | 124 +++++++++++---- src/group.rs | 19 +++ src/install.rs | 2 + src/main.rs | 128 +++++++++++++++ src/parallel.rs | 48 ++---- src/rootfs.rs | 482 ++++++++++++++++++++++++++++++++++++++++---------------- 7 files changed, 617 insertions(+), 206 deletions(-) (limited to 'src') diff --git a/src/config.rs b/src/config.rs index 6fc440f..698d58e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -11,7 +11,7 @@ pub struct RepositoryConfig { pub mirror: Option, } -#[derive(Debug, Deserialize, Serialize, Default)] +#[derive(Debug, Deserialize, Serialize, Clone)] pub struct GlobalConfig { #[serde(default = "default_ignore_speed")] pub ignore_speed: bool, @@ -19,12 +19,26 @@ pub struct GlobalConfig { pub strict_gpg: bool, #[serde(default)] pub allow_external_binaries: bool, + #[serde(default = "default_parallel_downloads")] + pub parallel_downloads: usize, +} + +impl Default for GlobalConfig { + fn default() -> Self { + Self { + ignore_speed: false, + strict_gpg: false, + allow_external_binaries: false, + parallel_downloads: default_parallel_downloads(), + } + } } fn default_ignore_speed() -> bool { false } fn default_strict_gpg() -> bool { false } +fn default_parallel_downloads() -> usize { 4 } -#[derive(Debug, Deserialize, Serialize, Default)] +#[derive(Debug, Deserialize, Serialize, Default, Clone)] pub struct Config { #[serde(default)] pub global: GlobalConfig, @@ -54,6 +68,7 @@ impl Config { let mut lines = vec!["[global]".to_string()]; lines.push(format!("ignore_speed = {}", self.global.ignore_speed)); lines.push(format!("strict_gpg = {}", self.global.strict_gpg)); + lines.push(format!("parallel_downloads = {}", self.global.parallel_downloads)); lines.push(String::new()); for (name, repo) in &self.repositories { lines.push(format!("[repositories.{}]", name)); @@ -78,6 +93,7 @@ impl Config { "[global]\n", "ignore_speed = false\n", "strict_gpg = false\n", + "parallel_downloads = 4\n", "\n", "[repositories.rorkos]\n", "url = \"https://github.com/RorkOS/RorkOS_package\"\n", diff --git a/src/delete.rs b/src/delete.rs index c95d661..affbd8d 100644 --- a/src/delete.rs +++ b/src/delete.rs @@ -4,53 +4,90 @@ use colored::Colorize; use std::process::Command; use crate::install::{load_package, InstalledDB, Package, find_package_file}; +const CRITICAL_ROLES: &[&str] = &["init-system", "sh"]; + fn has_role(pkg_name: &str, role: &str) -> bool { - if let Some(pkg) = load_package(pkg_name) { - return pkg.provides.contains(&role.to_string()); - } - false + load_package(pkg_name) + .map(|p| p.provides.contains(&role.to_string())) + .unwrap_or(false) } pub fn check_critical_removal(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; - if pkg.provides.contains(&"init-system".to_string()) { - let other_inits_count = db.packages.values() - .filter(|p| p.name != pkg_name && has_role(&p.name, "init-system")) + for &role in CRITICAL_ROLES { + if !pkg.provides.contains(&role.to_string()) { + continue; + } + let others = db.packages.values() + .filter(|p| p.name != pkg_name && has_role(&p.name, role)) .count(); - - if other_inits_count == 0 { + if others == 0 { return Err(format!( - "{} CRITICAL ERROR: '{}' is your last init-system! Removing it will break RorkOS. Install an alternative first.", + "{} CRITICAL: '{}' is your only provider of '{}'. Install an alternative first, or use --di to replace atomically.", "[ror]".red().bold(), - pkg_name + pkg_name, + role )); } } + Ok(()) } -pub fn remove_package(pkg_name: &str) { - let mut db = InstalledDB::load(); +pub fn check_critical_removal_with_replacement(pkg_name: &str, replacement: &str, db: &InstalledDB) -> Result<(), String> { + let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; + let replacement_pkg = load_package(replacement).ok_or("Replacement package not found in repository")?; - let record = match db.packages.get(pkg_name) { - Some(r) => r, - None => { - eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), pkg_name); - return; + for &role in CRITICAL_ROLES { + if !pkg.provides.contains(&role.to_string()) { + continue; } - }; + let replacement_covers = replacement_pkg.provides.contains(&role.to_string()); + let other_installed = db.packages.values() + .filter(|p| p.name != pkg_name && has_role(&p.name, role)) + .count(); + if !replacement_covers && other_installed == 0 { + return Err(format!( + "{} CRITICAL: removing '{}' would leave the system without a '{}' provider, and '{}' does not provide it.", + "[ror]".red().bold(), + pkg_name, + role, + replacement + )); + } + } - if let Err(e) = check_critical_removal(pkg_name, &db) { - eprintln!("{}", e); - return; + Ok(()) +} + +pub fn check_critical_install(pkg_name: &str, db: &InstalledDB) -> Result<(), String> { + let pkg = load_package(pkg_name).ok_or("Package info not found in repository")?; + + for &role in CRITICAL_ROLES { + if !pkg.provides.contains(&role.to_string()) { + continue; + } + if let Some(existing) = db.packages.values().find(|p| has_role(&p.name, role)) { + return Err(format!( + "{} CRITICAL: '{}' provides '{}', but '{}' already provides it. Use --di {} {} to replace it atomically.", + "[ror]".red().bold(), + pkg_name, + role, + existing.name, + existing.name, + pkg_name + )); + } } - println!("{} Removing package '{}'...", "[ror]".blue().bold(), pkg_name); + Ok(()) +} +pub fn remove_package_files_only(pkg_name: &str, files: &[String]) -> bool { let mut failed = false; - for rel_path in &record.files { + for rel_path in files { let full_path = Path::new("/").join(rel_path); if full_path.exists() { if let Err(e) = fs::remove_file(&full_path) { @@ -59,8 +96,6 @@ pub fn remove_package(pkg_name: &str) { } else { println!("{} Removed {}", ">>>".green(), full_path.display()); } - } else { - println!("{} File {} already missing", ">>>".yellow(), full_path.display()); } } @@ -68,34 +103,53 @@ pub fn remove_package(pkg_name: &str) { if let Ok(content) = fs::read_to_string(pkg_path) { if let Ok(pkg) = serde_yaml::from_str::(&content) { if !pkg.delete_steps.trim().is_empty() { - println!("{} Running delete steps...", ">>>".yellow()); + println!("{} Running delete steps for '{}'...", ">>>".yellow(), pkg_name); let status = Command::new("sh") .arg("-c") .arg(&pkg.delete_steps) .status() .expect("Failed to execute delete steps"); if !status.success() { - eprintln!("{} Delete steps failed with exit code {:?}", "[ror]".red().bold(), status.code()); + eprintln!("{} Delete steps for '{}' failed", "[ror]".red().bold(), pkg_name); failed = true; - } else { - println!("{} Delete steps completed", ">>>".green()); } } } } - } else { - println!("{} Package recipe not found, skipping delete steps", ">>>".yellow()); } + + !failed +} + +pub fn remove_package(pkg_name: &str) { + let mut db = InstalledDB::load(); + + let files: Vec = match db.packages.get(pkg_name) { + Some(r) => r.files.iter().cloned().collect(), + None => { + eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), pkg_name); + return; + } + }; + + if let Err(e) = check_critical_removal(pkg_name, &db) { + eprintln!("{}", e); + return; + } + + println!("{} Removing package '{}'...", "[ror]".blue().bold(), pkg_name); + + let success = remove_package_files_only(pkg_name, &files); + db.packages.remove(pkg_name); if let Err(e) = db.save() { eprintln!("{} Failed to update installed DB: {}", "[ror]".red().bold(), e); - failed = true; } else { println!("{} Package '{}' removed from database.", "[ror]".green(), pkg_name); } - if failed { - eprintln!("{} Some errors occurred during removal.", "[ror]".red().bold()); + if !success { + eprintln!("{} Some errors occurred while removing '{}'.", "[ror]".red().bold(), pkg_name); } else { println!("{} Package '{}' successfully removed.", "[ror]".green().bold(), pkg_name); } diff --git a/src/group.rs b/src/group.rs index a3e5fde..4252e27 100644 --- a/src/group.rs +++ b/src/group.rs @@ -64,3 +64,22 @@ pub fn load_group(group_name: &str) -> Result { .map_err(|e| format!("Group YAML error: {}", e))?; Ok(group) } +pub fn list_groups() { + let groups_dir = "/var/ror/packages/groups"; + if !Path::new(groups_dir).exists() { + println!("{} Groups directory not found.", "[ror]".yellow()); + return; + } + + println!("{} Available package groups:", "[ror]".blue().bold()); + if let Ok(entries) = std::fs::read_dir(groups_dir) { + for entry in entries.flatten() { + if let Some(name) = entry.file_name().to_str() { + if name.ends_with(".yaml") { + let group_name = name.trim_end_matches(".yaml"); + println!(" {}", group_name.green()); + } + } + } + } +} diff --git a/src/install.rs b/src/install.rs index b2f0ad5..970fa22 100644 --- a/src/install.rs +++ b/src/install.rs @@ -506,6 +506,8 @@ pub fn install_files_with_root(source_dir: &Path, root: &Path, files: &[String]) symlink(&target, &dst) .map_err(|e| format!("Failed to create symlink {}: {}", dst.display(), e))?; } else { + let _ = fs::remove_file(&dst); + fs::copy(&src, &dst) .map_err(|e| format!("Failed to copy {}: {}", src.display(), e))?; } diff --git a/src/main.rs b/src/main.rs index 99b27c8..8daccab 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,7 @@ use clap::Parser; use std::path::{Path, PathBuf}; use std::sync::Arc; +use std::thread; use colored::Colorize; mod sync; @@ -74,6 +75,12 @@ struct Args { #[arg(long = "rootfs-arch", default_value = "native")] rootfs_arch: String, + + #[arg(long = "di", value_names = ["DELETE", "INSTALL"], num_args = 2)] + delete_install: Option>, + + #[arg(long = "lg", alias = "listgroups")] + listgroups: bool, } fn main() { @@ -83,6 +90,7 @@ fn main() { println!("ror {}", env!("CARGO_PKG_VERSION")); return; } + if args.gen_config { let config_path = Path::new("/var/ror/ror.conf"); match config::Config::create_default_config(config_path) { @@ -102,18 +110,114 @@ fn main() { let cfg = Arc::new(config::Config::load()); + if let Some(di_args) = args.delete_install { + let del_pkg = di_args[0].clone(); + let inst_pkg = di_args[1].clone(); + + let db = install::InstalledDB::load(); + + if !db.is_installed(&del_pkg) { + eprintln!("{} Package '{}' is not installed.", "[ror]".red().bold(), del_pkg); + return; + } + + if let Err(e) = delete::check_critical_removal_with_replacement(&del_pkg, &inst_pkg, &db) { + eprintln!("{}", e); + return; + } + + if let Err(e) = delete::check_critical_install(&inst_pkg, &db) { + let already_installed_by_same = db.packages.get(&inst_pkg).is_some(); + if !already_installed_by_same { + let conflict_is_the_deleted = e.contains(&del_pkg); + if !conflict_is_the_deleted { + eprintln!("{}", e); + return; + } + } + } + + let record_files = db.packages + .get(&del_pkg) + .map(|r| r.files.clone()) + .unwrap_or_default(); + + println!( + "{} Replacing '{}' with '{}'...", + "[ror]".blue().bold(), + del_pkg, + inst_pkg + ); + + let del_pkg_for_thread = del_pkg.clone(); + let inst_pkg_for_thread = inst_pkg.clone(); + let cfg_for_thread = Arc::clone(&cfg); + + let del_handle = thread::spawn(move || { + println!("{} [remove] Starting removal of '{}'", ">>>".yellow(), del_pkg_for_thread); + let ok = delete::remove_package_files_only(&del_pkg_for_thread, &record_files); + if ok { + println!("{} [remove] Files removed for '{}'", ">>>".green(), del_pkg_for_thread); + } else { + eprintln!("{} [remove] Errors during removal of '{}'", "[ror]".red().bold(), del_pkg_for_thread); + } + ok + }); + + let inst_handle = thread::spawn(move || { + println!("{} [install] Starting install of '{}'", ">>>".cyan(), inst_pkg_for_thread); + install::install_package_with_result(&inst_pkg_for_thread, &cfg_for_thread) + }); + + let del_ok = del_handle.join().unwrap_or(false); + let inst_result = inst_handle.join().unwrap_or_else(|_| Err("install thread panicked".to_string())); + + let mut db = install::InstalledDB::load(); + + if del_ok { + db.packages.remove(&del_pkg); + println!("{} '{}' removed from database", "[ror]".green(), del_pkg); + } + + match inst_result { + Ok(installed_pkg) => { + db.add_package(installed_pkg); + println!("{} '{}' added to database", "[ror]".green(), inst_pkg); + } + Err(e) => { + eprintln!("{} Failed to install '{}': {}", "[ror]".red().bold(), inst_pkg, e); + } + } + + if let Err(e) = db.save() { + eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); + } else { + println!( + "{} Replace operation finished: '{}' -> '{}'", + "[ror]".green().bold(), + del_pkg, + inst_pkg + ); + } + + return; + } + if let Some(pkg) = args.info { info::print_package_info(&pkg); return; } + if args.sync { sync::run_sync(&cfg); return; } + if args.listinstalled { listinstalled::print_installed(); return; } + if args.build_rootfs { let arch = if args.rootfs_arch == "native" { "native" @@ -129,15 +233,29 @@ fn main() { } return; } + if let Some(pkg) = args.delete { delete::remove_package(&pkg); return; } + if let Some(query) = args.search { search::search_packages(&query); return; } + if !args.install.is_empty() { + let db = install::InstalledDB::load(); + for pkg_name in &args.install { + if pkg_name.starts_with('@') { + continue; + } + if let Err(e) = delete::check_critical_install(pkg_name, &db) { + eprintln!("{}", e); + return; + } + } + if args.install[0].starts_with('@') { let group_name = &args.install[0][1..]; match group::load_group(group_name) { @@ -155,6 +273,7 @@ fn main() { } return; } + if args.upgrade { if args.dry_run { let upgradable = update::list_upgradable(); @@ -171,16 +290,19 @@ fn main() { } return; } + if args.repo_list { repo::list_repositories(); return; } + if let Some(repo_args) = args.repo_remove { if let Err(e) = repo::remove_repository(&repo_args) { eprintln!("{} {}", "[ror]".red().bold(), e); } return; } + if let Some(repo_args) = args.repo_add { if repo_args.len() < 2 { eprintln!("{} Usage: --repo-add [mirror]", "[ror]".red().bold()); @@ -194,8 +316,14 @@ fn main() { } return; } + if let Some(pkg) = args.update { update::update_package(&pkg, &cfg, args.dry_run); return; } + + if args.listgroups { + group::list_groups(); + return; + } } diff --git a/src/parallel.rs b/src/parallel.rs index 60f3b5e..9f629a9 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -40,14 +40,12 @@ impl DependencyGraph { in_degree.entry(child.clone()).or_insert(0); } } - let mut levels = Vec::new(); let mut queue: VecDeque = in_degree.iter() - .filter(|(_, °)| deg == 0) + .filter(|&(_, °)| deg == 0) .map(|(pkg, _)| pkg.clone()) .collect(); debug!("compute_levels: initial queue: {:?}", queue); - while !queue.is_empty() { let level_pkgs: Vec = queue.drain(..).collect(); debug!("compute_levels: level {}: {:?}", levels.len(), level_pkgs); @@ -65,12 +63,10 @@ impl DependencyGraph { } } } - let cyclic: Vec<_> = in_degree.iter() - .filter(|(_, &d)| d > 0) + .filter(|&(_, &d)| d > 0) .map(|(name, _)| name.as_str()) .collect(); - if !cyclic.is_empty() { eprintln!( "{} Warning: cycle detected among packages, they will be installed in arbitrary order", @@ -78,7 +74,6 @@ impl DependencyGraph { ); debug!("compute_levels: circular dependency among: {:?}", cyclic); } - debug!("compute_levels: levels count = {}", levels.len()); levels } @@ -88,7 +83,6 @@ fn collect_required_packages(packages: &[String], installed_db: &InstalledDB) -> debug!("collect_required_packages: start with packages {:?}", packages); let mut required = HashSet::new(); let mut stack: Vec = packages.iter().cloned().collect(); - while let Some(pkg_name) = stack.pop() { debug!("collect_required_packages: processing {}", pkg_name); if installed_db.is_installed(&pkg_name) || required.contains(&pkg_name) { @@ -96,7 +90,6 @@ fn collect_required_packages(packages: &[String], installed_db: &InstalledDB) -> continue; } required.insert(pkg_name.clone()); - let pkg = match load_package(&pkg_name) { Some(p) => p, None => { @@ -104,7 +97,6 @@ fn collect_required_packages(packages: &[String], installed_db: &InstalledDB) -> return Err(format!("Package '{}' not found", pkg_name)); } }; - for dep in &pkg.depends { match dep { Dependency::Single(name) => { @@ -115,22 +107,20 @@ fn collect_required_packages(packages: &[String], installed_db: &InstalledDB) -> } Dependency::Any(alternatives) => { debug!("collect_required_packages: any dependency {:?}", alternatives); + let installed_alt = alternatives.iter().find(|alt| installed_db.is_installed(*alt)); if installed_alt.is_some() { debug!("collect_required_packages: an alternative already installed, skipping"); continue; } - let chosen = alternatives.iter() - .find(|alt| required.contains(*alt)) - .cloned() - .or_else(|| alternatives.first().cloned()) - .ok_or_else(|| { - debug!("collect_required_packages: empty alternative list"); - format!("Empty alternative list in package {}", pkg_name) - })?; - debug!("collect_required_packages: chosen alternative {}", chosen); - if !required.contains(&chosen) { - stack.push(chosen); + + if let Some(primary_dep) = alternatives.first().cloned() { + debug!("collect_required_packages: chosen primary alternative {}", primary_dep); + if !required.contains(&primary_dep) { + stack.push(primary_dep); + } + } else { + return Err(format!("Empty alternative list in package {}", pkg_name)); } } } @@ -196,7 +186,6 @@ fn check_conflicts(required: &HashSet, installed_db: &InstalledDB) -> Re }; pkg_map.insert(pkg_name.clone(), pkg); } - for (name, pkg) in &pkg_map { for conflict in &pkg.conflicts { if installed_db.is_installed(conflict) { @@ -205,7 +194,6 @@ fn check_conflicts(required: &HashSet, installed_db: &InstalledDB) -> Re } } } - let names: Vec<_> = pkg_map.keys().cloned().collect(); for i in 0..names.len() { for j in i+1..names.len() { @@ -258,31 +246,23 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc) -> Resul debug!("install_packages_parallel: no packages required"); return Ok(()); } - check_conflicts(&required, &installed_db)?; - let graph = build_graph(&required, &installed_db)?; let mut levels = graph.compute_levels(); - if levels.is_empty() && !required.is_empty() { debug!("install_packages_parallel: no dependencies, creating single level"); levels.push(required.iter().cloned().collect()); } - debug!("install_packages_parallel: levels: {:?}", levels); - let total_pkgs: usize = levels.iter().map(|l| l.len()).sum(); let mut installed_count = 0usize; - println!( "{} Installing {} package(s) across {} level(s)", "[ror]".blue().bold(), total_pkgs, levels.len() ); - let db_mutex = Arc::new(Mutex::new(InstalledDB::load())); - for (level_idx, level_pkgs) in levels.into_iter().enumerate() { println!( "{} Level {}: {} package(s)", @@ -291,10 +271,8 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc) -> Resul level_pkgs.len() ); debug!("install_packages_parallel: starting level {} with {:?}", level_idx, level_pkgs); - let level_total = level_pkgs.len(); let mut handles = Vec::new(); - for pkg in level_pkgs { let pkg_name = pkg.clone(); let cfg = Arc::clone(&cfg); @@ -304,10 +282,8 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc) -> Resul }); handles.push((pkg, handle)); } - let mut errors = Vec::new(); let mut level_done = 0usize; - for (pkg_name, handle) in handles { match handle.join() { Ok(Ok(())) => { @@ -334,14 +310,12 @@ pub fn install_packages_parallel(packages: &[String], cfg: Arc) -> Resul } } eprintln!(); - if !errors.is_empty() { eprintln!("{} Errors during level {}: {:?}", "[ror]".red().bold(), level_idx, errors); debug!("install_packages_parallel: level {} failed with {} errors", level_idx, errors.len()); return Err(format!("Installation failed at level {}", level_idx)); } } - println!("{} All packages installed successfully.", "[ror]".green().bold()); debug!("install_packages_parallel: completed successfully"); Ok(()) diff --git a/src/rootfs.rs b/src/rootfs.rs index 8b89efe..0624ab0 100644 --- a/src/rootfs.rs +++ b/src/rootfs.rs @@ -1,17 +1,255 @@ +use std::collections::{HashMap, HashSet, VecDeque}; use std::fs; use std::path::Path; -use std::collections::HashSet; use std::process::Command; use std::os::unix::fs::symlink; +use std::sync::{Arc, Mutex}; +use std::thread; use colored::Colorize; +use serde::Serialize; use crate::config; use crate::group::Group; use crate::progress::ProgressBar; use crate::install::{ - Dependency, Package, load_package, download_and_verify, + Dependency, load_package, download_and_verify, extract_native, install_files_with_root, select_binary_for_arch, }; +struct DownloadTask { + pkg_name: String, + urls: Vec, + sha256: String, +} + +#[derive(Serialize)] +struct InstalledEntry { + name: String, + version: String, +} + +#[derive(Serialize)] +struct ListInstalled { + packages: Vec, +} + +fn collect_install_order(start_pkgs: &[String]) -> Result, String> { + let mut order: Vec = Vec::new(); + let mut visited: HashSet = HashSet::new(); + + fn visit( + name: &str, + visited: &mut HashSet, + order: &mut Vec, + ) -> Result<(), String> { + if visited.contains(name) { + return Ok(()); + } + visited.insert(name.to_string()); + + let pkg = load_package(name) + .ok_or_else(|| format!("Package '{}' not found in repository", name))?; + + for dep in &pkg.depends { + match dep { + Dependency::Single(d) => visit(d, visited, order)?, + Dependency::Any(alts) => { + if let Some(first) = alts.first() { + visit(first, visited, order)?; + } + } + } + } + + order.push(name.to_string()); + Ok(()) + } + + for pkg in start_pkgs { + visit(pkg, &mut visited, &mut order)?; + } + + Ok(order) +} + +fn build_download_tasks(packages: &[String], target_arch: &str) -> Result, String> { + let mut tasks = Vec::new(); + for pkg_name in packages { + let pkg = load_package(pkg_name) + .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; + + let binary = select_binary_for_arch(&pkg, target_arch) + .map_err(|e| format!("No binary for '{}': {}", pkg_name, e))?; + + let urls: Vec = if !binary.url.is_empty() { + vec![binary.url.clone()] + } else { + binary.mirrors.iter() + .map(|m| m.replace("{filename}", &binary.filename)) + .collect() + }; + + if urls.is_empty() { + return Err(format!("No download URLs for package '{}'", pkg_name)); + } + + tasks.push(DownloadTask { + pkg_name: pkg_name.clone(), + urls, + sha256: binary.sha256.clone(), + }); + } + + Ok(tasks) +} + +fn download_parallel( + tasks: Vec, + cfg: Arc, + n_parallel: usize, +) -> Result, String> { + let n = n_parallel.max(1).min(tasks.len().max(1)); + let total = tasks.len(); + println!( + "{} Downloading {} packages ({} in parallel)...", + ">>>".cyan().bold(), + total, + n + ); + + let queue: Arc>> = + Arc::new(Mutex::new(tasks.into_iter().collect())); + + let results: Arc>> = + Arc::new(Mutex::new(HashMap::new())); + + let first_error: Arc>> = Arc::new(Mutex::new(None)); + let done_count: Arc> = Arc::new(Mutex::new(0)); + + let mut handles = vec![]; + + for _ in 0..n { + let queue = Arc::clone(&queue); + let results = Arc::clone(&results); + let first_error = Arc::clone(&first_error); + let done_count = Arc::clone(&done_count); + let cfg = Arc::clone(&cfg); + + handles.push(thread::spawn(move || { + loop { + if first_error.lock().unwrap().is_some() { + return; + } + + let task = queue.lock().unwrap().pop_front(); + let task = match task { + Some(t) => t, + None => return, + }; + + let mut last_err = String::new(); + let mut downloaded = false; + + for url in &task.urls { + match download_and_verify(url, &task.sha256, &cfg) { + Ok(path) => { + results.lock().unwrap().insert(task.pkg_name.clone(), path); + downloaded = true; + + let mut count = done_count.lock().unwrap(); + *count += 1; + eprint!( + "\r\x1b[K{} [{}/{}] {} ", + ">>>".green(), + count, + total, + task.pkg_name + ); + use std::io::Write; + std::io::stderr().flush().ok(); + break; + } + Err(e) => last_err = e, + } + } + + if !downloaded { + let mut err = first_error.lock().unwrap(); + if err.is_none() { + *err = Some(format!( + "Failed to download '{}': {}", + task.pkg_name, last_err + )); + } + } + } + })); + } + + for handle in handles { + handle.join().ok(); + } + eprintln!(); + + if let Some(e) = first_error.lock().unwrap().take() { + return Err(e); + } + + Ok(Arc::try_unwrap(results).unwrap().into_inner().unwrap()) +} + +fn install_from_archive( + pkg_name: &str, + archive_path: &std::path::Path, + root_dir: &Path, + binary_files: &[String], +) -> Result, String> { + let work_dir = std::path::Path::new("/tmp/ror-rootfs").join(pkg_name); + if work_dir.exists() { + fs::remove_dir_all(&work_dir) + .map_err(|e| format!("Failed to clean temp dir for '{}': {}", pkg_name, e))?; + } + fs::create_dir_all(&work_dir) + .map_err(|e| format!("Failed to create temp dir for '{}': {}", pkg_name, e))?; + + let extracted = extract_native(archive_path, &work_dir) + .map_err(|e| format!("Extraction failed for '{}': {}", pkg_name, e))?; + + let file_list = if binary_files.is_empty() { + extracted + } else { + binary_files.to_vec() + }; + + let installed = install_files_with_root(&work_dir, root_dir, &file_list)?; + + let _ = fs::remove_dir_all(&work_dir); + let _ = fs::remove_file(archive_path); + + Ok(installed) +} + +fn write_listinstalled(target_dir: &Path, packages: &[String]) -> Result<(), String> { + let entries: Vec = packages.iter() + .filter_map(|name| { + let pkg = load_package(name)?; + Some(InstalledEntry { name: pkg.name, version: pkg.version }) + }) + .collect(); + + let list = ListInstalled { packages: entries }; + let yaml = serde_yaml::to_string(&list) + .map_err(|e| format!("Failed to serialize listinstalled: {}", e))?; + + let out_dir = target_dir.join("var/ror"); + fs::create_dir_all(&out_dir) + .map_err(|e| format!("Failed to create var/ror: {}", e))?; + + fs::write(out_dir.join("listinstalled.yaml"), yaml) + .map_err(|e| format!("Failed to write listinstalled.yaml: {}", e))?; + + Ok(()) +} + fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { for dir in &["bin", "lib", "lib64", "sbin"] { let path = target_dir.join(dir); @@ -32,11 +270,11 @@ fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { } for (link, target) in &[ - ("bin", "usr/bin"), - ("lib", "usr/lib"), + ("bin", "usr/bin"), + ("lib", "usr/lib"), ("lib64", "usr/lib64"), - ("sbin", "usr/sbin"), - ] { + ("sbin", "usr/sbin"), +] { symlink(target, target_dir.join(link)) .map_err(|e| format!("Failed to create symlink {} -> {}: {}", link, target, e))?; } @@ -44,13 +282,43 @@ fn setup_usr_merge(target_dir: &Path) -> Result<(), String> { Ok(()) } +fn create_fhs_skeleton(target_dir: &Path) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt; + + let dirs = &[ + "boot", "dev", "dev/pts", "dev/shm", "etc", "etc/ror", + "home", "mnt", "opt", "proc", "root", "run", "srv", "sys", + "tmp", "usr/include", "usr/local/bin", "usr/local/lib", + "usr/local/share", "usr/share", "usr/share/doc", + "var", "var/cache", "var/empty", "var/lib", "var/lock", + "var/log", "var/run", "var/spool", "var/tmp", + ]; + + for dir in dirs { + fs::create_dir_all(target_dir.join(dir)) + .map_err(|e| format!("Failed to create FHS dir {}: {}", dir, e))?; + } + + for dir in &["tmp", "var/tmp"] { + fs::set_permissions(target_dir.join(dir), fs::Permissions::from_mode(0o1777)) + .map_err(|e| format!("Failed to set sticky bit on {}: {}", dir, e))?; + } + + for dir in &["root", "var/empty"] { + fs::set_permissions(target_dir.join(dir), fs::Permissions::from_mode(0o700)) + .map_err(|e| format!("Failed to set permissions on {}: {}", dir, e))?; + } + + Ok(()) +} + fn mount_virtual_fs(root_dir: &Path) -> Result<(), String> { let mounts: &[(&str, &str, &str, bool)] = &[ - ("/dev", "dev", "devtmpfs", true), - ("/dev/pts", "dev/pts", "devpts", true), - ("/dev/shm", "dev/shm", "tmpfs", true), - ("proc", "proc", "proc", false), - ("sysfs", "sys", "sysfs", false), + ("/dev", "dev", "devtmpfs", true), + ("/dev/pts", "dev/pts", "devpts", true), + ("/dev/shm", "dev/shm", "tmpfs", true), + ("proc", "proc", "proc", false), + ("sysfs", "sys", "sysfs", false), ]; for (src, rel, fstype, bind) in mounts { @@ -87,16 +355,17 @@ fn umount_virtual_fs(root_dir: &Path) { } const SHELL_CANDIDATES: &[(&str, Option<&str>)] = &[ - ("/bin/sh", None), - ("/usr/bin/sh", None), - ("/bin/dash", None), - ("/usr/bin/dash", None), - ("/bin/bash", None), - ("/usr/bin/bash", None), - ("/bin/busybox", Some("sh")), + ("/bin/sh", None), + ("/usr/bin/sh", None), + ("/bin/dash", None), + ("/usr/bin/dash", None), + ("/bin/bash", None), + ("/usr/bin/bash", None), + ("/bin/busybox", Some("sh")), ("/usr/bin/busybox", Some("sh")), - ("/bin/ash", None), - ("/usr/bin/ash", None), + ("/bin/toybox", Some("sh")), + ("/bin/ash", None), + ("/usr/bin/ash", None), ]; fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static str>)> { @@ -113,9 +382,7 @@ fn find_working_shell(root_dir: &Path) -> Option<(&'static str, Option<&'static cmd.arg("-c").arg("exit 0"); match cmd.output() { - Ok(out) if out.status.success() => { - return Some((shell_path, subcmd)); - } + Ok(out) if out.status.success() => return Some((shell_path, subcmd)), Ok(out) => { let stderr = String::from_utf8_lossy(&out.stderr); eprintln!( @@ -162,109 +429,18 @@ fn run_install_steps_in_chroot( Ok(()) } else { Err(format!( - "install_steps for \'{}\' failed with exit code {:?}", + "install_steps for '{}' failed with exit code {:?}", pkg_name, status.code() )) } } -fn process_dependencies_chroot( - pkg: &Package, - cfg: &config::Config, - root_dir: &Path, - installing: &mut HashSet, - target_arch: &str, - progress: &mut ProgressBar, -) -> Result<(), String> { - for dep in &pkg.depends { - match dep { - Dependency::Single(name) => { - if !installing.contains(name) { - install_package_in_chroot(name, cfg, root_dir, installing, target_arch, progress)?; - } - } - Dependency::Any(alternatives) => { - if alternatives.iter().any(|alt| installing.contains(alt)) { - continue; - } - let chosen = alternatives.first() - .ok_or_else(|| format!("Empty alternative list in package {}", pkg.name))?; - install_package_in_chroot(chosen, cfg, root_dir, installing, target_arch, progress)?; - } - } - } - Ok(()) -} - -pub fn install_package_in_chroot( - pkg_name: &str, - cfg: &config::Config, - root_dir: &Path, - installing: &mut HashSet, - target_arch: &str, - progress: &mut ProgressBar, -) -> Result<(), String> { - if installing.contains(pkg_name) { - println!( - "{} {} already queued, dependencies are already installed", - "[ror]".green(), - pkg_name.green() - ); - return Ok(()); - } - installing.insert(pkg_name.to_string()); - - let pkg = load_package(pkg_name) - .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; - - process_dependencies_chroot(&pkg, cfg, root_dir, installing, target_arch, progress)?; - - let binary = select_binary_for_arch(&pkg, target_arch) - .map_err(|e| format!("Failed to select binary for {}: {}", pkg_name, e))?; - - progress.inc(&format!("Installing {}", pkg_name)); - - let mut last_err = None; - for mirror in &binary.mirrors { - let url = mirror.replace("{filename}", &binary.filename); - - let archive_path = match download_and_verify(&url, &binary.sha256, cfg) { - Ok(p) => p, - Err(e) => { last_err = Some(e); continue; } - }; - - let work_dir = Path::new("/tmp/ror-install").join(&pkg.name); - if work_dir.exists() { - fs::remove_dir_all(&work_dir) - .map_err(|e| format!("Failed to clean temp dir: {}", e))?; - } - fs::create_dir_all(&work_dir) - .map_err(|e| format!("Failed to create temp dir: {}", e))?; - - let files = extract_native(&archive_path, &work_dir) - .map_err(|e| format!("Extraction failed: {}", e))?; - - let file_list = if binary.files.is_empty() { files } else { binary.files.clone() }; - - install_files_with_root(&work_dir, root_dir, &file_list)?; - - let _ = fs::remove_dir_all(&work_dir); - let _ = fs::remove_file(&archive_path); - - println!("{} Installed {} into {}", ">>>".green(), pkg_name, root_dir.display()); - return Ok(()); - } - - Err(last_err.unwrap_or_else(|| "All mirrors failed".into())) -} - fn run_all_install_steps( group_order: &[String], all_installed: &HashSet, target_dir: &Path, ) -> Result<(), String> { let mut done: HashSet = HashSet::new(); - let mut queue: Vec<&str> = group_order.iter().map(|s| s.as_str()).collect(); let mut extras: Vec = all_installed.iter() @@ -272,7 +448,9 @@ fn run_all_install_steps( .cloned() .collect(); extras.sort(); - for e in &extras { queue.push(e.as_str()); } + for e in &extras { + queue.push(e.as_str()); + } let steps_pkgs: Vec = queue.iter() .filter(|&&pkg_name| { @@ -282,8 +460,7 @@ fn run_all_install_steps( .map(|s| s.to_string()) .collect(); - let total_steps = steps_pkgs.len(); - let mut pb = ProgressBar::new(total_steps.max(1), "Running install steps..."); + let mut pb = ProgressBar::new(steps_pkgs.len().max(1), "Running install steps..."); let (shell, subcmd) = find_working_shell(target_dir) .ok_or_else(|| "No working shell found in rootfs. Tried: sh, dash, bash, busybox, ash".to_string())?; @@ -292,7 +469,9 @@ fn run_all_install_steps( subcmd.map(|s| format!(" {}", s)).unwrap_or_default()); for pkg_name in queue { - if done.contains(pkg_name) || !all_installed.contains(pkg_name) { continue; } + if done.contains(pkg_name) || !all_installed.contains(pkg_name) { + continue; + } done.insert(pkg_name.to_string()); if let Some(pkg) = load_package(pkg_name) { @@ -330,37 +509,73 @@ pub fn build_rootfs( let group: Group = serde_yaml::from_str(&content) .map_err(|e| format!("Group YAML error: {}", e))?; - println!("{} Building rootfs in {} with group '{}'", - "[ror]".blue().bold(), target_dir.display(), group_name); + println!( + "{} Building rootfs in {} with group '{}'", + "[ror]".blue().bold(), + target_dir.display(), + group_name + ); if let Some(desc) = &group.description { println!("{} {}", "Description:".yellow(), desc); } println!("\n{} Phase 0: UsrMerge...", ">>>".cyan().bold()); setup_usr_merge(target_dir)?; - println!("{} UsrMerge done: bin/lib/lib64/sbin are now symlinks into usr/", ">>>".green()); + println!("{} bin/lib/lib64/sbin are now symlinks into usr/", ">>>".green()); + + println!("{} Creating FHS skeleton...", ">>>".cyan()); + create_fhs_skeleton(target_dir)?; + println!("{} FHS skeleton created.", ">>>".green()); - println!("\n{} Phase 1: installing files...", ">>>".cyan().bold()); + println!("\n{} Phase 1a: Resolving packages...", ">>>".cyan().bold()); + let all_packages = collect_install_order(&group.packages)?; + println!("{} {} packages to install (including dependencies)", ">>>".green(), all_packages.len()); - let estimated_total = group.packages.len() * 3; - let mut pb = ProgressBar::new(estimated_total.max(1), "Starting..."); + println!("\n{} Phase 1b: Building download queue...", ">>>".cyan().bold()); + let tasks = build_download_tasks(&all_packages, target_arch)?; + let n_parallel = cfg.global.parallel_downloads.max(1); + let cfg_arc = Arc::new(cfg.clone()); + let downloaded = download_parallel(tasks, cfg_arc, n_parallel)?; + println!("{} All downloads complete.", ">>>".green().bold()); + + println!("\n{} Phase 1c: Installing files...", ">>>".cyan().bold()); let mut installing: HashSet = HashSet::new(); - for pkg in &group.packages { - install_package_in_chroot(pkg, cfg, target_dir, &mut installing, target_arch, &mut pb)?; + let mut pb = ProgressBar::new(all_packages.len().max(1), "Installing..."); + + for pkg_name in &all_packages { + let pkg = load_package(pkg_name) + .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; + + let binary = select_binary_for_arch(&pkg, target_arch) + .map_err(|e| format!("Arch selection failed for '{}': {}", pkg_name, e))?; + + let archive_path = downloaded.get(pkg_name) + .ok_or_else(|| format!("Archive for '{}' was not downloaded", pkg_name))?; + + pb.inc(&format!("Installing {}", pkg_name)); + install_from_archive(pkg_name, archive_path, target_dir, &binary.files)?; + installing.insert(pkg_name.clone()); } - pb.finish(&format!("Phase 1 complete: {} packages installed", installing.len())); - println!("{} Phase 1 complete: {} packages.", ">>>".green(), installing.len()); + pb.finish(&format!("{} packages installed", installing.len())); + + println!("\n{} Writing listinstalled.yaml...", ">>>".cyan()); + write_listinstalled(target_dir, &all_packages)?; + println!("{} listinstalled.yaml written to var/ror/", ">>>".green()); if run_ldconfig { println!("{} Running ldconfig...", ">>>".cyan()); + let ld_conf = target_dir.join("etc/ld.so.conf"); + if !ld_conf.exists() { + let _ = fs::write(&ld_conf, "/usr/lib\n/usr/lib64\n"); + } match Command::new("ldconfig").arg("-r").arg(target_dir).status() { Ok(s) if s.success() => println!("{} ldconfig done.", ">>>".green()), _ => eprintln!("{} ldconfig failed (non-fatal)", "[ror]".yellow()), } } - println!("\n{} Phase 2: running install_steps in chroot...", ">>>".cyan().bold()); + println!("\n{} Phase 2: Running install_steps in chroot...", ">>>".cyan().bold()); println!("{} Mounting /dev /proc /sys...", ">>>".cyan()); mount_virtual_fs(target_dir)?; @@ -371,7 +586,10 @@ pub fn build_rootfs( result?; - println!("\n{} Rootfs created successfully at {}", - "[ror]".green().bold(), target_dir.display()); + println!( + "\n{} Rootfs built successfully at {} ", + "[ror]".green().bold(), + target_dir.display() + ); Ok(()) } -- cgit v1.2.3