blackship 0.6.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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
//! Configuration file parsing for Blackship
//!
//! Parses `blackship.toml` configuration files using serde

use crate::error::{Error, Result};
use crate::hooks::Hook;
use crate::sickbay::checker::HealthCheckConfig;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt::Write as _;
use std::fs;
use std::net::IpAddr;
use std::num::NonZeroU64;
use std::path::{Path, PathBuf};
use throttle_machines::TokenBucketPolicy;

/// A source of manifest configuration.
///
/// Library callers can continue to pass a single [`Path`]. The CLI uses
/// [`ConfigPaths`] so repeated `--config` arguments are merged with the same
/// semantics as Armada's repeated `--file` arguments.
pub trait ConfigSource {
    /// The first file names the project when `[config].project` is omitted and
    /// remains the canonical path reported by compatibility surfaces.
    fn primary_path(&self) -> &Path;

    /// Every contributing file in merge order.
    fn paths(&self) -> Vec<&Path> {
        vec![self.primary_path()]
    }

    /// Load and validate this source.
    fn load_config(&self) -> Result<BlackshipConfig>;

    /// Load this source, falling back to defaults when its only file is absent.
    fn load_config_or_default(&self) -> Result<BlackshipConfig>;
}

/// Ordered manifest paths supplied by the CLI.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigPaths {
    paths: Vec<PathBuf>,
}

impl ConfigPaths {
    /// Build an ordered source. CLI parsing always supplies at least the
    /// default `blackship.toml` path.
    pub fn new(paths: Vec<PathBuf>) -> Result<Self> {
        if paths.is_empty() {
            return Err(Error::ConfigValidation(
                "At least one configuration file is required".into(),
            ));
        }
        Ok(Self { paths })
    }
}

impl ConfigSource for ConfigPaths {
    fn primary_path(&self) -> &Path {
        &self.paths[0]
    }

    fn paths(&self) -> Vec<&Path> {
        self.paths.iter().map(PathBuf::as_path).collect()
    }

    fn load_config(&self) -> Result<BlackshipConfig> {
        if self.paths.len() == 1 {
            load_file(self.primary_path())
        } else {
            load_merged(&self.paths)
        }
    }

    fn load_config_or_default(&self) -> Result<BlackshipConfig> {
        if self.paths.len() == 1 {
            load_file_or_default(self.primary_path())
        } else {
            load_merged(&self.paths)
        }
    }
}

impl ConfigSource for Path {
    fn primary_path(&self) -> &Path {
        self
    }

    fn load_config(&self) -> Result<BlackshipConfig> {
        load_file(self)
    }

    fn load_config_or_default(&self) -> Result<BlackshipConfig> {
        load_file_or_default(self)
    }
}

impl ConfigSource for PathBuf {
    fn primary_path(&self) -> &Path {
        self.as_path()
    }

    fn load_config(&self) -> Result<BlackshipConfig> {
        load_file(self)
    }

    fn load_config_or_default(&self) -> Result<BlackshipConfig> {
        load_file_or_default(self)
    }
}

/// Reserved jail tag used to declare that a jail should be running after boot.
pub const AUTOSTART_TAG: &str = "autostart";

/// Validate a jail/project/network name: these reach paths, ZFS datasets and netgraph nodes.
pub fn validate_name(kind: &str, name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::ConfigValidation(format!(
            "{kind} name cannot be empty"
        )));
    }
    if name.contains('/') || name.contains('\0') || name == "." || name == ".." {
        return Err(Error::ConfigValidation(format!(
            "{kind} name '{name}' contains invalid characters"
        )));
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
    {
        return Err(Error::ConfigValidation(format!(
            "{kind} name '{name}' contains invalid characters (only alphanumeric, dash, underscore, dot allowed)"
        )));
    }
    Ok(())
}

/// Root directory for on-disk state stores, falling back to the packaged
/// default when no config was loaded.
pub fn data_root(config: Option<&BlackshipConfig>) -> PathBuf {
    config.map_or_else(
        || PathBuf::from("/var/blackship"),
        |cfg| cfg.config.data_dir.clone(),
    )
}

/// Reject a store record name that would escape its store directory.
pub fn validate_record_name(kind: &str, name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::InvalidArgument(format!(
            "{kind} name cannot be empty"
        )));
    }
    if name.contains('/') || name.contains('\\') || name.contains("..") {
        return Err(Error::InvalidArgument(format!(
            "{kind} name '{name}' contains invalid characters"
        )));
    }
    Ok(())
}

/// Validate a ZFS pool/dataset/snapshot name; leading dashes would parse as zfs(8) options.
fn validate_zfs_component(kind: &str, name: &str) -> Result<()> {
    if name.is_empty() {
        return Err(Error::ConfigValidation(format!(
            "{kind} name cannot be empty"
        )));
    }
    if name.starts_with('-') {
        return Err(Error::ConfigValidation(format!(
            "{kind} name '{name}' must not start with '-'"
        )));
    }
    if name == "." || name == ".." || name.contains("..") {
        return Err(Error::ConfigValidation(format!(
            "{kind} name '{name}' contains invalid component"
        )));
    }
    if name.contains('@') || name.contains('\0') {
        return Err(Error::ConfigValidation(format!(
            "{kind} name '{name}' contains invalid characters"
        )));
    }
    if !name
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ':' | '/'))
    {
        return Err(Error::ConfigValidation(format!(
            "{kind} name '{name}' contains invalid characters"
        )));
    }
    Ok(())
}

