main.rs 13 KB

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