main.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. #![deny(clippy::wildcard_imports)]
  2. use anyhow::Result;
  3. use clap::Parser;
  4. fluent_i18n::i18n!("locales", fallback = "en");
  5. mod after_stop;
  6. mod before_serve;
  7. mod builtin_scripts;
  8. mod cli;
  9. mod cluster_state;
  10. mod config;
  11. mod docker;
  12. mod doctor;
  13. mod ends;
  14. mod engine_flags;
  15. mod exec;
  16. mod health;
  17. mod home_assistant;
  18. mod host_keys;
  19. mod locale;
  20. mod orchestrate;
  21. mod power;
  22. mod pre_serve;
  23. mod ssh;
  24. mod tmux;
  25. use crate::cli::{Cli, Commands, PowerAction};
  26. use crate::config::{
  27. Cluster, Config, DeployTarget, default_config_dir, load_recipe, resolve_cluster,
  28. select_cluster_by_name,
  29. };
  30. use crate::ssh::fetch_host_key;
  31. use std::collections::HashSet;
  32. /// Resolve the path to the config file.
  33. ///
  34. /// Search order:
  35. /// 1. `--config <path>` from CLI (always wins; error if missing)
  36. /// 2. `./config.toml` in cwd
  37. /// 3. `<default_config_dir>/config.toml`
  38. ///
  39. /// Returns an error if nothing is found, with a hint pointing the user
  40. /// to copy the example config to one of the two paths.
  41. fn resolve_config_path(cli_config: &str) -> std::path::PathBuf {
  42. use std::path::PathBuf;
  43. let explicit = PathBuf::from(cli_config);
  44. // User passed a non-default path: use it as-is.
  45. if cli_config != "config.toml" {
  46. return explicit;
  47. }
  48. // Default value (or no flag): try cwd first, then default folder.
  49. if explicit.exists() {
  50. return explicit;
  51. }
  52. if let Some(dir) = default_config_dir() {
  53. let candidate = dir.join("config.toml");
  54. if candidate.exists() {
  55. return candidate;
  56. }
  57. }
  58. // Fall through; the loader will report a clean error.
  59. explicit
  60. }
  61. #[tokio::main]
  62. async fn main() -> Result<()> {
  63. // Locale: check LANG env var first (macOS sys-locale ignores it).
  64. // Normalize "ru_RU.UTF-8" → "ru-RU" for unic-langid.
  65. let locale = std::env::var("LANG")
  66. .ok()
  67. .map(|l| l.split('.').next().unwrap_or(&l).replace('_', "-"));
  68. let _ = fluent_i18n::set_locale(locale.as_deref());
  69. // Capture for spawned tasks — set_locale is thread-local, so tokio
  70. // workers miss it. spawn_with_locale re-applies from this global.
  71. locale::set_global_locale(locale.clone());
  72. tracing_subscriber::fmt()
  73. .with_env_filter(
  74. tracing_subscriber::EnvFilter::try_from_default_env()
  75. .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
  76. )
  77. .init();
  78. let cli = Cli::parse();
  79. let config_path = resolve_config_path(&cli.config);
  80. let raw_config = tokio::fs::read_to_string(&config_path).await?;
  81. let config: Config = toml::from_str(&raw_config)?;
  82. let dry_run = cli.dry_run;
  83. match cli.command {
  84. Commands::Serve {
  85. recipe,
  86. cluster,
  87. node,
  88. keep,
  89. skip_before_serve,
  90. follow,
  91. auto_power_on,
  92. sync_image,
  93. sync_image_source,
  94. build_node,
  95. force_build,
  96. force,
  97. solo,
  98. } => {
  99. handle_serve(
  100. &config,
  101. &recipe,
  102. &cluster,
  103. node,
  104. docker::ServeOpts {
  105. keep,
  106. skip_before_serve,
  107. dry_run,
  108. auto_power_on,
  109. sync_image,
  110. sync_image_source,
  111. build_node,
  112. force_build,
  113. force,
  114. solo,
  115. },
  116. follow,
  117. dry_run,
  118. )
  119. .await?;
  120. }
  121. Commands::Build {
  122. recipe,
  123. build_node,
  124. cluster,
  125. force_build,
  126. } => {
  127. handle_build_cmd(
  128. &config,
  129. &recipe,
  130. &build_node,
  131. &cluster,
  132. force_build,
  133. dry_run,
  134. )
  135. .await?;
  136. }
  137. Commands::Logs {
  138. recipe: recipe_name,
  139. cluster,
  140. follow,
  141. node,
  142. } => {
  143. handle_logs(&config, &recipe_name, &cluster, follow, node, dry_run).await?;
  144. }
  145. Commands::Stop {
  146. recipe: recipe_name,
  147. cluster,
  148. node,
  149. power_off,
  150. } => {
  151. handle_stop(&config, &recipe_name, &cluster, &node, power_off, dry_run).await?;
  152. }
  153. Commands::Health {
  154. cluster: cluster_name,
  155. fingerprint,
  156. } => {
  157. handle_health(&config, cluster_name, fingerprint).await?;
  158. }
  159. Commands::Doctor {
  160. recipe,
  161. cluster,
  162. repair,
  163. } => {
  164. doctor::doctor(&config, &recipe, &cluster, repair, dry_run).await?;
  165. }
  166. Commands::Tmux(tmux_cmd) => {
  167. crate::tmux::handle_tmux(&config, tmux_cmd, dry_run).await?;
  168. }
  169. Commands::InitHostKeys { cluster } => {
  170. host_keys::init_host_keys(
  171. &config,
  172. cluster.as_deref(),
  173. config_path.to_str().unwrap_or("config.toml"),
  174. )
  175. .await?;
  176. }
  177. Commands::Exec {
  178. cluster,
  179. recipe,
  180. node,
  181. alias,
  182. command,
  183. } => {
  184. handle_exec(&config, cluster, recipe, node, alias, command, dry_run).await?;
  185. }
  186. Commands::Power { action } => {
  187. handle_power(&config, action, dry_run).await?;
  188. }
  189. }
  190. Ok(())
  191. }
  192. // ---------------------------------------------------------------------------
  193. // Per-command handler functions
  194. // ---------------------------------------------------------------------------
  195. /// Handle `serve` command: launch inference containers on a cluster.
  196. ///
  197. /// Dispatches to `docker::serve` or `tmux::serve` based on the recipe's
  198. /// `deploy` field. Docker-only CLI opts (sync_image, build_node,
  199. /// force_build, keep, auto_power_on) are ignored with a warning when
  200. /// `deploy = "tmux"`.
  201. async fn handle_serve(
  202. config: &Config,
  203. recipe: &str,
  204. cluster: &str,
  205. node: Option<String>,
  206. opts: docker::ServeOpts,
  207. follow: bool,
  208. dry_run: bool,
  209. ) -> Result<()> {
  210. let recipe_obj = load_recipe(recipe).await?;
  211. match recipe_obj.deploy {
  212. DeployTarget::Docker => {
  213. let cluster = docker::serve(config, recipe, cluster, node.as_deref(), opts).await?;
  214. if follow && !dry_run {
  215. tracing::info!("{}", fluent_i18n::t!("container-log-header"));
  216. docker::show_logs(config, &cluster, recipe, true, node.as_deref(), dry_run).await?;
  217. }
  218. }
  219. DeployTarget::Tmux => {
  220. // Warn about docker-only CLI opts that are silently ignored.
  221. let ignored: Vec<&str> = [
  222. (opts.sync_image, "--sync-image"),
  223. (opts.sync_image_source.is_some(), "--sync-image-source"),
  224. (opts.build_node.is_some(), "--build-node"),
  225. (opts.force_build, "--force-build"),
  226. (opts.keep, "--keep"),
  227. (opts.auto_power_on, "--on"),
  228. (opts.force, "--force"),
  229. (opts.solo.is_some(), "--solo/--no-solo"),
  230. ]
  231. .iter()
  232. .filter_map(|(set, flag)| if *set { Some(*flag) } else { None })
  233. .collect();
  234. if !ignored.is_empty() {
  235. tracing::warn!(
  236. "{}",
  237. fluent_i18n::t!("tmux-deploy-ignored-opts", { "opts" => &ignored.join(", ") })
  238. );
  239. }
  240. crate::tmux::serve::tmux_serve(
  241. config,
  242. recipe,
  243. cluster,
  244. opts.skip_before_serve,
  245. dry_run,
  246. )
  247. .await?;
  248. if follow && !dry_run {
  249. tracing::info!(
  250. "{}",
  251. fluent_i18n::t!("tmux-following-logs", { "name" => recipe.to_string() })
  252. );
  253. crate::tmux::ops::tmux_logs(config, recipe, cluster, true, dry_run).await?;
  254. }
  255. }
  256. }
  257. Ok(())
  258. }
  259. /// Handle `build` command: build a Docker image on a remote node.
  260. async fn handle_build_cmd(
  261. config: &Config,
  262. recipe: &str,
  263. build_node: &str,
  264. cluster: &str,
  265. force_build: bool,
  266. dry_run: bool,
  267. ) -> Result<()> {
  268. let recipe_obj = crate::config::load_recipe(recipe).await?;
  269. let cluster = resolve_cluster_for_op(config, recipe, cluster).await?;
  270. let opts = docker::ServeOpts {
  271. keep: false,
  272. skip_before_serve: true,
  273. dry_run,
  274. auto_power_on: false,
  275. sync_image: false,
  276. sync_image_source: None,
  277. build_node: Some(build_node.to_string()),
  278. force_build,
  279. force: false,
  280. solo: None,
  281. };
  282. docker::build::handle_build(config, &cluster, recipe, &recipe_obj, &opts, build_node).await?;
  283. Ok(())
  284. }
  285. /// Handle `logs` command: show container logs.
  286. async fn handle_logs(
  287. config: &Config,
  288. recipe_name: &str,
  289. cluster: &str,
  290. follow: bool,
  291. node: Option<String>,
  292. dry_run: bool,
  293. ) -> Result<()> {
  294. let cluster = resolve_cluster_for_op(config, recipe_name, cluster).await?;
  295. docker::show_logs(
  296. config,
  297. &cluster,
  298. recipe_name,
  299. follow,
  300. node.as_deref(),
  301. dry_run,
  302. )
  303. .await?;
  304. Ok(())
  305. }
  306. /// Handle `stop` command: stop containers and optionally power off.
  307. async fn handle_stop(
  308. config: &Config,
  309. recipe_name: &str,
  310. cluster: &str,
  311. node: &[String],
  312. power_off: bool,
  313. dry_run: bool,
  314. ) -> Result<()> {
  315. let (stopped_cluster, stopped_nodes): (Cluster, Vec<String>) = if !node.is_empty() {
  316. let cluster = resolve_cluster_for_op(config, recipe_name, cluster).await?;
  317. let nodes = node.to_vec();
  318. docker::stop_cluster(config, &cluster, recipe_name, &nodes, dry_run).await?;
  319. (cluster, nodes)
  320. } else {
  321. let variants = docker::deploy::discover_recipe_deployments(config, recipe_name).await?;
  322. if variants.is_empty() {
  323. anyhow::bail!("No running containers found for recipe '{}'", recipe_name);
  324. }
  325. if variants.len() == 1 {
  326. let v = &variants[0];
  327. let cluster = select_cluster_by_name(config, &v.cluster)?;
  328. let nodes = v.nodes.clone();
  329. docker::stop_cluster(config, &cluster, recipe_name, &nodes, dry_run).await?;
  330. (cluster, nodes)
  331. } else {
  332. let mut msg = format!(
  333. "Multiple deployments of '{}' found — use --node to select:\n",
  334. recipe_name
  335. );
  336. for (i, v) in variants.iter().enumerate() {
  337. let nodes = v
  338. .nodes
  339. .iter()
  340. .map(|n| format!("--node {}", n))
  341. .collect::<Vec<_>>()
  342. .join(" ");
  343. msg.push_str(&format!(
  344. " {}: cluster '{}' with {}\n",
  345. i + 1,
  346. v.cluster,
  347. nodes
  348. ));
  349. }
  350. anyhow::bail!(msg);
  351. }
  352. };
  353. // Run recipe `after_stop` hooks (e.g. restore_dgx_services) on the
  354. // nodes that were actually stopped. Best-effort against the loaded
  355. // recipe; if the recipe file is unavailable, skip silently.
  356. if let Ok(recipe) = crate::config::load_recipe(recipe_name).await {
  357. crate::after_stop::run(config, &stopped_cluster, &recipe, dry_run).await?;
  358. }
  359. if power_off {
  360. crate::power::power_off(config, &stopped_cluster, &stopped_nodes, dry_run).await?;
  361. }
  362. Ok(())
  363. }
  364. /// Handle `health` command: check cluster health or show host key fingerprints.
  365. async fn handle_health(
  366. config: &Config,
  367. cluster_name: Option<String>,
  368. fingerprint: bool,
  369. ) -> Result<()> {
  370. if fingerprint {
  371. let clusters_to_check: Vec<Cluster> = match &cluster_name {
  372. Some(name) => vec![select_cluster_by_name(config, name)?],
  373. None => config.clusters.clone(),
  374. };
  375. for cluster in &clusters_to_check {
  376. println!(
  377. "\n{}",
  378. fluent_i18n::t!("cluster-section", { "name" => &cluster.name })
  379. );
  380. for node in &cluster.nodes {
  381. match fetch_host_key(config, node).await {
  382. Ok(fp) => println!(
  383. "{}",
  384. fluent_i18n::t!("host-key-line", { "name" => &node.name, "ip" => &node.ssh_ip, "key" => &fp })
  385. ),
  386. Err(e) => println!(
  387. "{}",
  388. fluent_i18n::t!("host-key-error", { "name" => &node.name, "ip" => &node.ssh_ip, "error" => &e.to_string() })
  389. ),
  390. }
  391. }
  392. }
  393. } else {
  394. match cluster_name {
  395. Some(ref name) => {
  396. let cluster = select_cluster_by_name(config, name)?;
  397. docker::health::health_check(config, &cluster, false).await?;
  398. let tmux_entries = tmux::discover::tmux_health_for_cluster(config, &cluster).await;
  399. tmux::discover::print_tmux_health(&tmux_entries);
  400. }
  401. None => {
  402. for cluster in &config.clusters {
  403. docker::health::health_check(config, cluster, false).await?;
  404. let tmux_entries =
  405. tmux::discover::tmux_health_for_cluster(config, cluster).await;
  406. tmux::discover::print_tmux_health(&tmux_entries);
  407. }
  408. docker::health::health_summary(config).await?;
  409. }
  410. }
  411. }
  412. Ok(())
  413. }
  414. /// Handle `exec` command: run a command on cluster nodes via SSH.
  415. async fn handle_exec(
  416. config: &Config,
  417. cluster: Option<String>,
  418. recipe: Option<String>,
  419. node: Option<String>,
  420. alias: Option<String>,
  421. command: Vec<String>,
  422. dry_run: bool,
  423. ) -> Result<()> {
  424. let (cluster, _recipe) =
  425. exec::resolve_target(config, cluster.as_deref(), recipe.as_deref()).await?;
  426. let cmd_str = exec::resolve_command(config, alias.as_deref(), &command)?;
  427. exec::run(config, &cluster, node.as_deref(), &cmd_str, dry_run).await?;
  428. Ok(())
  429. }
  430. /// Handle `power` command: power on/off/switch nodes.
  431. async fn handle_power(config: &Config, action: PowerAction, dry_run: bool) -> Result<()> {
  432. match action {
  433. PowerAction::Off { cluster, node } => {
  434. let cluster = select_cluster_by_name(config, &cluster)?;
  435. let nodes = node.into_iter().collect::<Vec<_>>();
  436. power::power_off(config, &cluster, &nodes, dry_run).await?;
  437. }
  438. PowerAction::On { cluster, node } => {
  439. let cluster = select_cluster_by_name(config, &cluster)?;
  440. let nodes = node.into_iter().collect::<Vec<_>>();
  441. power::power_on(config, &cluster, &nodes, dry_run).await?;
  442. }
  443. PowerAction::Switch { from, to } => {
  444. let from = select_cluster_by_name(config, &from)?;
  445. let to = select_cluster_by_name(config, &to)?;
  446. power::power_switch(config, &from, &to, dry_run).await?;
  447. }
  448. }
  449. Ok(())
  450. }
  451. /// Resolve a cluster for container operations (stop/logs).
  452. /// When `auto`, tries live container label lookup first, then falls back
  453. /// to config-based auto-selection (for dry-run / offline scenarios).
  454. async fn resolve_cluster_for_op(
  455. config: &Config,
  456. recipe_name: &str,
  457. cluster_name: &str,
  458. ) -> Result<Cluster> {
  459. if cluster_name != "auto" {
  460. let recipe = load_recipe(recipe_name).await?;
  461. let (cluster, _) = resolve_cluster(config, &recipe, cluster_name, &HashSet::new())?;
  462. return Ok(cluster);
  463. }
  464. // Try live container label lookup first
  465. if let Ok(c) = docker::resolve_cluster_by_container_label(config, recipe_name).await {
  466. return Ok(c.clone());
  467. }
  468. // Fall back to config-based auto (dry-run / containers not running)
  469. let recipe = load_recipe(recipe_name).await?;
  470. let (cluster, _) = resolve_cluster(config, &recipe, "auto", &HashSet::new())?;
  471. Ok(cluster)
  472. }