/// Read a config file, mapping IO errors to `ConfigRead`
pub fn read_config_file(path: &Path) -> Result<String> {
    fs::read_to_string(path).map_err(|e| Error::ConfigRead {
        path: path.to_path_buf(),
        source: e,
    })
}

/// Derive a project name from the directory holding the config file, so the
/// same manifest yields the same jail names however its path is spelled
/// (`blackship.toml`, `../blackship.toml`, absolute). Falls back to a random
/// name when that directory has no usable name (`/`).
fn project_name_from_path(path: &Path) -> String {
    std::path::absolute(path)
        .ok()
        .and_then(|p| p.canonicalize().ok().or(Some(p)))
        .as_deref()
        .and_then(Path::parent)
        .and_then(Path::file_name)
        .and_then(|n| n.to_str())
        .map_or_else(|| black_ship_name_from_path(path), ToString::to_string)
}

/// Load configuration from one file or an ordered collection of files.
pub fn load(source: &(impl ConfigSource + ?Sized)) -> Result<BlackshipConfig> {
    source.load_config()
}

fn load_file(path: &Path) -> Result<BlackshipConfig> {
    let content = read_config_file(path)?;

    let mut config: BlackshipConfig =
        toml::from_str(&content).map_err(|source| Error::ConfigFileParse {
            path: path.to_path_buf(),
            source,
        })?;

    if config.config.project.is_none() {
        config.config.project = Some(project_name_from_path(path));
    }

    config.validate()?;

    Ok(config)
}

/// Load a config, falling back to defaults when the file does not exist.
///
/// System-level commands (bootstrap, releases, setup) work against the
/// default paths and should not demand a blackship.toml.
pub fn load_or_default(source: &(impl ConfigSource + ?Sized)) -> Result<BlackshipConfig> {
    source.load_config_or_default()
}

fn load_file_or_default(path: &Path) -> Result<BlackshipConfig> {
    if path.exists() {
        load_file(path)
    } else {
        let mut config: BlackshipConfig = toml::from_str("[config]\n")?;
        config.config.project = Some(project_name_from_path(path));
        Ok(config)
    }
}

/// Load and merge multiple configuration files
///
/// Files are merged in order at the TOML level, before anything is
/// deserialized, so a later file overrides exactly the keys it writes and
/// nothing it leaves out: tables merge recursively, `[[jails]]` and
/// `[[networks]]` entries merge with the earlier entry of the same `name` (or
/// are appended), and any other value, arrays included, replaces the earlier
/// one. Merging typed structs instead cannot tell an absent key from one set
/// to its default, and silently reset settings such as `zfs_enabled`.
pub fn load_merged(paths: &[PathBuf]) -> Result<BlackshipConfig> {
    let Some(first_path) = paths.first() else {
        return Err(Error::ConfigValidation(
            "No configuration files provided".into(),
        ));
    };

    let mut merged = toml::Table::new();
    for path in paths {
        let overlay = parse_fragment(path, &read_config_file(path)?)?;
        merge_tables(&mut merged, overlay);
    }

    let mut config: BlackshipConfig = toml::Value::Table(merged).try_into()?;

    if config.config.project.is_none() {
        config.config.project = Some(project_name_from_path(first_path));
    }

    config.validate()?;
    Ok(config)
}

/// Arrays of tables merged entry by entry on their `name` key.
const NAMED_ARRAYS: &[&str] = &["jails", "networks"];

/// Parse one file of a merge, naming it in every error. A name repeated inside
/// one file is refused: merging would silently fold the second entry into the
/// first, while a duplicate in a single manifest has always been an error.
fn parse_fragment(path: &Path, content: &str) -> Result<toml::Table> {
    let table: toml::Table =
        toml::from_str(content).map_err(|source| Error::ConfigFileParse {
            path: path.to_path_buf(),
            source,
        })?;
    for key in NAMED_ARRAYS {
        let Some(toml::Value::Array(entries)) = table.get(*key) else {
            continue;
        };
        let mut seen = std::collections::HashSet::new();
        for entry in entries {
            let Some(name) = entry.get("name").and_then(toml::Value::as_str) else {
                return Err(Error::ConfigValidation(format!(
                    "{}: [[{key}]] entry without a name",
                    path.display()
                )));
            };
            if !seen.insert(name) {
                return Err(Error::ConfigValidation(format!(
                    "{}: duplicate [[{key}]] name '{name}' in one file",
                    path.display()
                )));
            }
        }
    }
    Ok(table)
}

