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
//! Configuration management.
//!
//! `ArcBox` configuration is loaded from multiple sources with the following priority:
//!
//! 1. Environment variables (ARCBOX_*)
//! 2. Configuration file (~/.config/arcbox/config.toml)
//! 3. Default values
//!
//! ## Example Configuration File
//!
//! ```toml
//! # ArcBox configuration file
//! data_dir = "~/.arcbox"
//!
//! [vm]
//! # cpus = 8         # default: host core count
//! # memory_mb = 8192  # default: half of host RAM (512–16384)
//!
//! [machine]
//! disk_gb = 50
//! default_distro = "ubuntu"
//!
//! [network]
//! subnet = "10.0.2.0/24"
//! dns = ["8.8.8.8", "8.8.4.4"]
//!
//! [docker]
//! socket_path = "~/.arcbox/run/docker.sock"
//!
//! [container]
//! guest_docker_vsock_port = 2375
//!
//! [logging]
//! level = "info"
//! ```

use arcbox_constants::ports::DOCKER_API_VSOCK_PORT;
use figment::{
    Figment,
    providers::{Env, Format, Serialized, Toml},
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// `ArcBox` configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Data directory.
    pub data_dir: PathBuf,
    /// Default VM configuration.
    pub vm: VmDefaults,
    /// Default machine configuration.
    pub machine: MachineDefaults,
    /// Network configuration.
    pub network: NetworkConfig,
    /// Docker API configuration.
    pub docker: DockerConfig,
    /// Container runtime backend configuration.
    pub container: ContainerRuntimeConfig,
    /// Logging configuration.
    pub logging: LoggingConfig,
    /// Storage configuration.
    pub storage: StorageConfig,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            data_dir: default_data_dir(),
            vm: VmDefaults::default(),
            machine: MachineDefaults::default(),
            network: NetworkConfig::default(),
            docker: DockerConfig::default(),
            container: ContainerRuntimeConfig::default(),
            logging: LoggingConfig::default(),
            storage: StorageConfig::default(),
        }
    }
}

impl Config {
    /// Loads configuration from files and environment.
    ///
    /// Configuration sources (in order of precedence):
    /// 1. Environment variables (ARCBOX_*)
    /// 2. User config file (~/.config/arcbox/config.toml)
    /// 3. System config file (/etc/arcbox/config.toml)
    /// 4. Default values
    ///
    /// # Errors
    ///
    /// Returns an error if configuration cannot be loaded.
    pub fn load() -> Result<Self, Box<figment::Error>> {
        Figment::new()
            .merge(Serialized::defaults(Self::default()))
            .merge(Toml::file(system_config_path()))
            .merge(Toml::file(user_config_path()))
            .merge(Env::prefixed("ARCBOX_").split("_"))
            .extract()
            .map_err(Box::new)
    }

    /// Loads configuration from a specific file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed.
    pub fn load_from(path: impl AsRef<std::path::Path>) -> Result<Self, Box<figment::Error>> {
        Figment::new()
            .merge(Serialized::defaults(Self::default()))
            .merge(Toml::file(path))
            .merge(Env::prefixed("ARCBOX_").split("_"))
            .extract()
            .map_err(Box::new)
    }

    /// Returns the path to the persistent data directory (`data/`).
    #[must_use]
    pub fn data_subdir(&self) -> PathBuf {
        self.data_dir.join(arcbox_constants::paths::host::DATA)
    }

    /// Returns the path to the images directory (`data/images/`).
    #[must_use]
    pub fn images_dir(&self) -> PathBuf {
        self.data_subdir().join("images")
    }

    /// Returns the path to the containers directory (`data/containers/`).
    #[must_use]
    pub fn containers_dir(&self) -> PathBuf {
        self.data_subdir().join("containers")
    }

    /// Returns the path to the machines directory (`data/machines/`).
    #[must_use]
    pub fn machines_dir(&self) -> PathBuf {
        self.data_subdir().join("machines")
    }

    /// Returns the path to the volumes directory (`data/volumes/`).
    #[must_use]
    pub fn volumes_dir(&self) -> PathBuf {
        self.data_subdir().join("volumes")
    }

    /// Returns the path to the runtime state directory (`run/`).
    #[must_use]
    pub fn run_dir(&self) -> PathBuf {
        self.data_dir.join(arcbox_constants::paths::host::RUN)
    }

    /// Returns the path to the log directory (`log/`).
    #[must_use]
    pub fn log_dir(&self) -> PathBuf {
        self.data_dir.join(arcbox_constants::paths::host::LOG)
    }

    /// Returns the path to the persistent Docker data image (`data/docker.img`).
    #[must_use]
    pub fn docker_img_path(&self) -> PathBuf {
        self.data_subdir().join("docker.img")
    }
}

/// Default VM configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct VmDefaults {
    /// Default number of CPUs (default: host core count).
    pub cpus: u32,
    /// Default memory in MB.
    pub memory_mb: u64,
    /// Kernel path (optional, uses embedded kernel if not set).
    pub kernel_path: Option<PathBuf>,
}

impl VmDefaults {
    /// Returns the effective CPU count, resolving `0` to the host core
    /// count default.
    ///
    /// `0` means "use the default" both on the wire (gRPC
    /// `CreateMachineRequest.cpus`) and in `config.toml`, so callers must
    /// never propagate it into a VM configuration verbatim.
    #[must_use]
    pub fn effective_cpus(&self) -> u32 {
        if self.cpus == 0 {
            arcbox_hypervisor::default_vm_cpu_count()
        } else {
            self.cpus
        }
    }
}

