boxlite 0.9.3

Embeddable virtual machine runtime for secure, isolated code execution
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
//! Box state backend.
//!
//! Pure database access layer for box persistence.
//! No in-memory cache - queries go directly to database.

use std::sync::Arc;

use boxlite_shared::errors::{BoxliteError, BoxliteResult};

use crate::db::BoxStore;
use crate::litebox::config::BoxConfig;
use crate::runtime::id::BoxID;
use crate::runtime::types::BoxState;

/// State backend for box persistence.
///
/// Pure database access layer for box state.
/// All queries go directly to database - no in-memory cache.
#[derive(Clone)]
pub struct BoxManager {
    store: Arc<BoxStore>,
}

impl std::fmt::Debug for BoxManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BoxManager").finish()
    }
}

impl BoxManager {
    /// Create a new manager with the given store.
    pub fn new(store: BoxStore) -> Self {
        Self {
            store: Arc::new(store),
        }
    }

    /// Get a reference to the underlying database.
    #[allow(dead_code)] // Used by snapshots (temporarily disabled)
    pub(crate) fn db(&self) -> crate::db::Database {
        self.store.db()
    }

    // ========================================================================
    // State Interface
    // ========================================================================

    /// Add a new box to the database.
    pub fn add_box(&self, config: &BoxConfig, state: &BoxState) -> BoxliteResult<()> {
        // Check name uniqueness if name is set
        if let Some(ref name) = config.name
            && self.lookup_box_id(name)?.is_some()
        {
            return Err(BoxliteError::InvalidState(format!(
                "box with name '{}' already exists",
                name
            )));
        }

        // Check ID uniqueness
        if self.has_box(&config.id)? {
            return Err(BoxliteError::InvalidState(format!(
                "box {} already exists",
                config.id
            )));
        }

        self.store.save(config, state)?;

        tracing::debug!(
            box_id = %config.id,
            name = ?config.name,
            status = ?state.status,
            "Added box to state"
        );

        Ok(())
    }

    /// Remove a box from the database.
    pub fn remove_box(&self, id: &BoxID) -> BoxliteResult<()> {
        // Check if box exists
        if !self.has_box(id)? {
            return Err(BoxliteError::NotFound(format!("box {}", id)));
        }

        self.store.delete(id.as_str())?;

        tracing::debug!(box_id = %id, "Removed box from state");

        Ok(())
    }

    /// Get a box by exact ID.
    pub fn box_by_id(&self, id: &BoxID) -> BoxliteResult<Option<(BoxConfig, BoxState)>> {
        self.store.load(id.as_str())
    }

    /// Lookup a box by ID prefix or name.
    ///
    /// Tries exact name match first, then ID prefix match.
    pub fn lookup_box(&self, id_or_name: &str) -> BoxliteResult<Option<(BoxConfig, BoxState)>> {
        // First try exact ID match
        if let Some(result) = self.store.load(id_or_name)? {
            return Ok(Some(result));
        }

        // Try name match
        let all = self.store.list_all()?;

        // Exact name match
        for (config, state) in &all {
            if config.name.as_deref() == Some(id_or_name) {
                return Ok(Some((config.clone(), state.clone())));
            }
        }

        // ID prefix match
        let matches: Vec<_> = all
            .iter()
            .filter(|(config, _)| config.id.starts_with(id_or_name))
            .collect();

        match matches.len() {
            0 => Ok(None),
            1 => Ok(Some((matches[0].0.clone(), matches[0].1.clone()))),
            _ => Err(BoxliteError::InvalidArgument(format!(
                "multiple boxes match prefix '{}': {:?}",
                id_or_name,
                matches
                    .iter()
                    .map(|(c, _)| c.id.as_str())
                    .collect::<Vec<_>>()
            ))),
        }
    }

    /// Lookup a box ID by ID prefix or name.
    pub fn lookup_box_id(&self, id_or_name: &str) -> BoxliteResult<Option<BoxID>> {
        self.lookup_box(id_or_name)
            .map(|opt| opt.map(|(config, _)| config.id))
    }

    /// Check if a box exists by exact ID.
    pub fn has_box(&self, id: &BoxID) -> BoxliteResult<bool> {
        self.store.load(id.as_str()).map(|opt| opt.is_some())
    }