fn merge_tables(base: &mut toml::Table, overlay: toml::Table) {
    for (key, value) in overlay {
        match (base.get_mut(&key), value) {
            (Some(toml::Value::Table(existing)), toml::Value::Table(table)) => {
                merge_tables(existing, table);
            }
            (Some(toml::Value::Array(existing)), toml::Value::Array(entries))
                if NAMED_ARRAYS.contains(&key.as_str()) =>
            {
                merge_named_entries(existing, entries);
            }
            (_, value) => {
                base.insert(key, value);
            }
        }
    }
}

fn merge_named_entries(base: &mut Vec<toml::Value>, overlay: Vec<toml::Value>) {
    for entry in overlay {
        let name = entry.get("name").and_then(toml::Value::as_str);
        let existing = name.and_then(|name| {
            base.iter_mut()
                .find(|candidate| candidate.get("name").and_then(toml::Value::as_str) == Some(name))
        });
        match (existing, entry) {
            (Some(toml::Value::Table(existing)), toml::Value::Table(table)) => {
                merge_tables(existing, table);
            }
            (_, entry) => base.push(entry),
        }
    }
}

/// Root configuration structure
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BlackshipConfig {
    /// Global configuration settings
    pub config: GlobalConfig,

    /// Network definitions (_unused: future feature)
    #[serde(default)]
    pub networks: Vec<NetworkConfig>,

    /// Jail definitions
    #[serde(default)]
    pub jails: Vec<JailDef>,

    /// OTLP telemetry export. Absent means fully disabled.
    pub telemetry: Option<crate::telemetry::TelemetryConfig>,
}

impl BlackshipConfig {
    /// Validate the configuration
    pub fn validate(&self) -> Result<()> {
        validate_name("project", self.config.project_name())?;

        let mut names = std::collections::HashSet::new();
        let mut full_names = std::collections::HashSet::new();
        for jail in &self.jails {
            validate_name("jail", &jail.name)?;
            if !names.insert(&jail.name) {
                return Err(Error::ConfigValidation(format!(
                    "Duplicate jail name: {}",
                    jail.name
                )));
            }
            // project="demo" + jails "web"/"demo-web" both resolve to "demo-web".
            let full = self.jail_name(&jail.name);
            if full_names.contains(&full) {
                return Err(Error::ConfigValidation(format!(
                    "Jail '{}' resolves to full name '{}' which collides with another jail",
                    jail.name, full
                )));
            }
            full_names.insert(full);
        }

        // Check that all dependencies exist
        for jail in &self.jails {
            for dep in &jail.depends_on {
                if !names.contains(dep) {
                    return Err(Error::UnknownDependency(dep.clone()));
                }
            }
        }

        // Check for self-dependencies
        for jail in &self.jails {
            if jail.depends_on.contains(&jail.name) {
                return Err(Error::ConfigValidation(format!(
                    "Jail '{}' depends on itself",
                    jail.name
                )));
            }
        }

        for net in &self.networks {
            validate_name("network", &net.name)?;
        }

        for jail in &self.jails {
            if let Some(release) = &jail.release {
                validate_name("release", release)?;
            }
            if let Some(net) = &jail.network {
                if let Some(bridge) = &net.bridge {
                    validate_name("bridge", bridge)?;
                }
                for net_ref in &net.networks {
                    validate_name("network reference", net_ref)?;
                }
            }
            if let Some(mount) = &jail.mount {
                let volumes = mount.parsed_volumes()?;
                for (index, volume) in volumes.iter().enumerate() {
                    for other in &volumes[index + 1..] {
                        let (a, b) = (volume.jail_path(), other.jail_path());
                        if a == b {
                            return Err(Error::ConfigValidation(format!(
                                "Jail '{}' mounts more than one volume at '{}'",
                                jail.name,
                                a.display()
                            )));
                        }
                        if a.starts_with(b) || b.starts_with(a) {
                            return Err(Error::ConfigValidation(format!(
                                "Jail '{}' nests volume '{}' inside volume '{}'; a read-only volume cannot hold the child mountpoint",
                                jail.name,
                                if a.starts_with(b) { a } else { b }.display(),
                                if a.starts_with(b) { b } else { a }.display()
                            )));
                        }
                    }
                }
            }
        }

        self.config.rate_limit.jail_start_policy()?;
        self.config.rate_limit.health_policy()?;

        if let Some(pacer) = &self.config.rate_limit.health_concurrency {
            pacer.build()?;
        }

        for jail in &self.jails {
            for check in &jail.healthcheck.checks {
                if let Some(suspicion) = &check.suspicion {
                    suspicion.build(check.interval)?;
                }
            }
        }

        // Check ZFS configuration
        if self.config.zfs_enabled {
            if self.config.zpool.is_none() {
                return Err(Error::ConfigValidation(
                    "ZFS is enabled but no zpool specified".into(),
                ));
            }
            if let Some(pool) = &self.config.zpool {
                validate_zfs_component("zpool", pool)?;
            }
            validate_zfs_component("dataset", &self.config.dataset)?;
        }

        Ok(())
    }

    /// The jail whose service name is `name`, else the one whose full name is.
    fn exact_jail(&self, name: &str) -> Option<&JailDef> {
        self.jails.iter().find(|j| j.name == name).or_else(|| {
            self.jails
                .iter()
                .find(|j| self.full_name_matches(&j.name, name))
        })
    }

