arcbox-core 0.4.9

Core orchestration layer for ArcBox
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
//! Boot asset management for VM startup.
//!
//! Thin wrapper around `arcbox_boot::AssetManager`.
//! All downloading, caching, and verification logic lives in the
//! `arcbox-boot` crate; this module provides daemon-specific
//! configuration defaults, error mapping, and the `BootAssets` struct
//! that `vm_lifecycle` consumes.

use crate::error::{CoreError, Result};
use arcbox_boot::asset_manager::{AssetManager, AssetManagerConfig};
use arcbox_boot::download::{PrepareProgress, ProgressCallback as InnerProgressCallback};
use arcbox_constants::env::BOOT_ASSET_VERSION as BOOT_ASSET_VERSION_ENV;
use sha2::Digest;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

// Re-exports for consumers (CLI, lib.rs).
pub use arcbox_boot::download::{PreparePhase, PrepareProgress as DownloadProgress};
pub use arcbox_boot::manifest::Manifest as BootAssetManifest;

// =============================================================================
// Lockfile
// =============================================================================

/// Embedded lockfile (compiled-in from workspace root).
const LOCK_TOML: &str = include_str!("../../../assets.lock");

/// Top-level lockfile structure.
#[derive(Debug, serde::Deserialize)]
struct AssetsLock {
    boot: BootSection,
}

/// The `[boot]` section of `assets.lock`.
#[derive(Debug, serde::Deserialize)]
struct BootSection {
    version: String,
    cdn: Option<String>,
    manifest_sha256: Option<String>,
}

static LOCK: LazyLock<AssetsLock> =
    LazyLock::new(|| toml::from_str(LOCK_TOML).expect("invalid assets.lock"));

/// Default CDN base URL (fallback when lockfile omits `cdn`).
const DEFAULT_CDN_BASE_URL: &str = "https://boot.arcboxcdn.com";

/// Boot asset version pinned by this daemon release.
#[must_use]
pub fn boot_asset_version() -> &'static str {
    &LOCK.boot.version
}

/// CDN base URL resolved from lockfile (or default).
#[must_use]
pub fn boot_asset_cdn() -> &'static str {
    LOCK.boot.cdn.as_deref().unwrap_or(DEFAULT_CDN_BASE_URL)
}

// =============================================================================
// Configuration
// =============================================================================

/// Boot asset configuration.
#[derive(Debug, Clone)]
pub struct BootAssetConfig {
    /// Base URL for asset downloads.
    pub cdn_base_url: String,
    /// Asset version to download.
    pub version: String,
    /// Target architecture.
    pub arch: String,
    /// Cache directory for downloaded assets.
    pub cache_dir: PathBuf,
    /// Custom kernel path (skip download).
    pub custom_kernel: Option<PathBuf>,
}

impl Default for BootAssetConfig {
    fn default() -> Self {
        let version = std::env::var(BOOT_ASSET_VERSION_ENV)
            .unwrap_or_else(|_| boot_asset_version().to_string());

        let arch = if cfg!(target_arch = "aarch64") {
            "arm64"
        } else {
            "x86_64"
        }
        .to_string();

        Self {
            cdn_base_url: boot_asset_cdn().to_string(),
            version,
            arch,
            cache_dir: dirs::home_dir()
                .unwrap_or_else(|| PathBuf::from("."))
                .join(".arcbox")
                .join("boot"),
            custom_kernel: None,
        }
    }
}

impl BootAssetConfig {
    /// Creates config with an explicit cache directory.
    #[must_use]
    pub fn with_cache_dir(cache_dir: PathBuf) -> Self {
        Self {
            cache_dir,
            ..Default::default()
        }
    }

    /// Override asset version.
    pub fn with_version(mut self, version: impl Into<String>) -> Self {
        self.version = version.into();
        self
    }

    /// Returns the versioned cache directory (e.g. `~/.arcbox/boot/0.2.0`).
    #[must_use]
    pub fn version_cache_dir(&self) -> PathBuf {
        self.cache_dir.join(&self.version)
    }
}

// =============================================================================
// Boot Assets (consumed by vm_lifecycle)
// =============================================================================

/// Boot assets required for VM startup.
///
/// Contains kernel + EROFS read-only rootfs. No initramfs.
#[derive(Debug, Clone)]
pub struct BootAssets {
    /// Path to kernel image.
    pub kernel: PathBuf,
    /// Path to EROFS rootfs image (attached as /dev/vda, read-only).
    pub rootfs_image: PathBuf,
    /// Kernel command line.
    pub cmdline: String,
    /// Asset version.
    pub version: String,
    /// Parsed manifest metadata.
    pub manifest: BootAssetManifest,
}

impl BootAssets {
    /// Default kernel command line for EROFS rootfs boot.
    #[must_use]
    pub fn default_cmdline() -> String {
        "console=hvc0 root=/dev/vda ro rootfstype=erofs earlycon swiotlb=noforce".to_string()
    }
}

// =============================================================================
// Progress Callback
// =============================================================================

/// Progress callback type.
pub type ProgressCallback = Box<dyn Fn(PrepareProgress) + Send + Sync>;

