boxlite-cli 0.7.5

Command-line interface for BoxLite container runtime
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! `boxlite serve` — long-running REST API server.
//!
//! Holds a single BoxliteRuntime and exposes box lifecycle + exec operations
//! over HTTP so that multiple callers share the same runtime (no lock contention).

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;

use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use base64::Engine;
use clap::Args;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

use boxlite::{BoxCommand, BoxInfo, BoxOptions, BoxliteRuntime, Execution, LiteBox, RootfsSpec};

use crate::cli::GlobalFlags;

// ============================================================================
// CLI Args
// ============================================================================

#[derive(Args, Debug)]
pub struct ServeArgs {
    /// Port to listen on
    #[arg(long, default_value = "8100")]
    pub port: u16,

    /// Host/address to bind to
    #[arg(long, default_value = "0.0.0.0")]
    pub host: String,
}

// ============================================================================
// Shared State
// ============================================================================

struct AppState {
    runtime: BoxliteRuntime,
    /// Cached box handles (box_id -> Arc<LiteBox>).
    boxes: RwLock<HashMap<String, Arc<LiteBox>>>,
    /// Active executions (execution_id -> ActiveExecution).
    executions: RwLock<HashMap<String, ActiveExecution>>,
}

struct ActiveExecution {
    execution: Execution,
    started_at: Instant,
}

/// Internal message type for multiplexing stdout/stderr SSE events.
enum SseItem {
    Event(Event),
    StreamDone,
}

// ============================================================================
// Wire Types (request/response JSON)
// ============================================================================

#[derive(Deserialize)]
struct CreateBoxRequest {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    image: Option<String>,
    #[serde(default)]
    rootfs_path: Option<String>,
    #[serde(default)]
    cpus: Option<u8>,
    #[serde(default)]
    memory_mib: Option<u32>,
    #[serde(default)]
    disk_size_gb: Option<u64>,
    #[serde(default)]
    working_dir: Option<String>,
    #[serde(default)]
    env: Option<HashMap<String, String>>,
    #[serde(default)]
    entrypoint: Option<Vec<String>>,
    #[serde(default)]
    cmd: Option<Vec<String>>,
    #[serde(default)]
    user: Option<String>,
    #[serde(default)]
    auto_remove: Option<bool>,
    #[serde(default)]
    detach: Option<bool>,
}

#[derive(Serialize)]
struct BoxResponse {
    box_id: String,
    name: Option<String>,
    status: String,
    created_at: String,
    updated_at: String,
    pid: Option<u32>,
    image: String,
    cpus: u8,
    memory_mib: u32,
    labels: HashMap<String, String>,
}

#[derive(Serialize)]
struct ListBoxesResponse {
    boxes: Vec<BoxResponse>,
}

#[derive(Deserialize)]
struct ExecRequest {
    command: String,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    stdin: Option<String>,
    #[serde(default)]
    env: Option<HashMap<String, String>>,
    #[serde(default)]
    timeout_seconds: Option<f64>,
    #[serde(default)]
    working_dir: Option<String>,
    #[serde(default)]
    tty: bool,
}

#[derive(Serialize)]
struct ExecResponse {
    execution_id: String,
}

#[derive(Serialize)]
struct ErrorBody {
    error: ErrorDetail,
}

#[derive(Serialize)]
struct ErrorDetail {
    message: String,
    #[serde(rename = "type")]
    error_type: String,
    code: u16,
}

#[derive(Serialize)]
struct ConfigResponse {
    defaults: ConfigDefaults,
}

#[derive(Serialize)]
struct ConfigDefaults {
    cpus: u8,
    memory_mib: u32,
    disk_size_gb: u64,
}

// ============================================================================
// Conversions
// ============================================================================

fn box_info_to_response(info: &BoxInfo) -> BoxResponse {
    BoxResponse {
        box_id: info.id.to_string(),
        name: info.name.clone(),
        status: info.status.as_str().to_string(),
        created_at: info.created_at.to_rfc3339(),
        updated_at: info.last_updated.to_rfc3339(),
        pid: info.pid,
        image: info.image.clone(),
        cpus: info.cpus,
        memory_mib: info.memory_mib,
        labels: info.labels.clone(),
    }
}