    /// Get a jail definition by name (can match either service name or full name)
    pub fn get_jail(&self, name: &str) -> Option<&JailDef> {
        self.exact_jail(name)
    }

    /// [`Self::resolve_jail_names`], failing with [`Error::JailNotFound`].
    pub fn require_jail_names(&self, name: &str) -> Result<(String, String)> {
        self.resolve_jail_names(name)
            .ok_or_else(|| Error::JailNotFound(name.to_string()))
    }

    /// Resolve a jail identifier to (`service_name`, `full_name`)
    pub fn resolve_jail_names(&self, name: &str) -> Option<(String, String)> {
        let names_of = |jail: &JailDef| (jail.name.clone(), self.jail_name(&jail.name));

        if let Some(jail) = self.exact_jail(name) {
            return Some(names_of(jail));
        }

        // Unambiguous prefix of a service or full name
        let mut matches = self
            .jails
            .iter()
            .filter(|j| j.name.starts_with(name) || self.full_name_starts_with(&j.name, name));
        let first = matches.next()?;
        if matches.next().is_none() {
            return Some(names_of(first));
        }

        None
    }

    /// Does `service_name`'s full form equal `candidate`, without building it?
    fn full_name_matches(&self, service_name: &str, candidate: &str) -> bool {
        if self.is_prefixed(service_name) {
            return service_name == candidate;
        }
        match candidate.strip_prefix(self.config.project_name()) {
            Some(rest) => rest.strip_prefix('-') == Some(service_name),
            None => false,
        }
    }

    /// Does `service_name`'s full form start with `prefix`, without building it?
    fn full_name_starts_with(&self, service_name: &str, prefix: &str) -> bool {
        if self.is_prefixed(service_name) {
            return service_name.starts_with(prefix);
        }
        let project = self.config.project_name();
        match prefix.len().cmp(&project.len()) {
            std::cmp::Ordering::Less | std::cmp::Ordering::Equal => project.starts_with(prefix),
            std::cmp::Ordering::Greater => match prefix.strip_prefix(project) {
                Some(rest) => match rest.strip_prefix('-') {
                    Some(tail) => service_name.starts_with(tail),
                    None => false,
                },
                None => false,
            },
        }
    }

    fn is_prefixed(&self, service_name: &str) -> bool {
        service_name
            .strip_prefix(self.config.project_name())
            .is_some_and(|rest| rest.starts_with('-'))
    }

    /// Get the full jail name with project prefix
    /// Format: {project}-{service_name}
    pub fn jail_name(&self, service_name: &str) -> String {
        if self.is_prefixed(service_name) {
            service_name.to_string()
        } else {
            format!("{}-{}", self.config.project_name(), service_name)
        }
    }
}

/// Known Black Ship names from Warhammer 40K lore
/// Used for random project name generation
const BLACK_SHIP_NAMES: &[&str] = &[
    "aegis_of_truth",
    "aeria_gloris",
    "enduring_abundance",
    "honour_haltis",
    "lamentation",
    "norns_ghost",
    "psythanatos",
    "validus",
    "white_sun",
];

/// Generate a Black Ship name based on a seed (deterministic)
pub fn black_ship_name(seed: usize) -> String {
    BLACK_SHIP_NAMES[seed % BLACK_SHIP_NAMES.len()].to_string()
}

/// Generate a Black Ship name from a path (uses path hash for determinism)
pub fn black_ship_name_from_path(path: &Path) -> String {
    let hash = path.to_string_lossy().bytes().fold(0usize, |acc, b| {
        acc.wrapping_add(b as usize).wrapping_mul(31)
    });
    black_ship_name(hash)
}

/// Global configuration settings
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GlobalConfig {
    /// Project name (used as prefix for jail names)
    /// If not set, a random Black Ship name will be used
    pub project: Option<String>,

    /// Base data directory for Blackship (defaults to ~/.local/share/blackship)
    #[serde(default = "default_data_dir")]
    pub data_dir: PathBuf,

    /// Enable ZFS dataset management
    #[serde(default)]
    pub zfs_enabled: bool,

    /// ZFS pool name (required if `zfs_enabled` is true)
    pub zpool: Option<String>,

    /// Base dataset name under the pool
    #[serde(default = "default_dataset")]
    pub dataset: String,

    /// Directory for FreeBSD releases
    #[serde(default = "default_releases_dir")]
    pub releases_dir: PathBuf,

    /// Cache directory for downloads
    #[serde(default = "default_cache_dir")]
    pub cache_dir: PathBuf,

    /// FreeBSD mirror URL
    #[serde(default = "default_mirror_url")]
    pub mirror_url: String,

    /// Dead-man switch: URL fetched periodically by the supervisor
    /// (healthchecks.io / Uptime Kuma style). Silence means trouble.
    pub monitor_ping_url: Option<String>,

    /// Archives to bootstrap (base, lib32, ports, src)
    #[serde(default = "default_bootstrap_archives")]
    pub bootstrap_archives: Vec<String>,

    /// Rate limiting configuration
    #[serde(default)]
    pub rate_limit: RateLimitConfig,

    /// Global health check defaults
    #[serde(default)]
    pub health: HealthDefaults,

    /// Retry/backoff configuration for HTTP operations
    #[serde(default)]
    pub retry: RetryConfig,

    /// Bridge VLAN configuration (FreeBSD 15.0+)
    pub bridge: Option<BridgeVlanConfig>,

    /// How often `supervise` samples racct usage into scope peaks and `OTel`
    /// gauges. Defaults to 30s; `0` disables sampling.
    pub usage_sample_secs: Option<u64>,
}