    /// Get all boxes.
    pub fn all_boxes(&self, _load_state: bool) -> BoxliteResult<Vec<(BoxConfig, BoxState)>> {
        self.store.list_all()
    }

    /// Save box state to the database.
    ///
    /// Reads state from the provided BoxState and persists to DB.
    pub fn save_box(&self, id: &BoxID, state: &BoxState) -> BoxliteResult<()> {
        self.store.update_state(id.as_str(), state)?;

        tracing::trace!(
            box_id = %id,
            status = ?state.status,
            "Saved box state to database"
        );

        Ok(())
    }

    /// Load box state from the database.
    ///
    /// Returns the latest state from DB.
    pub fn update_box(&self, id: &BoxID) -> BoxliteResult<BoxState> {
        self.store
            .load_state(id.as_str())?
            .ok_or_else(|| BoxliteError::NotFound(id.to_string()))
    }

    // ========================================================================
    // Recovery helpers
    // ========================================================================

    /// Check and handle system reboot.
    ///
    /// Returns true if a reboot was detected.
    pub fn check_and_handle_reboot(&self) -> BoxliteResult<bool> {
        let is_reboot = self.store.check_and_update_boot()?;

        if is_reboot {
            tracing::info!("Detected system reboot, resetting active boxes to stopped");
            let reset_ids = self.store.reset_active_boxes_after_reboot()?;
            for id in &reset_ids {
                tracing::info!(box_id = %id, "Reset box to stopped after reboot");
            }
        }

        Ok(is_reboot)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Database;
    use crate::litebox::config::ContainerRuntimeConfig;
    use crate::runtime::id::BoxID;
    use crate::runtime::types::{BoxStatus, ContainerID};
    use crate::vmm::VmmKind;
    use boxlite_shared::Transport;
    use chrono::Utc;
    use std::path::PathBuf;
    use tempfile::tempdir;

    fn create_test_store() -> BoxStore {
        let dir = tempdir().unwrap();
        let db_path = dir.path().join("test.db");
        let db = Database::open(&db_path).unwrap();
        BoxStore::new(db)
    }

    fn create_test_config(id: &str) -> BoxConfig {
        use crate::runtime::options::{BoxOptions, RootfsSpec};
        BoxConfig {
            id: BoxID::parse(id).unwrap(),
            name: None,
            created_at: Utc::now(),
            container: ContainerRuntimeConfig {
                id: ContainerID::new(),
            },
            options: BoxOptions {
                rootfs: RootfsSpec::Image("test:latest".to_string()),
                cpus: Some(2),
                memory_mib: Some(512),
                ..Default::default()
            },
            engine_kind: VmmKind::Libkrun,
            transport: Transport::unix(PathBuf::from("/tmp/test.sock")),
            box_home: PathBuf::from("/tmp/box"),
            ready_socket_path: PathBuf::from("/tmp/ready"),
        }
    }

    fn create_test_state(status: BoxStatus) -> BoxState {
        let mut state = BoxState::new();
        state.set_status(status);
        state
    }

    const TEST_ID_1: &str = "01HJK4TNRPQSXYZ8WM6NCVT9R1";
    const TEST_ID_2: &str = "01HJK4TNRPQSXYZ8WM6NCVT9R2";
    const TEST_ID_3: &str = "01HJK4TNRPQSXYZ8WM6NCVT9R3";

    #[test]
    fn test_add_box_and_box_by_id() {
        let store = create_test_store();
        let manager = BoxManager::new(store);
        let config = create_test_config(TEST_ID_1);
        let state = BoxState::new();

        manager.add_box(&config, &state).unwrap();

        let (retrieved_config, retrieved_state) = manager.box_by_id(&config.id).unwrap().unwrap();
        assert_eq!(retrieved_config.id, config.id);
        assert_eq!(retrieved_state.status, BoxStatus::Configured);
    }

    #[test]
    fn test_add_box_duplicate_id_fails() {
        let store = create_test_store();
        let manager = BoxManager::new(store);
        let config = create_test_config(TEST_ID_1);
        let state = BoxState::new();

        manager.add_box(&config, &state).unwrap();
        let result = manager.add_box(&config, &state);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already exists"));
    }

    #[test]
    fn test_add_box_duplicate_name_fails() {
        let store = create_test_store();
        let manager = BoxManager::new(store);

        let mut config1 = create_test_config(TEST_ID_1);
        config1.name = Some("my-box".to_string());
        let state1 = BoxState::new();

        let mut config2 = create_test_config(TEST_ID_2);
        config2.name = Some("my-box".to_string());
        let state2 = BoxState::new();

        manager.add_box(&config1, &state1).unwrap();
        let result = manager.add_box(&config2, &state2);

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already exists"));
    }

    #[test]
    fn test_has_box() {
        let store = create_test_store();
        let manager = BoxManager::new(store);
        let config = create_test_config(TEST_ID_1);
        let state = BoxState::new();

        assert!(!manager.has_box(&config.id).unwrap());
        manager.add_box(&config, &state).unwrap();
        assert!(manager.has_box(&config.id).unwrap());
    }

    #[test]
    fn test_lookup_box_by_name() {
        let store = create_test_store();
        let manager = BoxManager::new(store);

        let mut config = create_test_config(TEST_ID_1);
        config.name = Some("my-box".to_string());
        let state = BoxState::new();

        manager.add_box(&config, &state).unwrap();

        let result = manager.lookup_box("my-box").unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().0.id.as_str(), TEST_ID_1);
    }