fn build_box_options(req: &CreateBoxRequest) -> BoxOptions {
    let rootfs = if let Some(ref path) = req.rootfs_path {
        RootfsSpec::RootfsPath(path.clone())
    } else {
        RootfsSpec::Image(req.image.clone().unwrap_or_else(|| "alpine:latest".into()))
    };

    let env: Vec<(String, String)> = req
        .env
        .as_ref()
        .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
        .unwrap_or_default();

    BoxOptions {
        rootfs,
        cpus: req.cpus,
        memory_mib: req.memory_mib,
        disk_size_gb: req.disk_size_gb,
        working_dir: req.working_dir.clone(),
        env,
        entrypoint: req.entrypoint.clone(),
        cmd: req.cmd.clone(),
        user: req.user.clone(),
        auto_remove: req.auto_remove.unwrap_or(false),
        detach: req.detach.unwrap_or(true),
        ..Default::default()
    }
}

fn build_box_command(req: &ExecRequest) -> BoxCommand {
    let mut cmd = BoxCommand::new(&req.command).args(req.args.iter().map(String::as_str));

    if let Some(ref env_map) = req.env {
        for (k, v) in env_map {
            cmd = cmd.env(k, v);
        }
    }
    if let Some(ref wd) = req.working_dir {
        cmd = cmd.working_dir(wd);
    }
    if req.tty {
        cmd = cmd.tty(true);
    }
    if let Some(secs) = req.timeout_seconds {
        cmd = cmd.timeout(std::time::Duration::from_secs_f64(secs));
    }
    cmd
}

// ============================================================================
// Error Helpers
// ============================================================================

fn error_response(status: StatusCode, message: impl Into<String>, error_type: &str) -> Response {
    let body = ErrorBody {
        error: ErrorDetail {
            message: message.into(),
            error_type: error_type.to_string(),
            code: status.as_u16(),
        },
    };
    (status, Json(body)).into_response()
}

fn classify_boxlite_error(err: &boxlite::BoxliteError) -> (StatusCode, &'static str) {
    let msg = err.to_string().to_lowercase();
    if msg.contains("not found") {
        (StatusCode::NOT_FOUND, "NotFoundError")
    } else if msg.contains("already") || msg.contains("conflict") {
        (StatusCode::CONFLICT, "ConflictError")
    } else if msg.contains("unsupported") {
        (StatusCode::BAD_REQUEST, "UnsupportedError")
    } else {
        (StatusCode::INTERNAL_SERVER_ERROR, "InternalError")
    }
}

// ============================================================================
// Handlers
// ============================================================================

async fn get_config() -> Json<ConfigResponse> {
    Json(ConfigResponse {
        defaults: ConfigDefaults {
            cpus: 2,
            memory_mib: 512,
            disk_size_gb: 10,
        },
    })
}

async fn create_box(
    State(state): State<Arc<AppState>>,
    Json(req): Json<CreateBoxRequest>,
) -> Response {
    let name = req.name.clone();
    let options = build_box_options(&req);

    let litebox = match state.runtime.create(options, name).await {
        Ok(b) => b,
        Err(e) => {
            let (status, etype) = classify_boxlite_error(&e);
            return error_response(status, e.to_string(), etype);
        }
    };

    let info = litebox.info();
    let box_id = info.id.to_string();
    let resp = box_info_to_response(&info);

    state.boxes.write().await.insert(box_id, Arc::new(litebox));

    (StatusCode::CREATED, Json(resp)).into_response()
}

async fn list_boxes(State(state): State<Arc<AppState>>) -> Response {
    match state.runtime.list_info().await {
        Ok(infos) => {
            let boxes = infos.iter().map(box_info_to_response).collect();
            Json(ListBoxesResponse { boxes }).into_response()
        }
        Err(e) => {
            let (status, etype) = classify_boxlite_error(&e);
            error_response(status, e.to_string(), etype)
        }
    }
}

async fn get_box(State(state): State<Arc<AppState>>, Path(box_id): Path<String>) -> Response {
    match state.runtime.get_info(&box_id).await {
        Ok(Some(info)) => Json(box_info_to_response(&info)).into_response(),
        Ok(None) => error_response(
            StatusCode::NOT_FOUND,
            format!("box not found: {box_id}"),
            "NotFoundError",
        ),
        Err(e) => {
            let (status, etype) = classify_boxlite_error(&e);
            error_response(status, e.to_string(), etype)
        }
    }
}