impl GlobalConfig {
    /// Root directory holding every jail's filesystem
    pub fn jails_dir(&self) -> PathBuf {
        self.data_dir.join("jails")
    }

    /// Filesystem root for one jail, by full (project-prefixed) name
    pub fn jail_root(&self, full_name: &str) -> PathBuf {
        self.jails_dir().join(full_name)
    }

    /// Get the effective project name
    /// Should always be set by `load/load_merged`, but falls back to "blackship" if not
    pub fn project_name(&self) -> &str {
        self.project.as_deref().unwrap_or("blackship")
    }
}

/// The same values serde fills in for an empty `[config]` table.
impl Default for GlobalConfig {
    fn default() -> Self {
        Self {
            project: None,
            data_dir: default_data_dir(),
            zfs_enabled: false,
            zpool: None,
            dataset: default_dataset(),
            releases_dir: default_releases_dir(),
            cache_dir: default_cache_dir(),
            mirror_url: default_mirror_url(),
            monitor_ping_url: None,
            bootstrap_archives: default_bootstrap_archives(),
            rate_limit: RateLimitConfig::default(),
            health: HealthDefaults::default(),
            retry: RetryConfig::default(),
            bridge: None,
            usage_sample_secs: None,
        }
    }
}

/// An empty manifest: default paths, no jails, no networks.
impl Default for BlackshipConfig {
    fn default() -> Self {
        Self {
            config: GlobalConfig::default(),
            networks: Vec::new(),
            jails: Vec::new(),
            telemetry: None,
        }
    }
}

fn default_dataset() -> String {
    "blackship".into()
}

/// Get user's home directory, falling back to /root
fn get_home_dir() -> PathBuf {
    std::env::var("HOME").map_or_else(|_| PathBuf::from("/root"), PathBuf::from)
}

/// Get XDG data directory for blackship (~/.local/share/blackship)
pub fn get_xdg_data_dir() -> PathBuf {
    std::env::var("XDG_DATA_HOME")
        .map_or_else(|_| get_home_dir().join(".local/share"), PathBuf::from)
        .join("blackship")
}

/// Get XDG cache directory for blackship (~/.cache/blackship)
pub fn get_xdg_cache_dir() -> PathBuf {
    std::env::var("XDG_CACHE_HOME")
        .map_or_else(|_| get_home_dir().join(".cache"), PathBuf::from)
        .join("blackship")
}

/// Default data directory (XDG compliant)
pub fn default_data_dir() -> PathBuf {
    get_xdg_data_dir()
}

fn default_releases_dir() -> PathBuf {
    get_xdg_data_dir().join("releases")
}

fn default_cache_dir() -> PathBuf {
    get_xdg_cache_dir()
}

fn default_mirror_url() -> String {
    "https://download.freebsd.org/releases".into()
}

fn default_bootstrap_archives() -> Vec<String> {
    vec!["base".into()]
}

const fn default_jail_start_capacity() -> f64 {
    3.0
}

const fn default_health_capacity() -> f64 {
    5.0
}

const fn default_health_refill_rate() -> f64 {
    0.5
}

/// Rate limiting configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RateLimitConfig {
    /// Max jails to start concurrently
    #[serde(default = "default_jail_start_capacity")]
    pub jail_start_capacity: f64,

    /// Health check rate limit capacity
    #[serde(default = "default_health_capacity")]
    pub health_capacity: f64,

    /// Health check rate limit refill rate (tokens per second)
    #[serde(default = "default_health_refill_rate")]
    pub health_refill_rate: f64,

    /// Adaptive bound on concurrent health-check runs; unset leaves them unbounded
    pub health_concurrency: Option<crate::sickbay::pacer::PacerConfig>,
}

/// Token bucket of `capacity` whole tokens refilled at `refill_rate` per second.
fn token_bucket_policy(what: &str, capacity: f64, refill_rate: f64) -> Result<TokenBucketPolicy> {
    let invalid = |reason: &str| Error::ConfigValidation(format!("rate limit {what}: {reason}"));
    if !capacity.is_finite() || capacity < 1.0 {
        return Err(invalid("capacity must be at least 1"));
    }
    if !refill_rate.is_finite() || refill_rate <= 0.0 {
        return Err(invalid("refill rate must be positive"));
    }
    // Saturating float cast: a bucket holds whole tokens.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let capacity = NonZeroU64::new(capacity.floor() as u64).ok_or_else(|| invalid("capacity"))?;
    let refill_every = std::time::Duration::try_from_secs_f64(refill_rate.recip())
        .map_err(|_| invalid("refill rate is too small"))?;
    TokenBucketPolicy::new(capacity, refill_every)
        .ok_or_else(|| invalid("refill rate is too large"))
}