// =============================================================================
// Boot Asset Provider
// =============================================================================

/// Boot asset provider — delegates to `arcbox_boot::AssetManager`.
pub struct BootAssetProvider {
    manager: AssetManager,
    config: BootAssetConfig,
}

impl BootAssetProvider {
    /// Creates a provider with default config rooted at `cache_dir`.
    pub fn new(cache_dir: PathBuf) -> Result<Self> {
        let config = BootAssetConfig::with_cache_dir(cache_dir);
        Self::with_config(config)
    }

    /// Creates a provider from explicit config.
    pub fn with_config(config: BootAssetConfig) -> Result<Self> {
        let inner_config = Self::build_inner_config(&config);
        let manager = AssetManager::new(inner_config)
            .map_err(|e| CoreError::config(format!("invalid boot asset config: {e}")))?;
        Ok(Self { manager, config })
    }

    /// Override the kernel path.
    pub fn with_kernel(mut self, kernel: PathBuf) -> Result<Self> {
        if kernel.as_os_str().is_empty() {
            return Ok(self);
        }
        self.config.custom_kernel = Some(kernel);
        self.rebuild_manager()?;
        Ok(self)
    }

    /// Returns the configuration.
    #[must_use]
    pub const fn config(&self) -> &BootAssetConfig {
        &self.config
    }

    /// Prepare boot assets (download if not cached), returning
    /// the `BootAssets` struct that `vm_lifecycle` consumes.
    pub async fn get_assets(&self) -> Result<BootAssets> {
        self.get_assets_with_progress(None).await
    }

    /// Prepare boot assets with optional progress callback.
    pub async fn get_assets_with_progress(
        &self,
        progress: Option<ProgressCallback>,
    ) -> Result<BootAssets> {
        let cb: Option<InnerProgressCallback> = progress.map(|p| -> InnerProgressCallback { p });
        let prepared = self
            .manager
            .prepare(cb)
            .await
            .map_err(|e| CoreError::config(format!("boot asset error: {e}")))?;

        // Verify manifest SHA256 if the lockfile specifies one.
        if let Some(expected) = LOCK
            .boot
            .manifest_sha256
            .as_deref()
            .filter(|s| !s.is_empty())
        {
            let manifest_path = self.config.version_cache_dir().join("manifest.json");
            let bytes = std::fs::read(&manifest_path)
                .map_err(|e| CoreError::config(format!("read manifest: {e}")))?;
            let actual = format!("{:x}", sha2::Sha256::digest(&bytes));
            if actual != expected {
                return Err(CoreError::config(format!(
                    "manifest SHA256 mismatch: expected {expected}, got {actual}"
                )));
            }
        }

        Ok(BootAssets {
            kernel: prepared.kernel,
            rootfs_image: prepared.rootfs,
            cmdline: prepared.kernel_cmdline,
            version: prepared.version,
            manifest: prepared.manifest,
        })
    }

    /// Prepare host-side runtime binaries into `dest_dir` — every binary in the
    /// boot manifest for the guest arch: dockerd, containerd,
    /// containerd-shim-runc-v2, runc, docker-init, k3s, and (when the release
    /// ships it) the optional FEX x86_64 interpreter used for
    /// `linux/amd64` workloads. ArcBox's FEX carries a small patch making it
    /// binfmt-only — no FEXServer.
    pub async fn prepare_binaries(
        &self,
        dest_dir: &Path,
        progress: Option<ProgressCallback>,
    ) -> Result<()> {
        let cb: Option<InnerProgressCallback> = progress.map(|p| -> InnerProgressCallback { p });
        self.manager
            .prepare_binaries(dest_dir, cb)
            .await
            .map_err(|e| CoreError::config(format!("binary prepare error: {e}")))
    }

    // =========================================================================
    // CLI convenience methods
    // =========================================================================

    /// Returns true if the current version's boot assets are fully cached
    /// (manifest + kernel + rootfs all present).
    #[must_use]
    pub fn is_cached(&self) -> bool {
        let dir = self.config.version_cache_dir();
        dir.join("manifest.json").exists()
            && dir.join("kernel").exists()
            && dir.join("rootfs.erofs").exists()
    }

    /// Prefetches boot assets (downloads if not cached).
    pub async fn prefetch_with_progress(&self, progress: Option<ProgressCallback>) -> Result<()> {
        let _ = self.get_assets_with_progress(progress).await?;
        Ok(())
    }

    /// Removes the version cache directory for the current version.
    pub async fn clear_cache(&self) -> Result<()> {
        let dir = self.config.version_cache_dir();
        if dir.exists() {
            tokio::fs::remove_dir_all(&dir)
                .await
                .map_err(|e| CoreError::config(format!("failed to clear cache: {e}")))?;
        }
        Ok(())
    }

    /// Reads and returns the cached manifest for the current version.
    pub async fn read_cached_manifest_required(&self) -> Result<BootAssetManifest> {
        let path = self.config.version_cache_dir().join("manifest.json");
        let bytes = tokio::fs::read(&path)
            .await
            .map_err(|e| CoreError::config(format!("failed to read manifest: {e}")))?;
        serde_json::from_slice(&bytes)
            .map_err(|e| CoreError::config(format!("failed to parse manifest: {e}")))
    }

