blackship 0.5.1

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
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
603
604
605
606
607
608
609
610
611
612
613
614
615
//! ZFS dataset management for jail roots
//!
//! Provides basic ZFS operations:
//! - Create datasets for jails
//! - Set compression and other properties
//! - Destroy datasets on jail removal

use crate::error::{Error, Result};
use jiff::Zoned;
use std::path::{Path, PathBuf};
use std::process::Command;

/// Spawn /sbin/zfs and wait for its exit status.
fn zfs_status(args: &[&str]) -> Result<std::process::ExitStatus> {
    Command::new("/sbin/zfs").args(args).status().map_err(|e| {
        Error::Zfs(format!(
            "Failed to run zfs {}: {}",
            args.first().unwrap_or(&"?"),
            e
        ))
    })
}

/// Spawn /sbin/zfs and capture its output.
fn zfs_output(args: &[&str]) -> Result<std::process::Output> {
    Command::new("/sbin/zfs").args(args).output().map_err(|e| {
        Error::Zfs(format!(
            "Failed to run zfs {}: {}",
            args.first().unwrap_or(&"?"),
            e
        ))
    })
}

/// Run a zfs command, mapping a non-zero exit to the given error message.
fn zfs_run(args: &[&str], fail_msg: impl FnOnce() -> String) -> Result<()> {
    if zfs_status(args)?.success() {
        Ok(())
    } else {
        Err(Error::Zfs(fail_msg()))
    }
}

/// ZFS dataset manager
pub struct ZfsManager {
    /// Base dataset name (e.g., "blackship")
    base_dataset: String,
    /// Where the jails dataset is mounted (`data_dir/jails`).
    jails_mountpoint: PathBuf,
}

impl ZfsManager {
    /// Create a new ZFS manager
    pub fn new(
        pool: impl Into<String>,
        base: impl Into<String>,
        jails_mountpoint: impl Into<PathBuf>,
    ) -> Self {
        let pool = pool.into();
        let base = base.into();
        Self {
            base_dataset: format!("{pool}/{base}"),
            jails_mountpoint: jails_mountpoint.into(),
        }
    }

    /// Get the full dataset path for jails
    fn jails_dataset(&self) -> String {
        format!("{}/jails", self.base_dataset)
    }

    /// Get the dataset name for a specific jail
    fn jail_dataset(&self, name: &str) -> String {
        format!("{}/{}", self.jails_dataset(), name)
    }

    /// Public dataset name for a jail (pool/base/jails/<name>)
    pub fn jail_dataset_name(&self, name: &str) -> String {
        self.jail_dataset(name)
    }

    /// Get the mountpoint path for a jail
    pub fn jail_path(&self, name: &str) -> PathBuf {
        self.jails_mountpoint.join(name)
    }

    /// Initialize the base dataset structure
    ///
    /// Creates: pool/blackship and pool/blackship/jails (mounted at `data_dir/jails`).
    pub fn init(&self) -> Result<()> {
        // Create base dataset if it doesn't exist
        if !self.dataset_exists(&self.base_dataset)? {
            Self::create_dataset(&self.base_dataset)?;
        }

        let jails = self.jails_dataset();
        let mountpoint = self.jails_mountpoint.display().to_string();
        // Datasets under it carry their own mountpoint; an existing parent may serve another data_dir.
        if !self.dataset_exists(&jails)? {
            Self::create_dataset(&jails)?;
            Self::set_property(&jails, "mountpoint", &mountpoint)?;
        }

        Ok(())
    }

    /// Check if a dataset exists
    #[allow(clippy::unused_self)] // a ZfsManager in hand is the proof ZFS is enabled here
    pub fn dataset_exists(&self, dataset: &str) -> Result<bool> {
        Ok(zfs_output(&["list", "-H", "-o", "name", dataset])?
            .status
            .success())
    }

    /// Create a dataset with default properties
    fn create_dataset(dataset: &str) -> Result<()> {
        zfs_run(&["create", "-p", "-o", "compression=lz4", dataset], || {
            format!("Failed to create dataset '{dataset}'")
        })
    }

    /// Check whether a jail's dataset exists
    pub fn jail_dataset_exists(&self, name: &str) -> Result<bool> {
        self.dataset_exists(&self.jail_dataset(name))
    }

    /// Dataset name for a bootstrapped/committed release
    pub(crate) fn release_dataset(&self, release: &str) -> String {
        format!("{}/releases/{}", self.base_dataset, release)
    }