impl RateLimitConfig {
    /// Bucket gating jail starts, refilled at one start per second.
    pub fn jail_start_policy(&self) -> Result<TokenBucketPolicy> {
        token_bucket_policy("jail_start_capacity", self.jail_start_capacity, 1.0)
    }

    /// Bucket gating each health check.
    pub fn health_policy(&self) -> Result<TokenBucketPolicy> {
        token_bucket_policy("health", self.health_capacity, self.health_refill_rate)
    }
}

impl Default for RateLimitConfig {
    fn default() -> Self {
        Self {
            jail_start_capacity: default_jail_start_capacity(),
            health_capacity: default_health_capacity(),
            health_refill_rate: default_health_refill_rate(),
            health_concurrency: None,
        }
    }
}

const fn default_health_interval() -> u64 {
    30
}

const fn default_health_timeout() -> u64 {
    10
}

const fn default_health_start_period() -> u64 {
    60
}

const fn default_health_retries() -> u32 {
    3
}

/// Global health check default settings
///
/// These values are used as defaults for health checks when not specified
/// at the individual check level.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HealthDefaults {
    /// Default interval between health checks in seconds
    #[serde(default = "default_health_interval")]
    pub interval: u64,

    /// Default timeout for health check commands in seconds
    #[serde(default = "default_health_timeout")]
    pub timeout: u64,

    /// Default start period before health checks begin in seconds
    #[serde(default = "default_health_start_period")]
    pub start_period: u64,

    /// Default number of retries before marking unhealthy
    #[serde(default = "default_health_retries")]
    pub retries: u32,
}

impl Default for HealthDefaults {
    fn default() -> Self {
        Self {
            interval: default_health_interval(),
            timeout: default_health_timeout(),
            start_period: default_health_start_period(),
            retries: default_health_retries(),
        }
    }
}

// Retry configuration defaults
const fn default_base_delay_ms() -> u64 {
    1000
}

const fn default_max_delay_ms() -> u64 {
    30000
}

const fn default_multiplier() -> f64 {
    2.0
}

const fn default_max_attempts() -> u8 {
    5
}

const fn default_jitter_factor() -> f64 {
    0.25
}

/// Retry/backoff configuration for HTTP operations
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RetryConfig {
    /// Base delay in milliseconds before first retry
    #[serde(default = "default_base_delay_ms")]
    pub base_delay_ms: u64,

    /// Maximum delay in milliseconds between retries
    #[serde(default = "default_max_delay_ms")]
    pub max_delay_ms: u64,

    /// Multiplier for exponential backoff
    #[serde(default = "default_multiplier")]
    pub multiplier: f64,

    /// Maximum number of retry attempts
    #[serde(default = "default_max_attempts")]
    pub max_attempts: u8,

    /// Jitter factor (0.0-1.0) to randomize delays
    #[serde(default = "default_jitter_factor")]
    pub jitter_factor: f64,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            base_delay_ms: default_base_delay_ms(),
            max_delay_ms: default_max_delay_ms(),
            multiplier: default_multiplier(),
            max_attempts: default_max_attempts(),
            jitter_factor: default_jitter_factor(),
        }
    }
}

/// Network configuration
///
/// Used for defining virtual networks that jails can be attached to.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkConfig {
    /// Network name
    pub name: String,

    /// Subnet in CIDR notation (e.g., "10.0.1.0/24")
    pub subnet: String,

    /// Gateway address (first usable address if not specified)
    pub gateway: Option<IpAddr>,
}

/// Bridge with VLAN filtering configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BridgeVlanConfig {
    /// Bridge interface name (e.g., "vswitch1")
    pub name: String,

    /// Enable VLAN filtering on bridge (requires FreeBSD 15.0+)
    #[serde(default)]
    pub vlan_filtering: bool,

    /// Trunk interface configuration
    pub trunk: Option<TrunkConfig>,
}

/// Physical trunk interface configuration for VLAN filtering
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TrunkConfig {
    /// Physical interface (e.g., "igb1", "em0")
    pub interface: String,

    /// Tagged VLANs allowed on trunk (e.g., [10, 20, 21, 30, 99])
    #[serde(default)]
    pub tagged: Vec<u16>,

    /// Disable hardware VLAN filter (for Broadcom NICs that cause issues)
    #[serde(default)]
    pub disable_hwfilter: bool,
}

