blackship 0.4.2

A FreeBSD jail manager with state machine control
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
//! Armada (docker-compose style) orchestration commands

use std::path::{Path, PathBuf};

use serde::Serialize;

use crate::bridge::CheckReport;
use crate::cli::ArmadaAction;
use crate::error::Result;
use crate::image::copy_release_to;
use crate::output::capture_stdout;
use crate::{blueprint, bridge, error, manifest, provision};

pub fn handle(
    _config_path: &Path,
    verbose: bool,
    files: &[PathBuf],
    action: ArmadaAction,
) -> Result<()> {
    match action {
        ArmadaAction::Init { file, force } => init(&file, force),

        ArmadaAction::Up {
            detach,
            jails,
            build,
            no_build,
            dry_run,
        } => {
            let mode = if no_build {
                None
            } else if build {
                Some(BuildMode::Force)
            } else {
                Some(BuildMode::IfMissing)
            };
            up(files, verbose, &jails, mode, dry_run, detach)
        }

        ArmadaAction::Down { jails, dry_run } => down(files, verbose, &jails, dry_run),

        ArmadaAction::Build { jails, dry_run } => {
            let config = manifest::load_merged(files)?;

            let jails_to_build = select_jails(&config, &jails)?;

            if dry_run {
                println!("=== DRY RUN - No changes will be made ===\n");
            }

            build_jails(&config, &jails_to_build, BuildMode::Force, dry_run, verbose)?;
            Ok(())
        }

        ArmadaAction::Ps { json } => {
            let config = manifest::load_merged(files)?;
            let bridge = bridge::Bridge::open(config, verbose)?;
            bridge.ps(json);
            Ok(())
        }

        ArmadaAction::Config { show } => config(files, show),
    }
}

/// Structured result for every Armada action other than `ps`, whose existing
/// status payload remains unchanged for compatibility.
#[derive(Debug, Serialize)]
#[serde(tag = "action", rename_all = "snake_case")]
pub enum ActionReport {
    Init {
        file: String,
        created: bool,
        messages: Vec<String>,
    },
    Up {
        files: Vec<String>,
        jails: Vec<String>,
        dry_run: bool,
        build: &'static str,
        detach: bool,
        messages: Vec<String>,
    },
    Down {
        files: Vec<String>,
        jails: Vec<String>,
        dry_run: bool,
        messages: Vec<String>,
    },
    Build {
        files: Vec<String>,
        jails: Vec<String>,
        dry_run: bool,
        messages: Vec<String>,
    },
    Config {
        files: Vec<String>,
        valid: bool,
        check: Box<CheckReport>,
        #[serde(skip_serializing_if = "Option::is_none")]
        resolved: Option<Box<manifest::BlackshipConfig>>,
    },
}

