main.rs 10 KB

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