/// Jail definition from config file
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JailDef {
    /// Unique jail name
    pub name: String,

    /// Path to jail root (can be auto-generated with ZFS)
    pub path: Option<PathBuf>,

    /// FreeBSD release to use for auto-provisioning (e.g., "15.1-RELEASE")
    /// If specified and jail path doesn't exist, it will be created from this release
    pub release: Option<String>,

    /// Build context directory containing a Jailfile
    /// Used by `armada build` to build the jail from a Jailfile
    pub build: Option<PathBuf>,

    /// Explicit path to a Jailfile (alternative to `build`)
    /// If not specified and `build` is set, looks for Jailfile in the build directory
    pub jailfile: Option<PathBuf>,

    /// Hostname for the jail
    pub hostname: Option<String>,

    /// Jails that must be started before this one
    #[serde(default)]
    pub depends_on: Vec<String>,

    /// Jail parameters (exec.start, `allow.raw_sockets`, etc.)
    #[serde(default)]
    pub params: HashMap<String, toml::Value>,

    /// Network configuration
    pub network: Option<JailNetworkConfig>,

    /// Host directories exposed in the jail through read-only nullfs mounts.
    pub mount: Option<JailMountConfig>,

    /// Lifecycle hooks
    #[serde(default)]
    pub hooks: Vec<Hook>,

    /// Health check configuration
    #[serde(default)]
    pub healthcheck: HealthCheckConfig,

    /// Resource limits (RCTL)
    #[serde(default)]
    pub resources: crate::rctl::ResourceConfig,

    /// Two-phase resource limits. Wins over `resources` when present.
    pub qos: Option<crate::rctl::QosConfig>,

    /// Refuse new connections and wait for established ones before teardown.
    pub drain: Option<DrainConfig>,

    /// What happens to jails that depend on this one when it stops.
    #[serde(default)]
    pub cascade: crate::scope::CascadePolicy,

    /// Allow reclamation to destroy this jail's dataset without `--force`.
    pub ephemeral: Option<bool>,

    /// devfs ruleset applied to the jail's /dev mount.
    /// Defaults to ruleset 4 (`devfsrules_jail`); set to 0 to skip mounting devfs.
    pub devfs_ruleset: Option<u32>,

    /// Run /etc/rc at start and /etc/rc.shutdown at stop (default: true).
    /// Disable for process-style jails that exec a single command.
    pub init: Option<bool>,

    /// Command run inside the jail before teardown. Overrides a Jailfile `STOP`.
    pub stop: Option<String>,

    /// Tags for group targeting (e.g., `blackship down web`)
    #[serde(default)]
    pub tags: Vec<String>,
}

impl JailDef {
    /// Whether this jail is an explicit project autostart target.
    ///
    /// Dependencies do not need the tag themselves: project reconciliation
    /// includes the full dependency closure of every tagged jail.
    pub fn autostarts(&self) -> bool {
        self.tags.iter().any(|tag| tag == AUTOSTART_TAG)
    }

    /// Get the effective path for this jail
    ///
    /// If ZFS is enabled and no path is specified, returns the ZFS mountpoint.
    /// The provided name should be the full jail name (project-prefixed).
    pub fn effective_path(&self, global: &GlobalConfig, full_name: &str) -> PathBuf {
        if let Some(path) = &self.path {
            path.clone()
        } else {
            // With ZFS enabled the jails dataset is mounted at data_dir/jails,
            // so this is the jail root either way.
            global.jail_root(full_name)
        }
    }

    /// The `QoS` startup profile when configured, else the static `resources` block.
    pub const fn startup_resources(&self) -> &crate::rctl::ResourceConfig {
        match &self.qos {
            Some(qos) => &qos.startup,
            None => &self.resources,
        }
    }

    /// The command to run inside the jail before teardown.
    ///
    /// An explicit manifest `stop` wins; otherwise the referenced Jailfile's
    /// `STOP` instruction is the default.
    pub fn resolve_stop(&self) -> Option<String> {
        if let Some(stop) = &self.stop {
            return Some(stop.clone());
        }
        let path = self.jailfile_path()?;
        let content = std::fs::read_to_string(path).ok()?;
        crate::blueprint::parser::parse_jailfile(&content)
            .ok()?
            .stop
    }

    /// The Jailfile this jail is built from, if any exists on disk.
    pub fn jailfile_path(&self) -> Option<PathBuf> {
        if let Some(explicit) = &self.jailfile
            && explicit.exists()
        {
            return Some(explicit.clone());
        }
        let candidate = self.build.as_ref()?.join("Jailfile");
        candidate.exists().then_some(candidate)
    }
}

/// Connection draining before teardown
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DrainConfig {
    #[serde(default = "default_true")]
    pub enabled: bool,

    /// How long to wait for established connections to close.
    #[serde(default = "default_drain_timeout")]
    pub timeout_secs: u64,
}

impl Default for DrainConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            timeout_secs: default_drain_timeout(),
        }
    }
}

const fn default_true() -> bool {
    true
}

const fn default_drain_timeout() -> u64 {
    30
}