/// Execute an Armada action while keeping stdout as one versioned JSON
/// envelope. Human progress emitted by existing lower layers is captured in
/// `messages`; warnings continue to use stderr.
pub fn action_data(verbose: bool, files: &[PathBuf], action: ArmadaAction) -> Result<ActionReport> {
    let file_names = files
        .iter()
        .map(|file| file.display().to_string())
        .collect::<Vec<_>>();

    match action {
        ArmadaAction::Init { file, force } => {
            let shown = file.display().to_string();
            let ((), messages) = capture_stdout(|| init(&file, force))?;
            Ok(ActionReport::Init {
                file: shown,
                created: true,
                messages,
            })
        }
        ArmadaAction::Up {
            detach,
            jails,
            build,
            no_build,
            dry_run,
        } => {
            let config = manifest::load_merged(files)?;
            let selected = selected_jail_names(&config, &jails)?;
            let (mode, build_name) = if no_build {
                (None, "none")
            } else if build {
                (Some(BuildMode::Force), "force")
            } else {
                (Some(BuildMode::IfMissing), "if_missing")
            };
            let ((), messages) =
                capture_stdout(|| up(files, verbose, &jails, mode, dry_run, detach))?;
            Ok(ActionReport::Up {
                files: file_names,
                jails: selected,
                dry_run,
                build: build_name,
                detach,
                messages,
            })
        }
        ArmadaAction::Down { jails, dry_run } => {
            let config = manifest::load_merged(files)?;
            let selected = selected_jail_names(&config, &jails)?;
            let ((), messages) = capture_stdout(|| down(files, verbose, &jails, dry_run))?;
            Ok(ActionReport::Down {
                files: file_names,
                jails: selected,
                dry_run,
                messages,
            })
        }
        ArmadaAction::Build { jails, dry_run } => {
            let config = manifest::load_merged(files)?;
            let selected = select_jails(&config, &jails)?;
            let selected_names = selected
                .iter()
                .map(|jail| config.jail_name(&jail.name))
                .collect();
            let ((), messages) = capture_stdout(|| {
                if dry_run {
                    println!("=== DRY RUN - No changes will be made ===\n");
                }
                build_jails(&config, &selected, BuildMode::Force, dry_run, verbose)
            })?;
            Ok(ActionReport::Build {
                files: file_names,
                jails: selected_names,
                dry_run,
                messages,
            })
        }
        ArmadaAction::Config { show } => {
            let config = manifest::load_merged(files)?;
            let bridge = bridge::Bridge::open(config.clone(), verbose)?;
            Ok(ActionReport::Config {
                files: file_names,
                valid: true,
                check: Box::new(bridge.check_data()?),
                resolved: show.then(|| Box::new(config)),
            })
        }
        ArmadaAction::Ps { .. } => Err(error::Error::UnsupportedOutputFormat),
    }
}

/// Return Armada jail status without writing terminal output.
pub fn ps_data(files: &[PathBuf], verbose: bool) -> Result<serde_json::Value> {
    let config = manifest::load_merged(files)?;
    let bridge = bridge::Bridge::open(config, verbose)?;
    serde_json::to_value(bridge.ps_data())
        .map_err(|error| error::Error::JsonOutput(error.to_string()))
}

/// Starter manifest written by `armada init`
const ARMADA_TEMPLATE: &str = r#"# Blackship Armada Configuration
# https://github.com/seuros/blackship

[config]
# data_dir defaults to ~/.local/share/blackship (XDG_DATA_HOME)
# Uncomment to override:
# data_dir = "/var/blackship"
# zfs_enabled = true
# zpool = "zroot"

# Example jail referencing a Jailfile:
# [[jails]]
# name = "web"
# build = "./web"              # Directory containing Jailfile
# depends_on = ["db"]
#
# [jails.network]
# ip_cidr = "10.0.1.10/24"
#
# [[jails.hooks]]
# phase = "post_start"
# command = "echo 'Web started'"

# Example jail without Jailfile (using release directly):
# [[jails]]
# name = "db"
# release = "15.1-RELEASE"
# path = "/jails/db"
"#;

/// `armada init`: write a starter blackship.toml
fn init(file: &Path, force: bool) -> Result<()> {
    if file.exists() && !force {
        return Err(error::Error::User(format!(
            "{} already exists. Use -y/--force to overwrite.",
            file.display()
        )));
    }

    std::fs::write(file, ARMADA_TEMPLATE)?;
    println!("Created {}", file.display());
    println!("\nNext steps:");
    println!("  1. Edit {} to define your jails", file.display());
    println!("  2. Run 'blackship armada up' to start all jails");
    Ok(())
}

