main.rs 16 KB

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