main.rs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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, dry_run).await?;
  93. }
  94. }
  95. Commands::Logs {
  96. recipe: recipe_name,
  97. cluster,
  98. follow,
  99. } => {
  100. let cluster = resolve_cluster_for_op(&config, &recipe_name, &cluster).await?;
  101. docker::show_logs(&config, &cluster, &recipe_name, follow, dry_run).await?;
  102. }
  103. Commands::Stop {
  104. recipe: recipe_name,
  105. cluster,
  106. node,
  107. } => {
  108. let cluster = resolve_cluster_for_op(&config, &recipe_name, &cluster).await?;
  109. docker::stop_cluster(&config, &cluster, &recipe_name, node.as_deref(), dry_run).await?;
  110. }
  111. Commands::Health {
  112. cluster: cluster_name,
  113. fingerprint,
  114. } => {
  115. if fingerprint {
  116. let clusters_to_check: Vec<Cluster> = match &cluster_name {
  117. Some(name) => vec![select_cluster_by_name(&config, name)?],
  118. None => config.clusters.clone(),
  119. };
  120. for cluster in &clusters_to_check {
  121. println!("\n=== Кластер: {} ===", cluster.name);
  122. for node in &cluster.nodes {
  123. match fetch_host_key(&config, node).await {
  124. Ok(fp) => {
  125. println!("{} ({}) -> host_key = \"{}\"", node.name, node.ssh_ip, fp)
  126. }
  127. Err(e) => println!("{} ({}) -> error: {}", node.name, node.ssh_ip, e),
  128. }
  129. }
  130. }
  131. } else {
  132. match cluster_name {
  133. Some(ref name) => {
  134. let cluster = select_cluster_by_name(&config, name)?;
  135. docker::health::health_check(&config, &cluster, dry_run).await?;
  136. }
  137. None => {
  138. for cluster in &config.clusters {
  139. docker::health::health_check(&config, cluster, dry_run).await?;
  140. }
  141. }
  142. }
  143. }
  144. }
  145. Commands::Doctor {
  146. recipe,
  147. cluster,
  148. repair,
  149. } => {
  150. doctor::doctor(&config, &recipe, &cluster, repair, dry_run).await?;
  151. }
  152. Commands::Tmux(tmux_cmd) => {
  153. crate::tmux::handle_tmux(&config, tmux_cmd, dry_run).await?;
  154. }
  155. Commands::InitHostKeys { cluster } => {
  156. host_keys::init_host_keys(
  157. &config,
  158. cluster.as_deref(),
  159. config_path.to_str().unwrap_or("config.toml"),
  160. )
  161. .await?;
  162. }
  163. Commands::Exec {
  164. cluster,
  165. recipe,
  166. node,
  167. alias,
  168. command,
  169. } => {
  170. let (cluster, _recipe) =
  171. exec::resolve_target(&config, cluster.as_deref(), recipe.as_deref()).await?;
  172. // Resolve command: alias takes precedence, otherwise join
  173. // the trailing positional args into a single command line.
  174. let cmd_str = exec::resolve_command(&config, alias.as_deref(), &command)?;
  175. exec::run(&config, &cluster, node.as_deref(), &cmd_str, dry_run).await?;
  176. }
  177. Commands::Power { action } => match action {
  178. cli::PowerAction::Off { cluster, node } => {
  179. let cluster = select_cluster_by_name(&config, &cluster)?;
  180. power::power_off(&config, &cluster, node.as_deref(), dry_run).await?;
  181. }
  182. cli::PowerAction::On { cluster, node } => {
  183. let cluster = select_cluster_by_name(&config, &cluster)?;
  184. power::power_on(&config, &cluster, node.as_deref(), dry_run).await?;
  185. }
  186. cli::PowerAction::Switch { from, to } => {
  187. let from = select_cluster_by_name(&config, &from)?;
  188. let to = select_cluster_by_name(&config, &to)?;
  189. power::power_switch(&config, &from, &to, dry_run).await?;
  190. }
  191. },
  192. }
  193. Ok(())
  194. }
  195. /// Resolve a cluster for container operations (stop/logs).
  196. /// When `auto`, tries live container label lookup first, then falls back
  197. /// to config-based auto-selection (for dry-run / offline scenarios).
  198. async fn resolve_cluster_for_op(
  199. config: &Config,
  200. recipe_name: &str,
  201. cluster_name: &str,
  202. ) -> Result<Cluster> {
  203. if cluster_name != "auto" {
  204. let recipe = load_recipe(recipe_name).await?;
  205. let (cluster, _) = resolve_cluster(config, &recipe, cluster_name)?;
  206. return Ok(cluster);
  207. }
  208. // Try live container label lookup first
  209. if let Ok(c) = docker::resolve_cluster_by_container_label(config, recipe_name).await {
  210. return Ok(c.clone());
  211. }
  212. // Fall back to config-based auto (dry-run / containers not running)
  213. let recipe = load_recipe(recipe_name).await?;
  214. let (cluster, _) = resolve_cluster(config, &recipe, "auto")?;
  215. Ok(cluster)
  216. }