crates/state/deploy/src/lib.rs 65.7 KiB 1883 lines Raw
1 //! inf3r-deploy — the host binding file.2 //!3 //! The engine ships without a deploy file because a binding is a choice of the4 //! host: the same binaries run elsewhere with different devices and budgets.5 //! This crate reads that choice and refuses every line it cannot honour. There6 //! is no TOML dependency, only the subset that the file uses, so an unsupported7 //! line is an error with its line number instead of a setting that did nothing.8 9 use std::collections::BTreeSet;10 use std::fmt;11 use std::fs;12 use std::path::{Component, Path, PathBuf};13 use std::time::Duration;14 15 #[derive(Clone, Copy, PartialEq, Eq, Debug)]16 enum Section {17     None,18     Node,19     Bind,20     Cache,21     Tier,22     Class,23 }24 25 /// One host and the bundles that it serves.26 #[derive(Clone, PartialEq, Eq, Debug)]27 pub struct Deploy {28     /// The single node of the file. A deploy names exactly one host.29     pub node: Node,30 }31 32 /// The settings of one host.33 #[derive(Clone, PartialEq, Eq, Debug)]34 pub struct Node {35     /// The name that operators and logs use.36     pub host: String,37     /// The directory that holds the bundle binaries.38     pub bin_dir: PathBuf,39     /// The directories that hold bundle manifests, in lookup order.40     pub bundle_dirs: Vec<PathBuf>,41     /// The host directories whose read-only contents an engine may mount.42     /// Empty means no host asset mount is allowed. A container bind names43     /// only a source below one of these directories; weights and media use44     /// descriptors instead (D28).45     pub asset_dirs: Vec<PathBuf>,46     /// The directory that holds the content store.47     pub blob_dir: PathBuf,48     /// Where the control creates one private socket directory per engine.49     /// `None` uses the supervisor's default (`/run/inf3r` or `INF3R_RUN_DIR`).50     pub socket_dir: Option<PathBuf>,51     /// The same root as the Docker daemon sees it. A control container can52     /// mount the host runtime directory at `socket_dir`; the engine then53     /// receives the host path and the control passes the container path on54     /// argv. `None` means the two roots are identical, which is the host-mode55     /// default.56     pub socket_host_dir: Option<PathBuf>,57     /// The image that runs the generic probe helper. A container bind that58     /// names a CUDA device needs it; the helper supplies GPU totals and host59     /// pid memory from outside the control's namespaces (D28).60     pub probe_image: Option<String>,61     /// The byte ceiling of the store. A missing value leaves it to the free62     /// space of `blob_dir`.63     pub blob_bound: Option<u64>,64     /// The longest wait for the driver to free a stopped child's bytes. A65     /// missing value uses [`DEFAULT_SETTLE`].66     pub settle: Duration,67     /// How clients reach the engine.68     pub web: Web,69     /// The file that holds the client token.70     pub auth_file: PathBuf,71     /// One entry per bundle that this host serves.72     pub binds: Vec<Bind>,73     /// Host-global KV cache intent. `None` means no cache was declared.74     pub cache: Option<Cache>,75 }76 77 /// Host-global KV cache intent.78 #[derive(Clone, PartialEq, Eq, Debug, Default)]79 pub struct Cache {80     pub enabled: bool,81     pub persist: CachePersist,82     pub pin_bound: u64,83     pub flush_budget: Duration,84     pub default_ttl: Duration,85     pub classes: Vec<CacheClass>,86     pub tiers: Vec<CacheTier>,87 }88 89 /// What a cache survives.90 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]91 pub enum CachePersist {92     #[default]93     Reboot,94     Session,95 }96 97 /// A named host-global retention class.98 #[derive(Clone, PartialEq, Eq, Debug)]99 pub struct CacheClass {100     pub name: String,101     pub ttl: Duration,102 }103 104 /// One host-global cache tier.105 #[derive(Clone, PartialEq, Eq, Debug)]106 pub struct CacheTier {107     pub name: String,108     pub dir: PathBuf,109     pub bound: Option<u64>,110     pub headroom: u64,111     pub ttl: Option<Duration>,112 }113 114 /// How a bind uses the host cache.115 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]116 pub enum CacheMode {117     #[default]118     Auto,119     ReadOnly,120     Off,121 }122 123 /// The listeners of the web layer. At least one transport is configured; a124 /// host may expose a Unix socket for local clients, a TCP address for remote125 /// clients, or both.126 #[derive(Clone, PartialEq, Eq, Debug)]127 pub struct Web {128     /// A Unix socket path.129     pub unix: Option<PathBuf>,130     /// A TCP address as `host:port`.131     pub tcp: Option<String>,132 }133 134 /// How one bind runs its engine.135 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]136 pub enum Runtime {137     /// A plugin binary in `bin_dir`, started as a child of the control.138     #[default]139     Process,140     /// A sibling Docker container. The image carries the plugin.141     Container,142 }143 144 /// One bind mount for a container bind.145 #[derive(Clone, PartialEq, Eq, Debug)]146 pub struct BindMount {147     /// The host path.148     pub source: PathBuf,149     /// The path inside the container.150     pub target: PathBuf,151     /// A mount is read-only unless the deploy file explicitly says `rw`; a152     /// writable host path would escape the one socket directory that D28153     /// allows.154     pub read_only: bool,155 }156 157 /// The choice to serve one bundle with certain models on certain devices.158 #[derive(Clone, PartialEq, Eq, Debug)]159 pub struct Bind {160     /// The bundle id: the path below a bundle directory.161     pub bundle: String,162     /// Process or sibling container.163     pub runtime: Runtime,164     /// The image reference for a container bind. `None` in process mode.165     pub image: Option<String>,166     /// The entrypoint override and its arguments. Empty keeps the image's own167     /// entrypoint and command.168     pub command: Vec<String>,169     /// The Docker network. D28 permits `none`.170     pub network: String,171     /// Read-only host mounts that the image needs.172     pub mounts: Vec<BindMount>,173     /// The models that this bind serves. No model appears in two binds.174     pub models: Vec<String>,175     /// The devices that the bundle runs on, at least one.176     pub devices: Vec<String>,177     /// The weight files that the bind hands to the bundle, in order. A relative178     /// path is resolved as written because the operator names the file.179     pub weights: Vec<PathBuf>,180     /// Bytes of VRAM per device. Empty means the manifest decides.181     pub vram: Vec<u64>,182     /// A pinned model stays on the device and is never unloaded.183     pub pin: bool,184     /// A warm model loads at startup. `false` loads it on first use.185     pub warm: bool,186     /// The idle time after which the core unloads the model.187     pub idle_unload: Option<Duration>,188     /// The default priority of the jobs of this bind.189     pub priority: Priority,190     /// The most jobs that may run at once. None leaves it to the bundle.191     pub max_inflight: Option<u16>,192     /// The host-global retention class this bind names. Empty means the193     /// default class, if one exists.194     pub cache_class: Option<String>,195     /// Whether this bind may write the cache.196     pub cache_mode: CacheMode,197     /// The process limit for a container bind. None keeps Docker's default.198     pub pids_limit: Option<u32>,199     /// The host memory ceiling for a container bind, in bytes.200     pub memory_bytes: Option<u64>,201     /// The `/dev/shm` size for a container bind, in bytes.202     pub shm_bytes: Option<u64>,203     /// The rotated Docker log size, in bytes.204     pub log_max_bytes: Option<u64>,205     /// The number of rotated Docker log files.206     pub log_max_files: Option<u32>,207 }208 209 /// The scheduling class of the jobs of a bind.210 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]211 pub enum Priority {212     /// A job that a person is waiting for.213     #[default]214     Interactive,215     /// A job that may wait behind interactive work.216     Background,217 }218 219 /// The reason a deploy file was refused.220 #[derive(Clone, PartialEq, Eq, Debug)]221 pub enum DeployError {222     /// A line is outside the supported subset.223     Syntax {224         /// The one-based line number.225         line: usize,226         /// What the parser found and what it expected.227         message: String,228     },229     /// The file could not be read.230     Io(String),231     /// A required key is absent. The value names the key.232     Missing(&'static str),233     /// The file holds more than one `[[node]]`.234     ManyNodes,235     /// `web` names neither `unix` nor `tcp`.236     Web,237     /// A key is not defined by its table.238     Unknown {239         /// The one-based line number.240         line: usize,241         /// The key that no table defines.242         key: String,243     },244     /// Two settings cannot both hold.245     Conflicting {246         /// The one-based line number of the setting that loses.247         line: usize,248         /// Which settings conflict.249         message: String,250     },251     /// Two binds serve the same model, so one would never be reached.252     DuplicateModel(String),253     /// A value that must be positive is zero. The value names the key.254     Zero(&'static str),255     /// A byte size that [`bytes`] rejects.256     Size(String),257     /// A duration that [`duration`] rejects, with the line that holds it.258     Duration(String),259 }260 261 impl fmt::Display for DeployError {262     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {263         match self {264             DeployError::Syntax { line, message } => write!(f, "line {line}: {message}"),265             DeployError::Io(why) => write!(f, "cannot read the deploy file: {why}"),266             DeployError::Missing(key) => write!(f, "missing {key}"),267             DeployError::ManyNodes => write!(f, "more than one [[node]]"),268             DeployError::Web => write!(f, "web needs unix, tcp, or both"),269             DeployError::Unknown { line, key } => write!(f, "line {line}: unknown key {key}"),270             DeployError::Conflicting { line, message } => write!(f, "line {line}: {message}"),271             DeployError::DuplicateModel(model) => {272                 write!(f, "model {model} is served by two binds")273             }274             DeployError::Zero(key) => write!(f, "{key} is zero"),275             DeployError::Size(text) => write!(f, "{text} is not a byte size"),276             DeployError::Duration(text) => write!(f, "{text} is not a duration"),277         }278     }279 }280 281 impl std::error::Error for DeployError {}282 283 /// A decimal byte unit. The operators and `df` agree on 10^3, so the file284 /// means the same number that the tool showed them.285 const BYTE: u64 = 1;286 /// One thousand bytes.287 const KB: u64 = 1_000;288 /// One million bytes.289 const MB: u64 = 1_000 * KB;290 /// One billion bytes.291 const GB: u64 = 1_000 * MB;292 /// One trillion bytes.293 const TB: u64 = 1_000 * GB;294 295 /// The default settle budget. A driver frees mmapped weights some time after296 /// the process exits; two seconds covers that lag without holding a reservation297 /// through the next load's patience. It matches the core's own default so that298 /// a file without this key behaves like one that names it.299 pub const DEFAULT_SETTLE: Duration = Duration::from_secs(2);300 /// A cache entry that no class names lasts a week.301 pub const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(7 * 24 * 60 * 60);302 /// The longest unload waits for dirty slots.303 pub const DEFAULT_FLUSH_BUDGET: Duration = Duration::from_secs(5);304 305 /// Milliseconds in one second.306 const MILLIS_PER_SECOND: u64 = 1_000;307 /// Milliseconds in one minute.308 const MILLIS_PER_MINUTE: u64 = 60 * MILLIS_PER_SECOND;309 /// Milliseconds in one hour.310 const MILLIS_PER_HOUR: u64 = 60 * MILLIS_PER_MINUTE;311 /// Milliseconds in one day.312 const MILLIS_PER_DAY: u64 = 24 * MILLIS_PER_HOUR;313 314 /// Parses a decimal byte size.315 ///316 /// The units are decimal because a disk vendor and `df` report decimal sizes;317 /// a binary unit would make the file disagree with the tool that the operator318 /// used to choose the number.319 pub fn bytes(text: &str) -> Option<u64> {320     let split = text321         .find(|c: char| !c.is_ascii_digit())322         .unwrap_or(text.len());323     let number = text[..split].parse::<u64>().ok()?;324     let unit = match text[split..].to_ascii_uppercase().as_str() {325         "" | "B" => BYTE,326         "KB" => KB,327         "MB" => MB,328         "GB" => GB,329         "TB" => TB,330         _ => return None,331     };332     number.checked_mul(unit)333 }334 335 /// Parses a duration.336 ///337 /// The suffixes are the ones an operator writes in a deploy file (`ms`, `s`,338 /// `m`, `h`). A unit is required: a bare number would be ambiguous between339 /// seconds and milliseconds at the point where an unload is decided.340 pub fn duration(text: &str) -> Option<Duration> {341     let split = text342         .find(|c: char| !c.is_ascii_digit())343         .unwrap_or(text.len());344     let number = text[..split].parse::<u64>().ok()?;345     let millis = match &text[split..] {346         "ms" => number,347         "s" => number.checked_mul(MILLIS_PER_SECOND)?,348         "m" => number.checked_mul(MILLIS_PER_MINUTE)?,349         "h" => number.checked_mul(MILLIS_PER_HOUR)?,350         "d" => number.checked_mul(MILLIS_PER_DAY)?,351         _ => return None,352     };353     Some(Duration::from_millis(millis))354 }355 356 impl Deploy {357     /// Parses a deploy file.358     ///359     /// A setting that the parser does not understand is an error rather than a360     /// skipped line: a typo that silently did nothing would bind a host that361     /// the operator did not describe.362     pub fn parse(text: &str) -> Result<Deploy, DeployError> {363         let mut node: Option<NodeBuilder> = None;364         let mut binds: Vec<BindBuilder> = Vec::new();365         let mut section = Section::None;366 367         for (index, raw) in text.lines().enumerate() {368             let line = index + 1;369             let content = strip_comment(raw).trim();370             if content.is_empty() {371                 continue;372             }373             if let Some(header) = content.strip_prefix("[[") {374                 let Some(name) = header.strip_suffix("]]") else {375                     return Err(syntax(line, "unterminated table header"));376                 };377                 match name {378                     "node" => {379                         if node.is_some() {380                             return Err(DeployError::ManyNodes);381                         }382                         node = Some(NodeBuilder::default());383                         section = Section::Node;384                     }385                     "node.bind" => {386                         if node.is_none() {387                             return Err(syntax(line, "bind before [[node]]"));388                         }389                         binds.push(BindBuilder::default());390                         section = Section::Bind;391                     }392                     "node.cache.class" => {393                         let node = node394                             .as_mut()395                             .ok_or_else(|| syntax(line, "class before [[node]]"))?;396                         node.cache.classes.push(CacheClassBuilder {397                             line,398                             ..CacheClassBuilder::default()399                         });400                         node.cache.seen = true;401                         section = Section::Class;402                     }403                     "node.cache.tier" => {404                         let node = node405                             .as_mut()406                             .ok_or_else(|| syntax(line, "tier before [[node]]"))?;407                         node.cache.tiers.push(CacheTierBuilder {408                             line,409                             ..CacheTierBuilder::default()410                         });411                         node.cache.seen = true;412                         section = Section::Tier;413                     }414                     _ => return Err(syntax(line, "unknown table header")),415                 }416                 continue;417             }418             if let Some(name) = content.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {419                 if name != "node.cache" {420                     return Err(syntax(line, "unknown table header"));421                 }422                 let node = node423                     .as_mut()424                     .ok_or_else(|| syntax(line, "cache before [[node]]"))?;425                 node.cache.seen = true;426                 section = Section::Cache;427                 continue;428             }429             let (key, value) = parse_pair(content, line)?;430             match section {431                 Section::None => return Err(syntax(line, "key outside a table")),432                 Section::Node => {433                     let node = node434                         .as_mut()435                         .ok_or_else(|| syntax(line, "key before [[node]]"))?;436                     node_key(node, &key, value, line)?;437                 }438                 Section::Bind => {439                     let bind = binds440                         .last_mut()441                         .ok_or_else(|| syntax(line, "bind before [[node]]"))?;442                     bind_key(bind, &key, value, line)?;443                 }444                 Section::Cache => {445                     let node = node446                         .as_mut()447                         .ok_or_else(|| syntax(line, "cache before [[node]]"))?;448                     cache_key(&mut node.cache, &key, value, line)?;449                 }450                 Section::Tier => {451                     let node = node452                         .as_mut()453                         .ok_or_else(|| syntax(line, "tier before [[node]]"))?;454                     let tier = node455                         .cache456                         .tiers457                         .last_mut()458                         .ok_or_else(|| syntax(line, "tier before [[node]]"))?;459                     tier_key(tier, &key, value, line)?;460                 }461                 Section::Class => {462                     let node = node463                         .as_mut()464                         .ok_or_else(|| syntax(line, "class before [[node]]"))?;465                     let class = node466                         .cache467                         .classes468                         .last_mut()469                         .ok_or_else(|| syntax(line, "class before [[node]]"))?;470                     class_key(class, &key, value, line)?;471                 }472             }473         }474 475         let node = node.ok_or(DeployError::Missing("[[node]]"))?;476         let host = node.host.ok_or(DeployError::Missing("host"))?;477         let bin_dir = node.bin_dir.ok_or(DeployError::Missing("bin_dir"))?;478         let bundle_dirs = node479             .bundle_dirs480             .ok_or(DeployError::Missing("bundle_dirs"))?;481         let blob_dir = node.blob_dir.ok_or(DeployError::Missing("blob_dir"))?;482         let web = node.web.ok_or(DeployError::Missing("web"))?;483         let auth_file = node.auth_file.ok_or(DeployError::Missing("auth_file"))?;484         let cache = finish_cache(node.cache, &blob_dir)?;485 486         let mut seen = BTreeSet::new();487         let mut finished = Vec::with_capacity(binds.len());488         for bind in binds {489             let bind = finish_bind(bind)?;490             for model in &bind.models {491                 if !seen.insert(model.clone()) {492                     return Err(DeployError::DuplicateModel(model.clone()));493                 }494             }495             finished.push(bind);496         }497 498         Ok(Deploy {499             node: Node {500                 host,501                 bin_dir,502                 bundle_dirs,503                 asset_dirs: node.asset_dirs.unwrap_or_default(),504                 blob_dir,505                 socket_dir: node.socket_dir,506                 socket_host_dir: node.socket_host_dir,507                 probe_image: node.probe_image,508                 blob_bound: node.blob_bound,509                 settle: node.settle.unwrap_or(DEFAULT_SETTLE),510                 web,511                 auth_file,512                 binds: finished,513                 cache,514             },515         })516     }517 518     /// Reads and parses a deploy file.519     pub fn read(path: &Path) -> Result<Deploy, DeployError> {520         let text = fs::read_to_string(path).map_err(|e| DeployError::Io(e.to_string()))?;521         Deploy::parse(&text)522     }523 }524 525 /// One reason that a deploy file cannot be honoured.526 ///527 /// A conflict is not a parse error: each field is valid on its own, and the528 /// file only fails when two fields meet. They are collected rather than529 /// returned on the first one because an operator who has to restart once per530 /// conflict learns nothing from the second restart.531 #[derive(Clone, PartialEq, Eq, Debug)]532 pub struct Conflict {533     /// The bind that owns the conflict, when one does.534     pub bind: Option<usize>,535     /// What is wrong, in the words the operator needs to fix it.536     pub message: String,537 }538 539 impl fmt::Display for Conflict {540     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {541         match self.bind {542             Some(index) => write!(f, "bind {}: {}", index + 1, self.message),543             None => write!(f, "{}", self.message),544         }545     }546 }547 548 impl Node {549     /// Every setting that cannot be honoured, in file order.550     ///551     /// The caller starts nothing when this is not empty: a half-bound host is552     /// worse than a host that refuses, because a client cannot tell the553     /// difference between a model that is absent and a model that failed.554     pub fn conflicts(&self) -> Vec<Conflict> {555         let mut found = Vec::new();556         if let Some(dir) = &self.socket_dir557             && !dir.is_absolute()558         {559             found.push(Conflict {560                 bind: None,561                 message: format!("socket_dir {} is not absolute", dir.display()),562             });563         }564         if let Some(dir) = &self.socket_host_dir {565             if !dir.is_absolute() {566                 found.push(Conflict {567                     bind: None,568                     message: format!("socket_host_dir {} is not absolute", dir.display()),569                 });570             }571             if self.socket_dir.is_none() {572                 found.push(Conflict {573                     bind: None,574                     message: "socket_host_dir needs socket_dir".to_string(),575                 });576             }577         }578         if self.web.unix.is_none() && self.web.tcp.is_none() {579             found.push(Conflict {580                 bind: None,581                 message: "web names no listener".to_string(),582             });583         }584         let classes: BTreeSet<&str> = self585             .cache586             .as_ref()587             .map(|cache| {588                 cache589                     .classes590                     .iter()591                     .map(|class| class.name.as_str())592                     .collect()593             })594             .unwrap_or_default();595         let mut bundles: BTreeSet<&str> = BTreeSet::new();596         let mut models: BTreeSet<&str> = BTreeSet::new();597         let mut needs_probe = false;598         let mut private: Vec<PathBuf> = vec![self.blob_dir.clone()];599         if let Some(cache) = &self.cache {600             private.extend(cache.tiers.iter().map(|tier| tier.dir.clone()));601         }602         let socket_root = self603             .socket_dir604             .clone()605             .unwrap_or_else(|| PathBuf::from("/run/inf3r"));606         let socket_host_root = self607             .socket_host_dir608             .clone()609             .unwrap_or_else(|| socket_root.clone());610         if let Some(image) = &self.probe_image611             && let Err(why) = image_pinned(image)612         {613             found.push(Conflict {614                 bind: None,615                 message: format!("probe_image {image} {why}"),616             });617         }618         let mut assets = Vec::new();619         for dir in &self.asset_dirs {620             match checked_asset_dir(self, dir) {621                 Ok(path) => assets.push(path),622                 Err(why) => found.push(Conflict {623                     bind: None,624                     message: format!("asset_dirs {} {why}", dir.display()),625                 }),626             }627         }628         for (index, bind) in self.binds.iter().enumerate() {629             if !bundles.insert(bind.bundle.as_str()) {630                 found.push(Conflict {631                     bind: Some(index),632                     message: format!(633                         "bundle {} is bound twice; one binary has one socket",634                         bind.bundle635                     ),636                 });637             }638             if !bound_id(&bind.bundle) {639                 found.push(Conflict {640                     bind: Some(index),641                     message: format!(642                         "bundle {:?} is not a path below the bundle directory",643                         bind.bundle644                     ),645                 });646             }647             if bind.runtime == Runtime::Container {648                 // The probe is the only memory view outside the control's PID649                 // namespace. A CPU-only sibling needs it just as much as a CUDA650                 // one: `HostMemory` would read the wrong process tree.651                 needs_probe = true;652                 match bind.image.as_deref() {653                     None => found.push(Conflict {654                         bind: Some(index),655                         message: "a container bind needs image".to_string(),656                     }),657                     Some(image) => {658                         if let Err(why) = image_pinned(image) {659                             found.push(Conflict {660                                 bind: Some(index),661                                 message: format!("image {image} {why}"),662                             });663                         }664                     }665                 }666                 if bind.network != "none" {667                     found.push(Conflict {668                         bind: Some(index),669                         message: format!(670                             "network {:?} is not none; an engine is a sibling with no network",671                             bind.network672                         ),673                     });674                 }675                 for mount in &bind.mounts {676                     if !mount.read_only {677                         found.push(Conflict {678                             bind: Some(index),679                             message: format!(680                                 "mount {}:{} is writable; only the private socket directory is writable",681                                 mount.source.display(),682                                 mount.target.display()683                             ),684                         });685                     }686                     let (source, target) = match checked_mount(self, &assets, mount) {687                         Ok(paths) => paths,688                         Err(why) => {689                             found.push(Conflict {690                                 bind: Some(index),691                                 message: format!(692                                     "mount {}:{} {why}",693                                     mount.source.display(),694                                     mount.target.display()695                                 ),696                             });697                             continue;698                         }699                     };700                     if private.iter().any(|path| overlap(&source, path)) {701                         found.push(Conflict {702                             bind: Some(index),703                             message: format!(704                                 "mount {} overlaps the control's private store",705                                 mount.source.display()706                             ),707                         });708                     }709                     if overlap(&source, &socket_root)710                         || overlap(&target, &socket_root)711                         || overlap(&source, &socket_host_root)712                         || overlap(&target, &socket_host_root)713                     {714                         found.push(Conflict {715                             bind: Some(index),716                             message: format!(717                                 "mount {}:{} overlaps the private socket root",718                                 mount.source.display(),719                                 mount.target.display()720                             ),721                         });722                     }723                 }724             } else if bind.image.is_some()725                 || !bind.command.is_empty()726                 || !bind.mounts.is_empty()727                 || bind.pids_limit.is_some()728                 || bind.memory_bytes.is_some()729                 || bind.shm_bytes.is_some()730                 || bind.log_max_bytes.is_some()731                 || bind.log_max_files.is_some()732             {733                 found.push(Conflict {734                     bind: Some(index),735                     message:736                         "a process bind cannot name image, command, mounts, or container limits"737                             .to_string(),738                 });739             }740             if bind.pin && bind.idle_unload.is_some() {741                 found.push(Conflict {742                     bind: Some(index),743                     message: "a pinned model is never unloaded, so idle_unload does nothing"744                         .to_string(),745                 });746             }747             if !bind.vram.is_empty() && bind.vram.len() != bind.devices.len() {748                 found.push(Conflict {749                     bind: Some(index),750                     message: format!(751                         "vram has {} values for {} devices",752                         bind.vram.len(),753                         bind.devices.len()754                     ),755                 });756             }757             let mut devices: BTreeSet<&str> = BTreeSet::new();758             for device in &bind.devices {759                 if !devices.insert(device.as_str()) {760                     found.push(Conflict {761                         bind: Some(index),762                         message: format!("device {device} is named twice"),763                     });764                 }765             }766             if let Some(class) = &bind.cache_class767                 && !classes.contains(class.as_str())768             {769                 found.push(Conflict {770                     bind: Some(index),771                     message: format!("cache_class {class} is not declared under [node.cache]"),772                 });773             }774             for model in &bind.models {775                 if model.trim().is_empty() {776                     found.push(Conflict {777                         bind: Some(index),778                         message: "a model name is empty".to_string(),779                     });780                 } else if !models.insert(model.as_str()) {781                     found.push(Conflict {782                         bind: Some(index),783                         message: format!("model {model} is served by two binds"),784                     });785                 }786             }787         }788         if needs_probe && self.probe_image.is_none() {789             found.push(Conflict {790                 bind: None,791                 message: "a container bind needs probe_image".to_string(),792             });793         }794         found795     }796 }797 798 /// Normalizes an absolute Unix path without touching the filesystem. A799 /// `..` component is refused rather than removed: removing it would hide a800 /// path that the operator did not intend to name.801 fn normalized(path: &Path) -> Result<PathBuf, String> {802     if !path.is_absolute() {803         return Err("is not absolute".to_string());804     }805     let mut out = PathBuf::from("/");806     for component in path.components() {807         match component {808             Component::RootDir | Component::CurDir => {}809             Component::Normal(part) => out.push(part),810             Component::ParentDir => return Err("contains ..".to_string()),811             Component::Prefix(_) => return Err("is not a Unix path".to_string()),812         }813     }814     Ok(out)815 }816 817 /// Whether a path names or contains the Docker socket. The check is on the818 /// normalized spelling, so a trailing slash does not evade it.819 fn docker_socket(path: &Path) -> bool {820     path.components()821         .any(|component| component.as_os_str() == "docker.sock")822 }823 824 /// Rejects a symlink in any component of an existing absolute path. A825 /// canonicalized path alone is not enough: it would hide the symlink that the826 /// operator named, and the next process could replace the target.827 fn no_symlink(path: &Path) -> Result<(), String> {828     let mut current = PathBuf::from("/");829     for component in path.components() {830         if let Component::Normal(part) = component {831             current.push(part);832             match fs::symlink_metadata(&current) {833                 Ok(meta) if meta.file_type().is_symlink() => {834                     return Err(format!("component {} is a symlink", current.display()));835                 }836                 Ok(_) => {}837                 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {838                     return Err(format!("{} does not exist", current.display()));839                 }840                 Err(error) => {841                     return Err(format!("{} cannot be read: {error}", current.display()));842                 }843             }844         }845     }846     Ok(())847 }848 849 /// The absolute spelling of a deploy path, relative to the process directory850 /// when the operator wrote it relative.851 fn absolute(path: &Path) -> Option<PathBuf> {852     if path.as_os_str().is_empty() {853         return None;854     }855     if path.is_absolute() {856         return normalized(path).ok();857     }858     let current = std::env::current_dir().ok()?;859     normalized(&current.join(path)).ok()860 }861 862 /// The one control home that an engine must not see.863 fn control_home() -> Option<PathBuf> {864     let home = std::env::var_os("HOME")865         .map(PathBuf::from)866         .unwrap_or_else(|| PathBuf::from("/root"));867     absolute(&home)868 }869 870 /// A host path that an engine may not receive, in either direction: the path871 /// itself, anything below it, or a parent that would expose it.872 fn protected(path: &Path, node: &Node) -> Option<String> {873     for root in ["/etc", "/var/run", "/run", "/root"] {874         let root = Path::new(root);875         if path.starts_with(root) || root.starts_with(path) {876             return Some(format!("overlaps {root}", root = root.display()));877         }878     }879     if let Some(home) = control_home()880         && (path == home || home.starts_with(path))881     {882         return Some("is the control home or a parent".to_string());883     }884     if let Some(token) = absolute(&node.auth_file)885         && (token.starts_with(path) || path.starts_with(&token))886     {887         return Some("names the control token".to_string());888     }889     None890 }891 892 /// Validates one declared asset root. It must exist, be a directory, and not893 /// expose a protected host path.894 fn checked_asset_dir(node: &Node, path: &Path) -> Result<PathBuf, String> {895     let path = normalized(path)?;896     if docker_socket(&path) {897         return Err("names the Docker socket".to_string());898     }899     no_symlink(&path)?;900     let meta = fs::metadata(&path).map_err(|error| {901         if error.kind() == std::io::ErrorKind::NotFound {902             "does not exist".to_string()903         } else {904             format!("cannot be read: {error}")905         }906     })?;907     if !meta.is_dir() {908         return Err("is not a directory".to_string());909     }910     let path = fs::canonicalize(&path).map_err(|error| format!("cannot be resolved: {error}"))?;911     if let Some(why) = protected(&path, node) {912         return Err(why);913     }914     Ok(path)915 }916 917 /// Validates a mount source. The source must resolve below one declared asset918 /// root, must be a real file or directory, and must not contain a Docker919 /// socket.920 fn checked_mount_source(node: &Node, assets: &[PathBuf], path: &Path) -> Result<PathBuf, String> {921     let path = normalized(path)?;922     if docker_socket(&path) {923         return Err("names the Docker socket".to_string());924     }925     no_symlink(&path)?;926     let meta = fs::metadata(&path).map_err(|error| {927         if error.kind() == std::io::ErrorKind::NotFound {928             "does not exist".to_string()929         } else {930             format!("cannot be read: {error}")931         }932     })?;933     let path = fs::canonicalize(&path).map_err(|error| format!("cannot be resolved: {error}"))?;934     if let Some(why) = protected(&path, node) {935         return Err(why);936     }937     if !assets938         .iter()939         .any(|root| path == *root || path.starts_with(root))940     {941         return Err("is not below an asset_dirs entry".to_string());942     }943     if meta.is_dir() {944         let entries = fs::read_dir(&path).map_err(|error| format!("cannot be listed: {error}"))?;945         if entries946             .flatten()947             .any(|entry| entry.file_name() == "docker.sock")948         {949             return Err("contains the Docker socket".to_string());950         }951     }952     Ok(path)953 }954 955 /// Validates a mount target inside the engine. It cannot be canonicalized956 /// because the target lives in the image, but its spelling must still be957 /// absolute, `..`-free, and clear of the socket.958 fn checked_mount_target(path: &Path) -> Result<PathBuf, String> {959     let path = normalized(path)?;960     if path == Path::new("/") {961         return Err("targets the container root".to_string());962     }963     if docker_socket(&path) {964         return Err("names the Docker socket".to_string());965     }966     for root in ["/etc", "/var/run", "/run", "/root"] {967         let root = Path::new(root);968         if path.starts_with(root) {969             return Err(format!("targets {root}", root = root.display()));970         }971     }972     Ok(path)973 }974 975 fn checked_mount(976     node: &Node,977     assets: &[PathBuf],978     mount: &BindMount,979 ) -> Result<(PathBuf, PathBuf), String> {980     let source = checked_mount_source(node, assets, &mount.source)?;981     let target = checked_mount_target(&mount.target)?;982     Ok((source, target))983 }984 985 /// Whether two paths name the same store or one contains the other.986 fn overlap(a: &Path, b: &Path) -> bool {987     let a = std::fs::canonicalize(a).unwrap_or_else(|_| a.to_path_buf());988     let b = std::fs::canonicalize(b).unwrap_or_else(|_| b.to_path_buf());989     a == b || a.starts_with(&b) || b.starts_with(&a)990 }991 992 /// Whether a bundle id names a path below the bundle directory.993 ///994 /// The id becomes a binary name and a private socket directory, so a `..`, a leading995 /// `/`, or an empty segment would leave the directory that the operator named.996 fn bound_id(id: &str) -> bool {997     !id.is_empty()998         && !id.starts_with('/')999         && id1000             .split('/')1001             .all(|part| !part.is_empty() && part != "." && part != "..")1002 }1003 1004 /// The fields of `[[node]]` before the required ones are checked.1005 #[derive(Default)]1006 struct NodeBuilder {1007     host: Option<String>,1008     bin_dir: Option<PathBuf>,1009     bundle_dirs: Option<Vec<PathBuf>>,1010     asset_dirs: Option<Vec<PathBuf>>,1011     blob_dir: Option<PathBuf>,1012     socket_dir: Option<PathBuf>,1013     socket_host_dir: Option<PathBuf>,1014     probe_image: Option<String>,1015     blob_bound: Option<u64>,1016     settle: Option<Duration>,1017     web: Option<Web>,1018     auth_file: Option<PathBuf>,1019     cache: CacheBuilder,1020 }1021 1022 #[derive(Default)]1023 struct CacheBuilder {1024     seen: bool,1025     enabled: Option<bool>,1026     persist: Option<CachePersist>,1027     pin_bound: Option<u64>,1028     flush_budget: Option<Duration>,1029     default_ttl: Option<Duration>,1030     classes: Vec<CacheClassBuilder>,1031     tiers: Vec<CacheTierBuilder>,1032 }1033 1034 #[derive(Default)]1035 struct CacheClassBuilder {1036     name: Option<String>,1037     ttl: Option<Duration>,1038     line: usize,1039 }1040 1041 #[derive(Default)]1042 struct CacheTierBuilder {1043     name: Option<String>,1044     dir: Option<PathBuf>,1045     bound: Option<u64>,1046     headroom: Option<u64>,1047     ttl: Option<Duration>,1048     line: usize,1049 }1050 1051 /// The fields of one `[[node.bind]]` before the required ones are checked.1052 #[derive(Default)]1053 struct BindBuilder {1054     bundle: Option<String>,1055     runtime: Option<Runtime>,1056     image: Option<String>,1057     command: Vec<String>,1058     network: Option<String>,1059     mounts: Vec<BindMount>,1060     models: Option<Vec<String>>,1061     devices: Option<Vec<String>>,1062     weights: Option<Vec<PathBuf>>,1063     vram: Option<Vec<u64>>,1064     vram_line: usize,1065     pin: Option<bool>,1066     warm: Option<bool>,1067     idle_unload: Option<Duration>,1068     idle_line: usize,1069     priority: Option<Priority>,1070     max_inflight: Option<u16>,1071     cache_class: Option<String>,1072     cache_mode: Option<CacheMode>,1073     pids_limit: Option<u32>,1074     memory_bytes: Option<u64>,1075     shm_bytes: Option<u64>,1076     log_max_bytes: Option<u64>,1077     log_max_files: Option<u32>,1078 }1079 1080 /// A value in the supported subset. It borrows nothing because a bind outlives1081 /// the line that produced it.1082 enum Value {1083     Str(String),1084     Bool(bool),1085     Int(u64),1086     Array(Vec<Value>),1087     Table(Vec<(String, Value)>),1088 }1089 1090 impl Value {1091     /// The name that an error message uses for a kind mismatch.1092     fn kind(&self) -> &'static str {1093         match self {1094             Value::Str(_) => "string",1095             Value::Bool(_) => "bool",1096             Value::Int(_) => "integer",1097             Value::Array(_) => "array",1098             Value::Table(_) => "inline table",1099         }1100     }1101 }1102 1103 fn syntax(line: usize, message: impl Into<String>) -> DeployError {1104     DeployError::Syntax {1105         line,1106         message: message.into(),1107     }1108 }1109 1110 fn bad_duration(line: usize, text: &str) -> DeployError {1111     DeployError::Duration(format!("line {line}: {text}"))1112 }1113 1114 /// Cuts a comment at the first `#` that is outside a string.1115 fn strip_comment(line: &str) -> &str {1116     let mut in_string = false;1117     let mut escaped = false;1118     for (index, c) in line.char_indices() {1119         if in_string {1120             if escaped {1121                 escaped = false;1122             } else if c == '\\' {1123                 escaped = true;1124             } else if c == '"' {1125                 in_string = false;1126             }1127         } else if c == '"' {1128             in_string = true;1129         } else if c == '#' {1130             return &line[..index];1131         }1132     }1133     line1134 }1135 1136 fn is_bare_key(key: &str) -> bool {1137     !key.is_empty() && key.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')1138 }1139 1140 fn parse_pair(text: &str, line: usize) -> Result<(String, Value), DeployError> {1141     let equals = text1142         .find('=')1143         .ok_or_else(|| syntax(line, "expected key = value"))?;1144     let key = text[..equals].trim();1145     if !is_bare_key(key) {1146         return Err(syntax(line, format!("key {key:?} is not [a-z_]+")));1147     }1148     let mut parser = ValueParser {1149         text: text[equals + 1..].trim(),1150         pos: 0,1151         line,1152     };1153     let value = parser.value()?;1154     parser.space();1155     if !parser.done() {1156         return Err(syntax(line, "trailing text after the value"));1157     }1158     Ok((key.to_string(), value))1159 }1160 1161 fn node_key(1162     node: &mut NodeBuilder,1163     key: &str,1164     value: Value,1165     line: usize,1166 ) -> Result<(), DeployError> {1167     match key {1168         "host" => node.host = Some(string(value, key, line)?),1169         "bin_dir" => node.bin_dir = Some(PathBuf::from(string(value, key, line)?)),1170         "bundle_dirs" => {1171             node.bundle_dirs = Some(1172                 strings(value, key, line)?1173                     .into_iter()1174                     .map(PathBuf::from)1175                     .collect(),1176             );1177         }1178         "asset_dirs" => {1179             node.asset_dirs = Some(1180                 strings(value, key, line)?1181                     .into_iter()1182                     .map(PathBuf::from)1183                     .collect(),1184             );1185         }1186         "blob_dir" => node.blob_dir = Some(PathBuf::from(string(value, key, line)?)),1187         "socket_dir" => node.socket_dir = Some(PathBuf::from(string(value, key, line)?)),1188         "socket_host_dir" => node.socket_host_dir = Some(PathBuf::from(string(value, key, line)?)),1189         "probe_image" => node.probe_image = Some(string(value, key, line)?),1190         "blob_bound" => {1191             let text = string(value, key, line)?;1192             node.blob_bound = Some(bytes(&text).ok_or(DeployError::Size(text))?);1193         }1194         "settle" => {1195             let text = string(value, key, line)?;1196             node.settle = Some(duration(&text).ok_or_else(|| bad_duration(line, &text))?);1197         }1198         "web" => node.web = Some(web(value, line)?),1199         "auth_file" => node.auth_file = Some(PathBuf::from(string(value, key, line)?)),1200         _ => {1201             return Err(DeployError::Unknown {1202                 line,1203                 key: key.to_string(),1204             });1205         }1206     }1207     Ok(())1208 }1209 1210 fn bind_key(1211     bind: &mut BindBuilder,1212     key: &str,1213     value: Value,1214     line: usize,1215 ) -> Result<(), DeployError> {1216     match key {1217         "bundle" => bind.bundle = Some(string(value, key, line)?),1218         "runtime" => {1219             let text = string(value, key, line)?;1220             bind.runtime = Some(match text.as_str() {1221                 "process" => Runtime::Process,1222                 "container" => Runtime::Container,1223                 _ => {1224                     return Err(syntax(1225                         line,1226                         format!("runtime {text:?} is not process or container"),1227                     ));1228                 }1229             });1230         }1231         "image" => bind.image = Some(string(value, key, line)?),1232         "command" => bind.command = strings(value, key, line)?,1233         "network" => bind.network = Some(string(value, key, line)?),1234         "mounts" => {1235             bind.mounts = strings(value, key, line)?1236                 .iter()1237                 .map(|text| mount(text, line))1238                 .collect::<Result<Vec<_>, _>>()?;1239         }1240         "models" => bind.models = Some(strings(value, key, line)?),1241         "devices" => bind.devices = Some(strings(value, key, line)?),1242         "weights" => {1243             bind.weights = Some(1244                 strings(value, key, line)?1245                     .into_iter()1246                     .map(PathBuf::from)1247                     .collect(),1248             );1249         }1250         "vram" => {1251             bind.vram = Some(integers(value, key, line)?);1252             bind.vram_line = line;1253         }1254         "pin" => bind.pin = Some(boolean(value, key, line)?),1255         "warm" => bind.warm = Some(boolean(value, key, line)?),1256         "idle_unload" => {1257             let text = string(value, key, line)?;1258             bind.idle_unload = Some(duration(&text).ok_or_else(|| bad_duration(line, &text))?);1259             bind.idle_line = line;1260         }1261         "priority" => {1262             let text = string(value, key, line)?;1263             bind.priority = Some(match text.as_str() {1264                 "interactive" => Priority::Interactive,1265                 "background" => Priority::Background,1266                 _ => {1267                     return Err(syntax(1268                         line,1269                         format!("priority {text:?} is not interactive or background"),1270                     ));1271                 }1272             });1273         }1274         "max_inflight" => {1275             let number = integer(value, key, line)?;1276             let number = u16::try_from(number)1277                 .map_err(|_| syntax(line, format!("{key} is larger than {}", u16::MAX)))?;1278             if number == 0 {1279                 return Err(DeployError::Zero("max_inflight"));1280             }1281             bind.max_inflight = Some(number);1282         }1283         "pids_limit" | "pids" => {1284             let number = integer(value, key, line)?;1285             let number = u32::try_from(number)1286                 .map_err(|_| syntax(line, format!("{key} is larger than {}", u32::MAX)))?;1287             if number == 0 {1288                 return Err(DeployError::Zero("pids_limit"));1289             }1290             bind.pids_limit = Some(number);1291         }1292         "memory" | "memory_bytes" => {1293             let text = string(value, key, line)?;1294             let bytes = bytes(&text).ok_or(DeployError::Size(text))?;1295             if bytes == 0 {1296                 return Err(DeployError::Zero("memory"));1297             }1298             bind.memory_bytes = Some(bytes);1299         }1300         "shm" | "shm_size" => {1301             let text = string(value, key, line)?;1302             let bytes = bytes(&text).ok_or(DeployError::Size(text))?;1303             if bytes == 0 {1304                 return Err(DeployError::Zero("shm"));1305             }1306             bind.shm_bytes = Some(bytes);1307         }1308         "log_max_size" | "log_size" => {1309             let text = string(value, key, line)?;1310             let bytes = bytes(&text).ok_or(DeployError::Size(text))?;1311             if bytes == 0 {1312                 return Err(DeployError::Zero("log_max_size"));1313             }1314             bind.log_max_bytes = Some(bytes);1315         }1316         "log_max_files" | "log_files" => {1317             let number = integer(value, key, line)?;1318             let number = u32::try_from(number)1319                 .map_err(|_| syntax(line, format!("{key} is larger than {}", u32::MAX)))?;1320             if number == 0 {1321                 return Err(DeployError::Zero("log_max_files"));1322             }1323             bind.log_max_files = Some(number);1324         }1325         "cache_class" => bind.cache_class = Some(string(value, key, line)?),1326         "cache_mode" => {1327             let text = string(value, key, line)?;1328             bind.cache_mode = Some(match text.as_str() {1329                 "auto" => CacheMode::Auto,1330                 "read_only" => CacheMode::ReadOnly,1331                 "off" => CacheMode::Off,1332                 _ => {1333                     return Err(syntax(1334                         line,1335                         format!("cache_mode {text:?} is not auto, read_only, or off"),1336                     ));1337                 }1338             });1339         }1340         _ => {1341             return Err(DeployError::Unknown {1342                 line,1343                 key: key.to_string(),1344             });1345         }1346     }1347     Ok(())1348 }1349 1350 fn cache_key(1351     cache: &mut CacheBuilder,1352     key: &str,1353     value: Value,1354     line: usize,1355 ) -> Result<(), DeployError> {1356     match key {1357         "enabled" => cache.enabled = Some(boolean(value, key, line)?),1358         "persist" => {1359             let text = string(value, key, line)?;1360             cache.persist = Some(match text.as_str() {1361                 "reboot" => CachePersist::Reboot,1362                 "session" => CachePersist::Session,1363                 _ => {1364                     return Err(syntax(1365                         line,1366                         format!("persist {text:?} is not reboot or session"),1367                     ));1368                 }1369             });1370         }1371         "pin_bound" => {1372             let text = string(value, key, line)?;1373             cache.pin_bound = Some(bytes(&text).ok_or(DeployError::Size(text))?);1374         }1375         "flush_budget" => {1376             let text = string(value, key, line)?;1377             cache.flush_budget = Some(duration(&text).ok_or_else(|| bad_duration(line, &text))?);1378         }1379         "default_ttl" => {1380             let text = string(value, key, line)?;1381             cache.default_ttl = Some(duration(&text).ok_or_else(|| bad_duration(line, &text))?);1382         }1383         _ => {1384             return Err(DeployError::Unknown {1385                 line,1386                 key: key.to_string(),1387             });1388         }1389     }1390     Ok(())1391 }1392 1393 fn tier_key(1394     tier: &mut CacheTierBuilder,1395     key: &str,1396     value: Value,1397     line: usize,1398 ) -> Result<(), DeployError> {1399     match key {1400         "name" => tier.name = Some(string(value, key, line)?),1401         "dir" => tier.dir = Some(PathBuf::from(string(value, key, line)?)),1402         "bound" => {1403             let text = string(value, key, line)?;1404             tier.bound = Some(bytes(&text).ok_or(DeployError::Size(text))?);1405         }1406         "headroom" => {1407             let text = string(value, key, line)?;1408             tier.headroom = Some(bytes(&text).ok_or(DeployError::Size(text))?);1409         }1410         "ttl" => {1411             let text = string(value, key, line)?;1412             tier.ttl = Some(duration(&text).ok_or_else(|| bad_duration(line, &text))?);1413         }1414         _ => {1415             return Err(DeployError::Unknown {1416                 line,1417                 key: key.to_string(),1418             });1419         }1420     }1421     Ok(())1422 }1423 1424 fn class_key(1425     class: &mut CacheClassBuilder,1426     key: &str,1427     value: Value,1428     line: usize,1429 ) -> Result<(), DeployError> {1430     match key {1431         "name" => class.name = Some(string(value, key, line)?),1432         "ttl" => {1433             let text = string(value, key, line)?;1434             class.ttl = Some(duration(&text).ok_or_else(|| bad_duration(line, &text))?);1435         }1436         _ => {1437             return Err(DeployError::Unknown {1438                 line,1439                 key: key.to_string(),1440             });1441         }1442     }1443     Ok(())1444 }1445 1446 fn finish_cache(builder: CacheBuilder, blob_dir: &Path) -> Result<Option<Cache>, DeployError> {1447     if !builder.seen {1448         return Ok(None);1449     }1450     let mut classes = Vec::new();1451     let mut class_names = BTreeSet::new();1452     for class in builder.classes {1453         let name = class.name.ok_or(DeployError::Missing("class.name"))?;1454         if !class_names.insert(name.clone()) {1455             return Err(DeployError::Conflicting {1456                 line: class.line,1457                 message: format!("cache class {name} is declared twice"),1458             });1459         }1460         let ttl = class.ttl.ok_or_else(|| DeployError::Conflicting {1461             line: class.line,1462             message: format!("cache class {name} has no ttl"),1463         })?;1464         classes.push(CacheClass { name, ttl });1465     }1466     let mut tiers = Vec::new();1467     let mut tier_names = BTreeSet::new();1468     let mut tier_dirs = BTreeSet::new();1469     for tier in builder.tiers {1470         let name = tier.name.ok_or(DeployError::Missing("tier.name"))?;1471         let dir = tier.dir.ok_or(DeployError::Missing("tier.dir"))?;1472         if !tier_names.insert(name.clone()) || !tier_dirs.insert(dir.clone()) {1473             return Err(DeployError::Conflicting {1474                 line: tier.line,1475                 message: format!("cache tier {name} or {} is duplicated", dir.display()),1476             });1477         }1478         if tier.bound == Some(0) {1479             return Err(DeployError::Zero("tier.bound"));1480         }1481         let headroom = tier.headroom.unwrap_or(0);1482         if tier.bound.is_none() && headroom == 0 {1483             return Err(DeployError::Conflicting {1484                 line: tier.line,1485                 message: format!("cache tier {name} is unbounded and needs headroom"),1486             });1487         }1488         let canonical_dir = std::fs::canonicalize(&dir).unwrap_or_else(|_| dir.clone());1489         let canonical_blob =1490             std::fs::canonicalize(blob_dir).unwrap_or_else(|_| blob_dir.to_path_buf());1491         if canonical_dir == canonical_blob1492             || canonical_dir.starts_with(&canonical_blob)1493             || canonical_blob.starts_with(&canonical_dir)1494         {1495             return Err(DeployError::Conflicting {1496                 line: tier.line,1497                 message: format!("cache tier {} overlaps blob_dir", dir.display()),1498             });1499         }1500         tiers.push(CacheTier {1501             name,1502             dir,1503             bound: tier.bound,1504             headroom,1505             ttl: tier.ttl,1506         });1507     }1508     let enabled = builder.enabled.unwrap_or(false);1509     if enabled && tiers.is_empty() {1510         return Err(DeployError::Missing("node.cache.tier"));1511     }1512     let pin_bound = builder.pin_bound.unwrap_or(0);1513     let total: u64 = tiers.iter().filter_map(|tier| tier.bound).sum();1514     if pin_bound != 0 && total != 0 && pin_bound >= total {1515         return Err(DeployError::Conflicting {1516             line: 0,1517             message: format!("pin_bound {pin_bound} must be below the total tier bound {total}"),1518         });1519     }1520     Ok(Some(Cache {1521         enabled,1522         persist: builder.persist.unwrap_or_default(),1523         pin_bound,1524         flush_budget: builder.flush_budget.unwrap_or(DEFAULT_FLUSH_BUDGET),1525         default_ttl: builder.default_ttl.unwrap_or(DEFAULT_CACHE_TTL),1526         classes,1527         tiers,1528     }))1529 }1530 1531 fn finish_bind(bind: BindBuilder) -> Result<Bind, DeployError> {1532     let bundle = bind.bundle.ok_or(DeployError::Missing("bundle"))?;1533     let models = bind.models.ok_or(DeployError::Missing("models"))?;1534     if models.is_empty() {1535         return Err(DeployError::Missing("models"));1536     }1537     let devices = bind.devices.ok_or(DeployError::Missing("devices"))?;1538     if devices.is_empty() {1539         return Err(DeployError::Missing("devices"));1540     }1541     let weights = bind.weights.unwrap_or_default();1542     let vram = bind.vram.unwrap_or_default();1543     if !vram.is_empty() && vram.len() != devices.len() {1544         return Err(DeployError::Conflicting {1545             line: bind.vram_line,1546             message: format!(1547                 "vram has {} values for {} devices",1548                 vram.len(),1549                 devices.len()1550             ),1551         });1552     }1553     let pin = bind.pin.unwrap_or(false);1554     if pin && bind.idle_unload.is_some() {1555         return Err(DeployError::Conflicting {1556             line: bind.idle_line,1557             message: "idle_unload cannot apply to a pinned model".to_string(),1558         });1559     }1560     Ok(Bind {1561         bundle,1562         runtime: bind.runtime.unwrap_or_default(),1563         image: bind.image,1564         command: bind.command,1565         network: bind.network.unwrap_or_else(|| "none".to_string()),1566         mounts: bind.mounts,1567         models,1568         devices,1569         weights,1570         vram,1571         pin,1572         warm: bind.warm.unwrap_or(true),1573         idle_unload: bind.idle_unload,1574         priority: bind.priority.unwrap_or_default(),1575         max_inflight: bind.max_inflight,1576         cache_class: bind.cache_class,1577         cache_mode: bind.cache_mode.unwrap_or_default(),1578         pids_limit: bind.pids_limit,1579         memory_bytes: bind.memory_bytes,1580         shm_bytes: bind.shm_bytes,1581         log_max_bytes: bind.log_max_bytes,1582         log_max_files: bind.log_max_files,1583     })1584 }1585 1586 /// `source:target[:ro|rw]`. A colon in a path is unsupported; a deploy file1587 /// that needs one can name it through a symlink with a colon-free path.1588 fn mount(text: &str, line: usize) -> Result<BindMount, DeployError> {1589     let mut parts = text.split(':');1590     let source = parts.next().unwrap_or_default();1591     let target = parts1592         .next()1593         .ok_or_else(|| syntax(line, "a mount needs source:target"))?;1594     let mode = parts.next();1595     if parts.next().is_some() {1596         return Err(syntax(line, "a mount has at most source:target:mode"));1597     }1598     if source.is_empty() || target.is_empty() {1599         return Err(syntax(line, "a mount source and target cannot be empty"));1600     }1601     let read_only = match mode {1602         None | Some("ro") => true,1603         Some("rw") => false,1604         Some(other) => {1605             return Err(syntax(1606                 line,1607                 format!("mount mode {other:?} is not ro or rw"),1608             ));1609         }1610     };1611     Ok(BindMount {1612         source: PathBuf::from(source),1613         target: PathBuf::from(target),1614         read_only,1615     })1616 }1617 1618 fn string(value: Value, key: &str, line: usize) -> Result<String, DeployError> {1619     match value {1620         Value::Str(text) => Ok(text),1621         other => Err(syntax(1622             line,1623             format!("{key} needs a string, found {}", other.kind()),1624         )),1625     }1626 }1627 1628 fn strings(value: Value, key: &str, line: usize) -> Result<Vec<String>, DeployError> {1629     match value {1630         Value::Array(items) => items1631             .into_iter()1632             .map(|item| string(item, key, line))1633             .collect(),1634         other => Err(syntax(1635             line,1636             format!("{key} needs an array, found {}", other.kind()),1637         )),1638     }1639 }1640 1641 fn integers(value: Value, key: &str, line: usize) -> Result<Vec<u64>, DeployError> {1642     match value {1643         Value::Array(items) => items1644             .into_iter()1645             .map(|item| integer(item, key, line))1646             .collect(),1647         other => Err(syntax(1648             line,1649             format!("{key} needs an array, found {}", other.kind()),1650         )),1651     }1652 }1653 1654 fn integer(value: Value, key: &str, line: usize) -> Result<u64, DeployError> {1655     match value {1656         Value::Int(number) => Ok(number),1657         other => Err(syntax(1658             line,1659             format!("{key} needs an integer, found {}", other.kind()),1660         )),1661     }1662 }1663 1664 fn boolean(value: Value, key: &str, line: usize) -> Result<bool, DeployError> {1665     match value {1666         Value::Bool(flag) => Ok(flag),1667         other => Err(syntax(1668             line,1669             format!("{key} needs true or false, found {}", other.kind()),1670         )),1671     }1672 }1673 1674 fn web(value: Value, line: usize) -> Result<Web, DeployError> {1675     let Value::Table(entries) = value else {1676         return Err(syntax(1677             line,1678             format!("web needs an inline table, found {}", value.kind()),1679         ));1680     };1681     let mut unix = None;1682     let mut tcp = None;1683     for (key, value) in entries {1684         match key.as_str() {1685             "unix" => unix = Some(PathBuf::from(string(value, "unix", line)?)),1686             "tcp" => tcp = Some(string(value, "tcp", line)?),1687             _ => return Err(DeployError::Unknown { line, key }),1688         }1689     }1690     if unix.is_none() && tcp.is_none() {1691         return Err(DeployError::Web);1692     }1693     Ok(Web { unix, tcp })1694 }1695 1696 /// A cursor over one value on one line.1697 struct ValueParser<'a> {1698     text: &'a str,1699     pos: usize,1700     line: usize,1701 }1702 1703 impl ValueParser<'_> {1704     fn peek(&self) -> Option<char> {1705         self.text[self.pos..].chars().next()1706     }1707 1708     fn bump(&mut self) -> Option<char> {1709         let c = self.peek()?;1710         self.pos += c.len_utf8();1711         Some(c)1712     }1713 1714     fn done(&self) -> bool {1715         self.pos == self.text.len()1716     }1717 1718     fn space(&mut self) {1719         while matches!(self.peek(), Some(' ' | '\t')) {1720             self.pos += 1;1721         }1722     }1723 1724     fn value(&mut self) -> Result<Value, DeployError> {1725         self.space();1726         match self.peek() {1727             Some('"') => self.string().map(Value::Str),1728             Some('t' | 'f') => self.boolean(),1729             Some('[') => self.array(),1730             Some('{') => self.table(),1731             Some(c) if c.is_ascii_digit() => self.integer().map(Value::Int),1732             Some(c) => Err(syntax(self.line, format!("unexpected {c:?}"))),1733             None => Err(syntax(self.line, "missing value")),1734         }1735     }1736 1737     fn string(&mut self) -> Result<String, DeployError> {1738         self.bump();1739         let mut out = String::new();1740         loop {1741             let c = self1742                 .bump()1743                 .ok_or_else(|| syntax(self.line, "unclosed string"))?;1744             match c {1745                 '"' => return Ok(out),1746                 '\\' => {1747                     let escape = self1748                         .bump()1749                         .ok_or_else(|| syntax(self.line, "unclosed string"))?;1750                     match escape {1751                         '"' => out.push('"'),1752                         '\\' => out.push('\\'),1753                         'n' => out.push('\n'),1754                         't' => out.push('\t'),1755                         other => {1756                             return Err(syntax(1757                                 self.line,1758                                 format!("escape \\{other} is not supported"),1759                             ));1760                         }1761                     }1762                 }1763                 other => out.push(other),1764             }1765         }1766     }1767 1768     fn boolean(&mut self) -> Result<Value, DeployError> {1769         let start = self.pos;1770         while matches!(self.peek(), Some(c) if c.is_ascii_alphabetic()) {1771             self.bump();1772         }1773         match &self.text[start..self.pos] {1774             "true" => Ok(Value::Bool(true)),1775             "false" => Ok(Value::Bool(false)),1776             word => Err(syntax(self.line, format!("{word:?} is not true or false"))),1777         }1778     }1779 1780     fn integer(&mut self) -> Result<u64, DeployError> {1781         let start = self.pos;1782         while matches!(self.peek(), Some(c) if c.is_ascii_digit()) {1783             self.bump();1784         }1785         let text = &self.text[start..self.pos];1786         text.parse::<u64>()1787             .map_err(|_| syntax(self.line, format!("integer {text} does not fit u64")))1788     }1789 1790     fn array(&mut self) -> Result<Value, DeployError> {1791         self.bump();1792         let mut items: Vec<Value> = Vec::new();1793         self.space();1794         if self.peek() == Some(']') {1795             self.bump();1796             return Ok(Value::Array(items));1797         }1798         loop {1799             let item = self.value()?;1800             if let Some(first) = items.first()1801                 && first.kind() != item.kind()1802             {1803                 return Err(syntax(self.line, "array values have different kinds"));1804             }1805             items.push(item);1806             self.space();1807             match self.bump() {1808                 Some(',') => self.space(),1809                 Some(']') => return Ok(Value::Array(items)),1810                 _ => return Err(syntax(self.line, "expected , or ] in an array")),1811             }1812         }1813     }1814 1815     fn table(&mut self) -> Result<Value, DeployError> {1816         self.bump();1817         let mut entries = Vec::new();1818         self.space();1819         if self.peek() == Some('}') {1820             self.bump();1821             return Ok(Value::Table(entries));1822         }1823         loop {1824             self.space();1825             let start = self.pos;1826             while matches!(self.peek(), Some(c) if c.is_ascii_lowercase() || c == '_') {1827                 self.bump();1828             }1829             let key = &self.text[start..self.pos];1830             if !is_bare_key(key) {1831                 return Err(syntax(self.line, "expected a bare key in an inline table"));1832             }1833             self.space();1834             if self.bump() != Some('=') {1835                 return Err(syntax(self.line, "expected = after an inline table key"));1836             }1837             let value = self.value()?;1838             entries.push((key.to_string(), value));1839             self.space();1840             match self.bump() {1841                 Some(',') => self.space(),1842                 Some('}') => return Ok(Value::Table(entries)),1843                 _ => return Err(syntax(self.line, "expected , or } in an inline table")),1844             }1845         }1846     }1847 }1848 1849 /// Refuses an image reference that a deploy cannot pin.1850 ///1851 /// A reference is pinned when it names a non-`latest` tag or a digest. Docker1852 /// resolves a bare name as `:latest`, so a bare name is not a pin even though1853 /// it has no `:latest` suffix in the file. The parser is shared by the deploy1854 /// checks and the command line so a spelling cannot be accepted in one place1855 /// and refused in another.1856 pub fn image_pinned(reference: &str) -> Result<(), String> {1857     let reference = reference.trim();1858     if reference.is_empty() {1859         return Err("is empty".to_string());1860     }1861     if let Some((_, digest)) = reference.rsplit_once('@') {1862         let Some(hex) = digest.strip_prefix("sha256:") else {1863             return Err("has a digest that is not sha256".to_string());1864         };1865         if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {1866             return Err("has a malformed sha256 digest".to_string());1867         }1868         return Ok(());1869     }1870     let name = reference1871         .rfind('/')1872         .map_or(reference, |slash| &reference[slash + 1..]);1873     let Some((_, tag)) = name.rsplit_once(':') else {1874         return Err("has no tag or digest".to_string());1875     };1876     if tag.is_empty() {1877         return Err("has an empty tag".to_string());1878     }1879     if tag == "latest" {1880         return Err("is latest; pin a tag or digest".to_string());1881     }1882     Ok(())1883 }