/// Jail network configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JailNetworkConfig {
    /// Enable VNET (virtual network stack) for this jail
    /// When true, the jail gets its own network stack with epair interface
    #[serde(default)]
    pub vnet: bool,

    /// Share the host's network stack (`ip4=inherit`). Ignored if `vnet` is true.
    #[serde(default)]
    pub shared: bool,

    /// Bridge interface to attach the epair to (required for VNET)
    /// e.g., "blackship0"
    pub bridge: Option<String>,

    /// Networks to attach to
    #[serde(default)]
    pub networks: Vec<String>,

    /// IP address assignment (with optional CIDR prefix for VNET, e.g., "10.0.1.10/24")
    pub ip: Option<IpAddr>,

    /// IP address with prefix length for VNET jails (e.g., "10.0.1.10/24")
    pub ip_cidr: Option<String>,

    /// Gateway address for VNET jails
    pub gateway: Option<IpAddr>,

    /// Static MAC address
    /// If not specified, the system assigns a random MAC
    pub mac_address: Option<String>,

    /// VLAN ID for this jail's interface (untagged/PVID) (FreeBSD 15.0+)
    /// When using VLAN filtering, this sets the port VLAN ID for the jail's epair
    pub vlan_id: Option<u16>,

    /// Network backend: "epair" or "netgraph".
    /// When omitted, inherited from the attached named network (default: epair).
    pub backend: Option<crate::network::vnet::NetworkBackend>,

    /// DNS configuration for this jail
    #[serde(default)]
    pub dns: DnsConfig,
}

impl JailNetworkConfig {
    /// The jail's static address: the address part of `ip_cidr`, else `ip`.
    /// Every reader goes through this, so an `ip_cidr` jail's address is
    /// reserved, drained, forwarded to, and diffed like any other.
    pub fn static_ip(&self) -> Option<IpAddr> {
        self.ip_cidr
            .as_deref()
            .and_then(|cidr| cidr.split('/').next()?.parse().ok())
            .or(self.ip)
    }
}

/// DNS configuration for a jail
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct DnsConfig {
    /// DNS servers (e.g., `["8.8.8.8", "8.8.4.4"]`)
    /// If empty, uses "inherit" mode (copies from host)
    #[serde(default)]
    pub nameservers: Vec<String>,

    /// Search domains (e.g., `["example.com", "local"]`)
    #[serde(default)]
    pub search: Vec<String>,

    /// Domain name
    pub domain: Option<String>,

    /// Mode: "inherit" to copy from host, "custom" to use nameservers above
    /// Defaults to "inherit" if nameservers is empty
    #[serde(default = "default_dns_mode")]
    pub mode: String,
}

fn default_dns_mode() -> String {
    "inherit".to_string()
}

impl DnsConfig {
    /// Check if this config inherits from host
    pub fn is_inherit(&self) -> bool {
        self.mode == "inherit" || (self.mode != "custom" && self.nameservers.is_empty())
    }

    /// Generate resolv.conf content
    pub fn to_resolv_conf(&self) -> Option<String> {
        if self.is_inherit() {
            return None; // Will copy from host
        }

        let mut content = String::new();

        if let Some(domain) = &self.domain {
            let _ = writeln!(content, "domain {domain}"); // fmt::Write into a String is infallible
        }

        if !self.search.is_empty() {
            content.push_str("search ");
            for (i, term) in self.search.iter().enumerate() {
                if i > 0 {
                    content.push(' ');
                }
                content.push_str(term);
            }
            content.push('\n');
        }

        for ns in &self.nameservers {
            let _ = writeln!(content, "nameserver {ns}"); // fmt::Write into a String is infallible
        }

        Some(content)
    }
}

/// Jail nullfs mount configuration.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct JailMountConfig {
    /// Read-only volume mounts in `host:jail[:ro]` format.
    #[serde(default)]
    pub volumes: Vec<String>,
}

impl JailMountConfig {
    pub(crate) fn parsed_volumes(&self) -> Result<Vec<crate::container::Mount>> {
        self.volumes
            .iter()
            .map(|volume| Self::parse_volume(volume))
            .collect()
    }

    fn parse_volume(volume: &str) -> Result<crate::container::Mount> {
        let fields: Vec<&str> = volume.split(':').collect();
        if !(2..=3).contains(&fields.len()) || fields[0].is_empty() || fields[1].is_empty() {
            return Err(Error::ConfigValidation(format!(
                "Invalid volume '{volume}'; expected host:jail[:ro]"
            )));
        }
        if let Some(options) = fields.get(2) {
            for option in options.split(',') {
                if !matches!(option, "ro" | "nosuid" | "noexec") {
                    return Err(Error::ConfigValidation(format!(
                        "Invalid volume '{volume}'; manifest volumes are read-only, nosuid, and noexec"
                    )));
                }
            }
        }

        let mount = crate::container::Mount::read_only(fields[0], fields[1])
            .nosuid()
            .noexec();
        mount.validate_shape().map_err(|error| {
            Error::ConfigValidation(format!("Invalid volume '{volume}': {error}"))
        })?;
        if mount.jail_path().starts_with("/dev") {
            return Err(Error::ConfigValidation(format!(
                "Invalid volume '{volume}': targets below /dev are reserved for the jail devfs"
            )));
        }
        if fields[1].chars().any(char::is_whitespace) {
            return Err(Error::ConfigValidation(format!(
                "Invalid volume '{volume}': jail targets cannot contain whitespace"
            )));
        }
        Ok(mount)
    }
}

#[cfg(test)]
mod tests;