/// `armada up`: build what `mode` asks for (`None` = --no-build), then start
fn up(
    files: &[PathBuf],
    verbose: bool,
    jails: &[String],
    mode: Option<BuildMode>,
    dry_run: bool,
    detach: bool,
) -> Result<()> {
    let config = manifest::load_merged(files)?;

    let selected = select_jails(&config, jails)?;
    if let Some(mode) = mode {
        build_jails(&config, &selected, mode, dry_run, verbose)?;
    } else {
        for jail_def in &selected {
            if jail_def.build.is_some() && !jail_rootfs(&config, &jail_def.name).exists() {
                return Err(error::Error::User(format!(
                    "Jail '{}' is not built and --no-build was given. Run 'blackship armada build {}' first.",
                    jail_def.name, jail_def.name
                )));
            }
        }
    }

    let mut bridge = bridge::Bridge::open(config, verbose)?;

    if jails.is_empty() {
        if dry_run {
            bridge.up_dry_run(None)?;
        } else {
            bridge.up(None)?;
        }
    } else {
        for jail in jails {
            if dry_run {
                bridge.up_dry_run(Some(jail))?;
            } else {
                bridge.up(Some(jail))?;
            }
        }
    }

    if detach {
        println!("Jails started in background.");
        println!("Use 'blackship supervise' for warden mode with auto-restart.");
    }
    Ok(())
}

/// `armada down`: stop the selected jails, or all of them
fn down(files: &[PathBuf], verbose: bool, jails: &[String], dry_run: bool) -> Result<()> {
    let config = manifest::load_merged(files)?;
    let mut bridge = bridge::Bridge::open(config, verbose)?;

    if jails.is_empty() {
        if dry_run {
            bridge.down_dry_run(None)?;
        } else {
            bridge.down(None)?;
        }
    } else {
        for jail in jails {
            if dry_run {
                bridge.down_dry_run(Some(jail))?;
            } else {
                bridge.down(Some(jail))?;
            }
        }
    }
    Ok(())
}

/// `armada config`: validate the merged config, optionally print it
fn config(files: &[PathBuf], show: bool) -> Result<()> {
    let config = manifest::load_merged(files)?;

    if show {
        println!("# Merged configuration from: {files:?}\n");
        println!("[config]");
        println!("data_dir = \"{}\"", config.config.data_dir.display());
        if config.config.zfs_enabled {
            println!("zfs_enabled = true");
            if let Some(pool) = &config.config.zpool {
                println!("zpool = \"{pool}\"");
            }
        }
        println!();
        for jail in &config.jails {
            println!("[[jails]]");
            println!("name = \"{}\"", jail.name);
            if let Some(path) = &jail.path {
                println!("path = \"{}\"", path.display());
            }
            if let Some(release) = &jail.release {
                println!("release = \"{release}\"");
            }
            if let Some(build) = &jail.build {
                println!("build = \"{}\"", build.display());
            }
            if !jail.depends_on.is_empty() {
                println!("depends_on = {:?}", jail.depends_on);
            }
            println!();
        }
    } else {
        println!("Configuration valid.");
        println!("  Files: {files:?}");
        println!("  Jails: {}", config.jails.len());
    }
    Ok(())
}

/// Whether a build should replace an existing rootfs or only fill a missing one
#[derive(Clone, Copy)]
enum BuildMode {
    Force,
    IfMissing,
}

/// Resolve requested jail names against the config, or select all jails
fn select_jails<'a>(
    config: &'a manifest::BlackshipConfig,
    jails: &[String],
) -> Result<Vec<&'a manifest::JailDef>> {
    if jails.is_empty() {
        return Ok(config.jails.iter().collect());
    }
    let mut service_names = Vec::new();
    for name in jails {
        let (service_name, _full_name) = config.require_jail_names(name)?;
        service_names.push(service_name);
    }
    Ok(config
        .jails
        .iter()
        .filter(|j| service_names.contains(&j.name))
        .collect())
}

fn selected_jail_names(
    config: &manifest::BlackshipConfig,
    jails: &[String],
) -> Result<Vec<String>> {
    Ok(select_jails(config, jails)?
        .iter()
        .map(|jail| config.jail_name(&jail.name))
        .collect())
}

