main.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #![deny(clippy::wildcard_imports)]
  2. use anyhow::Result;
  3. use clap::Parser;
  4. fluent_i18n::i18n!("locales", fallback = "en");
  5. mod before_serve;
  6. mod cli;
  7. mod config;
  8. mod docker;
  9. mod doctor;
  10. mod exec;
  11. mod health;
  12. mod home_assistant;
  13. mod host_keys;
  14. mod power;
  15. mod pre_serve;
  16. mod ssh;
  17. mod tmux;
  18. use crate::cli::{Cli, Commands};
  19. use crate::config::{
  20. Cluster, Config, default_config_dir, load_recipe, resolve_cluster, select_cluster_by_name,
  21. };
  22. use crate::ssh::fetch_host_key;
  23. /// Resolve the path to the config file.
  24. ///
  25. /// Search order:
  26. /// 1. `--config <path>` from CLI (always wins; error if missing)
  27. /// 2. `./config.toml` in cwd
  28. /// 3. `<default_config_dir>/config.toml`
  29. ///
  30. /// Returns an error if nothing is found, with a hint pointing the user
  31. /// to copy the example config to one of the two paths.
  32. fn resolve_config_path(cli_config: &str) -> std::path::PathBuf {
  33. use std::path::PathBuf;
  34. let explicit = PathBuf::from(cli_config);
  35. // User passed a non-default path: use it as-is.
  36. if cli_config != "config.toml" {
  37. return explicit;
  38. }
  39. // Default value (or no flag): try cwd first, then default folder.
  40. if explicit.exists() {
  41. return explicit;
  42. }
  43. if let Some(dir) = default_config_dir() {
  44. let candidate = dir.join("config.toml");
  45. if candidate.exists() {
  46. return candidate;
  47. }
  48. }
  49. // Fall through; the loader will report a clean error.
  50. explicit
  51. }
  52. #[tokio::main]
  53. async fn main() -> Result<()> {
  54. // Locale: check LANG env var first (macOS sys-locale ignores it).
  55. // Normalize "ru_RU.UTF-8" → "ru-RU" for unic-langid.
  56. let locale = std::env::var("LANG")
  57. .ok()
  58. .map(|l| l.split('.').next().unwrap_or(&l).replace('_', "-"));
  59. let _ = fluent_i18n::set_locale(locale.as_deref());
  60. tracing_subscriber::fmt()
  61. .with_env_filter(
  62. tracing_subscriber::EnvFilter::try_from_default_env()
  63. .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
  64. )
  65. .init();
  66. let cli = Cli::parse();
  67. let config_path = resolve_config_path(&cli.config);
  68. let raw_config = tokio::fs::read_to_string(&config_path).await?;
  69. let config: Config = toml::from_str(&raw_config)?;
  70. let dry_run = cli.dry_run;
  71. match cli.command {
  72. Commands::Serve {
  73. recipe,
  74. cluster,
  75. node,
  76. keep,
  77. skip_before_serve,
  78. follow,
  79. } => {
  80. let cluster = docker::serve(
  81. &config,
  82. &recipe,
  83. &cluster,
  84. node.as_deref(),
  85. keep,
  86. skip_before_serve,
  87. dry_run,
  88. )
  89. .await?;
  90. if follow && !dry_run {
  91. tracing::info!("{}", fluent_i18n::t!("container-log-header"));
  92. docker::show_logs(&config, &cluster, &recipe, true, node.as_deref(), dry_run)
  93. .await?;
  94. }
  95. }
  96. Commands::Logs {
  97. recipe: recipe_name,
  98. cluster,
  99. follow,
  100. node,
  101. } => {
  102. let cluster = resolve_cluster_for_op(&config, &recipe_name, &cluster).await?;
  103. docker::show_logs(
  104. &config,
  105. &cluster,
  106. &recipe_name,
  107. follow,
  108. node.as_deref(),
  109. dry_run,
  110. )
  111. .await?;
  112. }
  113. Commands::Stop {
  114. recipe: recipe_name,
  115. cluster,
  116. node,
  117. } => {
  118. if !node.is_empty() {
  119. // User specified specific nodes — stop only those.
  120. let cluster = resolve_cluster_for_op(&config, &recipe_name, &cluster).await?;
  121. docker::stop_cluster(&config, &cluster, &recipe_name, &node, dry_run).await?;
  122. } else {
  123. // Discover running deployments and resolve ambiguity.
  124. let variants =
  125. docker::deploy::discover_recipe_deployments(&config, &recipe_name).await?;
  126. if variants.is_empty() {
  127. anyhow::bail!("No running containers found for recipe '{}'", recipe_name);
  128. }
  129. if variants.len() == 1 {
  130. let v = &variants[0];
  131. let cluster = select_cluster_by_name(&config, &v.cluster)?;
  132. docker::stop_cluster(&config, &cluster, &recipe_name, &v.nodes, dry_run)
  133. .await?;
  134. } else {
  135. let mut msg = format!(
  136. "Multiple deployments of '{}' found — use --node to select:\n",
  137. recipe_name
  138. );
  139. for (i, v) in variants.iter().enumerate() {
  140. let nodes = v
  141. .nodes
  142. .iter()
  143. .map(|n| format!("--node {}", n))
  144. .collect::<Vec<_>>()
  145. .join(" ");
  146. msg.push_str(&format!(
  147. " {}: cluster '{}' with {}\n",
  148. i + 1,
  149. v.cluster,
  150. nodes
  151. ));
  152. }
  153. anyhow::bail!(msg);
  154. }
  155. }
  156. }
  157. Commands::Health {
  158. cluster: cluster_name,
  159. fingerprint,
  160. } => {
  161. if fingerprint {
  162. let clusters_to_check: Vec<Cluster> = match &cluster_name {
  163. Some(name) => vec![select_cluster_by_name(&config, name)?],
  164. None => config.clusters.clone(),
  165. };
  166. for cluster in &clusters_to_check {
  167. println!("\n=== Кластер: {} ===", cluster.name);
  168. for node in &cluster.nodes {
  169. match fetch_host_key(&config, node).await {
  170. Ok(fp) => {
  171. println!("{} ({}) -> host_key = \"{}\"", node.name, node.ssh_ip, fp)
  172. }
  173. Err(e) => println!("{} ({}) -> error: {}", node.name, node.ssh_ip, e),
  174. }
  175. }
  176. }
  177. } else {
  178. match cluster_name {
  179. Some(ref name) => {
  180. let cluster = select_cluster_by_name(&config, name)?;
  181. docker::health::health_check(&config, &cluster, dry_run).await?;
  182. }
  183. None => {
  184. for cluster in &config.clusters {
  185. docker::health::health_check(&config, cluster, dry_run).await?;
  186. }
  187. docker::health::health_summary(&config).await?;
  188. }
  189. }
  190. }
  191. }
  192. Commands::Doctor {
  193. recipe,
  194. cluster,
  195. repair,
  196. } => {
  197. doctor::doctor(&config, &recipe, &cluster, repair, dry_run).await?;
  198. }
  199. Commands::Tmux(tmux_cmd) => {
  200. crate::tmux::handle_tmux(&config, tmux_cmd, dry_run).await?;
  201. }
  202. Commands::InitHostKeys { cluster } => {
  203. host_keys::init_host_keys(
  204. &config,
  205. cluster.as_deref(),
  206. config_path.to_str().unwrap_or("config.toml"),
  207. )
  208. .await?;
  209. }
  210. Commands::Exec {
  211. cluster,
  212. recipe,
  213. node,
  214. alias,
  215. command,
  216. } => {
  217. let (cluster, _recipe) =
  218. exec::resolve_target(&config, cluster.as_deref(), recipe.as_deref()).await?;
  219. // Resolve command: alias takes precedence, otherwise join
  220. // the trailing positional args into a single command line.
  221. let cmd_str = exec::resolve_command(&config, alias.as_deref(), &command)?;
  222. exec::run(&config, &cluster, node.as_deref(), &cmd_str, dry_run).await?;
  223. }
  224. Commands::Power { action } => match action {
  225. cli::PowerAction::Off { cluster, node } => {
  226. let cluster = select_cluster_by_name(&config, &cluster)?;
  227. power::power_off(&config, &cluster, node.as_deref(), dry_run).await?;
  228. }
  229. cli::PowerAction::On { cluster, node } => {
  230. let cluster = select_cluster_by_name(&config, &cluster)?;
  231. power::power_on(&config, &cluster, node.as_deref(), dry_run).await?;
  232. }
  233. cli::PowerAction::Switch { from, to } => {
  234. let from = select_cluster_by_name(&config, &from)?;
  235. let to = select_cluster_by_name(&config, &to)?;
  236. power::power_switch(&config, &from, &to, dry_run).await?;
  237. }
  238. },
  239. }
  240. Ok(())
  241. }
  242. /// Resolve a cluster for container operations (stop/logs).
  243. /// When `auto`, tries live container label lookup first, then falls back
  244. /// to config-based auto-selection (for dry-run / offline scenarios).
  245. use std::collections::HashSet;
  246. async fn resolve_cluster_for_op(
  247. config: &Config,
  248. recipe_name: &str,
  249. cluster_name: &str,
  250. ) -> Result<Cluster> {
  251. if cluster_name != "auto" {
  252. let recipe = load_recipe(recipe_name).await?;
  253. let (cluster, _) = resolve_cluster(config, &recipe, cluster_name, &HashSet::new())?;
  254. return Ok(cluster);
  255. }
  256. // Try live container label lookup first
  257. if let Ok(c) = docker::resolve_cluster_by_container_label(config, recipe_name).await {
  258. return Ok(c.clone());
  259. }
  260. // Fall back to config-based auto (dry-run / containers not running)
  261. let recipe = load_recipe(recipe_name).await?;
  262. let (cluster, _) = resolve_cluster(config, &recipe, "auto", &HashSet::new())?;
  263. Ok(cluster)
  264. }