    #[test]
    fn test_lookup_box_by_id_prefix() {
        let store = create_test_store();
        let manager = BoxManager::new(store);
        let config = create_test_config(TEST_ID_1);
        let state = BoxState::new();

        manager.add_box(&config, &state).unwrap();

        // Use first 12 chars as prefix
        let result = manager.lookup_box(&TEST_ID_1[..12]).unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().0.id.as_str(), TEST_ID_1);
    }

    #[test]
    fn test_lookup_box_ambiguous_prefix() {
        let store = create_test_store();
        let manager = BoxManager::new(store);

        // Use IDs with same prefix
        manager
            .add_box(&create_test_config(TEST_ID_1), &BoxState::new())
            .unwrap();
        manager
            .add_box(&create_test_config(TEST_ID_2), &BoxState::new())
            .unwrap();

        // Common prefix for TEST_ID_1 and TEST_ID_2
        let result = manager.lookup_box("01HJK4TNRPQSXYZ8WM6NCVT9R");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("multiple boxes match")
        );
    }

    #[test]
    fn test_all_boxes() {
        let store = create_test_store();
        let manager = BoxManager::new(store);

        manager
            .add_box(
                &create_test_config(TEST_ID_1),
                &create_test_state(BoxStatus::Running),
            )
            .unwrap();
        manager
            .add_box(
                &create_test_config(TEST_ID_2),
                &create_test_state(BoxStatus::Stopped),
            )
            .unwrap();
        manager
            .add_box(
                &create_test_config(TEST_ID_3),
                &create_test_state(BoxStatus::Running),
            )
            .unwrap();

        let boxes = manager.all_boxes(true).unwrap();
        assert_eq!(boxes.len(), 3);
    }

    #[test]
    fn test_remove_box() {
        let store = create_test_store();
        let manager = BoxManager::new(store);
        let config = create_test_config(TEST_ID_1);
        let state = BoxState::new();

        manager.add_box(&config, &state).unwrap();
        manager.remove_box(&config.id).unwrap();

        assert!(manager.box_by_id(&config.id).unwrap().is_none());
    }

    #[test]
    fn test_save_and_update_box() {
        let store = create_test_store();
        let manager = BoxManager::new(store);
        let config = create_test_config(TEST_ID_1);
        let state = BoxState::new();

        manager.add_box(&config, &state).unwrap();

        // Save new state
        let mut new_state = BoxState::new();
        new_state.set_status(BoxStatus::Running);
        new_state.set_pid(Some(12345));
        manager.save_box(&config.id, &new_state).unwrap();

        // Update (load from DB)
        let loaded_state = manager.update_box(&config.id).unwrap();
        assert_eq!(loaded_state.status, BoxStatus::Running);
        assert_eq!(loaded_state.pid, Some(12345));
    }
}