    /// The snapshot releases are cloned from
    const PRISTINE: &'static str = "pristine";

    /// Check whether a release is dataset-backed
    pub fn release_dataset_exists(&self, release: &str) -> Result<bool> {
        self.dataset_exists(&self.release_dataset(release))
    }

    /// Create a release dataset mounted at the given path (idempotent)
    pub fn create_release_dataset(&self, release: &str, mountpoint: &Path) -> Result<()> {
        let dataset = self.release_dataset(release);
        if !self.dataset_exists(&dataset)? {
            Self::create_dataset(&dataset)?;
        }
        Self::set_property(&dataset, "mountpoint", &mountpoint.display().to_string())
    }

    /// Snapshot a release as @pristine so jails can be cloned from it
    pub fn snapshot_release_pristine(&self, release: &str) -> Result<()> {
        let dataset = self.release_dataset(release);
        let snapshot = format!("{}@{}", dataset, Self::PRISTINE);
        if Self::snapshot_exists(&snapshot)? {
            return Ok(());
        }
        Self::take_snapshot(&snapshot)
    }

    /// Whether a release can be clone-provisioned (dataset with @pristine)
    pub fn release_is_cloneable(&self, release: &str) -> bool {
        let snapshot = format!("{}@{}", self.release_dataset(release), Self::PRISTINE);
        Self::snapshot_exists(&snapshot).unwrap_or(false)
    }

    /// Provision a jail root instantly by cloning the release's @pristine
    pub fn clone_jail_from_release(&self, release: &str, jail: &str) -> Result<PathBuf> {
        let snapshot = format!("{}@{}", self.release_dataset(release), Self::PRISTINE);
        let target = self.jail_dataset(jail);
        if self.dataset_exists(&target)? {
            return Err(Error::Zfs(format!("Dataset '{target}' already exists")));
        }
        zfs_run(&["clone", &snapshot, &target], || {
            format!("Failed to clone '{snapshot}' to '{target}'")
        })?;
        Self::set_property(
            &target,
            "mountpoint",
            &self.jail_path(jail).display().to_string(),
        )?;
        Ok(self.jail_path(jail))
    }

    /// Freeze a dataset into a reusable release: snapshot, clone, promote.
    pub(crate) fn commit_dataset_to_release(
        &self,
        source: &str,
        release: &str,
        release_mountpoint: &Path,
    ) -> Result<()> {
        if !self.dataset_exists(source)? {
            return Err(Error::Zfs(format!("Dataset '{source}' does not exist")));
        }
        let target = self.release_dataset(release);
        if self.dataset_exists(&target)? {
            return Err(Error::Zfs(format!("Release '{release}' already exists")));
        }

        let snapshot = format!("{}@{}", source, Self::PRISTINE);
        if !Self::snapshot_exists(&snapshot)? {
            Self::take_snapshot(&snapshot)?;
        }

        zfs_run(&["clone", &snapshot, &target], || {
            format!("Failed to clone '{snapshot}' to '{target}'")
        })?;

        if !zfs_status(&["promote", &target])?.success() {
            // Rollback; keep the original error.
            let _ = zfs_status(&["destroy", &target]);
            return Err(Error::Zfs(format!("Failed to promote '{target}'")));
        }

        Self::set_property(
            &target,
            "mountpoint",
            &release_mountpoint.display().to_string(),
        )
    }

    /// Dataset holding an ephemeral container root (pool/base/containers/<name>)
    pub(crate) fn container_dataset(&self, name: &str) -> String {
        format!("{}/containers/{}", self.base_dataset, name)
    }

    /// Clone a release's @pristine into `dataset`, mounted at `mountpoint` from the start.
    pub(crate) fn clone_release_into(
        &self,
        release: &str,
        dataset: &str,
        mountpoint: &Path,
    ) -> Result<()> {
        let snapshot = format!("{}@{}", self.release_dataset(release), Self::PRISTINE);
        let mountpoint = format!("mountpoint={}", mountpoint.display());
        zfs_run(
            &["clone", "-p", "-o", &mountpoint, &snapshot, dataset],
            || format!("Failed to clone '{snapshot}' to '{dataset}'"),
        )
    }

