优化: ssh/mongo/redis-proxy 超时分级与日志默认开
- ssh: exec_timeout_secs 600s(408断会话)/idle 300→1800s/日志级别规则/截断500→2000 - mongo/redis: query_timeout 60s + idle_timeout 落配置 - 四代理: 日志默认开启(default_log_path exe同目录logs/),未设env也记录 - mysql: default_log_path 共享实现注释同步
This commit is contained in:
1 parent
ecdebdd6c0
commit
95dfe8504d
20 files changed
+3494
-121
No files matched your search
Generated
+3023
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "ssh-proxy"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
description = "SSH HTTP proxy with session pooling"
|
||||
|
||||
|
||||
+23
-2
@@ -76,12 +76,28 @@ impl Cli {
|
||||
}
|
||||
|
||||
/// 执行远程命令
|
||||
pub fn exec(&self, server: &str, command: &str, format: &str) -> Result<()> {
|
||||
pub fn exec(&self, server: &str, command: &str, format: &str, bg: bool) -> Result<()> {
|
||||
let start = Instant::now();
|
||||
|
||||
// --bg: nohup 断流拉起远端长命令, 立即返回日志路径(防 exec 会话超时连带杀进程)
|
||||
let command = if bg {
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs())
|
||||
.unwrap_or(0);
|
||||
format!(
|
||||
"nohup sh -c {} > /tmp/sshproxy-bg-{}.log 2>&1 < /dev/null & echo BG-STARTED pid=$! log=/tmp/sshproxy-bg-{}.log",
|
||||
Self::sh_quote(command),
|
||||
ts,
|
||||
ts
|
||||
)
|
||||
} else {
|
||||
command.to_string()
|
||||
};
|
||||
|
||||
let body = serde_json::to_string(&ExecRequest {
|
||||
server: server.to_string(),
|
||||
command: command.to_string(),
|
||||
command,
|
||||
})?;
|
||||
|
||||
let response = ureq::post(&format!("{}/exec", self.server))
|
||||
@@ -232,6 +248,11 @@ impl Cli {
|
||||
}
|
||||
}
|
||||
|
||||
/// sh 单引号转义标准实现: ' -> '\'' (关闭引号+转义引号+重开引号)
|
||||
fn sh_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', r"'\''"))
|
||||
}
|
||||
|
||||
/// 上传文件到远程服务器
|
||||
pub fn upload(&self, server: &str, local_path: &str, remote_path: &str, concurrency: usize) -> Result<()> {
|
||||
let body = serde_json::to_string(&UploadRequest {
|
||||
|
||||
@@ -21,16 +21,21 @@ pub struct PoolConfig {
|
||||
pub idle_timeout_secs: u64,
|
||||
#[serde(default = "default_check_interval")]
|
||||
pub check_interval_secs: u64,
|
||||
/// 单次 exec/upload/download 执行上限(秒):超时返回 408,防远端命令挂死通道
|
||||
#[serde(default = "default_exec_timeout")]
|
||||
pub exec_timeout_secs: u64,
|
||||
}
|
||||
|
||||
fn default_idle_timeout() -> u64 { 300 }
|
||||
fn default_idle_timeout() -> u64 { 1800 }
|
||||
fn default_check_interval() -> u64 { 60 }
|
||||
fn default_exec_timeout() -> u64 { 600 }
|
||||
|
||||
impl Default for PoolConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
idle_timeout_secs: default_idle_timeout(),
|
||||
check_interval_secs: default_check_interval(),
|
||||
exec_timeout_secs: default_exec_timeout(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,11 +82,15 @@ pub async fn exec(
|
||||
let result = manager.exec(&req.server, &req.command).await
|
||||
.map_err(|e| {
|
||||
logger.log(&LogEntry::new("/exec", "http").with_server(&req.server).with_command(&req.command).with_error(&e.to_string()));
|
||||
// 执行超时(远端命令挂死/超 deadline)返回 408,与参数错(400)区分
|
||||
if e.to_string().starts_with("EXEC_TIMED_OUT") {
|
||||
return (StatusCode::REQUEST_TIMEOUT, Json(ErrorResponse::new(&e.to_string())));
|
||||
}
|
||||
let usage = format!(
|
||||
"Usage: POST /exec {{\"server\": \"server_name\", \"command\": \"your command\"}}\n\nAvailable servers: {}",
|
||||
server_names
|
||||
);
|
||||
error_response_with_usage(&e.to_string(), &usage)
|
||||
manager_error(manager, &req.server, &e.to_string(), usage)
|
||||
})?;
|
||||
|
||||
let duration_ms = start.elapsed().as_millis() as u64;
|
||||
@@ -113,6 +117,45 @@ pub async fn servers(
|
||||
Json(ServersResponse { servers: manager.list_servers() })
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct EndpointDoc {
|
||||
pub method: &'static str,
|
||||
pub path: &'static str,
|
||||
pub desc: &'static str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub request: Option<&'static str>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct HelpResponse {
|
||||
pub service: &'static str,
|
||||
pub version: &'static str,
|
||||
pub endpoints: Vec<EndpointDoc>,
|
||||
pub notes: Vec<&'static str>,
|
||||
}
|
||||
|
||||
/// GET /_help - self-describing API guide for AI agents and humans.
|
||||
pub async fn help() -> Json<HelpResponse> {
|
||||
Json(HelpResponse {
|
||||
service: "ssh-proxy",
|
||||
version: env!("CARGO_PKG_VERSION"),
|
||||
endpoints: vec![
|
||||
EndpointDoc { method: "GET", path: "/_help", desc: "API guide (this)", request: None },
|
||||
EndpointDoc { method: "GET", path: "/health", desc: "Health check", request: None },
|
||||
EndpointDoc { method: "GET", path: "/servers", desc: "List configured servers (name/host/port/user/status)", request: None },
|
||||
EndpointDoc { method: "POST", path: "/exec", desc: "Execute remote command", request: Some(r#"{"server":"<name>","command":"<cmd>"}"#) },
|
||||
EndpointDoc { method: "POST", path: "/upload", desc: "Upload file via SFTP (parallel channels)", request: Some(r#"{"server":"<name>","localPath":"<local>","remotePath":"<remote>"}"#) },
|
||||
EndpointDoc { method: "POST", path: "/download", desc: "Download file via SFTP (parallel channels)", request: Some(r#"{"server":"<name>","remotePath":"<remote>","localPath":"<local>"}"#) },
|
||||
EndpointDoc { method: "POST", path: "/servers/add", desc: "Add server dynamically (temporary, lost on restart)", request: Some(r#"{"name":"x","host":"1.2.3.4","port":22,"user":"root","password":"..."}"#) },
|
||||
],
|
||||
notes: vec![
|
||||
"Workflow: GET /servers to pick a `name`, then pass it as `server` to /exec, /upload or /download.",
|
||||
"CLI equivalents: ssh-proxy exec -n <name> -c \"<cmd>\" | ssh-proxy servers | ssh-proxy upload/download",
|
||||
"Sessions are lazy + pooled; status pending = configured but not connected yet.",
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn add_server(
|
||||
State(state): State<AppState>,
|
||||
Json(req): Json<AddServerRequest>,
|
||||
@@ -238,7 +281,7 @@ pub async fn upload(
|
||||
"Usage: POST /upload {{\"server\": \"name\", \"localPath\": \"./file.txt\", \"remotePath\": \"/remote/file.txt\"}}\n\nAvailable servers: {}",
|
||||
server_names
|
||||
);
|
||||
error_response_with_usage(&e.to_string(), &usage)
|
||||
manager_error(manager, &req.server, &e.to_string(), usage)
|
||||
})?;
|
||||
|
||||
let duration_ms = result.duration_ms;
|
||||
@@ -273,7 +316,7 @@ pub async fn download(
|
||||
"Usage: POST /download {{\"server\": \"name\", \"remotePath\": \"/remote/file.txt\", \"localPath\": \"./file.txt\"}}\n\nAvailable servers: {}",
|
||||
server_names
|
||||
);
|
||||
error_response_with_usage(&e.to_string(), &usage)
|
||||
manager_error(manager, &req.server, &e.to_string(), usage)
|
||||
})?;
|
||||
|
||||
let duration_ms = result.duration_ms;
|
||||
@@ -327,6 +370,17 @@ fn error_response_with_usage(msg: &str, usage: &str) -> (StatusCode, Json<ErrorR
|
||||
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage)))
|
||||
}
|
||||
|
||||
// 执行类错误分流:server 名不存在才提示用法(用户可能拼错名/临时连接丢失);
|
||||
// 名字存在但执行失败(文件不存在/连接断等)只给原始错误,避免 Usage 提示把排查带偏
|
||||
fn manager_error(manager: &SessionManager, server: &str, e: &str, usage: String) -> (StatusCode, Json<ErrorResponse>) {
|
||||
let known = manager.list_servers().iter().any(|s| s.name == server);
|
||||
if known {
|
||||
error_response(e)
|
||||
} else {
|
||||
error_response_with_usage(e, &usage)
|
||||
}
|
||||
}
|
||||
|
||||
fn list_server_names(manager: &SessionManager) -> String {
|
||||
manager.list_servers()
|
||||
.iter()
|
||||
|
||||
@@ -123,23 +123,22 @@ impl LogEntry {
|
||||
|
||||
pub fn with_sql(mut self, sql: &str) -> Self {
|
||||
// 截断过长的 SQL
|
||||
self.sql = Some(truncate_string(sql, 1000));
|
||||
self.sql = Some(truncate_string(sql, 2000));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_command(mut self, command: &str) -> Self {
|
||||
// 截断过长的命令
|
||||
self.command = Some(truncate_string(command, 500));
|
||||
self.command = Some(truncate_string(command, 2000));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_duration(mut self, ms: u64) -> Self {
|
||||
self.duration_ms = ms;
|
||||
// 慢请求告警: >3s 为 WARN, >10s 为 ERROR
|
||||
// 注意: 后台命令(nohup)可能耗时很长但 exitCode=0,不标记错误
|
||||
if ms > 10000 && self.level == "INFO" {
|
||||
self.level = "ERROR".to_string();
|
||||
} else if ms > 3000 && self.level == "INFO" {
|
||||
// 慢请求告警: >3s 为 WARN, >30s 为 WARN(长任务)——
|
||||
// 此前 >10s 一律标 ERROR,但 exit_code=0 的正常长命令(如 nohup 启动)
|
||||
// 被误标成失败,日志噪音大。真正的错误由 with_exit_code/with_error 判
|
||||
if ms > 3000 && self.level == "INFO" {
|
||||
self.level = "WARN".to_string();
|
||||
}
|
||||
self
|
||||
|
||||
+44
-8
@@ -8,6 +8,17 @@ use axum::{routing::{get, post}, Router};
|
||||
use clap::{Parser, Subcommand};
|
||||
use std::sync::Arc;
|
||||
|
||||
// ⚠ 共享实现,修改需同步至 mysql/mongo/redis-proxy/src/main.rs
|
||||
/// 默认请求日志路径(未设置 SSH_PROXY_LOG 时): exe同目录 logs/ssh-proxy.log
|
||||
fn default_log_path(name: &str) -> String {
|
||||
match std::env::current_exe() {
|
||||
Ok(exe) => exe.parent()
|
||||
.map(|d| d.join("logs").join(format!("{}.log", name)).to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| format!("{}.log", name)),
|
||||
Err(_) => format!("{}.log", name),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ssh-proxy")]
|
||||
#[command(about = "SSH HTTP proxy with session pooling")]
|
||||
@@ -36,6 +47,9 @@ enum Commands {
|
||||
/// Output format: text, json
|
||||
#[arg(short = 'F', long, default_value = "text")]
|
||||
format: String,
|
||||
/// 后台执行: 远端 nohup 断流拉起, 立即返回 BG-STARTED + 日志路径(长命令防会话超时连杀)
|
||||
#[arg(long)]
|
||||
bg: bool,
|
||||
},
|
||||
Servers,
|
||||
/// Upload file to remote server (SFTP)
|
||||
@@ -83,19 +97,38 @@ enum Commands {
|
||||
},
|
||||
}
|
||||
|
||||
// ⚠ 共享实现,修改需同步至 mysql/mongo/redis-proxy/src/main.rs
|
||||
/// 将相对路径基于可执行文件所在目录解析为绝对路径
|
||||
fn resolve_config_path(path: &str) -> String {
|
||||
if std::path::Path::new(path).is_absolute() || path.starts_with('~') {
|
||||
return path.to_string();
|
||||
}
|
||||
match std::env::current_exe() {
|
||||
Ok(exe) => {
|
||||
if let Some(dir) = exe.parent() {
|
||||
dir.join(path).to_string_lossy().into_owned()
|
||||
} else {
|
||||
path.to_string()
|
||||
}
|
||||
}
|
||||
Err(_) => path.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = Args::parse();
|
||||
let config_path = resolve_config_path(&args.config);
|
||||
match args.command {
|
||||
Some(Commands::Server { port, host }) => run_server(&args.config, port, host).await,
|
||||
Some(Commands::Exec { name, command, format }) => run_cli_exec(&args.server, &name, &command, &format),
|
||||
Some(Commands::Server { port, host }) => run_server(&config_path, port, host).await,
|
||||
Some(Commands::Exec { name, command, format, bg }) => run_cli_exec(&args.server, &name, &command, &format, bg),
|
||||
Some(Commands::Servers) => run_cli_servers(&args.server),
|
||||
Some(Commands::Upload { name, src, dst, concurrency }) => run_cli_transfer(&args.server, "upload", &name, &src, &dst, concurrency),
|
||||
Some(Commands::Download { name, src, dst, concurrency }) => run_cli_transfer(&args.server, "download", &name, &src, &dst, concurrency),
|
||||
Some(Commands::AddServer { name, host, port, user, password, private_key }) => {
|
||||
run_cli_add_server(&args.server, name, host, port, user, password, private_key)
|
||||
}
|
||||
None => run_server(&args.config, None, None).await,
|
||||
None => run_server(&config_path, None, None).await,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,14 +139,15 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
|
||||
if let Some(h) = host { config.server.host = h; }
|
||||
|
||||
// 初始化日志
|
||||
let log_path = std::env::var("SSH_PROXY_LOG").ok();
|
||||
let log_path = std::env::var("SSH_PROXY_LOG").ok()
|
||||
.or_else(|| Some(default_log_path("ssh-proxy")));
|
||||
let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref()));
|
||||
if logger.is_enabled() {
|
||||
println!("Request logging: enabled");
|
||||
}
|
||||
|
||||
println!("Initializing SSH sessions...\n");
|
||||
let manager = Arc::new(session::SessionManager::new(&config.servers)?);
|
||||
let manager = Arc::new(session::SessionManager::new(&config.servers, config.pool.exec_timeout_secs)?);
|
||||
|
||||
let manager_clone = manager.clone();
|
||||
let idle_timeout = config.pool.idle_timeout_secs;
|
||||
@@ -133,6 +167,7 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
|
||||
.route("/upload", post(handler::upload))
|
||||
.route("/download", post(handler::download))
|
||||
.route("/health", get(handler::health))
|
||||
.route("/_help", get(handler::help))
|
||||
.with_state(Arc::new((manager, logger)));
|
||||
|
||||
let addr = format!("{}:{}", config.server.host, config.server.port);
|
||||
@@ -145,6 +180,7 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
|
||||
println!(" POST /download - Download file (SFTP)");
|
||||
println!(" POST /servers/add - Add server (temporary)");
|
||||
println!(" GET /servers - List all servers");
|
||||
println!(" GET /_help - API guide (endpoints + usage)");
|
||||
println!(" GET /health - Health check");
|
||||
println!("\nCLI Usage:");
|
||||
println!(" ssh-proxy exec -n flux_dev -c \"docker ps\"");
|
||||
@@ -156,7 +192,7 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn run_cli_exec(server_url: &str, server: &str, command: &str, format: &str) -> anyhow::Result<()> {
|
||||
fn run_cli_exec(server_url: &str, server: &str, command: &str, format: &str, bg: bool) -> anyhow::Result<()> {
|
||||
let cli = cli::Cli::new(Some(server_url.to_string()));
|
||||
if !cli.check_server()? {
|
||||
eprintln!();
|
||||
@@ -170,7 +206,7 @@ fn run_cli_exec(server_url: &str, server: &str, command: &str, format: &str) ->
|
||||
eprintln!("配置文件中的服务器信息见: ssh-proxy.toml");
|
||||
anyhow::bail!("Proxy server not running at {}", server_url);
|
||||
}
|
||||
cli.exec(server, command, format)
|
||||
cli.exec(server, command, format, bg)
|
||||
}
|
||||
|
||||
fn run_cli_servers(server_url: &str) -> anyhow::Result<()> {
|
||||
@@ -217,4 +253,4 @@ fn run_cli_add_server(
|
||||
anyhow::bail!("Proxy server not running at {}", server_url);
|
||||
}
|
||||
cli.add_server(name, host, port, user, password, private_key)
|
||||
}
|
||||
}
|
||||
+28
-17
@@ -20,6 +20,7 @@ struct SessionState {
|
||||
pub struct SessionManager {
|
||||
sessions: Mutex<HashMap<String, SessionState>>,
|
||||
configs: Mutex<HashMap<String, SshServerConfig>>,
|
||||
exec_timeout_secs: u64,
|
||||
}
|
||||
|
||||
// 简单的 SSH 客户端处理器
|
||||
@@ -37,7 +38,7 @@ impl client::Handler for Client {
|
||||
}
|
||||
|
||||
impl SessionManager {
|
||||
pub fn new(configs: &[SshServerConfig]) -> Result<Self> {
|
||||
pub fn new(configs: &[SshServerConfig], exec_timeout_secs: u64) -> Result<Self> {
|
||||
let mut config_map = HashMap::new();
|
||||
for cfg in configs {
|
||||
config_map.insert(cfg.name.clone(), cfg.clone());
|
||||
@@ -47,6 +48,7 @@ impl SessionManager {
|
||||
Ok(Self {
|
||||
sessions: Mutex::new(HashMap::new()),
|
||||
configs: Mutex::new(config_map),
|
||||
exec_timeout_secs,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,25 +153,34 @@ impl SessionManager {
|
||||
let mut stderr = String::new();
|
||||
let mut exit_code: i32 = -1;
|
||||
|
||||
// 读取输出
|
||||
while let Some(msg) = channel.wait().await {
|
||||
match msg {
|
||||
russh::ChannelMsg::Data { data } => {
|
||||
stdout.push_str(&String::from_utf8_lossy(&data));
|
||||
}
|
||||
russh::ChannelMsg::ExtendedData { data, ext } => {
|
||||
if ext == 1 { // stderr
|
||||
stderr.push_str(&String::from_utf8_lossy(&data));
|
||||
// 读取输出,带执行上限:远端命令挂死(如 nohup 子进程未正确脱离通道)时
|
||||
// wait() 永不返回——实测日志曾挂 6.7h(durationMs 24010328)。超时放弃通道
|
||||
// 并断开会话(通道状态不可信),返回 EXEC_TIMED_OUT 供 handler 定级 408
|
||||
let deadline = Duration::from_secs(self.exec_timeout_secs);
|
||||
let wait_loop = async {
|
||||
while let Some(msg) = channel.wait().await {
|
||||
match msg {
|
||||
russh::ChannelMsg::Data { data } => {
|
||||
stdout.push_str(&String::from_utf8_lossy(&data));
|
||||
}
|
||||
russh::ChannelMsg::ExtendedData { data, ext } => {
|
||||
if ext == 1 { // stderr
|
||||
stderr.push_str(&String::from_utf8_lossy(&data));
|
||||
}
|
||||
}
|
||||
russh::ChannelMsg::ExitStatus { exit_status } => {
|
||||
exit_code = exit_status as i32;
|
||||
}
|
||||
russh::ChannelMsg::Eof => {
|
||||
// 继续等待 ExitStatus(流结束但进程可能未退出)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
russh::ChannelMsg::ExitStatus { exit_status } => {
|
||||
exit_code = exit_status as i32;
|
||||
}
|
||||
russh::ChannelMsg::Eof => {
|
||||
// 继续等待 ExitStatus
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(deadline, wait_loop).await.is_err() {
|
||||
self.remove_session(name).await;
|
||||
anyhow::bail!("EXEC_TIMED_OUT: 命令超过 {}s 未完成(可能挂死或确需更久,可在 toml [pool] exec_timeout_secs 调整)", deadline.as_secs());
|
||||
}
|
||||
|
||||
Ok(ExecResult {
|
||||
|
||||
Reference in new issue
Block a user