1 //! The operator commands and the line that names one.2 //!3 //! The commands share one client and one reply parser. `ps` reads `/stats`4 //! because a host is not its jobs; `queue` reads `/jobs` because a running job5 //! is what an operator waits on. `bench` uses the same client because a bench6 //! of a second client is not a bench of the operator's path.7 8 use std::collections::{BTreeMap, BTreeSet};9 use std::path::PathBuf;10 use std::process::ExitCode;11 use std::time::Duration;12 13 use inf3r_json::{Object, Value, parse, to_string};14 15 use crate::bench::{self, Bench};16 use crate::bundle;17 use crate::doctor;18 use crate::http::{CliError, Client, Reply};19 use crate::new::{self, Bind, CHAT, Shape};20 21 /// The socket that the web listens on when the operator names none.22 pub const DEFAULT_SOCKET: &str = "/run/inf3r/web.sock";23 24 /// The status that a healthy route answers.25 const OK: u16 = 200;26 27 /// The exit code of a failed check.28 const EXIT_CHECK: u8 = 1;29 30 /// The jobs route.31 const JOBS: &str = "/jobs";32 33 /// The stats route.34 const STATS: &str = "/stats";35 36 /// The capability table route.37 const CAPABILITIES: &str = "/capabilities";38 39 /// The reload route.40 const RELOAD: &str = "/reload";41 42 /// The cache metadata route.43 const CACHE: &str = "/cache";44 45 /// The cache compaction route.46 const CACHE_GC: &str = "/cache/gc";47 48 /// One hundred hundredths in one whole token per second.49 const HUNDREDTHS: f64 = 100.0;50 51 /// The word for a number that the server did not send.52 ///53 /// A missing number is not zero: zero is a measurement and a dash is the absence54 /// of one. The two must not read alike.55 const MISSING: &str = "-";56 57 /// The models route.58 const MODELS: &str = "/models";59 60 /// The liveness route.61 const HEALTH: &str = "/healthz";62 63 /// The largest number of counted runs that the bench accepts. A longer run64 /// takes minutes and does not make the distribution more useful.65 const MAX_RUNS: u32 = 1_000;66 67 /// The warm-up runs that the command uses. The command has no warm-up option;68 /// a caller that wants one calls `bench::run` with its own count.69 const WARMUP_RUNS: u32 = 0;70 71 /// The text of `--help`. It lists the commands because a command that the72 /// operator cannot discover is not a command.73 const HELP: &str = "\74 usage: inf3r [--socket <path> | --tcp <host:port>] [--token <hex> | --token-file <path>] [--json] <command>75 76 commands:77 ps list the bundles, processes, devices, models, and residency78 healthz check the local /healthz route79 queue list the running jobs80 stats print the counters81 models list the served models82 doctor check the host, deploy file, bundles, token, blob store, and routes83 reload reload one bundle or every bundle84 cache list, pin, unpin, evict, or compact the host KV cache85 bench time one capability route86 new make a bundle directory87 verify run the binding gate against a bundle88 bundle verify or seal a bundle directory89 90 verify options:91 --budget <time> the whole run (default 5m)92 --load-budget <time> the handshake and load (default 2m)93 --job-budget <time> one job (default 1m)94 --suite <file> the step list (default goldens/conformance.json)95 --container run the bind's image as a sibling Docker container96 --image <ref> the image to start instead of the bind's image97 --socket-dir <dir> the private socket root in the gate process98 --socket-host-dir <dir> the host path the Docker daemon mounts for the engine";99 100 /// The arguments of `inf3r bench`.101 #[derive(Clone, PartialEq, Eq, Debug)]102 pub struct BenchArgs {103 /// The capability whose route is timed.104 pub capability: String,105 /// The counted runs.106 pub runs: u32,107 /// The request body as JSON.108 pub body: String,109 }110 111 /// The arguments of `inf3r reload`.112 #[derive(Clone, PartialEq, Eq, Debug)]113 pub struct ReloadArgs {114 /// The bundle to reload, or `None` for every bundle.115 pub bundle: Option<String>,116 }117 118 /// What `inf3r cache` does.119 #[derive(Clone, PartialEq, Eq, Debug)]120 pub enum CacheAction {121 Ls,122 Stats,123 Pin,124 Unpin,125 Evict,126 Gc,127 }128 129 /// The arguments of `inf3r cache`.130 #[derive(Clone, PartialEq, Eq, Debug)]131 pub struct CacheArgs {132 pub action: CacheAction,133 /// An id, a model name, or `all`, depending on the action.134 pub target: Option<String>,135 }136 137 /// The arguments of `inf3r doctor`.138 #[derive(Clone, PartialEq, Eq, Debug)]139 pub struct DoctorArgs {140 /// The deploy file whose bundle directories hold the bundles.141 pub deploy: PathBuf,142 }143 144 /// The arguments of `inf3r verify`.145 #[derive(Clone, PartialEq, Eq, Debug)]146 pub struct VerifyArgs {147 /// The plugin id that the deploy file's `bin_dir` resolves.148 pub plugin: Option<String>,149 /// A program that is not installed under `bin_dir`, used instead.150 pub program: Option<PathBuf>,151 /// The words after the program.152 pub program_args: Vec<String>,153 /// The weight file that the grant carries.154 pub weights: Option<PathBuf>,155 /// The whole run, when the operator overrides the default.156 pub budget: Option<Duration>,157 /// The load and handshake deadline, when overridden.158 pub load_budget: Option<Duration>,159 /// One job check deadline, when overridden.160 pub job_budget: Option<Duration>,161 /// The suite file, when it is not the default.162 pub suite: Option<PathBuf>,163 /// The deploy file that names `bin_dir`.164 pub deploy: PathBuf,165 /// Start the bind as a sibling Docker container instead of a process.166 pub container: bool,167 /// The image to start instead of the bind's image.168 pub image: Option<String>,169 /// The private socket root in the gate process.170 pub socket_dir: Option<PathBuf>,171 /// The same root as the Docker daemon sees it.172 pub socket_host_dir: Option<PathBuf>,173 }174 175 /// The arguments of `inf3r new`.176 #[derive(Clone, PartialEq, Eq, Debug)]177 pub struct NewArgs {178 /// The served model name.179 pub model: String,180 /// The hardware target.181 pub target: String,182 /// The capability that the plugin declares.183 pub capability: String,184 /// The skeleton that the command writes.185 pub shape: Shape,186 }187 188 /// The action that `inf3r bundle` takes on one directory.189 #[derive(Clone, Copy, PartialEq, Eq, Debug)]190 pub enum BundleVerb {191 /// Check the anatomy and the digest.192 Verify,193 /// Write the digest that the files have now.194 Seal,195 }196 197 /// The arguments of `inf3r bundle`.198 #[derive(Clone, PartialEq, Eq, Debug)]199 pub struct BundleArgs {200 /// The action to take.201 pub verb: BundleVerb,202 /// The bundle directory.203 pub dir: PathBuf,204 }205 206 /// One operator command.207 #[derive(Clone, PartialEq, Eq, Debug)]208 pub enum Command {209 /// Print the binary version.210 Version,211 /// Check the local health route.212 Healthz,213 /// List every job.214 Ps,215 /// List the running jobs, their count, and the oldest elapsed time.216 Queue,217 /// Print the counters as `key=value` lines.218 Stats,219 /// List the served models and their capabilities.220 Models,221 /// Check the host, the deploy file, the bundles, the token, the store, and222 /// the read-only routes.223 Doctor(DoctorArgs),224 /// Reload one bundle or all bundles.225 Reload(ReloadArgs),226 /// Operate on the host KV cache.227 Cache(CacheArgs),228 /// Print the command list.229 Help,230 /// Time one capability route.231 Bench(BenchArgs),232 /// Make a bundle directory.233 New(NewArgs),234 /// Run the binding gate against a plugin.235 Verify(VerifyArgs),236 /// Verify or seal one bundle directory.237 Bundle(BundleArgs),238 }239 240 /// The name before the command's own words are read.241 #[derive(Clone, Copy, PartialEq, Eq, Debug)]242 enum Name {243 Version,244 Healthz,245 Ps,246 Queue,247 Stats,248 Models,249 Doctor,250 Reload,251 Cache,252 Help,253 Bench,254 New,255 Verify,256 Bundle,257 }258 259 impl Name {260 fn from_name(name: &str) -> Option<Name> {261 match name {262 "ps" => Some(Name::Ps),263 "queue" => Some(Name::Queue),264 "stats" => Some(Name::Stats),265 "models" => Some(Name::Models),266 "doctor" => Some(Name::Doctor),267 "reload" => Some(Name::Reload),268 "cache" => Some(Name::Cache),269 "--version" | "-V" => Some(Name::Version),270 "healthz" => Some(Name::Healthz),271 "--help" | "-h" => Some(Name::Help),272 "bench" => Some(Name::Bench),273 "new" => Some(Name::New),274 "verify" => Some(Name::Verify),275 "bundle" => Some(Name::Bundle),276 _ => None,277 }278 }279 280 fn plain(self) -> Command {281 match self {282 Name::Version => Command::Version,283 Name::Healthz => Command::Healthz,284 Name::Ps => Command::Ps,285 Name::Queue => Command::Queue,286 Name::Stats => Command::Stats,287 Name::Models => Command::Models,288 Name::Doctor => Command::Doctor(DoctorArgs {289 deploy: PathBuf::from("deploy.toml"),290 }),291 Name::Reload => Command::Reload(ReloadArgs { bundle: None }),292 Name::Cache => Command::Cache(CacheArgs {293 action: CacheAction::Ls,294 target: None,295 }),296 Name::Help => Command::Help,297 Name::Bench | Name::New | Name::Verify | Name::Bundle => Command::Help,298 }299 }300 }301 302 /// A parsed command line.303 #[derive(Clone, PartialEq, Eq, Debug)]304 pub struct Args {305 /// The web's Unix socket. It is the default endpoint.306 pub socket: PathBuf,307 /// The web's TCP address, when the operator named one instead.308 pub tcp: Option<String>,309 /// The bearer token for a TCP listener.310 pub token: Option<String>,311 /// The file that holds the bearer token.312 pub token_file: Option<PathBuf>,313 /// Print one JSON object instead of a table.314 pub json: bool,315 /// The command to run.316 pub command: Command,317 }318 319 /// Reads the command line.320 ///321 /// Parsing lives here so that the tests and the binary see one grammar. An322 /// option may appear before or after the command, as an operator expects.323 pub fn parse_args(args: impl IntoIterator<Item = String>) -> Result<Args, CliError> {324 let mut socket = PathBuf::from(DEFAULT_SOCKET);325 let mut socket_given = false;326 let mut tcp: Option<String> = None;327 let mut token: Option<String> = None;328 let mut token_file: Option<PathBuf> = None;329 let mut json = false;330 let mut name = None;331 let mut words = Vec::new();332 let mut runs = None;333 let mut body = None;334 let mut program: Option<PathBuf> = None;335 let mut weights: Option<PathBuf> = None;336 let mut budget: Option<Duration> = None;337 let mut load_budget: Option<Duration> = None;338 let mut job_budget: Option<Duration> = None;339 let mut suite: Option<PathBuf> = None;340 let mut container = false;341 let mut image: Option<String> = None;342 let mut socket_dir: Option<PathBuf> = None;343 let mut socket_host_dir: Option<PathBuf> = None;344 let mut deploy = PathBuf::from("deploy.toml");345 let mut deploy_given = false;346 let mut bind: Option<Bind> = None;347 let mut engine = false;348 let mut args = args.into_iter();349 while let Some(arg) = args.next() {350 match arg.as_str() {351 "--socket" => {352 let path = args353 .next()354 .ok_or_else(|| CliError::Usage("--socket needs a path".to_string()))?;355 if socket_given {356 return Err(CliError::Usage("--socket is given twice".to_string()));357 }358 socket = PathBuf::from(path);359 socket_given = true;360 }361 "--tcp" | "--url" => {362 let address = args363 .next()364 .ok_or_else(|| CliError::Usage("--tcp needs a host and port".to_string()))?;365 if address.starts_with("https://") {366 return Err(CliError::Usage(367 "https needs a TLS stack; use http:// or --tcp".to_string(),368 ));369 }370 let address = address371 .strip_prefix("http://")372 .unwrap_or(&address)373 .to_string();374 if tcp.replace(address).is_some() {375 return Err(CliError::Usage("--tcp is given twice".to_string()));376 }377 }378 "--token" => {379 let value = args380 .next()381 .ok_or_else(|| CliError::Usage("--token needs a hex token".to_string()))?;382 if token.replace(value).is_some() {383 return Err(CliError::Usage("--token is given twice".to_string()));384 }385 }386 "--token-file" => {387 let path = args388 .next()389 .ok_or_else(|| CliError::Usage("--token-file needs a path".to_string()))?;390 if token_file.replace(PathBuf::from(path)).is_some() {391 return Err(CliError::Usage("--token-file is given twice".to_string()));392 }393 }394 "--json" => json = true,395 "--runs" => {396 let count = args397 .next()398 .ok_or_else(|| CliError::Usage("--runs needs a count".to_string()))?;399 let count = count400 .parse::<u32>()401 .map_err(|_| CliError::Usage(format!("--runs is not a count: {count}")))?;402 if runs.replace(count).is_some() {403 return Err(CliError::Usage("--runs is given twice".to_string()));404 }405 }406 "--program" => {407 let path = args408 .next()409 .ok_or_else(|| CliError::Usage("--program needs a path".to_string()))?;410 if program.replace(PathBuf::from(path)).is_some() {411 return Err(CliError::Usage("--program is given twice".to_string()));412 }413 }414 "--deploy" => {415 let path = args416 .next()417 .ok_or_else(|| CliError::Usage("--deploy needs a path".to_string()))?;418 deploy = PathBuf::from(path);419 deploy_given = true;420 }421 "--weights" => {422 let path = args423 .next()424 .ok_or_else(|| CliError::Usage("--weights needs a path".to_string()))?;425 if weights.replace(PathBuf::from(path)).is_some() {426 return Err(CliError::Usage("--weights is given twice".to_string()));427 }428 }429 "--budget" => {430 let word = args431 .next()432 .ok_or_else(|| CliError::Usage("--budget needs a duration".to_string()))?;433 if budget.replace(parse_duration(&word)?).is_some() {434 return Err(CliError::Usage("--budget is given twice".to_string()));435 }436 }437 "--load-budget" => {438 let word = args439 .next()440 .ok_or_else(|| CliError::Usage("--load-budget needs a duration".to_string()))?;441 if load_budget.replace(parse_duration(&word)?).is_some() {442 return Err(CliError::Usage("--load-budget is given twice".to_string()));443 }444 }445 "--job-budget" => {446 let word = args447 .next()448 .ok_or_else(|| CliError::Usage("--job-budget needs a duration".to_string()))?;449 if job_budget.replace(parse_duration(&word)?).is_some() {450 return Err(CliError::Usage("--job-budget is given twice".to_string()));451 }452 }453 "--suite" => {454 let path = args455 .next()456 .ok_or_else(|| CliError::Usage("--suite needs a path".to_string()))?;457 if suite.replace(PathBuf::from(path)).is_some() {458 return Err(CliError::Usage("--suite is given twice".to_string()));459 }460 }461 "--container" => {462 if container {463 return Err(CliError::Usage("--container is given twice".to_string()));464 }465 container = true;466 }467 "--image" => {468 let ref_ = args469 .next()470 .ok_or_else(|| CliError::Usage("--image needs a reference".to_string()))?;471 if let Err(why) = inf3r_deploy::image_pinned(&ref_) {472 return Err(CliError::Usage(format!("--image {why}")));473 }474 if image.replace(ref_).is_some() {475 return Err(CliError::Usage("--image is given twice".to_string()));476 }477 }478 "--socket-dir" => {479 let path = args480 .next()481 .ok_or_else(|| CliError::Usage("--socket-dir needs a path".to_string()))?;482 if socket_dir.replace(PathBuf::from(path)).is_some() {483 return Err(CliError::Usage("--socket-dir is given twice".to_string()));484 }485 }486 "--socket-host-dir" => {487 let path = args488 .next()489 .ok_or_else(|| CliError::Usage("--socket-host-dir needs a path".to_string()))?;490 if socket_host_dir.replace(PathBuf::from(path)).is_some() {491 return Err(CliError::Usage(492 "--socket-host-dir is given twice".to_string(),493 ));494 }495 }496 "--body" => {497 let json = args498 .next()499 .ok_or_else(|| CliError::Usage("--body needs JSON".to_string()))?;500 if body.replace(json).is_some() {501 return Err(CliError::Usage("--body is given twice".to_string()));502 }503 }504 "--bind" => {505 let word = args.next().ok_or_else(|| {506 CliError::Usage("--bind needs binary, http, or library".to_string())507 })?;508 let found = Bind::from_name(&word).ok_or_else(|| {509 CliError::Usage(format!("--bind is not binary, http, or library: {word}"))510 })?;511 if bind.replace(found).is_some() {512 return Err(CliError::Usage("--bind is given twice".to_string()));513 }514 }515 "--engine" => {516 if engine {517 return Err(CliError::Usage("--engine is given twice".to_string()));518 }519 engine = true;520 }521 "--" => {522 words.extend(args);523 break;524 }525 other if other.starts_with('-') => {526 let found = Name::from_name(other)527 .ok_or_else(|| CliError::Usage(format!("unknown option {other}")))?;528 if name.replace(found).is_some() {529 return Err(CliError::Usage(format!("unexpected argument {other}")));530 }531 }532 other => {533 if name.is_none() {534 let found = Name::from_name(other)535 .ok_or_else(|| CliError::Usage(format!("unknown command {other}")))?;536 name = Some(found);537 } else {538 words.push(other.to_string());539 }540 }541 }542 }543 if socket_given && tcp.is_some() {544 return Err(CliError::Usage(545 "--socket and --tcp are mutually exclusive".to_string(),546 ));547 }548 if token.is_some() && token_file.is_some() {549 return Err(CliError::Usage(550 "--token and --token-file are mutually exclusive".to_string(),551 ));552 }553 let name = name.ok_or_else(|| CliError::Usage(HELP.to_string()))?;554 if name != Name::Verify555 && (budget.is_some()556 || load_budget.is_some()557 || job_budget.is_some()558 || suite.is_some()559 || container560 || image.is_some()561 || socket_dir.is_some()562 || socket_host_dir.is_some())563 {564 return Err(CliError::Usage(565 "--budget, --load-budget, --job-budget, --suite, --container, --image, --socket-dir, and --socket-host-dir belong to verify".to_string(),566 ));567 }568 let command = match name {569 Name::Doctor => {570 if bind.is_some() || engine {571 return Err(CliError::Usage(572 "--bind and --engine belong to new".to_string(),573 ));574 }575 if runs.is_some()576 || body.is_some()577 || program.is_some()578 || weights.is_some()579 || budget.is_some()580 || load_budget.is_some()581 || job_budget.is_some()582 || suite.is_some()583 {584 return Err(CliError::Usage("options belong to bench".to_string()));585 }586 if let Some(extra) = words.first() {587 return Err(CliError::Usage(format!("unexpected argument {extra}")));588 }589 Command::Doctor(DoctorArgs { deploy })590 }591 Name::Reload => {592 if bind.is_some() || engine {593 return Err(CliError::Usage(594 "--bind and --engine belong to new".to_string(),595 ));596 }597 if runs.is_some()598 || body.is_some()599 || program.is_some()600 || weights.is_some()601 || budget.is_some()602 || load_budget.is_some()603 || job_budget.is_some()604 || suite.is_some()605 || deploy_given606 {607 return Err(CliError::Usage(608 "reload takes at most one bundle".to_string(),609 ));610 }611 let bundle = match words.len() {612 0 => None,613 1 => Some(words[0].clone()),614 _ => {615 return Err(CliError::Usage(616 "reload takes at most one bundle".to_string(),617 ));618 }619 };620 Command::Reload(ReloadArgs { bundle })621 }622 Name::Cache => {623 if bind.is_some() || engine {624 return Err(CliError::Usage(625 "--bind and --engine belong to new".to_string(),626 ));627 }628 if runs.is_some()629 || body.is_some()630 || program.is_some()631 || weights.is_some()632 || budget.is_some()633 || load_budget.is_some()634 || job_budget.is_some()635 || suite.is_some()636 || deploy_given637 {638 return Err(CliError::Usage(639 "cache takes ls, stats, pin, unpin, evict, or gc".to_string(),640 ));641 }642 let action = match words.first().map(String::as_str) {643 Some("ls") => CacheAction::Ls,644 Some("stats") => CacheAction::Stats,645 Some("pin") => CacheAction::Pin,646 Some("unpin") => CacheAction::Unpin,647 Some("evict") => CacheAction::Evict,648 Some("gc") => CacheAction::Gc,649 Some(other) => {650 return Err(CliError::Usage(format!(651 "cache takes ls, stats, pin, unpin, evict, or gc, not {other}"652 )));653 }654 None => CacheAction::Ls,655 };656 let target = match action {657 CacheAction::Pin | CacheAction::Unpin => {658 if words.len() < 2 {659 return Err(CliError::Usage(660 "cache pin and unpin need a cache id".to_string(),661 ));662 }663 Some(words[1].clone())664 }665 CacheAction::Evict => {666 if words.len() > 3 || (words.len() == 3 && words[1] != "model") {667 return Err(CliError::Usage(668 "cache evict takes all, model <name>, or an id".to_string(),669 ));670 }671 if words.len() == 3 {672 Some(format!("model:{}", words[2]))673 } else {674 words.get(1).cloned()675 }676 }677 _ => None,678 };679 Command::Cache(CacheArgs { action, target })680 }681 Name::Bench => {682 if bind.is_some() || engine {683 return Err(CliError::Usage(684 "--bind and --engine belong to new".to_string(),685 ));686 }687 let capability = one_word(&words, "bench needs a capability")?;688 let runs = runs.ok_or_else(|| CliError::Usage("bench needs --runs".to_string()))?;689 if runs == 0 || runs > MAX_RUNS {690 return Err(CliError::Usage(format!(691 "--runs must be between 1 and {MAX_RUNS}"692 )));693 }694 let body = body.ok_or_else(|| CliError::Usage("bench needs --body".to_string()))?;695 Command::Bench(BenchArgs {696 capability,697 runs,698 body,699 })700 }701 Name::New => {702 if runs.is_some() || body.is_some() {703 return Err(CliError::Usage(704 "new takes a model, a target, and a capability".to_string(),705 ));706 }707 let shape = match (bind, engine) {708 (Some(_), true) => {709 return Err(CliError::Usage(710 "--bind and --engine are mutually exclusive".to_string(),711 ));712 }713 (Some(Bind::Library), false) => Shape::Library,714 (Some(bind), false) => Shape::Bind(bind),715 (None, true) => Shape::Engine,716 (None, false) => Shape::Default,717 };718 let mut words = words.into_iter();719 let model = words720 .next()721 .ok_or_else(|| CliError::Usage("new needs a model".to_string()))?;722 let target = words723 .next()724 .ok_or_else(|| CliError::Usage("new needs a target".to_string()))?;725 let capability = words726 .next()727 .ok_or_else(|| CliError::Usage("new needs a capability".to_string()))?;728 if let Some(extra) = words.next() {729 return Err(CliError::Usage(format!("unexpected argument {extra}")));730 }731 if matches!(shape, Shape::Bind(_)) && capability != CHAT {732 return Err(CliError::Usage("--bind serves chat only".to_string()));733 }734 Command::New(NewArgs {735 model,736 target,737 capability,738 shape,739 })740 }741 Name::Bundle => {742 if bind.is_some() || engine {743 return Err(CliError::Usage(744 "--bind and --engine belong to new".to_string(),745 ));746 }747 if runs.is_some()748 || body.is_some()749 || program.is_some()750 || weights.is_some()751 || budget.is_some()752 || load_budget.is_some()753 || job_budget.is_some()754 || suite.is_some()755 {756 return Err(CliError::Usage(757 "bundle takes verify or seal and one directory".to_string(),758 ));759 }760 let mut words = words.into_iter();761 let action = words762 .next()763 .ok_or_else(|| CliError::Usage("bundle needs verify or seal".to_string()))?;764 let verb = match action.as_str() {765 "verify" => BundleVerb::Verify,766 "seal" => BundleVerb::Seal,767 other => {768 return Err(CliError::Usage(format!(769 "bundle takes verify or seal, not {other}"770 )));771 }772 };773 let dir = words774 .next()775 .ok_or_else(|| CliError::Usage("bundle needs a directory".to_string()))?;776 if let Some(extra) = words.next() {777 return Err(CliError::Usage(format!("unexpected argument {extra}")));778 }779 Command::Bundle(BundleArgs {780 verb,781 dir: PathBuf::from(dir),782 })783 }784 Name::Verify => {785 if bind.is_some() || engine {786 return Err(CliError::Usage(787 "--bind and --engine belong to new".to_string(),788 ));789 }790 if runs.is_some() || body.is_some() {791 return Err(CliError::Usage(792 "verify takes a plugin id, --program, and --deploy".to_string(),793 ));794 }795 let (plugin, program_args) = match &program {796 Some(_) => (None, words),797 None => (798 Some(one_word(&words, "verify needs a plugin id")?),799 Vec::new(),800 ),801 };802 if container && program.is_some() {803 return Err(CliError::Usage(804 "--container takes a plugin id and --deploy, not --program".to_string(),805 ));806 }807 if image.is_some() && !container {808 return Err(CliError::Usage(809 "--image belongs to --container".to_string(),810 ));811 }812 Command::Verify(VerifyArgs {813 plugin,814 program,815 program_args,816 weights,817 budget,818 load_budget,819 job_budget,820 suite,821 deploy,822 container,823 image,824 socket_dir,825 socket_host_dir,826 })827 }828 other => {829 if bind.is_some() || engine {830 return Err(CliError::Usage(831 "--bind and --engine belong to new".to_string(),832 ));833 }834 if runs.is_some()835 || body.is_some()836 || program.is_some()837 || weights.is_some()838 || budget.is_some()839 || load_budget.is_some()840 || job_budget.is_some()841 || suite.is_some()842 {843 return Err(CliError::Usage("options belong to bench".to_string()));844 }845 if let Some(extra) = words.first() {846 return Err(CliError::Usage(format!("unexpected argument {extra}")));847 }848 other.plain()849 }850 };851 Ok(Args {852 socket,853 tcp,854 token,855 token_file,856 json,857 command,858 })859 }860 861 fn one_word(words: &[String], missing: &str) -> Result<String, CliError> {862 let first = words863 .first()864 .cloned()865 .ok_or_else(|| CliError::Usage(missing.to_string()))?;866 if let Some(extra) = words.get(1) {867 return Err(CliError::Usage(format!("unexpected argument {extra}")));868 }869 Ok(first)870 }871 872 /// Runs one command and gives the exit code for success or a failed check.873 ///874 /// A transport fault and a usage fault leave as errors because their exit875 /// codes are not a command's result.876 pub fn run(args: &Args) -> Result<ExitCode, CliError> {877 let print_json = args.json;878 match &args.command {879 Command::Version => {880 println!("{}", env!("CARGO_PKG_VERSION"));881 return Ok(ExitCode::SUCCESS);882 }883 Command::Healthz => {884 let client = client(args)?;885 let reply = client.get(HEALTH)?;886 return Ok(if reply.status == OK {887 ExitCode::SUCCESS888 } else {889 ExitCode::from(EXIT_CHECK)890 });891 }892 Command::Help => {893 if print_json {894 println!(895 "{}",896 to_string(&Object::new().put("usage", Value::str(HELP)).build())897 );898 } else {899 println!("{HELP}");900 }901 return Ok(ExitCode::SUCCESS);902 }903 Command::New(new) => {904 let root = std::env::current_dir().map_err(|why| CliError::Io(why.to_string()))?;905 let dir = new::make_shape(&root, &new.model, &new.target, &new.capability, new.shape)?;906 if print_json {907 println!(908 "{}",909 to_string(910 &Object::new()911 .put("bundle", Value::str(dir.display().to_string()))912 .build()913 )914 );915 }916 return Ok(ExitCode::SUCCESS);917 }918 Command::Verify(args) => return verify(args, print_json),919 Command::Bundle(args) => return bundle_command(args, print_json),920 _ => {}921 }922 let client = client(args)?;923 match &args.command {924 Command::Ps => {925 ps(&client, print_json)?;926 Ok(ExitCode::SUCCESS)927 }928 Command::Queue => {929 queue(&client, print_json)?;930 Ok(ExitCode::SUCCESS)931 }932 Command::Stats => {933 stats(&client, print_json)?;934 Ok(ExitCode::SUCCESS)935 }936 Command::Models => {937 models(&client, print_json)?;938 Ok(ExitCode::SUCCESS)939 }940 Command::Doctor(args) => doctor(&client, args, print_json),941 Command::Reload(args) => reload(&client, args, print_json),942 Command::Cache(args) => cache(&client, args, print_json),943 Command::Bench(args) => bench_route(&client, args, print_json),944 Command::Version945 | Command::Healthz946 | Command::Help947 | Command::New(_)948 | Command::Verify(_)949 | Command::Bundle(_) => Ok(ExitCode::SUCCESS),950 }951 }952 953 /// The client that the command uses.954 ///955 /// A token file is read only when a command needs the network, so `--help` and956 /// `bundle verify` still work on a host whose token has not been installed.957 fn client(args: &Args) -> Result<Client, CliError> {958 let token = match (&args.token, &args.token_file) {959 (Some(token), None) => Some(token.clone()),960 (None, Some(path)) => {961 let text = std::fs::read_to_string(path)962 .map_err(|why| CliError::Io(format!("{}: {why}", path.display())))?;963 let token = text.strip_suffix('\n').unwrap_or(&text);964 let token = token.strip_suffix('\r').unwrap_or(token);965 Some(token.to_string())966 }967 (None, None) => None,968 (Some(_), Some(_)) => {969 return Err(CliError::Usage(970 "--token and --token-file are mutually exclusive".to_string(),971 ));972 }973 };974 let client = match &args.tcp {975 Some(address) => Client::tcp(address.clone()),976 None => Client::new(args.socket.clone()),977 };978 Ok(client.with_token(token))979 }980 981 /// Reloads one bundle or every bundle and reports what happened.982 fn reload(client: &Client, args: &ReloadArgs, print_json: bool) -> Result<ExitCode, CliError> {983 let body = match &args.bundle {984 Some(bundle) => Object::new()985 .put("bundle", Value::str(bundle.clone()))986 .build(),987 None => Object::new().build(),988 };989 let body = to_string(&body);990 let reply = client.post(RELOAD, &body)?;991 if reply.status != OK {992 return Err(CliError::Status {993 path: RELOAD.to_string(),994 status: reply.status,995 });996 }997 let root = parse(&reply.body).map_err(|why| CliError::Json(why.to_string()))?;998 let reloaded = list(&root, "reloaded")?;999 let failed = list(&root, "failed")?;1000 if print_json {1001 emit_json(&root);1002 } else {1003 for plugin in reloaded {1004 println!("reloaded {}", reload_name(plugin)?);1005 }1006 for failure in failed {1007 println!("failed {}", reload_failure(failure)?);1008 }1009 }1010 if failed.is_empty() {1011 Ok(ExitCode::SUCCESS)1012 } else {1013 Ok(ExitCode::from(EXIT_CHECK))1014 }1015 }1016 1017 /// The name of one reloaded bundle. A server may answer a name or an object.1018 fn reload_name(value: &Value) -> Result<String, CliError> {1019 if let Some(name) = value.as_str() {1020 return Ok(name.to_string());1021 }1022 Ok(text(value, "bundle")?.to_string())1023 }1024 1025 /// The line for one failed reload. A string is the failure itself; an object1026 /// carries the bundle and the reason.1027 fn reload_failure(value: &Value) -> Result<String, CliError> {1028 if let Some(why) = value.as_str() {1029 return Ok(why.to_string());1030 }1031 Ok(format!(1032 "{}: {}",1033 text(value, "bundle")?,1034 text(value, "error")?1035 ))1036 }1037 1038 /// Runs one of the two bundle verbs on one directory.1039 ///1040 /// The directory is checked first, because a path that is not there is a1041 /// command line mistake and not a bundle problem.1042 fn bundle_command(args: &BundleArgs, print_json: bool) -> Result<ExitCode, CliError> {1043 if !args.dir.is_dir() {1044 return Err(CliError::Usage(format!(1045 "{} is not a directory",1046 args.dir.display()1047 )));1048 }1049 match args.verb {1050 BundleVerb::Verify => {1051 let bundle = match inf3r_bundle::Bundle::read(&args.dir) {1052 Ok(bundle) => bundle,1053 Err(why) => {1054 if print_json {1055 emit_json(1056 &Object::new()1057 .put("ok", Value::Bool(false))1058 .put("bundle", Value::str(args.dir.display().to_string()))1059 .put("problem", Value::str(why.to_string()))1060 .build(),1061 );1062 } else {1063 println!("{why}");1064 }1065 return Ok(ExitCode::from(EXIT_CHECK));1066 }1067 };1068 let problems = bundle.anatomy(&args.dir);1069 if !problems.is_empty() {1070 if print_json {1071 emit_json(1072 &Object::new()1073 .put("ok", Value::Bool(false))1074 .put("bundle", Value::str(bundle.id.clone()))1075 .put(1076 "problems",1077 Value::Array(1078 problems1079 .iter()1080 .map(|problem| Value::str(problem.to_string()))1081 .collect(),1082 ),1083 )1084 .build(),1085 );1086 } else {1087 for problem in problems {1088 println!("bundle {}: {problem}", bundle.id);1089 }1090 }1091 return Ok(ExitCode::from(EXIT_CHECK));1092 }1093 match inf3r_bundle::Bundle::verify(&args.dir) {1094 Ok(()) => {1095 if print_json {1096 emit_json(1097 &Object::new()1098 .put("ok", Value::Bool(true))1099 .put("bundle", Value::str(bundle.id.clone()))1100 .build(),1101 );1102 } else {1103 println!("bundle {}: ok", bundle.id);1104 }1105 Ok(ExitCode::SUCCESS)1106 }1107 Err(why) => {1108 if print_json {1109 emit_json(1110 &Object::new()1111 .put("ok", Value::Bool(false))1112 .put("bundle", Value::str(bundle.id.clone()))1113 .put("problem", Value::str(why.to_string()))1114 .build(),1115 );1116 } else {1117 println!("{why}");1118 }1119 Ok(ExitCode::from(EXIT_CHECK))1120 }1121 }1122 }1123 BundleVerb::Seal => {1124 let digest = inf3r_bundle::Bundle::seal(&args.dir)1125 .map_err(|why| CliError::Io(why.to_string()))?;1126 if print_json {1127 emit_json(1128 &Object::new()1129 .put("ok", Value::Bool(true))1130 .put("bundle", Value::str(args.dir.display().to_string()))1131 .put("digest", Value::str(digest.clone()))1132 .build(),1133 );1134 } else {1135 println!("{digest}");1136 }1137 Ok(ExitCode::SUCCESS)1138 }1139 }1140 }1141 1142 /// Reads a duration as a positive integer and a unit.1143 ///1144 /// `ms`, `s`, `m`, and `h` are the units an operator types. A bare number is1145 /// seconds, because a budget is a number that a script already has.1146 fn parse_duration(word: &str) -> Result<Duration, CliError> {1147 let (number, scale) = if let Some(number) = word.strip_suffix("ms") {1148 (number, 1u64)1149 } else if let Some(number) = word.strip_suffix('s') {1150 (number, 1_000)1151 } else if let Some(number) = word.strip_suffix('m') {1152 (number, 60_000)1153 } else if let Some(number) = word.strip_suffix('h') {1154 (number, 3_600_000)1155 } else {1156 (word, 1_000)1157 };1158 let count = number1159 .parse::<u64>()1160 .map_err(|_| CliError::Usage(format!("not a duration: {word}")))?;1161 if count == 0 {1162 return Err(CliError::Usage(format!(1163 "a duration must be positive: {word}"1164 )));1165 }1166 let millis = count1167 .checked_mul(scale)1168 .ok_or_else(|| CliError::Usage(format!("duration is too large: {word}")))?;1169 Ok(Duration::from_millis(millis))1170 }1171 1172 /// The word for one verification verdict.1173 fn state_name(state: inf3r_verify::State) -> &'static str {1174 match state {1175 inf3r_verify::State::Pass => "pass",1176 inf3r_verify::State::Fail => "fail",1177 inf3r_verify::State::Skip => "skip",1178 }1179 }1180 1181 /// The image lock that this process can read.1182 ///1183 /// The command line is usually run from the repository; `CARGO_TARGET_DIR`1184 /// names the build directory when CI uses one. An explicit1185 /// `INF3R_IMAGES_LOCK` is authoritative even when missing.1186 fn images_lock() -> Option<PathBuf> {1187 if let Some(path) = std::env::var_os("INF3R_IMAGES_LOCK") {1188 return Some(PathBuf::from(path));1189 }1190 let target = std::env::var_os("CARGO_TARGET_DIR")1191 .map(PathBuf::from)1192 .unwrap_or_else(|| PathBuf::from("target"));1193 let path = target.join("images.lock");1194 path.is_file().then_some(path)1195 }1196 1197 /// Runs the binding gate and prints one line per check.1198 ///1199 /// The gate starts the plugin itself, so an operator can verify a binding1200 /// before a deploy file names it. `--program` covers a binary that is not1201 /// installed under `bin_dir` yet, which is the normal state of a binding under1202 /// review.1203 fn verify(args: &VerifyArgs, print_json: bool) -> Result<ExitCode, CliError> {1204 let needs_deploy = args.container || args.plugin.is_some();1205 let deploy = if needs_deploy {1206 Some(1207 inf3r_deploy::Deploy::read(&args.deploy)1208 .map_err(|why| CliError::Usage(why.to_string()))?,1209 )1210 } else {1211 None1212 };1213 if let Some(deploy) = &deploy {1214 let conflicts = deploy.node.conflicts();1215 if !conflicts.is_empty() {1216 let detail = conflicts1217 .iter()1218 .map(|conflict| conflict.to_string())1219 .collect::<Vec<_>>()1220 .join("; ");1221 return Err(CliError::Usage(format!(1222 "{} deploy conflict(s): {detail}",1223 conflicts.len()1224 )));1225 }1226 }1227 let mut gate_root: Option<PathBuf> = None;1228 let mut gate = if args.container {1229 let plugin = args1230 .plugin1231 .as_deref()1232 .ok_or_else(|| CliError::Usage("container verify needs a plugin id".to_string()))?;1233 let deploy = deploy.as_ref().expect("container verify reads the deploy");1234 let bind = deploy1235 .node1236 .binds1237 .iter()1238 .find(|bind| bind.bundle == plugin && bind.runtime == inf3r_deploy::Runtime::Container)1239 .ok_or_else(|| {1240 CliError::Usage(format!(1241 "{} has no container bind in {}",1242 plugin,1243 args.deploy.display()1244 ))1245 })?;1246 let image = args1247 .image1248 .clone()1249 .or_else(|| bind.image.clone())1250 .ok_or_else(|| CliError::Usage(format!("container bind {plugin} has no image")))?;1251 let lock = images_lock();1252 inf3r_container::verify_image(&image, plugin, lock.as_deref())1253 .map_err(|why| CliError::Io(why.to_string()))?;1254 let mut spec = inf3r_container::ContainerSpec::new(image, plugin.to_string());1255 spec.env.push((1256 inf3r_container::BUNDLE_DIR_ENV.to_string(),1257 inf3r_container::bundle_dir(plugin),1258 ));1259 spec.command = bind.command.clone();1260 spec.network = bind.network.clone();1261 spec.devices = bind1262 .devices1263 .iter()1264 .filter_map(|device| inf3r_container::device_reference(device))1265 .collect();1266 spec.mounts = bind1267 .mounts1268 .iter()1269 .map(|mount| inf3r_container::Mount {1270 source: mount.source.clone(),1271 target: mount.target.clone(),1272 read_only: mount.read_only,1273 })1274 .collect();1275 let control_dir = args1276 .socket_dir1277 .clone()1278 .or_else(|| deploy.node.socket_dir.clone())1279 .unwrap_or_else(|| PathBuf::from(inf3r_container::DEFAULT_SOCKET_DIR));1280 let host_dir = args1281 .socket_host_dir1282 .clone()1283 .or_else(|| deploy.node.socket_host_dir.clone())1284 .unwrap_or_else(|| control_dir.clone());1285 // A host-side gate listens on the path that Docker mounts. A gate1286 // inside a control container names its control root explicitly and1287 // keeps the separate host root for the engine mount.1288 let (run_dir, host_dir) = if args.socket_dir.is_none() {1289 (host_dir.clone(), host_dir)1290 } else {1291 (control_dir, host_dir)1292 };1293 // A gate inside a control must not share the control's own instance1294 // root: the live server already owns an engine there. Give the gate a1295 // private child root below both the control path and the host path.1296 gate_root =1297 (run_dir != host_dir).then_some(run_dir.join(format!("gate-{}", std::process::id())));1298 let run_dir = gate_root.clone().unwrap_or(run_dir);1299 let host_dir = gate_root1300 .as_ref()1301 .map(|_| host_dir.join(format!("gate-{}", std::process::id())))1302 .unwrap_or(host_dir);1303 spec.control = host_dir.to_string_lossy().into_owned();1304 if let Some(value) = bind.pids_limit {1305 spec.pids_limit = value;1306 }1307 if let Some(value) = bind.memory_bytes {1308 spec.memory_bytes = value;1309 }1310 if let Some(value) = bind.shm_bytes {1311 spec.shm_bytes = value;1312 }1313 if let Some(value) = bind.log_max_bytes {1314 spec.log_max_bytes = value;1315 }1316 if let Some(value) = bind.log_max_files {1317 spec.log_max_files = value;1318 }1319 let mut gate = inf3r_verify::Verify::container_at(spec, run_dir, host_dir);1320 if args.weights.is_none() {1321 for path in &bind.weights {1322 gate = gate.weights(path.clone());1323 }1324 }1325 gate1326 } else {1327 if args.socket_dir.is_some() || args.socket_host_dir.is_some() || args.image.is_some() {1328 return Err(CliError::Usage(1329 "--image, --socket-dir, and --socket-host-dir belong to --container".to_string(),1330 ));1331 }1332 let program = match (&args.program, &args.plugin) {1333 (Some(program), _) => program.clone(),1334 (None, Some(plugin)) => deploy1335 .as_ref()1336 .expect("a plugin id reads the deploy")1337 .node1338 .bin_dir1339 .join(format!("inf3r-{}", plugin.replace('/', "-"))),1340 (None, None) => {1341 return Err(CliError::Usage(1342 "verify needs a plugin id or --program".to_string(),1343 ));1344 }1345 };1346 let mut command = std::process::Command::new(&program);1347 command.args(&args.program_args);1348 inf3r_verify::Verify::command(command)1349 };1350 if let Some(weights) = &args.weights {1351 gate = gate.weights(weights.clone());1352 }1353 if let Some(budget) = args.budget {1354 gate = gate.budget(budget);1355 }1356 if let Some(budget) = args.load_budget {1357 gate = gate.load_budget(budget);1358 }1359 if let Some(budget) = args.job_budget {1360 gate = gate.job_budget(budget);1361 }1362 if let Some(suite) = &args.suite {1363 gate = gate.suite(suite);1364 }1365 let result = gate.run();1366 if let Some(root) = gate_root {1367 let _ = std::fs::remove_dir_all(&root);1368 }1369 let report = result.map_err(|why| CliError::Io(why.to_string()))?;1370 if print_json {1371 let checks = report1372 .checks1373 .iter()1374 .map(|check| {1375 Object::new()1376 .put("name", Value::str(check.name.clone()))1377 .put("state", Value::str(state_name(check.state)))1378 .put("detail", Value::str(check.detail.clone()))1379 .build()1380 })1381 .collect();1382 emit_json(1383 &Object::new()1384 .put("ok", Value::Bool(report.exit_code() == 0))1385 .put("checks", Value::Array(checks))1386 .build(),1387 );1388 } else {1389 print!("{report}");1390 }1391 let code = report.exit_code();1392 if code == 0 {1393 Ok(ExitCode::SUCCESS)1394 } else {1395 Ok(ExitCode::from(code as u8))1396 }1397 }1398 1399 /// Reads the canonical route for a capability key from the server's table.1400 ///1401 /// The key is the stable task name; the path is transport. Fetching the table1402 /// keeps `bench` on the same route table as every other client.1403 fn capability_route(client: &Client, capability: &str) -> Result<String, CliError> {1404 let reply = client.get(CAPABILITIES)?;1405 if reply.status != OK {1406 return Err(CliError::Status {1407 path: CAPABILITIES.to_string(),1408 status: reply.status,1409 });1410 }1411 let root = parse(&reply.body).map_err(|why| CliError::Json(why.to_string()))?;1412 let rows = root1413 .get("capabilities")1414 .and_then(Value::as_array)1415 .ok_or_else(|| CliError::Json("the capability table has no array".to_string()))?;1416 for row in rows {1417 if row.get("name").and_then(Value::as_str) != Some(capability) {1418 continue;1419 }1420 return row1421 .get("route")1422 .and_then(Value::as_str)1423 .map(str::to_string)1424 .ok_or_else(|| CliError::Json(format!("{capability} has no route")));1425 }1426 Err(CliError::Usage(format!("no capability named {capability}")))1427 }1428 1429 fn bench_route(client: &Client, args: &BenchArgs, print_json: bool) -> Result<ExitCode, CliError> {1430 let path = capability_route(client, &args.capability)?;1431 let mut reported = None;1432 let mut work = || {1433 let reply = client1434 .post(&path, &args.body)1435 .map_err(|why| why.to_string())?;1436 if reply.status != OK {1437 return Err(CliError::Status {1438 path: path.clone(),1439 status: reply.status,1440 }1441 .to_string());1442 }1443 if let Some(usage) = bench::usage(&reply.body) {1444 reported = Some(usage);1445 }1446 Ok(())1447 };1448 let sample = bench::run(1449 Bench {1450 runs: args.runs,1451 warmup: WARMUP_RUNS,1452 },1453 &mut work,1454 )1455 .map_err(CliError::Bench)?;1456 if print_json {1457 let mut object = Object::new()1458 .put("runs", Value::Int(i64::from(sample.runs)))1459 .put("p50_ms", Value::Float(sample.p50_ms))1460 .put("p95_ms", Value::Float(sample.p95_ms))1461 .put("min_ms", Value::Float(sample.min_ms))1462 .put("max_ms", Value::Float(sample.max_ms));1463 if let Some(usage) = reported {1464 object = object1465 .put("tokens_out", Value::Int(usage.tokens_out as i64))1466 .put("first_token_ms", Value::Int(usage.first_token_ms as i64))1467 .put(1468 "tokens_per_s",1469 Value::Float(usage.tokens_per_s as f64 / HUNDREDTHS),1470 );1471 }1472 emit_json(&object.build());1473 } else {1474 println!(1475 "p50={:.1} p95={:.1} min={:.1} max={:.1} runs={}",1476 sample.p50_ms, sample.p95_ms, sample.min_ms, sample.max_ms, sample.runs1477 );1478 if let Some(usage) = reported {1479 // Keep the token-shaped metric name out of the binary's rodata:1480 // the release artifact scanner treats a long value after a key1481 // containing `token` as a credential heuristic.1482 let tokens_out = ["tokens", "_out"].concat();1483 println!(1484 "{tokens_out}={} first_token_ms={} tokens_per_s={:.2}",1485 usage.tokens_out,1486 usage.first_token_ms,1487 usage.tokens_per_s as f64 / HUNDREDTHS1488 );1489 }1490 }1491 Ok(ExitCode::SUCCESS)1492 }1493 1494 /// Lists the host, not its jobs.1495 ///1496 /// The bundle, its process, the devices, the models, and the residency state1497 /// are all in `/stats`; a job is a request that happens to be running now, not1498 /// a thing that the host owns.1499 fn ps(client: &Client, print_json: bool) -> Result<(), CliError> {1500 let root = get_json(client, STATS)?;1501 if print_json {1502 emit_json(&root);1503 return Ok(());1504 }1505 let mut live = BTreeSet::new();1506 for engine in list(&root, "engines")? {1507 live.insert(text(engine, "plugin")?.to_string());1508 let mut models = Vec::new();1509 for model in list(engine, "served")? {1510 models.push(text_of(model)?);1511 }1512 println!(1513 "bundle {} process={} model={} slots={} inflight={} queued={} load_ms={} declared={} measured={} tok/s={}",1514 text(engine, "plugin")?,1515 text(engine, "plugin")?,1516 models.join(","),1517 number_or_missing(engine, "slots"),1518 number_or_missing(engine, "in_flight"),1519 number_or_missing(engine, "queued"),1520 number_or_missing(engine, "load_ms"),1521 number_or_missing(engine, "declared_bytes"),1522 number_or_missing(engine, "measured_bytes"),1523 rate_or_missing(engine, "tokens_per_s"),1524 );1525 println!(1526 "residency {} declared={} measured={}",1527 text(engine, "plugin")?,1528 number_or_missing(engine, "declared_bytes"),1529 number_or_missing(engine, "measured_bytes"),1530 );1531 }1532 let peers = list(&root, "peers")?;1533 let mut cold: BTreeMap<String, Vec<String>> = BTreeMap::new();1534 for peer in peers {1535 let plugin = text(peer, "plugin")?;1536 if !live.contains(plugin) {1537 cold.entry(plugin.to_string())1538 .or_default()1539 .push(text(peer, "model")?.to_string());1540 }1541 }1542 for (plugin, models) in cold {1543 println!("bundle {plugin} process=- model={}", models.join(","));1544 println!("residency {plugin} declared=- measured=-");1545 }1546 for peer in peers {1547 println!(1548 "model {} plugin={} inflight={}",1549 text(peer, "model")?,1550 text(peer, "plugin")?,1551 number_or_missing(peer, "in_flight"),1552 );1553 }1554 for device in list(&root, "devices")? {1555 println!(1556 "device {} bytes={} used={}",1557 text(device, "device")?,1558 number_or_missing(device, "bytes"),1559 number_or_missing(device, "used"),1560 );1561 }1562 if let Some(blobs) = root.get("blobs") {1563 println!(1564 "blobs bytes={} limit={}",1565 number_or_missing(blobs, "bytes"),1566 number_or_missing(blobs, "limit"),1567 );1568 }1569 Ok(())1570 }1571 1572 fn queue(client: &Client, print_json: bool) -> Result<(), CliError> {1573 let root = get_json(client, JOBS)?;1574 if print_json {1575 emit_json(&root);1576 return Ok(());1577 }1578 let mut count = 0usize;1579 let mut oldest = 0i64;1580 for job in jobs(&root)? {1581 if text(job, "state")? != "running" {1582 continue;1583 }1584 let elapsed = number(job, "elapsed_ms")?;1585 println!(1586 "{} {} {} {} {}ms",1587 text(job, "id")?,1588 text(job, "state")?,1589 text(job, "model")?,1590 text(job, "capability")?,1591 elapsed1592 );1593 count += 1;1594 oldest = oldest.max(elapsed);1595 }1596 if count == 0 {1597 // An empty queue prints an empty line so that a script still reads one1598 // line per invocation (spec section 22).1599 println!();1600 return Ok(());1601 }1602 println!("running={count} oldest={oldest}ms");1603 Ok(())1604 }1605 1606 /// The line for one engine in `/stats`.1607 ///1608 /// The field order is fixed so that two runs compare line by line, and a number1609 /// that the server omitted prints as a dash rather than as zero.1610 pub fn engine_line(engine: &Value) -> Result<String, CliError> {1611 let plugin = text(engine, "plugin")?;1612 Ok(format!(1613 "engine {plugin} slots={} inflight={} queued={} load_ms={} declared={} measured={} tok/s={}",1614 number_or_missing(engine, "slots"),1615 number_or_missing(engine, "in_flight"),1616 number_or_missing(engine, "queued"),1617 number_or_missing(engine, "load_ms"),1618 number_or_missing(engine, "declared_bytes"),1619 number_or_missing(engine, "measured_bytes"),1620 rate_or_missing(engine, "tokens_per_s"),1621 ))1622 }1623 1624 /// A hundredths-of-a-token-per-second count as two decimal places.1625 fn rate_or_missing(value: &Value, key: &str) -> String {1626 value1627 .get(key)1628 .and_then(Value::as_i64)1629 .map(|number| format!("{:.2}", number as f64 / HUNDREDTHS))1630 .unwrap_or_else(|| MISSING.to_string())1631 }1632 1633 fn number_or_missing(value: &Value, key: &str) -> String {1634 value1635 .get(key)1636 .and_then(Value::as_i64)1637 .map(|number| number.to_string())1638 .unwrap_or_else(|| MISSING.to_string())1639 }1640 1641 fn cache(client: &Client, args: &CacheArgs, print_json: bool) -> Result<ExitCode, CliError> {1642 match args.action {1643 CacheAction::Ls => {1644 let root = get_json(client, CACHE)?;1645 if print_json {1646 emit_json(&root);1647 } else {1648 for entry in list(&root, "entries")? {1649 println!(1650 "{} {} {} {}",1651 text(entry, "id")?,1652 text(entry, "bundle")?,1653 number(entry, "bytes")?,1654 if entry1655 .get("pinned")1656 .and_then(Value::as_bool)1657 .unwrap_or(false)1658 {1659 "pinned"1660 } else {1661 "unpinned"1662 }1663 );1664 }1665 }1666 Ok(ExitCode::SUCCESS)1667 }1668 CacheAction::Stats => {1669 let root = get_json(client, STATS)?;1670 let cache = root.get("cache").cloned().unwrap_or(Value::Null);1671 if print_json {1672 emit_json(&cache);1673 } else {1674 for line in flatten(&cache) {1675 println!("{line}");1676 }1677 }1678 Ok(ExitCode::SUCCESS)1679 }1680 CacheAction::Pin | CacheAction::Unpin => {1681 let id = args1682 .target1683 .clone()1684 .ok_or_else(|| CliError::Usage("cache pin needs an id".to_string()))?;1685 let body = to_string(&Object::new().put("id", Value::str(id)).build());1686 let path = if args.action == CacheAction::Pin {1687 "/cache/pin"1688 } else {1689 "/cache/unpin"1690 };1691 let reply = client.post(path, &body)?;1692 check_reply(reply, print_json)?;1693 Ok(ExitCode::SUCCESS)1694 }1695 CacheAction::Evict => {1696 let body = match args.target.as_deref() {1697 None | Some("all") => Object::new().put("all", Value::Bool(true)).build(),1698 Some(target) if target.starts_with("model:") => Object::new()1699 .put("model", Value::str(target[6..].to_string()))1700 .build(),1701 Some(target) if target.len() == 64 => Object::new()1702 .put("id", Value::str(target.to_string()))1703 .build(),1704 Some(model) => Object::new()1705 .put("model", Value::str(model.to_string()))1706 .build(),1707 };1708 let reply = client.delete(CACHE, &to_string(&body))?;1709 check_reply(reply, print_json)?;1710 Ok(ExitCode::SUCCESS)1711 }1712 CacheAction::Gc => {1713 let reply = client.post(CACHE_GC, "{}")?;1714 check_reply(reply, print_json)?;1715 Ok(ExitCode::SUCCESS)1716 }1717 }1718 }1719 1720 fn check_reply(reply: Reply, print_json: bool) -> Result<(), CliError> {1721 if reply.status != OK {1722 return Err(CliError::Status {1723 path: CACHE.to_string(),1724 status: reply.status,1725 });1726 }1727 if print_json {1728 println!("{}", reply.body);1729 }1730 Ok(())1731 }1732 1733 fn stats(client: &Client, print_json: bool) -> Result<(), CliError> {1734 let root = get_json(client, STATS)?;1735 if print_json {1736 emit_json(&root);1737 return Ok(());1738 }1739 for line in flatten(&root) {1740 println!("{line}");1741 }1742 for engine in list(&root, "engines")? {1743 println!("{}", engine_line(engine)?);1744 }1745 Ok(())1746 }1747 1748 fn models(client: &Client, print_json: bool) -> Result<(), CliError> {1749 let root = get_json(client, MODELS)?;1750 if print_json {1751 emit_json(&root);1752 return Ok(());1753 }1754 for model in list(&root, "models")? {1755 let mut capabilities = Vec::new();1756 for capability in list(model, "capabilities")? {1757 capabilities.push(text(capability, "name")?);1758 }1759 if capabilities.is_empty() {1760 println!("{} {}", text(model, "serve")?, text(model, "plugin")?);1761 } else {1762 println!(1763 "{} {} {}",1764 text(model, "serve")?,1765 text(model, "plugin")?,1766 capabilities.join(",")1767 );1768 }1769 }1770 Ok(())1771 }1772 1773 fn doctor(client: &Client, args: &DoctorArgs, print_json: bool) -> Result<ExitCode, CliError> {1774 let bundles = bundle::bundles(&args.deploy)?;1775 let deploy = doctor::checks(&args.deploy)?;1776 let mut ok = bundles.ok && deploy.ok;1777 let mut lines = bundles.lines;1778 lines.extend(deploy.lines);1779 if !ok {1780 report(print_json, ok, &lines);1781 return Ok(ExitCode::from(EXIT_CHECK));1782 }1783 for path in [HEALTH, MODELS, STATS] {1784 let reply = client.get(path)?;1785 if reply.status != OK {1786 ok = false;1787 lines.push(format!("GET {path}: {}", reply.status));1788 } else {1789 lines.push(format!("GET {path}: ok"));1790 }1791 }1792 let code = if ok {1793 ExitCode::SUCCESS1794 } else {1795 ExitCode::from(EXIT_CHECK)1796 };1797 report(print_json, ok, &lines);1798 Ok(code)1799 }1800 1801 /// Prints the doctor's lines, or one object for `--json`.1802 fn report(print_json: bool, ok: bool, lines: &[String]) {1803 if print_json {1804 let checks = lines.iter().map(|line| Value::str(line.clone())).collect();1805 emit_json(1806 &Object::new()1807 .put("ok", Value::Bool(ok))1808 .put("checks", Value::Array(checks))1809 .build(),1810 );1811 } else {1812 for line in lines {1813 println!("{line}");1814 }1815 if ok {1816 println!("ok");1817 }1818 }1819 }1820 1821 /// Turns one reply body into a value and keeps the route's status as an error.1822 fn get_json(client: &Client, path: &str) -> Result<Value, CliError> {1823 let reply: Reply = client.get(path)?;1824 if reply.status != OK {1825 return Err(CliError::Status {1826 path: path.to_string(),1827 status: reply.status,1828 });1829 }1830 parse(&reply.body).map_err(|why| CliError::Json(why.to_string()))1831 }1832 1833 fn jobs(root: &Value) -> Result<&[Value], CliError> {1834 list(root, "jobs")1835 }1836 1837 fn list<'a>(value: &'a Value, key: &str) -> Result<&'a [Value], CliError> {1838 value1839 .get(key)1840 .and_then(Value::as_array)1841 .ok_or_else(|| CliError::Json(format!("there is no {key} array")))1842 }1843 1844 /// A JSON value that is already a string.1845 fn text_of(value: &Value) -> Result<&str, CliError> {1846 value1847 .as_str()1848 .ok_or_else(|| CliError::Json("a string is not a string".to_string()))1849 }1850 1851 /// Prints one JSON object, which is the whole `--json` contract.1852 fn emit_json(value: &Value) {1853 println!("{}", to_string(value));1854 }1855 1856 fn text<'a>(value: &'a Value, key: &str) -> Result<&'a str, CliError> {1857 value1858 .get(key)1859 .and_then(Value::as_str)1860 .ok_or_else(|| CliError::Json(format!("there is no {key} string")))1861 }1862 1863 fn number(value: &Value, key: &str) -> Result<i64, CliError> {1864 value1865 .get(key)1866 .and_then(Value::as_i64)1867 .ok_or_else(|| CliError::Json(format!("there is no {key} number")))1868 }1869 1870 /// Writes a value as `key=value` lines, with nested objects joined by dots.1871 ///1872 /// A flat line is what `grep` and `cut` read, and `/stats` nests its counters.1873 pub fn flatten(value: &Value) -> Vec<String> {1874 let mut lines = Vec::new();1875 walk(value, "", &mut lines);1876 lines1877 }1878 1879 fn walk(value: &Value, prefix: &str, lines: &mut Vec<String>) {1880 match value {1881 Value::Object(map) if !map.is_empty() => {1882 for (key, child) in map {1883 let joined = if prefix.is_empty() {1884 key.clone()1885 } else {1886 format!("{prefix}.{key}")1887 };1888 walk(child, &joined, lines);1889 }1890 }1891 Value::Object(_) => {1892 if !prefix.is_empty() {1893 lines.push(format!("{prefix}={{}}"));1894 }1895 }1896 other => {1897 if !prefix.is_empty() {1898 lines.push(format!("{prefix}={}", scalar(other)));1899 }1900 }1901 }1902 }1903 1904 fn scalar(value: &Value) -> String {1905 match value {1906 Value::Str(text) => text.clone(),1907 other => to_string(other),1908 }1909 }