    /// Recursively destroy a dataset by full name; a missing one is fine.
    pub(crate) fn destroy_dataset(&self, dataset: &str) -> Result<()> {
        if !self.dataset_exists(dataset)? {
            return Ok(());
        }
        zfs_run(&["destroy", "-r", dataset], || {
            format!("Failed to destroy dataset '{dataset}'")
        })
    }

    /// Destroy a dataset and its snapshots; refused while a clone depends on it.
    #[allow(clippy::unused_self)] // a ZfsManager in hand is the proof ZFS is enabled here
    pub(crate) fn destroy_dataset_without_dependents(&self, dataset: &str) -> Result<()> {
        let output = zfs_output(&["destroy", "-r", dataset])?;
        if output.status.success() {
            return Ok(());
        }
        Err(Error::Zfs(format!(
            "Failed to destroy '{dataset}': {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )))
    }

    /// Bare names of every dataset directly under `containers/`.
    pub(crate) fn list_container_datasets(&self) -> Vec<String> {
        Self::list_children(&format!("{}/containers", self.base_dataset))
    }

    /// Name of a build layer snapshot: bs-layer-<index>-<hash>
    pub fn layer_snapshot_name(index: usize, hash: &str) -> String {
        format!("bs-layer-{index}-{hash}")
    }

    /// Check whether a jail has a given build layer snapshot
    pub fn has_layer(&self, jail: &str, layer: &str) -> bool {
        let snapshot = format!("{}@{}", self.jail_dataset(jail), layer);
        Self::snapshot_exists(&snapshot).unwrap_or(false)
    }

    /// Snapshot the jail dataset as a build layer
    pub fn create_layer(&self, jail: &str, layer: &str) -> Result<()> {
        Self::take_snapshot(&format!("{}@{}", self.jail_dataset(jail), layer))
    }

    /// Roll the jail dataset back to a build layer, discarding newer layers
    pub fn rollback_to_layer(&self, jail: &str, layer: &str) -> Result<()> {
        let snapshot = format!("{}@{}", self.jail_dataset(jail), layer);
        zfs_run(&["rollback", "-r", &snapshot], || {
            format!("Failed to rollback to '{snapshot}'")
        })
    }

    /// Take a snapshot by full name (dataset@snap)
    fn take_snapshot(snapshot_full: &str) -> Result<()> {
        zfs_run(&["snapshot", snapshot_full], || {
            format!("Failed to snapshot '{snapshot_full}'")
        })
    }

    /// Check if a snapshot exists by full name (dataset@snap)
    fn snapshot_exists(snapshot_full: &str) -> Result<bool> {
        Ok(
            zfs_output(&["list", "-H", "-t", "snapshot", "-o", "name", snapshot_full])?
                .status
                .success(),
        )
    }

    /// Create a dataset for a jail
    ///
    /// Creates: pool/blackship/jails/<name>
    pub fn create_jail_dataset(&self, name: &str) -> Result<PathBuf> {
        let dataset = self.jail_dataset(name);

        if self.dataset_exists(&dataset)? {
            return Err(Error::Zfs(format!("Dataset '{dataset}' already exists")));
        }

        let mountpoint = format!("mountpoint={}", self.jail_path(name).display());
        zfs_run(
            &[
                "create",
                "-p",
                "-o",
                "compression=lz4",
                "-o",
                &mountpoint,
                &dataset,
            ],
            || format!("Failed to create dataset '{dataset}'"),
        )?;
        Ok(self.jail_path(name))
    }

    const EPHEMERAL_PROPERTY: &'static str = "blackship:ephemeral";

    /// Record on the dataset that blackship created it, and whether a reaper may destroy it.
    pub fn mark_jail_dataset(&self, name: &str, ephemeral: bool) -> Result<()> {
        Self::set_property(
            &self.jail_dataset(name),
            Self::EPHEMERAL_PROPERTY,
            if ephemeral { "on" } else { "off" },
        )
    }

    /// `Some(ephemeral)` for a dataset blackship created; `None` for one it did not.
    pub fn jail_dataset_mark(&self, name: &str) -> Option<bool> {
        match Self::get_property(&self.jail_dataset(name), Self::EPHEMERAL_PROPERTY)
            .ok()?
            .as_str()
        {
            "on" => Some(true),
            "off" => Some(false),
            _ => None,
        }
    }

    const MIGRATED_PROPERTY: &'static str = "blackship:migrated";

    /// Fence a jail's dataset after a successful migration: read-only, and tagged with where it went.
    pub fn fence_jail_dataset(&self, name: &str, destination: &str) -> Result<()> {
        let dataset = self.jail_dataset(name);
        Self::set_property(&dataset, Self::MIGRATED_PROPERTY, destination)?;
        Self::set_property(&dataset, "readonly", "on")
    }

    /// Where the jail was migrated to, when its dataset is fenced.
    pub fn jail_migration_fence(&self, name: &str) -> Option<String> {
        let value = Self::get_property(&self.jail_dataset(name), Self::MIGRATED_PROPERTY).ok()?;
        (!value.is_empty() && value != "-").then_some(value)
    }

    /// Lift the fence: the dataset is writable again and forgets the migration.
    pub fn clear_jail_migration_fence(&self, name: &str) -> Result<()> {
        let dataset = self.jail_dataset(name);
        Self::set_property(&dataset, "readonly", "off")?;
        zfs_run(&["inherit", Self::MIGRATED_PROPERTY, &dataset], || {
            format!("Failed to clear the migration fence on '{dataset}'")
        })
    }

    /// Destroy a jail's dataset
    ///
    /// Warning: This recursively destroys all child datasets
    pub fn destroy_jail_dataset(&self, name: &str) -> Result<()> {
        self.destroy_dataset(&self.jail_dataset(name))
    }

    /// Every jail dataset under the `jails/` namespace, by bare jail name.
    ///
    /// Returns an empty list when the namespace itself does not exist, so a
    /// non-ZFS host is indistinguishable from a ZFS host with no jails.
    pub fn list_jail_datasets(&self) -> Vec<String> {
        Self::list_children(&self.jails_dataset())
    }

    /// Bare names of the filesystems directly below `parent`.
    fn list_children(parent: &str) -> Vec<String> {
        let prefix = format!("{parent}/");

        zfs_output(&[
            "list",
            "-H",
            "-r",
            "-d",
            "1",
            "-o",
            "name",
            "-t",
            "filesystem",
            parent,
        ])
        .ok()
        .filter(|o| o.status.success())
        .map(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .filter_map(|line| line.trim().strip_prefix(&prefix).map(str::to_string))
                .filter(|name| !name.is_empty() && !name.contains('/'))
                .collect()
        })
        .unwrap_or_default()
    }

    /// The snapshot a dataset was cloned from, or `None` for a plain dataset.
    #[allow(clippy::unused_self)] // a ZfsManager in hand is the proof ZFS is enabled here
    pub fn dataset_origin(&self, dataset: &str) -> Option<String> {
        Self::get_property(dataset, "origin")
            .ok()
            .filter(|origin| !origin.is_empty() && origin != "-")
    }

    /// Get a ZFS property value
    pub fn get_property(dataset: &str, property: &str) -> Result<String> {
        let output = zfs_output(&["get", "-H", "-o", "value", property, dataset])?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            Err(Error::Zfs(format!(
                "Failed to get property '{property}' for dataset '{dataset}'"
            )))
        }
    }

    /// Set a dataset property (no-op when it already holds the value)
    pub fn set_property(dataset: &str, property: &str, value: &str) -> Result<()> {
        let current = zfs_output(&["get", "-H", "-o", "value", property, dataset])?;
        if current.status.success() && String::from_utf8_lossy(&current.stdout).trim() == value {
            return Ok(());
        }

        zfs_run(&["set", &format!("{property}={value}"), dataset], || {
            format!("Failed to set property '{property}={value}' for dataset '{dataset}'")
        })
    }

    /// Check that a jail dataset exists, returning its name or an error
    fn require_jail_dataset(&self, jail: &str) -> Result<String> {
        let dataset = self.jail_dataset(jail);
        if !self.dataset_exists(&dataset)? {
            return Err(Error::Zfs(format!("Jail dataset '{jail}' does not exist")));
        }
        Ok(dataset)
    }

    /// Check that a snapshot exists via `zfs list`
    fn require_snapshot_exists(snapshot_full: &str, snapshot: &str) -> Result<()> {
        let output = zfs_output(&["list", "-H", "-t", "snapshot", snapshot_full])?;
        if !output.status.success() {
            return Err(Error::Zfs(format!("Snapshot '{snapshot}' does not exist")));
        }
        Ok(())
    }

    /// Create a snapshot of a jail
    ///
    /// If no name is provided, generates one with timestamp
    pub fn create_snapshot(&self, jail: &str, name: Option<&str>) -> Result<String> {
        let dataset = self.require_jail_dataset(jail)?;

        let snap_name = match name {
            Some(n) => n.to_string(),
            None => default_snapshot_name(),
        };

        let snapshot = format!("{dataset}@{snap_name}");

        zfs_run(&["snapshot", "-r", &snapshot], || {
            format!("Failed to create snapshot '{snapshot}'")
        })?;
        Ok(snap_name)
    }

    /// List snapshots for a jail
    pub fn list_snapshots(&self, jail: &str) -> Result<Vec<SnapshotInfo>> {
        let dataset = self.require_jail_dataset(jail)?;

        let output = zfs_output(&[
            "list",
            "-H",
            "-t",
            "snapshot",
            "-o",
            "name,creation,used,refer",
            "-r",
            &dataset,
        ])?;

        if !output.status.success() {
            return Err(Error::Zfs("Failed to list snapshots".into()));
        }

        let stdout = String::from_utf8_lossy(&output.stdout);
        let mut snapshots = Vec::new();

        for line in stdout.lines() {
            let parts: Vec<&str> = line.split('\t').collect();
            if parts.len() >= 4 {
                // Extract snapshot name from full path (pool/blackship/jails/foo@snap -> snap)
                let full_name = parts[0];
                if let Some(at_pos) = full_name.find('@') {
                    let name = &full_name[at_pos + 1..];
                    snapshots.push(SnapshotInfo {
                        name: name.to_string(),
                        creation: parts[1].to_string(),
                        used: parts[2].to_string(),
                        refer: parts[3].to_string(),
                    });
                }
            }
        }

        Ok(snapshots)
    }

    /// Rollback a jail to a snapshot
    ///
    /// Warning: This destroys all data newer than the snapshot
    pub fn rollback_snapshot(&self, jail: &str, snapshot: &str, force: bool) -> Result<()> {
        let dataset = self.jail_dataset(jail);
        let snapshot_full = format!("{dataset}@{snapshot}");

        // Check if snapshot exists
        Self::require_snapshot_exists(&snapshot_full, snapshot)?;

        let mut args = vec!["rollback"];
        if force {
            args.push("-r"); // Destroy later snapshots
        }
        args.push(&snapshot_full);

        zfs_run(&args, || {
            format!(
                "Failed to rollback to snapshot '{snapshot}'. Use --force to destroy newer snapshots."
            )
        })
    }

    /// Delete a snapshot
    pub fn delete_snapshot(&self, jail: &str, snapshot: &str) -> Result<()> {
        let dataset = self.jail_dataset(jail);
        let snapshot_full = format!("{dataset}@{snapshot}");

        zfs_run(&["destroy", &snapshot_full], || {
            format!("Failed to delete snapshot '{snapshot}'")
        })
    }

    /// Clone a jail from a snapshot
    ///
    /// Creates a new jail from an existing jail's snapshot
    pub fn clone_from_snapshot(
        &self,
        source_jail: &str,
        snapshot: &str,
        new_jail: &str,
    ) -> Result<PathBuf> {
        let source_dataset = self.jail_dataset(source_jail);
        let snapshot_full = format!("{source_dataset}@{snapshot}");
        let target_dataset = self.jail_dataset(new_jail);

        // Check if snapshot exists
        Self::require_snapshot_exists(&snapshot_full, &format!("{source_jail}@{snapshot}"))?;

        // Check if target already exists
        if self.dataset_exists(&target_dataset)? {
            return Err(Error::Zfs(format!("Jail '{new_jail}' already exists")));
        }

        zfs_run(&["clone", &snapshot_full, &target_dataset], || {
            format!("Failed to clone snapshot '{snapshot_full}' to '{new_jail}'")
        })?;
        Ok(self.jail_path(new_jail))
    }
}

fn default_snapshot_name() -> String {
    format!("snap-{}", Zoned::now().strftime("%Y%m%d-%H%M%S"))
}

/// Information about a ZFS snapshot
#[derive(Debug, Clone)]
pub struct SnapshotInfo {
    /// Snapshot name (without dataset prefix)
    pub name: String,
    /// Creation timestamp
    pub creation: String,
    /// Space used by snapshot
    pub used: String,
    /// Referenced space
    pub refer: String,
}

#[cfg(test)]
mod tests;