优化: 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:
lxy committed 2026-10-28 22:56:02 +08:00
1 parent ecdebdd6c0
commit 95dfe8504d
20 files changed
+3494 -121

No files matched your search

+4
View File
@@ -19,16 +19,20 @@ pub struct PoolConfig {
pub idle_timeout_secs: u64, pub idle_timeout_secs: u64,
#[serde(default = "default_check_interval")] #[serde(default = "default_check_interval")]
pub check_interval_secs: u64, pub check_interval_secs: u64,
#[serde(default = "default_query_timeout")]
pub query_timeout_secs: u64,
} }
fn default_idle_timeout() -> u64 { 300 } fn default_idle_timeout() -> u64 { 300 }
fn default_check_interval() -> u64 { 60 } fn default_check_interval() -> u64 { 60 }
fn default_query_timeout() -> u64 { 60 }
impl Default for PoolConfig { impl Default for PoolConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
idle_timeout_secs: default_idle_timeout(), idle_timeout_secs: default_idle_timeout(),
check_interval_secs: default_check_interval(), check_interval_secs: default_check_interval(),
query_timeout_secs: default_query_timeout(),
} }
} }
} }
+5
View File
@@ -94,6 +94,11 @@ impl ConnectionManager {
}).collect() }).collect()
} }
/// 单次操作执行超时(秒),用于 API handler 的 tokio::time::timeout
pub fn query_timeout_secs(&self) -> u64 {
self.pool_config.query_timeout_secs
}
pub fn cleanup_idle(&self) { pub fn cleanup_idle(&self) {
let mut clients = self.clients.lock().unwrap(); let mut clients = self.clients.lock().unwrap();
let now = Instant::now(); let now = Instant::now();
+107 -51
View File
@@ -7,7 +7,7 @@ use futures_util::TryStreamExt;
use mongodb::bson::Document; use mongodb::bson::Document;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::{Duration, Instant};
use crate::db::ConnectionManager; use crate::db::ConnectionManager;
use crate::logger::{LogEntry, RequestLogger}; use crate::logger::{LogEntry, RequestLogger};
@@ -197,19 +197,27 @@ pub async fn find(
if let Some(l) = req.limit { find = find.limit(l); } if let Some(l) = req.limit { find = find.limit(l); }
if let Some(s) = req.skip { find = find.skip(s); } if let Some(s) = req.skip { find = find.skip(s); }
let mut cursor = find.await let timeout_secs = manager.query_timeout_secs();
.map_err(|e| { let operation = async {
let mut cursor = find.await?;
let mut documents = Vec::new();
while let Some(result) = cursor.try_next().await? {
documents.push(bson_to_json(&result));
}
Ok::<_, mongodb::error::Error>(documents)
};
let documents = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
Ok(Ok(documents)) => documents,
Ok(Err(e)) => {
logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string())); logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
error_response(&e.to_string()) return Err(error_response(&e.to_string()));
})?; }
Err(_) => {
let mut documents = Vec::new(); let msg = format!("操作超时(>{}s)", timeout_secs);
while let Some(result) = cursor.try_next().await.map_err(|e: mongodb::error::Error| { logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
logger.log(&LogEntry::new("/find", "http").with_conn(&req.conn).with_error(&e.to_string())); return Err(timeout_response(timeout_secs));
error_response(&e.to_string()) }
})? { };
documents.push(bson_to_json(&result));
}
let count = documents.len(); let count = documents.len();
let duration = start.elapsed(); let duration = start.elapsed();
@@ -240,11 +248,18 @@ pub async fn insert(
let db = client.database(&get_database(manager, &req.conn)); let db = client.database(&get_database(manager, &req.conn));
let coll = db.collection::<Document>(&req.collection); let coll = db.collection::<Document>(&req.collection);
let result = coll.insert_many(req.documents).await let timeout_secs = manager.query_timeout_secs();
.map_err(|e| { let result = match tokio::time::timeout(Duration::from_secs(timeout_secs), coll.insert_many(req.documents)).await {
Ok(r) => r.map_err(|e| {
logger.log(&LogEntry::new("/insert", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string())); logger.log(&LogEntry::new("/insert", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
error_response(&e.to_string()) error_response(&e.to_string())
})?; })?,
Err(_) => {
let msg = format!("操作超时(>{}s)", timeout_secs);
logger.log(&LogEntry::new("/insert", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
return Err(timeout_response(timeout_secs));
}
};
let inserted_ids: Vec<String> = result.inserted_ids.iter() let inserted_ids: Vec<String> = result.inserted_ids.iter()
.map(|(k, v)| format!("{}:{}", k, v)) .map(|(k, v)| format!("{}:{}", k, v))
@@ -278,18 +293,29 @@ pub async fn update(
let db = client.database(&get_database(manager, &req.conn)); let db = client.database(&get_database(manager, &req.conn));
let coll = db.collection::<Document>(&req.collection); let coll = db.collection::<Document>(&req.collection);
let result = if req.multi.unwrap_or(false) { let timeout_secs = manager.query_timeout_secs();
let mut cmd = coll.update_many(req.filter, req.update); let operation = async {
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); } if req.multi.unwrap_or(false) {
cmd.await let mut cmd = coll.update_many(req.filter, req.update);
} else { if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
let mut cmd = coll.update_one(req.filter, req.update); cmd.await
if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); } } else {
cmd.await let mut cmd = coll.update_one(req.filter, req.update);
}.map_err(|e| { if req.upsert.unwrap_or(false) { cmd = cmd.upsert(true); }
logger.log(&LogEntry::new("/update", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string())); cmd.await
error_response(&e.to_string()) }
})?; };
let result = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
Ok(r) => r.map_err(|e| {
logger.log(&LogEntry::new("/update", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
error_response(&e.to_string())
})?,
Err(_) => {
let msg = format!("操作超时(>{}s)", timeout_secs);
logger.log(&LogEntry::new("/update", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
return Err(timeout_response(timeout_secs));
}
};
let upserted_id = result.upserted_id.map(|id| format!("{:?}", id)); let upserted_id = result.upserted_id.map(|id| format!("{:?}", id));
let duration = start.elapsed(); let duration = start.elapsed();
@@ -324,14 +350,25 @@ pub async fn delete(
let db = client.database(&get_database(manager, &req.conn)); let db = client.database(&get_database(manager, &req.conn));
let coll = db.collection::<Document>(&req.collection); let coll = db.collection::<Document>(&req.collection);
let result = if req.multi.unwrap_or(false) { let timeout_secs = manager.query_timeout_secs();
coll.delete_many(req.filter).await let operation = async {
} else { if req.multi.unwrap_or(false) {
coll.delete_one(req.filter).await coll.delete_many(req.filter).await
}.map_err(|e| { } else {
logger.log(&LogEntry::new("/delete", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string())); coll.delete_one(req.filter).await
error_response(&e.to_string()) }
})?; };
let result = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
Ok(r) => r.map_err(|e| {
logger.log(&LogEntry::new("/delete", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
error_response(&e.to_string())
})?,
Err(_) => {
let msg = format!("操作超时(>{}s)", timeout_secs);
logger.log(&LogEntry::new("/delete", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
return Err(timeout_response(timeout_secs));
}
};
let deleted_count = result.deleted_count; let deleted_count = result.deleted_count;
let duration = start.elapsed(); let duration = start.elapsed();
@@ -361,19 +398,27 @@ pub async fn aggregate(
let db = client.database(&get_database(manager, &req.conn)); let db = client.database(&get_database(manager, &req.conn));
let coll = db.collection::<Document>(&req.collection); let coll = db.collection::<Document>(&req.collection);
let mut cursor = coll.aggregate(req.pipeline).await let timeout_secs = manager.query_timeout_secs();
.map_err(|e| { let operation = async {
let mut cursor = coll.aggregate(req.pipeline).await?;
let mut documents = Vec::new();
while let Some(result) = cursor.try_next().await? {
documents.push(bson_to_json(&result));
}
Ok::<_, mongodb::error::Error>(documents)
};
let documents = match tokio::time::timeout(Duration::from_secs(timeout_secs), operation).await {
Ok(Ok(documents)) => documents,
Ok(Err(e)) => {
logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string())); logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
error_response(&e.to_string()) return Err(error_response(&e.to_string()));
})?; }
Err(_) => {
let mut documents = Vec::new(); let msg = format!("操作超时(>{}s)", timeout_secs);
while let Some(result) = cursor.try_next().await.map_err(|e: mongodb::error::Error| { logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
logger.log(&LogEntry::new("/aggregate", "http").with_conn(&req.conn).with_error(&e.to_string())); return Err(timeout_response(timeout_secs));
error_response(&e.to_string()) }
})? { };
documents.push(bson_to_json(&result));
}
let count = documents.len(); let count = documents.len();
let duration = start.elapsed(); let duration = start.elapsed();
@@ -404,11 +449,18 @@ pub async fn count(
let db = client.database(&get_database(manager, &req.conn)); let db = client.database(&get_database(manager, &req.conn));
let coll = db.collection::<Document>(&req.collection); let coll = db.collection::<Document>(&req.collection);
let count = coll.count_documents(req.filter.unwrap_or_default()).await let timeout_secs = manager.query_timeout_secs();
.map_err(|e| { let count = match tokio::time::timeout(Duration::from_secs(timeout_secs), coll.count_documents(req.filter.unwrap_or_default())).await {
Ok(r) => r.map_err(|e| {
logger.log(&LogEntry::new("/count", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string())); logger.log(&LogEntry::new("/count", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&e.to_string()));
error_response(&e.to_string()) error_response(&e.to_string())
})?; })?,
Err(_) => {
let msg = format!("操作超时(>{}s)", timeout_secs);
logger.log(&LogEntry::new("/count", "http").with_conn(&req.conn).with_command(&format!("{}.{}", req.conn, req.collection)).with_error(&msg));
return Err(timeout_response(timeout_secs));
}
};
let duration = start.elapsed(); let duration = start.elapsed();
@@ -482,6 +534,10 @@ fn error_response_with_usage(msg: &str, usage: &str) -> (StatusCode, Json<ErrorR
(StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage))) (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage)))
} }
fn timeout_response(secs: u64) -> (StatusCode, Json<ErrorResponse>) {
(StatusCode::REQUEST_TIMEOUT, Json(ErrorResponse::new(&format!("操作超时(>{}s)", secs))))
}
fn list_conn_names(manager: &ConnectionManager) -> String { fn list_conn_names(manager: &ConnectionManager) -> String {
manager.list_connections() manager.list_connections()
.iter() .iter()
+1 -1
View File
@@ -97,7 +97,7 @@ impl LogEntry {
} }
pub fn with_command(mut self, cmd: &str) -> Self { pub fn with_command(mut self, cmd: &str) -> Self {
self.command = Some(truncate_string(cmd, 500)); self.command = Some(truncate_string(cmd, 2000));
self self
} }
+34 -3
View File
@@ -11,6 +11,17 @@ use axum::{
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use std::sync::Arc; use std::sync::Arc;
// ⚠ 共享实现,修改需同步至 mysql/ssh/redis-proxy/src/main.rs
/// 默认请求日志路径(未设置 MONGO_PROXY_LOG 时): exe同目录 logs/mongo-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)] #[derive(Parser, Debug)]
#[command(name = "mongo-proxy")] #[command(name = "mongo-proxy")]
#[command(about = "MongoDB HTTP proxy with connection pooling")] #[command(about = "MongoDB HTTP proxy with connection pooling")]
@@ -154,13 +165,32 @@ enum Commands {
Connections, Connections,
} }
// ⚠ 共享实现,修改需同步至 mysql/ssh/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] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
let args = Args::parse(); let args = Args::parse();
let config_path = resolve_config_path(&args.config);
match args.command { match args.command {
Some(Commands::Server { port, host }) => { Some(Commands::Server { port, host }) => {
run_server(&args.config, port, host).await run_server(&config_path, port, host).await
} }
Some(Commands::Find { conn, collection, filter, projection, limit, skip, format }) => { Some(Commands::Find { conn, collection, filter, projection, limit, skip, format }) => {
run_find(&args.server, &conn, &collection, &filter, &format, projection.as_deref(), limit, skip) run_find(&args.server, &conn, &collection, &filter, &format, projection.as_deref(), limit, skip)
@@ -184,7 +214,7 @@ async fn main() -> anyhow::Result<()> {
list_connections(&args.server) list_connections(&args.server)
} }
None => { None => {
run_server(&args.config, None, None).await run_server(&config_path, None, None).await
} }
} }
} }
@@ -201,7 +231,8 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
config.server.host = host; config.server.host = host;
} }
let log_path = std::env::var("MONGO_PROXY_LOG").ok(); let log_path = std::env::var("MONGO_PROXY_LOG").ok()
.or_else(|| Some(default_log_path("mongo-proxy")));
let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref())); let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref()));
if logger.is_enabled() { if logger.is_enabled() {
println!("Request logging: enabled"); println!("Request logging: enabled");
+2 -2
View File
@@ -123,13 +123,13 @@ impl LogEntry {
pub fn with_sql(mut self, sql: &str) -> Self { pub fn with_sql(mut self, sql: &str) -> Self {
// 截断过长的 SQL // 截断过长的 SQL
self.sql = Some(truncate_string(sql, 1000)); self.sql = Some(truncate_string(sql, 2000));
self self
} }
pub fn with_command(mut self, command: &str) -> 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 self
} }
+13 -1
View File
@@ -64,6 +64,17 @@ enum Commands {
} }
// ⚠ 共享实现,修改需同步至 ssh/mongo/redis-proxy/src/main.rs // ⚠ 共享实现,修改需同步至 ssh/mongo/redis-proxy/src/main.rs
/// 默认请求日志路径(未设置 MYSQL_PROXY_LOG 时): exe同目录 logs/mysql-proxy.log
/// 日志默认开启——此前需手动设 env 才记录,排查只能靠复现
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),
}
}
/// 将相对路径基于可执行文件所在目录解析为绝对路径 /// 将相对路径基于可执行文件所在目录解析为绝对路径
fn resolve_config_path(path: &str) -> String { fn resolve_config_path(path: &str) -> String {
if std::path::Path::new(path).is_absolute() || path.starts_with('~') { if std::path::Path::new(path).is_absolute() || path.starts_with('~') {
@@ -118,7 +129,8 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
} }
// 初始化日志 // 初始化日志
let log_path = std::env::var("MYSQL_PROXY_LOG").ok(); let log_path = std::env::var("MYSQL_PROXY_LOG").ok()
.or_else(|| Some(default_log_path("mysql-proxy")));
let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref())); let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref()));
if logger.is_enabled() { if logger.is_enabled() {
println!("Request logging: enabled"); println!("Request logging: enabled");
+5 -1
View File
@@ -17,14 +17,18 @@ pub struct PoolConfig {
pub idle_timeout_secs: u64, pub idle_timeout_secs: u64,
#[serde(default = "default_check_interval")] #[serde(default = "default_check_interval")]
pub check_interval_secs: u64, pub check_interval_secs: u64,
/// 单操作执行超时(秒):防无界阻塞,超时返回 408
#[serde(default = "default_query_timeout")]
pub query_timeout_secs: u64,
} }
fn default_idle_timeout() -> u64 { 300 } fn default_idle_timeout() -> u64 { 300 }
fn default_check_interval() -> u64 { 60 } fn default_check_interval() -> u64 { 60 }
fn default_query_timeout() -> u64 { 60 }
impl Default for PoolConfig { impl Default for PoolConfig {
fn default() -> Self { fn default() -> Self {
Self { idle_timeout_secs: default_idle_timeout(), check_interval_secs: default_check_interval() } Self { idle_timeout_secs: default_idle_timeout(), check_interval_secs: default_check_interval(), query_timeout_secs: default_query_timeout() }
} }
} }
+4
View File
@@ -29,6 +29,10 @@ impl ConnectionManager {
Ok(Self { clients: Mutex::new(HashMap::new()), configs: Mutex::new(config_map), pool_config }) Ok(Self { clients: Mutex::new(HashMap::new()), configs: Mutex::new(config_map), pool_config })
} }
pub fn query_timeout_secs(&self) -> u64 {
self.pool_config.query_timeout_secs
}
pub fn get_conn(&self, name: &str) -> Result<(RedisClient, ConnectionConfig)> { pub fn get_conn(&self, name: &str) -> Result<(RedisClient, ConnectionConfig)> {
let client = { let client = {
let mut clients = self.clients.lock().unwrap(); let mut clients = self.clients.lock().unwrap();
+72 -13
View File
@@ -2,7 +2,7 @@ use axum::{extract::State, http::StatusCode, Json};
use redis::Commands; use redis::Commands;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::{Duration, Instant};
use crate::db::ConnectionManager; use crate::db::ConnectionManager;
use crate::logger::{LogEntry, RequestLogger}; use crate::logger::{LogEntry, RequestLogger};
@@ -71,6 +71,11 @@ type ApiError = (StatusCode, Json<ErrorResponse>);
fn err(msg: &str) -> ApiError { (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg))) } fn err(msg: &str) -> ApiError { (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg))) }
fn err_usage(msg: &str, usage: &str) -> ApiError { (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage))) } fn err_usage(msg: &str, usage: &str) -> ApiError { (StatusCode::BAD_REQUEST, Json(ErrorResponse::new(msg).with_usage(usage))) }
/// 操作执行超时:HTTP 408,提示调用方 Redis 操作占用资源过久而非配置错误
fn query_timeout_response(secs: u64) -> ApiError {
(StatusCode::REQUEST_TIMEOUT, Json(ErrorResponse::new(&format!("操作超时(>{}s)", secs))))
}
pub async fn run_cmd(State(state): State<AppState>, Json(req): Json<RunRequest>) -> Result<Json<RunResponse>, ApiError> { pub async fn run_cmd(State(state): State<AppState>, Json(req): Json<RunRequest>) -> Result<Json<RunResponse>, ApiError> {
let (manager, logger) = state.as_ref(); let (manager, logger) = state.as_ref();
let start = Instant::now(); let start = Instant::now();
@@ -78,14 +83,23 @@ pub async fn run_cmd(State(state): State<AppState>, Json(req): Json<RunRequest>)
let conn_name = req.conn.clone(); let conn_name = req.conn.clone();
let cmd_str = format!("{} {}", req.command, req.args.join(" ")); let cmd_str = format!("{} {}", req.command, req.args.join(" "));
let result: Result<serde_json::Value, ApiError> = tokio::task::spawn_blocking(move || { let deadline = Duration::from_secs(manager.query_timeout_secs());
let handle = tokio::task::spawn_blocking(move || -> Result<serde_json::Value, ApiError> {
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err_usage(&e.to_string(), "Usage: POST /run {\"conn\": \"name\", \"command\": \"GET\", \"args\": [\"key\"]}"))?; let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err_usage(&e.to_string(), "Usage: POST /run {\"conn\": \"name\", \"command\": \"GET\", \"args\": [\"key\"]}"))?;
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?; let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
let mut cmd = redis::cmd(&req.command); let mut cmd = redis::cmd(&req.command);
for arg in &req.args { cmd.arg(arg); } for arg in &req.args { cmd.arg(arg); }
let val: redis::Value = cmd.query(&mut conn).map_err(|e| err(&e.to_string()))?; let val: redis::Value = cmd.query(&mut conn).map_err(|e| err(&e.to_string()))?;
Ok(redis_value_to_json(&val)) Ok(redis_value_to_json(&val))
}).await.map_err(|_| err("Task join error"))?; });
let result: Result<serde_json::Value, ApiError> = match tokio::time::timeout(deadline, handle).await {
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
Err(_) => {
logger.log(&LogEntry::new("/run", "http").with_conn(&req.conn).with_command(&cmd_str).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
return Err(query_timeout_response(deadline.as_secs()));
}
};
let result = result.map_err(|e| { let result = result.map_err(|e| {
let msg = &e.1.error; let msg = &e.1.error;
@@ -105,12 +119,21 @@ pub async fn get(State(state): State<AppState>, Json(req): Json<GetRequest>) ->
let conn_name = req.conn.clone(); let conn_name = req.conn.clone();
let key_name = req.key.clone(); let key_name = req.key.clone();
let value: Result<Option<String>, ApiError> = tokio::task::spawn_blocking(move || { let deadline = Duration::from_secs(manager.query_timeout_secs());
let handle = tokio::task::spawn_blocking(move || -> Result<Option<String>, ApiError> {
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?; let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?; let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
let val: Option<String> = conn.get(&key_name).map_err(|e| err(&e.to_string()))?; let val: Option<String> = conn.get(&key_name).map_err(|e| err(&e.to_string()))?;
Ok(val) Ok(val)
}).await.map_err(|_| err("Task join error"))?; });
let value: Result<Option<String>, ApiError> = match tokio::time::timeout(deadline, handle).await {
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
Err(_) => {
logger.log(&LogEntry::new("/get", "http").with_conn(&req.conn).with_command(&format!("GET {}", req.key)).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
return Err(query_timeout_response(deadline.as_secs()));
}
};
let value = value.map_err(|e| { let value = value.map_err(|e| {
logger.log(&LogEntry::new("/get", "http").with_conn(&req.conn).with_command(&format!("GET {}", req.key)).with_error(&e.1.error)); logger.log(&LogEntry::new("/get", "http").with_conn(&req.conn).with_command(&format!("GET {}", req.key)).with_error(&e.1.error));
@@ -131,7 +154,8 @@ pub async fn set(State(state): State<AppState>, Json(req): Json<SetRequest>) ->
let value_str = req.value.clone(); let value_str = req.value.clone();
let ttl = req.ttl; let ttl = req.ttl;
let result: Result<(), ApiError> = tokio::task::spawn_blocking(move || { let deadline = Duration::from_secs(manager.query_timeout_secs());
let handle = tokio::task::spawn_blocking(move || -> Result<(), ApiError> {
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?; let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?; let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
if let Some(secs) = ttl { if let Some(secs) = ttl {
@@ -140,7 +164,15 @@ pub async fn set(State(state): State<AppState>, Json(req): Json<SetRequest>) ->
conn.set::<_, _, ()>(&key_name, &value_str).map_err(|e| err(&e.to_string()))?; conn.set::<_, _, ()>(&key_name, &value_str).map_err(|e| err(&e.to_string()))?;
} }
Ok(()) Ok(())
}).await.map_err(|_| err("Task join error"))?; });
let result: Result<(), ApiError> = match tokio::time::timeout(deadline, handle).await {
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
Err(_) => {
logger.log(&LogEntry::new("/set", "http").with_conn(&req.conn).with_command(&format!("SET {} {}", req.key, req.value)).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
return Err(query_timeout_response(deadline.as_secs()));
}
};
result.map_err(|e| { result.map_err(|e| {
logger.log(&LogEntry::new("/set", "http").with_conn(&req.conn).with_command(&format!("SET {} {}", req.key, req.value)).with_error(&e.1.error)); logger.log(&LogEntry::new("/set", "http").with_conn(&req.conn).with_command(&format!("SET {} {}", req.key, req.value)).with_error(&e.1.error));
@@ -159,12 +191,21 @@ pub async fn del(State(state): State<AppState>, Json(req): Json<DelRequest>) ->
let conn_name = req.conn.clone(); let conn_name = req.conn.clone();
let del_keys = req.keys.clone(); let del_keys = req.keys.clone();
let deleted: Result<u64, ApiError> = tokio::task::spawn_blocking(move || { let deadline = Duration::from_secs(manager.query_timeout_secs());
let handle = tokio::task::spawn_blocking(move || -> Result<u64, ApiError> {
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?; let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?; let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
let count: u64 = conn.del(&del_keys).map_err(|e| err(&e.to_string()))?; let count: u64 = conn.del(&del_keys).map_err(|e| err(&e.to_string()))?;
Ok(count) Ok(count)
}).await.map_err(|_| err("Task join error"))?; });
let deleted: Result<u64, ApiError> = match tokio::time::timeout(deadline, handle).await {
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
Err(_) => {
logger.log(&LogEntry::new("/del", "http").with_conn(&req.conn).with_command(&format!("DEL {}", req.keys.join(" "))).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
return Err(query_timeout_response(deadline.as_secs()));
}
};
let deleted = deleted.map_err(|e| { let deleted = deleted.map_err(|e| {
logger.log(&LogEntry::new("/del", "http").with_conn(&req.conn).with_command(&format!("DEL {}", req.keys.join(" "))).with_error(&e.1.error)); logger.log(&LogEntry::new("/del", "http").with_conn(&req.conn).with_command(&format!("DEL {}", req.keys.join(" "))).with_error(&e.1.error));
@@ -183,12 +224,21 @@ pub async fn keys(State(state): State<AppState>, Json(req): Json<KeysRequest>) -
let conn_name = req.conn.clone(); let conn_name = req.conn.clone();
let pattern = req.pattern.clone(); let pattern = req.pattern.clone();
let result: Result<Vec<String>, ApiError> = tokio::task::spawn_blocking(move || { let deadline = Duration::from_secs(manager.query_timeout_secs());
let handle = tokio::task::spawn_blocking(move || -> Result<Vec<String>, ApiError> {
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?; let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?; let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
let keys: Vec<String> = conn.keys(&pattern).map_err(|e| err(&e.to_string()))?; let keys: Vec<String> = conn.keys(&pattern).map_err(|e| err(&e.to_string()))?;
Ok(keys) Ok(keys)
}).await.map_err(|_| err("Task join error"))?; });
let result: Result<Vec<String>, ApiError> = match tokio::time::timeout(deadline, handle).await {
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
Err(_) => {
logger.log(&LogEntry::new("/keys", "http").with_conn(&req.conn).with_command(&format!("KEYS {}", req.pattern)).with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
return Err(query_timeout_response(deadline.as_secs()));
}
};
let result = result.map_err(|e| { let result = result.map_err(|e| {
logger.log(&LogEntry::new("/keys", "http").with_conn(&req.conn).with_command(&format!("KEYS {}", req.pattern)).with_error(&e.1.error)); logger.log(&LogEntry::new("/keys", "http").with_conn(&req.conn).with_command(&format!("KEYS {}", req.pattern)).with_error(&e.1.error));
@@ -206,12 +256,21 @@ pub async fn info(State(state): State<AppState>, Json(req): Json<InfoRequest>) -
let mgr = manager.clone(); let mgr = manager.clone();
let conn_name = req.conn.clone(); let conn_name = req.conn.clone();
let info: Result<String, ApiError> = tokio::task::spawn_blocking(move || { let deadline = Duration::from_secs(manager.query_timeout_secs());
let handle = tokio::task::spawn_blocking(move || -> Result<String, ApiError> {
let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?; let (client, _) = mgr.get_conn(&conn_name).map_err(|e| err(&e.to_string()))?;
let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?; let mut conn = client.get_connection().map_err(|e| err(&e.to_string()))?;
let info: String = redis::cmd("INFO").query(&mut conn).map_err(|e| err(&e.to_string()))?; let info: String = redis::cmd("INFO").query(&mut conn).map_err(|e| err(&e.to_string()))?;
Ok(info) Ok(info)
}).await.map_err(|_| err("Task join error"))?; });
let info: Result<String, ApiError> = match tokio::time::timeout(deadline, handle).await {
Ok(joined) => joined.map_err(|_| err("Task join error"))?,
Err(_) => {
logger.log(&LogEntry::new("/info", "http").with_conn(&req.conn).with_command("INFO").with_error(&format!("操作超时(>{}s)", deadline.as_secs())));
return Err(query_timeout_response(deadline.as_secs()));
}
};
let info = info.map_err(|e| { let info = info.map_err(|e| {
logger.log(&LogEntry::new("/info", "http").with_conn(&req.conn).with_command("INFO").with_error(&e.1.error)); logger.log(&LogEntry::new("/info", "http").with_conn(&req.conn).with_command("INFO").with_error(&e.1.error));
+1 -1
View File
@@ -63,7 +63,7 @@ impl LogEntry {
} }
} }
pub fn with_conn(mut self, conn: &str) -> Self { self.conn = Some(conn.to_string()); self } pub fn with_conn(mut self, conn: &str) -> Self { self.conn = Some(conn.to_string()); self }
pub fn with_command(mut self, cmd: &str) -> Self { self.command = Some(truncate_string(cmd, 500)); self } pub fn with_command(mut self, cmd: &str) -> Self { self.command = Some(truncate_string(cmd, 2000)); self }
pub fn with_duration(mut self, ms: u64) -> Self { pub fn with_duration(mut self, ms: u64) -> Self {
self.duration_ms = ms; self.duration_ms = ms;
if ms > 5000 && self.level == "INFO" { self.level = "ERROR".to_string(); } if ms > 5000 && self.level == "INFO" { self.level = "ERROR".to_string(); }
+58 -9
View File
@@ -8,6 +8,17 @@ use axum::{routing::{get, post}, Router};
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use std::sync::Arc; use std::sync::Arc;
// ⚠ 共享实现,修改需同步至 mysql/mongo/ssh-proxy/src/main.rs
/// 默认请求日志路径(未设置 REDIS_PROXY_LOG 时): exe同目录 logs/redis-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)] #[derive(Parser, Debug)]
#[command(name = "redis-proxy")] #[command(name = "redis-proxy")]
#[command(about = "Redis HTTP proxy with connection pooling")] #[command(about = "Redis HTTP proxy with connection pooling")]
@@ -31,18 +42,55 @@ enum Commands {
Connections, Connections,
} }
// ⚠ 共享实现,修改需同步至 mysql/ssh/mongo-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] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
let args = Args::parse(); let args = Args::parse();
let config_path = resolve_config_path(&args.config);
match args.command { match args.command {
Some(Commands::Server { port, host }) => run_server(&args.config, port, host).await, Some(Commands::Server { port, host }) => run_server(&config_path, port, host).await,
Some(Commands::Run { conn, command, args: ref keys }) => { let c = get_cli(&args.server)?; Ok(c.run(&conn, &command, keys)?) }, Some(Commands::Run { conn, command, args: ref keys }) => {
Some(Commands::Get { conn, key }) => { let c = get_cli(&args.server)?; Ok(c.get(&conn, &key)?) }, let c = get_cli(&args.server)?;
Some(Commands::Set { conn, key, value, ttl }) => { let c = get_cli(&args.server)?; Ok(c.set(&conn, &key, &value, ttl)?) }, Ok(c.run(&conn, &command, keys)?)
Some(Commands::Del { conn, key: ref keys }) => { let c = get_cli(&args.server)?; Ok(c.del(&conn, keys)?) }, }
Some(Commands::Keys { conn, pattern }) => { let c = get_cli(&args.server)?; Ok(c.keys(&conn, &pattern)?) }, Some(Commands::Get { conn, key }) => {
Some(Commands::Connections) => { let c = get_cli(&args.server)?; Ok(c.list_connections()?) }, let c = get_cli(&args.server)?;
None => run_server(&args.config, None, None).await, Ok(c.get(&conn, &key)?)
}
Some(Commands::Set { conn, key, value, ttl }) => {
let c = get_cli(&args.server)?;
Ok(c.set(&conn, &key, &value, ttl)?)
}
Some(Commands::Del { conn, key: ref keys }) => {
let c = get_cli(&args.server)?;
Ok(c.del(&conn, keys)?)
}
Some(Commands::Keys { conn, pattern }) => {
let c = get_cli(&args.server)?;
Ok(c.keys(&conn, &pattern)?)
}
Some(Commands::Connections) => {
let c = get_cli(&args.server)?;
Ok(c.list_connections()?)
}
None => run_server(&config_path, None, None).await,
} }
} }
@@ -61,7 +109,8 @@ async fn run_server(config_path: &str, port: Option<u16>, host: Option<String>)
if let Some(port) = port { config.server.port = port; } if let Some(port) = port { config.server.port = port; }
if let Some(host) = host { config.server.host = host; } if let Some(host) = host { config.server.host = host; }
let log_path = std::env::var("REDIS_PROXY_LOG").ok(); let log_path = std::env::var("REDIS_PROXY_LOG").ok()
.or_else(|| Some(default_log_path("redis-proxy")));
let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref())); let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref()));
if logger.is_enabled() { println!("Request logging: enabled"); } if logger.is_enabled() { println!("Request logging: enabled"); }
+3023
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "ssh-proxy" name = "ssh-proxy"
version = "0.1.0" version = "0.2.0"
edition = "2021" edition = "2021"
description = "SSH HTTP proxy with session pooling" description = "SSH HTTP proxy with session pooling"
+23 -2
View File
@@ -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(); 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 { let body = serde_json::to_string(&ExecRequest {
server: server.to_string(), server: server.to_string(),
command: command.to_string(), command,
})?; })?;
let response = ureq::post(&format!("{}/exec", self.server)) 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<()> { pub fn upload(&self, server: &str, local_path: &str, remote_path: &str, concurrency: usize) -> Result<()> {
let body = serde_json::to_string(&UploadRequest { let body = serde_json::to_string(&UploadRequest {
+6 -1
View File
@@ -21,16 +21,21 @@ pub struct PoolConfig {
pub idle_timeout_secs: u64, pub idle_timeout_secs: u64,
#[serde(default = "default_check_interval")] #[serde(default = "default_check_interval")]
pub check_interval_secs: u64, 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_check_interval() -> u64 { 60 }
fn default_exec_timeout() -> u64 { 600 }
impl Default for PoolConfig { impl Default for PoolConfig {
fn default() -> Self { fn default() -> Self {
Self { Self {
idle_timeout_secs: default_idle_timeout(), idle_timeout_secs: default_idle_timeout(),
check_interval_secs: default_check_interval(), check_interval_secs: default_check_interval(),
exec_timeout_secs: default_exec_timeout(),
} }
} }
} }
+57 -3
View File
@@ -82,11 +82,15 @@ pub async fn exec(
let result = manager.exec(&req.server, &req.command).await let result = manager.exec(&req.server, &req.command).await
.map_err(|e| { .map_err(|e| {
logger.log(&LogEntry::new("/exec", "http").with_server(&req.server).with_command(&req.command).with_error(&e.to_string())); 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!( let usage = format!(
"Usage: POST /exec {{\"server\": \"server_name\", \"command\": \"your command\"}}\n\nAvailable servers: {}", "Usage: POST /exec {{\"server\": \"server_name\", \"command\": \"your command\"}}\n\nAvailable servers: {}",
server_names 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; let duration_ms = start.elapsed().as_millis() as u64;
@@ -113,6 +117,45 @@ pub async fn servers(
Json(ServersResponse { servers: manager.list_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( pub async fn add_server(
State(state): State<AppState>, State(state): State<AppState>,
Json(req): Json<AddServerRequest>, 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: {}", "Usage: POST /upload {{\"server\": \"name\", \"localPath\": \"./file.txt\", \"remotePath\": \"/remote/file.txt\"}}\n\nAvailable servers: {}",
server_names 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; 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: {}", "Usage: POST /download {{\"server\": \"name\", \"remotePath\": \"/remote/file.txt\", \"localPath\": \"./file.txt\"}}\n\nAvailable servers: {}",
server_names 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; 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))) (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 { fn list_server_names(manager: &SessionManager) -> String {
manager.list_servers() manager.list_servers()
.iter() .iter()
+6 -7
View File
@@ -123,23 +123,22 @@ impl LogEntry {
pub fn with_sql(mut self, sql: &str) -> Self { pub fn with_sql(mut self, sql: &str) -> Self {
// 截断过长的 SQL // 截断过长的 SQL
self.sql = Some(truncate_string(sql, 1000)); self.sql = Some(truncate_string(sql, 2000));
self self
} }
pub fn with_command(mut self, command: &str) -> 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 self
} }
pub fn with_duration(mut self, ms: u64) -> Self { pub fn with_duration(mut self, ms: u64) -> Self {
self.duration_ms = ms; self.duration_ms = ms;
// 慢请求告警: >3s 为 WARN, >10s 为 ERROR // 慢请求告警: >3s 为 WARN, >30s 为 WARN(长任务)——
// 注意: 后台命令(nohup)可能耗时很长但 exitCode=0,不标记错误 // 此前 >10s 一律标 ERROR,但 exit_code=0 的正常长命令(如 nohup 启动)
if ms > 10000 && self.level == "INFO" { // 被误标成失败,日志噪音大。真正的错误由 with_exit_code/with_error 判
self.level = "ERROR".to_string(); if ms > 3000 && self.level == "INFO" {
} else if ms > 3000 && self.level == "INFO" {
self.level = "WARN".to_string(); self.level = "WARN".to_string();
} }
self self
+44 -8
View File
@@ -8,6 +8,17 @@ use axum::{routing::{get, post}, Router};
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use std::sync::Arc; 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)] #[derive(Parser, Debug)]
#[command(name = "ssh-proxy")] #[command(name = "ssh-proxy")]
#[command(about = "SSH HTTP proxy with session pooling")] #[command(about = "SSH HTTP proxy with session pooling")]
@@ -36,6 +47,9 @@ enum Commands {
/// Output format: text, json /// Output format: text, json
#[arg(short = 'F', long, default_value = "text")] #[arg(short = 'F', long, default_value = "text")]
format: String, format: String,
/// 后台执行: 远端 nohup 断流拉起, 立即返回 BG-STARTED + 日志路径(长命令防会话超时连杀)
#[arg(long)]
bg: bool,
}, },
Servers, Servers,
/// Upload file to remote server (SFTP) /// 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] #[tokio::main]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
let args = Args::parse(); let args = Args::parse();
let config_path = resolve_config_path(&args.config);
match args.command { match args.command {
Some(Commands::Server { port, host }) => run_server(&args.config, port, host).await, Some(Commands::Server { port, host }) => run_server(&config_path, port, host).await,
Some(Commands::Exec { name, command, format }) => run_cli_exec(&args.server, &name, &command, &format), 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::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::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::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 }) => { Some(Commands::AddServer { name, host, port, user, password, private_key }) => {
run_cli_add_server(&args.server, 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; } 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())); let logger = Arc::new(logger::RequestLogger::new(log_path.as_deref()));
if logger.is_enabled() { if logger.is_enabled() {
println!("Request logging: enabled"); println!("Request logging: enabled");
} }
println!("Initializing SSH sessions...\n"); 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 manager_clone = manager.clone();
let idle_timeout = config.pool.idle_timeout_secs; 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("/upload", post(handler::upload))
.route("/download", post(handler::download)) .route("/download", post(handler::download))
.route("/health", get(handler::health)) .route("/health", get(handler::health))
.route("/_help", get(handler::help))
.with_state(Arc::new((manager, logger))); .with_state(Arc::new((manager, logger)));
let addr = format!("{}:{}", config.server.host, config.server.port); 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 /download - Download file (SFTP)");
println!(" POST /servers/add - Add server (temporary)"); println!(" POST /servers/add - Add server (temporary)");
println!(" GET /servers - List all servers"); println!(" GET /servers - List all servers");
println!(" GET /_help - API guide (endpoints + usage)");
println!(" GET /health - Health check"); println!(" GET /health - Health check");
println!("\nCLI Usage:"); println!("\nCLI Usage:");
println!(" ssh-proxy exec -n flux_dev -c \"docker ps\""); 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(()) 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())); let cli = cli::Cli::new(Some(server_url.to_string()));
if !cli.check_server()? { if !cli.check_server()? {
eprintln!(); eprintln!();
@@ -170,7 +206,7 @@ fn run_cli_exec(server_url: &str, server: &str, command: &str, format: &str) ->
eprintln!("配置文件中的服务器信息见: ssh-proxy.toml"); eprintln!("配置文件中的服务器信息见: ssh-proxy.toml");
anyhow::bail!("Proxy server not running at {}", server_url); 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<()> { 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); anyhow::bail!("Proxy server not running at {}", server_url);
} }
cli.add_server(name, host, port, user, password, private_key) cli.add_server(name, host, port, user, password, private_key)
} }
+28 -17
View File
@@ -20,6 +20,7 @@ struct SessionState {
pub struct SessionManager { pub struct SessionManager {
sessions: Mutex<HashMap<String, SessionState>>, sessions: Mutex<HashMap<String, SessionState>>,
configs: Mutex<HashMap<String, SshServerConfig>>, configs: Mutex<HashMap<String, SshServerConfig>>,
exec_timeout_secs: u64,
} }
// 简单的 SSH 客户端处理器 // 简单的 SSH 客户端处理器
@@ -37,7 +38,7 @@ impl client::Handler for Client {
} }
impl SessionManager { 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(); let mut config_map = HashMap::new();
for cfg in configs { for cfg in configs {
config_map.insert(cfg.name.clone(), cfg.clone()); config_map.insert(cfg.name.clone(), cfg.clone());
@@ -47,6 +48,7 @@ impl SessionManager {
Ok(Self { Ok(Self {
sessions: Mutex::new(HashMap::new()), sessions: Mutex::new(HashMap::new()),
configs: Mutex::new(config_map), configs: Mutex::new(config_map),
exec_timeout_secs,
}) })
} }
@@ -151,25 +153,34 @@ impl SessionManager {
let mut stderr = String::new(); let mut stderr = String::new();
let mut exit_code: i32 = -1; let mut exit_code: i32 = -1;
// 读取输出 // 读取输出,带执行上限:远端命令挂死(如 nohup 子进程未正确脱离通道)时
while let Some(msg) = channel.wait().await { // wait() 永不返回——实测日志曾挂 6.7h(durationMs 24010328)。超时放弃通道
match msg { // 并断开会话(通道状态不可信),返回 EXEC_TIMED_OUT 供 handler 定级 408
russh::ChannelMsg::Data { data } => { let deadline = Duration::from_secs(self.exec_timeout_secs);
stdout.push_str(&String::from_utf8_lossy(&data)); let wait_loop = async {
} while let Some(msg) = channel.wait().await {
russh::ChannelMsg::ExtendedData { data, ext } => { match msg {
if ext == 1 { // stderr russh::ChannelMsg::Data { data } => {
stderr.push_str(&String::from_utf8_lossy(&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 { Ok(ExecResult {