    /// Lists all cached version directories.
    pub async fn list_cached_versions(&self) -> Result<Vec<String>> {
        let cache_dir = &self.config.cache_dir;
        if !cache_dir.exists() {
            return Ok(Vec::new());
        }
        let mut versions = Vec::new();
        let mut entries = tokio::fs::read_dir(cache_dir)
            .await
            .map_err(|e| CoreError::config(format!("failed to read cache dir: {e}")))?;
        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| CoreError::config(format!("failed to read cache entry: {e}")))?
        {
            let path = entry.path();
            if path.is_dir() && path.join("manifest.json").exists() {
                if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                    versions.push(name.to_string());
                }
            }
        }
        versions.sort();
        Ok(versions)
    }

    /// Fetch the latest boot-asset version string from the CDN.
    ///
    /// Returns `Ok(Some(version))` on success, `Ok(None)` if the CDN response
    /// is malformed, or `Err` on network/parse failure.
    pub async fn fetch_latest_version(&self) -> Result<Option<String>> {
        let url = format!("{}/latest.json", self.config.cdn_base_url);
        let resp = reqwest::get(&url)
            .await
            .map_err(|e| CoreError::config(format!("failed to fetch latest version: {e}")))?;
        let body: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| CoreError::config(format!("failed to parse latest.json: {e}")))?;
        Ok(body
            .get("version")
            .and_then(serde_json::Value::as_str)
            .map(String::from))
    }

    // =========================================================================
    // Internal helpers
    // =========================================================================

    fn build_inner_config(config: &BootAssetConfig) -> AssetManagerConfig {
        AssetManagerConfig {
            cdn_base_url: config.cdn_base_url.clone(),
            version: config.version.clone(),
            arch: config.arch.clone(),
            cache_dir: config.cache_dir.clone(),
            custom_kernel: config.custom_kernel.clone(),
        }
    }

    fn rebuild_manager(&mut self) -> Result<()> {
        let inner_config = Self::build_inner_config(&self.config);
        self.manager = AssetManager::new(inner_config)
            .map_err(|e| CoreError::config(format!("invalid boot asset config: {e}")))?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn test_default_config() {
        let config = BootAssetConfig::default();
        assert!(!config.cdn_base_url.is_empty());
        assert!(!config.version.is_empty());
        assert!(!config.arch.is_empty());
    }

    #[test]
    fn test_default_config_uses_boot_asset_version() {
        let _guard = ENV_LOCK.lock().unwrap();
        let original = std::env::var(BOOT_ASSET_VERSION_ENV).ok();
        // SAFETY: Test code running under ENV_LOCK mutex.
        unsafe { std::env::remove_var(BOOT_ASSET_VERSION_ENV) };

        let config = BootAssetConfig::default();
        assert_eq!(config.version, boot_asset_version());

        restore_env(original);
    }

    #[test]
    fn test_default_config_env_override() {
        let _guard = ENV_LOCK.lock().unwrap();
        let original = std::env::var(BOOT_ASSET_VERSION_ENV).ok();
        // SAFETY: Test code running under ENV_LOCK mutex.
        unsafe { std::env::set_var(BOOT_ASSET_VERSION_ENV, "9.9.9") };

        let config = BootAssetConfig::default();
        assert_eq!(config.version, "9.9.9");

        restore_env(original);
    }

    #[test]
    fn test_version_cache_dir() {
        let config = BootAssetConfig {
            version: "1.0.0".to_string(),
            cache_dir: PathBuf::from("/tmp/boot"),
            ..Default::default()
        };
        assert_eq!(config.version_cache_dir(), PathBuf::from("/tmp/boot/1.0.0"));
    }

    #[test]
    fn test_is_cached_requires_all_assets() {
        let temp = tempfile::tempdir().unwrap();
        let cache_dir = temp.path().to_path_buf();
        let version = "1.0.0".to_string();
        let version_dir = cache_dir.join(&version);
        std::fs::create_dir_all(&version_dir).unwrap();

        let config = BootAssetConfig {
            version,
            cache_dir,
            ..Default::default()
        };
        let provider = BootAssetProvider::with_config(config).unwrap();

        // Empty dir: not cached.
        assert!(!provider.is_cached());

        // Manifest only: not cached.
        std::fs::write(version_dir.join("manifest.json"), b"{}").unwrap();
        assert!(!provider.is_cached());

        // Manifest + kernel: not cached.
        std::fs::write(version_dir.join("kernel"), b"vmlinux").unwrap();
        assert!(!provider.is_cached());

        // Manifest + kernel + rootfs: cached.
        std::fs::write(version_dir.join("rootfs.erofs"), b"erofs").unwrap();
        assert!(provider.is_cached());
    }

    fn restore_env(original: Option<String>) {
        // SAFETY: Test code running under ENV_LOCK mutex.
        unsafe {
            match original {
                Some(value) => std::env::set_var(BOOT_ASSET_VERSION_ENV, value),
                None => std::env::remove_var(BOOT_ASSET_VERSION_ENV),
            }
        }
    }
}