async fn start_box(State(state): State<Arc<AppState>>, Path(box_id): Path<String>) -> Response {
    let litebox = match get_or_fetch_box(&state, &box_id).await {
        Ok(b) => b,
        Err(resp) => return resp,
    };

    if let Err(e) = litebox.start().await {
        let (status, etype) = classify_boxlite_error(&e);
        return error_response(status, e.to_string(), etype);
    }

    let info = litebox.info();
    Json(box_info_to_response(&info)).into_response()
}

async fn stop_box(State(state): State<Arc<AppState>>, Path(box_id): Path<String>) -> Response {
    let litebox = match get_or_fetch_box(&state, &box_id).await {
        Ok(b) => b,
        Err(resp) => return resp,
    };

    if let Err(e) = litebox.stop().await {
        let (status, etype) = classify_boxlite_error(&e);
        return error_response(status, e.to_string(), etype);
    }

    let info = litebox.info();
    Json(box_info_to_response(&info)).into_response()
}

async fn remove_box(State(state): State<Arc<AppState>>, Path(box_id): Path<String>) -> Response {
    // Evict from cache first
    state.boxes.write().await.remove(&box_id);

    match state.runtime.remove(&box_id, true).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(e) => {
            let (status, etype) = classify_boxlite_error(&e);
            error_response(status, e.to_string(), etype)
        }
    }
}

async fn start_execution(
    State(state): State<Arc<AppState>>,
    Path(box_id): Path<String>,
    Json(req): Json<ExecRequest>,
) -> Response {
    let litebox = match get_or_fetch_box(&state, &box_id).await {
        Ok(b) => b,
        Err(resp) => return resp,
    };

    let stdin_data = req.stdin.clone();
    let cmd = build_box_command(&req);

    let mut execution = match litebox.exec(cmd).await {
        Ok(e) => e,
        Err(e) => {
            let (status, etype) = classify_boxlite_error(&e);
            return error_response(status, e.to_string(), etype);
        }
    };

    // Write stdin and close it before storing the execution
    if let Some(ref data) = stdin_data
        && let Some(mut stdin) = execution.stdin()
    {
        let _ = stdin.write_all(data.as_bytes()).await;
        stdin.close();
    }

    let exec_id = execution.id().clone();

    state.executions.write().await.insert(
        exec_id.clone(),
        ActiveExecution {
            execution,
            started_at: Instant::now(),
        },
    );

    (
        StatusCode::CREATED,
        Json(ExecResponse {
            execution_id: exec_id,
        }),
    )
        .into_response()
}