impl Default for VmDefaults {
    fn default() -> Self {
        Self {
            cpus: arcbox_hypervisor::default_vm_cpu_count(),
            memory_mb: arcbox_hypervisor::default_vm_memory_size() / (1024 * 1024),
            kernel_path: None,
        }
    }
}

/// Default machine configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct MachineDefaults {
    /// Default disk size in GB.
    pub disk_gb: u64,
    /// Default Linux distribution.
    pub default_distro: String,
    /// Default distribution version.
    pub default_version: Option<String>,
    /// Auto-mount home directory.
    pub auto_mount_home: bool,
}

impl Default for MachineDefaults {
    fn default() -> Self {
        Self {
            disk_gb: 50,
            default_distro: "ubuntu".to_string(),
            default_version: None,
            auto_mount_home: true,
        }
    }
}

/// Network configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct NetworkConfig {
    /// Subnet for NAT networking.
    pub subnet: String,
    /// Gateway address (first address in subnet if not specified).
    pub gateway: Option<String>,
    /// DNS servers.
    pub dns: Vec<String>,
    /// Enable IPv6.
    pub ipv6: bool,
    /// MTU for virtual network interfaces.
    pub mtu: u16,
}

impl Default for NetworkConfig {
    fn default() -> Self {
        Self {
            subnet: "10.0.2.0/24".to_string(),
            gateway: None,
            dns: vec!["8.8.8.8".to_string(), "8.8.4.4".to_string()],
            ipv6: false,
            mtu: 1500,
        }
    }
}

/// Docker API configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DockerConfig {
    /// Unix socket path for Docker API.
    pub socket_path: PathBuf,
    /// Enable Docker API.
    pub enabled: bool,
}

impl Default for DockerConfig {
    fn default() -> Self {
        Self {
            socket_path: default_docker_socket_path(),
            enabled: true,
        }
    }
}

/// Container runtime configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ContainerRuntimeConfig {
    /// Guest dockerd API vsock port.
    pub guest_docker_vsock_port: u32,
    /// Backend startup timeout in milliseconds.
    pub startup_timeout_ms: u64,
}

impl Default for ContainerRuntimeConfig {
    fn default() -> Self {
        Self {
            guest_docker_vsock_port: DOCKER_API_VSOCK_PORT,
            startup_timeout_ms: 60_000,
        }
    }
}

fn default_docker_socket_path() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("/tmp"))
        .join(".arcbox")
        .join(arcbox_constants::paths::host::RUN)
        .join("docker.sock")
}

/// Logging configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoggingConfig {
    /// Log level (trace, debug, info, warn, error).
    pub level: String,
    /// Log to file.
    pub file: Option<PathBuf>,
    /// Log format (text, json).
    pub format: String,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: "info".to_string(),
            file: None,
            format: "text".to_string(),
        }
    }
}

/// Storage configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct StorageConfig {
    /// Storage driver (overlay2, btrfs, zfs).
    pub driver: String,
    /// Image storage backend.
    pub image_backend: String,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            driver: "overlay2".to_string(),
            image_backend: "oci".to_string(),
        }
    }
}

fn default_data_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("/var/lib"))
        .join(".arcbox")
}

fn user_config_path() -> PathBuf {
    dirs::config_dir()
        .unwrap_or_else(|| PathBuf::from("~/.config"))
        .join("arcbox")
        .join("config.toml")
}

fn system_config_path() -> PathBuf {
    PathBuf::from("/etc/arcbox/config.toml")
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.vm.cpus, arcbox_hypervisor::default_vm_cpu_count());
        // Default memory is half of host RAM, clamped to [512, 16384] MB.
        let expected_mb = arcbox_hypervisor::default_vm_memory_size() / (1024 * 1024);
        assert_eq!(config.vm.memory_mb, expected_mb);
        assert!(config.vm.memory_mb >= 512);
        assert!(config.vm.memory_mb <= 16384);
        assert_eq!(config.machine.disk_gb, 50);
        assert!(config.docker.enabled);
        assert_eq!(
            config.container.guest_docker_vsock_port,
            DOCKER_API_VSOCK_PORT
        );
    }

    #[test]
    fn test_effective_cpus_zero_resolves_to_default() {
        let vm = VmDefaults {
            cpus: 0,
            ..VmDefaults::default()
        };
        assert_eq!(
            vm.effective_cpus(),
            arcbox_hypervisor::default_vm_cpu_count()
        );
    }

    #[test]
    fn test_effective_cpus_explicit_passes_through() {
        let vm = VmDefaults {
            cpus: 3,
            ..VmDefaults::default()
        };
        assert_eq!(vm.effective_cpus(), 3);
    }

    #[test]
    fn test_config_paths() {
        let config = Config::default();
        assert!(config.images_dir().ends_with("data/images"));
        assert!(config.containers_dir().ends_with("data/containers"));
        assert!(config.machines_dir().ends_with("data/machines"));
        assert!(config.volumes_dir().ends_with("data/volumes"));
        assert!(config.run_dir().ends_with("run"));
        assert!(config.log_dir().ends_with("log"));
        assert!(config.docker_img_path().ends_with("data/docker.img"));
    }
}