1mod profiles;
2
3use std::path::{Path, PathBuf};
4use std::time::Duration;
5
6use clap::{Parser, Subcommand};
7
8use crate::config::AppConfig;
9use crate::core::ProxyCore;
10use crate::core::xray::XrayCore;
11use crate::engine::Watchdog;
12use crate::error::{PilotError, Result};
13use crate::notify::bale::BaleNotifier;
14use crate::notify::{AlertEvent, AlertSeverity, Notifier};
15use crate::probe::HealthProbe;
16use crate::probe::http::HttpHealthProbe;
17
18#[derive(Debug, Parser)]
19#[command(
20 name = "proxy-pilot",
21 version,
22 about = "Proxy health monitor and automatic failover daemon"
23)]
24pub struct Cli {
25 #[command(subcommand)]
26 pub command: Commands,
27}
28
29#[derive(Debug, Subcommand)]
30pub enum Commands {
31 Setup,
33 Run {
35 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
36 config: PathBuf,
37 },
38 Status {
40 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
41 config: PathBuf,
42 },
43 Add {
45 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
46 config: PathBuf,
47 #[arg(long)]
48 name: String,
49 #[arg(long)]
50 tag: String,
51 #[arg(long)]
52 priority: Option<u32>,
53 },
54 Import {
56 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
57 config: PathBuf,
58 #[arg(short, long)]
59 file: Option<PathBuf>,
60 #[arg(long)]
62 no_benchmark: bool,
63 links: Vec<String>,
65 },
66 Remove {
68 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
69 config: PathBuf,
70 #[arg(long, required_unless_present = "all", conflicts_with = "all")]
71 name: Option<String>,
72 #[arg(long, conflicts_with = "name")]
74 all: bool,
75 },
76 List {
78 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
79 config: PathBuf,
80 },
81 Benchmark {
83 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
84 config: PathBuf,
85 },
86 Prune {
88 #[arg(short, long, default_value = "/etc/proxy-pilot/config.yaml")]
89 config: PathBuf,
90 },
91}
92
93pub async fn dispatch(cli: Cli) -> Result<()> {
94 match cli.command {
95 Commands::Setup => {
96 println!("Interactive setup wizard is planned for the next milestone.");
97 println!("For now, copy config.example.yaml to /etc/proxy-pilot/config.yaml.");
98 Ok(())
99 }
100 Commands::Run { config } => run_daemon(&config).await,
101 Commands::Status { config } => show_status(&config).await,
102 Commands::Add {
103 config,
104 name,
105 tag,
106 priority,
107 } => profiles::add_profile(&config, name, tag, priority).await,
108 Commands::Import {
109 config,
110 file,
111 no_benchmark,
112 links,
113 } => profiles::import_profiles(&config, file.as_deref(), &links, !no_benchmark).await,
114 Commands::Remove { config, name, all } => {
115 if all {
116 profiles::remove_all_profiles(&config).await
117 } else if let Some(name) = name {
118 profiles::remove_profile(&config, &name).await
119 } else {
120 Err(PilotError::Config(
121 "either --name <NAME> or --all must be provided".into(),
122 ))
123 }
124 }
125 Commands::List { config } => profiles::list_profiles(&config).await,
126 Commands::Benchmark { config } => profiles::run_benchmark(&config, false).await,
127 Commands::Prune { config } => profiles::run_benchmark(&config, true).await,
128 }
129}
130
131pub(super) fn build_core(cfg: &AppConfig) -> Result<Box<dyn ProxyCore>> {
132 match cfg.core.kind.as_str() {
133 "xray" => Ok(Box::new(XrayCore::new(
134 &cfg.core.binary_path,
135 &cfg.core.config_path,
136 cfg.core.service_name.clone(),
137 ))),
138 other => Err(PilotError::Config(format!(
139 "unsupported core kind: {other}"
140 ))),
141 }
142}
143
144pub(super) fn build_notifiers(cfg: &AppConfig) -> Result<Vec<Box<dyn Notifier>>> {
145 let mut list: Vec<Box<dyn Notifier>> = Vec::new();
146 if let Some(bale) = &cfg.notify.bale
147 && bale.enabled
148 {
149 list.push(Box::new(BaleNotifier::new(
150 bale.resolved_token(),
151 bale.chat_id.clone(),
152 )?));
153 }
154 Ok(list)
155}
156
157pub(super) async fn notify_all(notifiers: &[Box<dyn Notifier>], event: &AlertEvent) {
158 for notifier in notifiers {
159 if let Err(err) = notifier.send(event).await {
160 tracing::warn!(
161 channel = notifier.channel_name(),
162 error = %err,
163 "failed to send alert notification"
164 );
165 }
166 }
167}
168
169async fn run_daemon(config_path: &Path) -> Result<()> {
170 let cfg = loop {
171 let raw = AppConfig::load_raw(config_path).await?;
172 let notifiers = build_notifiers(&raw)?;
173 if !raw.profiles.is_empty() {
174 raw.validate()?;
175 break raw;
176 }
177 let reminder_secs = raw.notify.empty_profiles_reminder_secs;
178 if reminder_secs > 0 {
179 notify_all(
180 ¬ifiers,
181 &AlertEvent {
182 severity: AlertSeverity::Critical,
183 title: "No proxy profiles configured".into(),
184 message: "0 proxy profiles found in config.yaml. Please import new profiles (`proxy-pilot import`).".into(),
185 },
186 )
187 .await;
188 }
189 let wait_secs = if reminder_secs > 0 { reminder_secs } else { 30 };
190 tracing::warn!(
191 retry_secs = wait_secs,
192 "no proxy profiles configured; waiting before re-checking config"
193 );
194 tokio::time::sleep(Duration::from_secs(wait_secs)).await;
195 };
196 let notifiers = build_notifiers(&cfg)?;
197 let timeout = Duration::from_secs(cfg.probe.timeout_secs);
198 let core = build_core(&cfg)?;
199 let probe: Box<dyn HealthProbe> =
200 Box::new(HttpHealthProbe::new(&cfg.core.local_proxy, timeout)?);
201
202 let mut watchdog = Watchdog::new(cfg, core, probe, notifiers)
203 .with_direct_probe(Box::new(HttpHealthProbe::direct(timeout)?))
204 .with_periodic_benchmark(
205 Some(config_path.to_path_buf()),
206 Box::new(move |endpoint| Ok(Box::new(HttpHealthProbe::new(endpoint, timeout)?))),
207 );
208 watchdog.run_forever().await
209}
210
211async fn show_status(config_path: &Path) -> Result<()> {
212 let cfg = AppConfig::load_raw(config_path).await?;
213 let core = build_core(&cfg)?;
214 let installed = core.is_installed().await;
215 let active = core.active_profile().await.unwrap_or(None);
216
217 println!("Core: {} (installed: {installed})", core.name());
218 println!("Active: {}", active.as_deref().unwrap_or("unknown"));
219 println!("Profiles: {}", cfg.profiles.len());
220 println!("Targets: {}", cfg.probe.targets.len());
221 Ok(())
222}