async fn stream_execution_output(
    State(state): State<Arc<AppState>>,
    Path((_box_id, exec_id)): Path<(String, String)>,
) -> Response {
    // Take the execution out of the map (streams can only be consumed once)
    let active = match state.executions.write().await.remove(&exec_id) {
        Some(a) => a,
        None => {
            return error_response(
                StatusCode::NOT_FOUND,
                format!("execution not found: {exec_id}"),
                "NotFoundError",
            );
        }
    };

    let started_at = active.started_at;
    let mut execution = active.execution;

    // Take stdout/stderr streams (can only be called once)
    let stdout = execution.stdout();
    let stderr = execution.stderr();

    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<SseItem>();

    // Spawn producer tasks for stdout and stderr
    let mut stream_count = 0u32;
    if let Some(mut out) = stdout {
        stream_count += 1;
        let tx_out = tx.clone();
        tokio::spawn(async move {
            let b64 = base64::engine::general_purpose::STANDARD;
            while let Some(line) = out.next().await {
                let encoded = b64.encode(line.as_bytes());
                let data = serde_json::json!({"data": encoded}).to_string();
                let event = Event::default().event("stdout").data(data);
                if tx_out.send(SseItem::Event(event)).is_err() {
                    break;
                }
            }
            let _ = tx_out.send(SseItem::StreamDone);
        });
    }

    if let Some(mut err_stream) = stderr {
        stream_count += 1;
        let tx_err = tx.clone();
        tokio::spawn(async move {
            let b64 = base64::engine::general_purpose::STANDARD;
            while let Some(line) = err_stream.next().await {
                let encoded = b64.encode(line.as_bytes());
                let data = serde_json::json!({"data": encoded}).to_string();
                let event = Event::default().event("stderr").data(data);
                if tx_err.send(SseItem::Event(event)).is_err() {
                    break;
                }
            }
            let _ = tx_err.send(SseItem::StreamDone);
        });
    }

    // Drop original sender so rx closes when all producers finish
    drop(tx);

    let stream = async_stream::stream! {
        // Multiplex stdout/stderr events
        let mut done = 0u32;
        while done < stream_count {
            match rx.recv().await {
                Some(SseItem::Event(event)) => {
                    yield Ok::<_, std::convert::Infallible>(event);
                }
                Some(SseItem::StreamDone) => {
                    done += 1;
                }
                None => break,
            }
        }

        // Wait for exit
        let result = execution.wait().await;
        let elapsed_ms = started_at.elapsed().as_millis() as u64;

        let (exit_code, _error_message) = match result {
            Ok(r) => (r.exit_code, r.error_message),
            Err(e) => (-1, Some(e.to_string())),
        };

        let exit_data = serde_json::json!({
            "exit_code": exit_code,
            "duration_ms": elapsed_ms,
        })
        .to_string();

        yield Ok(Event::default().event("exit").data(exit_data));
    };

    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

// ============================================================================
// Box Handle Cache Helper
// ============================================================================

async fn get_or_fetch_box(state: &AppState, box_id: &str) -> Result<Arc<LiteBox>, Response> {
    // Check cache first
    if let Some(b) = state.boxes.read().await.get(box_id) {
        return Ok(Arc::clone(b));
    }

    // Fetch from runtime
    match state.runtime.get(box_id).await {
        Ok(Some(b)) => {
            let id = b.info().id.to_string();
            let arc = Arc::new(b);
            state.boxes.write().await.insert(id, Arc::clone(&arc));
            Ok(arc)
        }
        Ok(None) => Err(error_response(
            StatusCode::NOT_FOUND,
            format!("box not found: {box_id}"),
            "NotFoundError",
        )),
        Err(e) => {
            let (status, etype) = classify_boxlite_error(&e);
            Err(error_response(status, e.to_string(), etype))
        }
    }
}

// ============================================================================
// Router
// ============================================================================

fn build_router(state: Arc<AppState>) -> Router {
    Router::new()
        .route("/v1/config", get(get_config))
        .route("/v1/local/boxes", post(create_box))
        .route("/v1/local/boxes", get(list_boxes))
        .route("/v1/local/boxes/{box_id}", get(get_box))
        .route("/v1/local/boxes/{box_id}", delete(remove_box))
        .route("/v1/local/boxes/{box_id}/start", post(start_box))
        .route("/v1/local/boxes/{box_id}/stop", post(stop_box))
        .route("/v1/local/boxes/{box_id}/exec", post(start_execution))
        .route(
            "/v1/local/boxes/{box_id}/executions/{exec_id}/output",
            get(stream_execution_output),
        )
        .with_state(state)
}

// ============================================================================
// Entry Point
// ============================================================================

pub async fn execute(args: ServeArgs, global: &GlobalFlags) -> anyhow::Result<()> {
    let runtime = global.create_runtime()?;

    let state = Arc::new(AppState {
        runtime,
        boxes: RwLock::new(HashMap::new()),
        executions: RwLock::new(HashMap::new()),
    });

    let app = build_router(state.clone());
    let addr = format!("{}:{}", args.host, args.port);
    let listener = tokio::net::TcpListener::bind(&addr).await?;

    tracing::info!("boxlite serve listening on {}", addr);
    eprintln!("BoxLite REST API server listening on http://{addr}");

    // Graceful shutdown on ctrl-c
    let shutdown_state = state.clone();
    axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            let _ = tokio::signal::ctrl_c().await;
            tracing::info!("shutting down...");
            eprintln!("\nShutting down...");
            let _ = shutdown_state.runtime.shutdown(Some(10)).await;
        })
        .await?;

    Ok(())
}