/// Where a jail's built rootfs lives
fn jail_rootfs(config: &manifest::BlackshipConfig, service_name: &str) -> std::path::PathBuf {
    config.config.jail_root(&config.jail_name(service_name))
}

/// Build every selected jail that has a build context, honoring `mode`
fn build_jails(
    config: &manifest::BlackshipConfig,
    jails: &[&manifest::JailDef],
    mode: BuildMode,
    dry_run: bool,
    verbose: bool,
) -> Result<()> {
    for jail_def in jails {
        let Some(build_path) = &jail_def.build else {
            continue;
        };
        if matches!(mode, BuildMode::IfMissing) && jail_rootfs(config, &jail_def.name).exists() {
            continue;
        }
        let jailfile_path = build_path.join("Jailfile");
        if jailfile_path.exists() {
            build_jail_from_file(
                config,
                &jailfile_path,
                &jail_def.name,
                Some(build_path),
                dry_run,
                verbose,
            )?;
        } else if let Some(jailfile_explicit) = &jail_def.jailfile {
            if jailfile_explicit.exists() {
                let context_dir = jailfile_explicit
                    .parent()
                    .unwrap_or_else(|| std::path::Path::new("."));
                build_jail_from_file(
                    config,
                    jailfile_explicit,
                    &jail_def.name,
                    Some(&context_dir.to_path_buf()),
                    dry_run,
                    verbose,
                )?;
            } else {
                eprintln!(
                    "Warning: Jailfile not found at {}",
                    jailfile_explicit.display()
                );
            }
        } else {
            eprintln!("Warning: No Jailfile found at {}", jailfile_path.display());
        }
    }
    Ok(())
}

/// Build a jail from a Jailfile, bootstrapping the base release if needed
fn build_jail_from_file(
    config: &manifest::BlackshipConfig,
    jailfile_path: &std::path::Path,
    service_name: &str,
    context_dir: Option<&std::path::PathBuf>,
    dry_run: bool,
    verbose: bool,
) -> Result<()> {
    use blueprint::{BuildContext, TemplateExecutor, parse_jailfile};

    let full_name = config.jail_name(service_name);
    println!(
        "Building jail '{}' from {}",
        full_name,
        jailfile_path.display()
    );

    let content = std::fs::read_to_string(jailfile_path).map_err(|e| {
        error::Error::TemplateParseFailed(format!(
            "Failed to read {}: {}",
            jailfile_path.display(),
            e
        ))
    })?;
    let jailfile = parse_jailfile(&content)?;

    let target_path = config.config.jail_root(&full_name);

    crate::blueprint::context::reject_symlink_ancestors(&config.config.data_dir, &target_path)?;
    crate::blueprint::context::reject_symlink_target(&target_path)?;

    if let Some(release) = &jailfile.from {
        crate::manifest::validate_name("release", release)?;
        let bs = provision::Provisioner::from_config(&config.config)?;
        let release_path = config.config.releases_dir.join(release);

        if !release_path.exists() {
            println!("  Base release '{release}' not found. Bootstrapping...");
            if !dry_run {
                bs.bootstrap(release, false)?;
            }
        }

        if !dry_run && !target_path.exists() {
            println!("  Creating jail root from {release}...");
            std::fs::create_dir_all(&target_path)?;
            copy_release_to(&release_path, &target_path)?;
        }
    }

    let ctx_dir = context_dir.map_or_else(
        || {
            jailfile_path
                .parent()
                .unwrap_or_else(|| std::path::Path::new("."))
        },
        std::path::PathBuf::as_path,
    );

    let ctx = BuildContext::new(ctx_dir, &target_path, &full_name).verbose(verbose);
    let mut executor = TemplateExecutor::new(ctx).dry_run(dry_run);
    executor.execute(&jailfile)?;

    if !dry_run {
        println!("  Build complete: {}\n", target_path.display());
    }

    Ok(())
}