server.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. use crate::cache::CacheRef;
  2. use anyhow::Result;
  3. use hyper::http::StatusCode;
  4. use hyper::service::{make_service_fn, service_fn};
  5. use hyper::{Body, Method, Request, Response, Server};
  6. use log::{error, info, warn};
  7. use std::convert::Infallible;
  8. use std::net::SocketAddr;
  9. /// 状态服务器
  10. pub struct StatusServer {
  11. cache: CacheRef,
  12. }
  13. impl StatusServer {
  14. /// 创建新的状态服务器实例
  15. #[inline]
  16. pub fn new(cache: CacheRef) -> Self {
  17. Self { cache }
  18. }
  19. /// 运行服务器
  20. pub async fn run(self, addr: SocketAddr) -> Result<()> {
  21. let cache = self.cache;
  22. let make_svc = make_service_fn(move |_conn| {
  23. let cache = cache.clone();
  24. async move {
  25. Ok::<_, Infallible>(service_fn(move |req| {
  26. let cache = cache.clone();
  27. Self::handle_request(req, cache)
  28. }))
  29. }
  30. });
  31. // 创建服务器并配置高并发参数
  32. let server = Server::bind(&addr)
  33. .http1_keepalive(true)
  34. .http1_half_close(false)
  35. .tcp_keepalive(Some(std::time::Duration::from_secs(10)))
  36. .tcp_nodelay(true)
  37. .serve(make_svc);
  38. info!("服务器运行在: http://{addr}");
  39. info!("已启用高并发模式,支持 HTTP/1.1 keep-alive");
  40. server.await.map_err(|e| {
  41. error!("服务器错误: {e}");
  42. anyhow::anyhow!("服务器运行错误: {e}")
  43. })?;
  44. info!("服务器正常关闭");
  45. Ok(())
  46. }
  47. /// 处理 HTTP 请求
  48. async fn handle_request(
  49. req: Request<Body>,
  50. cache: CacheRef,
  51. ) -> std::result::Result<Response<Body>, Infallible> {
  52. // 添加连接信息头部,便于调试
  53. match (req.method(), req.uri().path()) {
  54. (&Method::GET, "/") => {
  55. match Self::serve_html(cache).await {
  56. Ok(mut response) => {
  57. // 添加缓存控制头,减少客户端重复请求
  58. response.headers_mut().insert(
  59. "Cache-Control",
  60. hyper::header::HeaderValue::from_static(
  61. "no-cache, no-store, must-revalidate",
  62. ),
  63. );
  64. response.headers_mut().insert(
  65. "Pragma",
  66. hyper::header::HeaderValue::from_static("no-cache"),
  67. );
  68. response
  69. .headers_mut()
  70. .insert("Expires", hyper::header::HeaderValue::from_static("0"));
  71. Ok(response)
  72. }
  73. Err(_) => Ok(Self::serve_error(
  74. "数据获取失败".to_string(),
  75. StatusCode::INTERNAL_SERVER_ERROR,
  76. )),
  77. }
  78. }
  79. (&Method::GET, "/health") => Ok(Self::serve_health()),
  80. _ => Ok(Self::serve_404()),
  81. }
  82. }
  83. /// 提供健康检查端点
  84. #[inline]
  85. fn serve_health() -> Response<Body> {
  86. Response::builder()
  87. .status(StatusCode::OK)
  88. .header("content-type", "text/plain")
  89. .header("Cache-Control", "no-cache")
  90. .body(Body::from("OK"))
  91. .unwrap()
  92. }
  93. /// 提供 404 页面
  94. #[inline]
  95. fn serve_404() -> Response<Body> {
  96. warn!("请求了不存在的页面");
  97. Response::builder()
  98. .status(StatusCode::NOT_FOUND)
  99. .header("content-type", "text/plain; charset=utf-8")
  100. .body(Body::from("页面未找到"))
  101. .unwrap()
  102. }
  103. /// 提供错误页面
  104. #[inline]
  105. fn serve_error(message: String, status: StatusCode) -> Response<Body> {
  106. Response::builder()
  107. .status(status)
  108. .header("content-type", "text/plain; charset=utf-8")
  109. .body(Body::from(message))
  110. .unwrap()
  111. }
  112. /// 提供主页面
  113. async fn serve_html(cache: CacheRef) -> Result<Response<Body>> {
  114. // 获取系统数据
  115. let stats = cache.get_or_update().await.map_err(|e| {
  116. error!("获取系统数据失败: {e}");
  117. e
  118. })?;
  119. // 渲染 HTML 模板
  120. let html = Self::render_html_template(&stats);
  121. Ok(Response::builder()
  122. .status(StatusCode::OK)
  123. .header("content-type", "text/html; charset=utf-8")
  124. .body(Body::from(html))
  125. .unwrap())
  126. }
  127. /// 渲染 HTML 模板
  128. pub fn render_html_template(stats: &crate::stats::SystemStats) -> String {
  129. let total_mb = stats.memory_total / 1024 / 1024;
  130. let used_mb = stats.memory_used / 1024 / 1024;
  131. let available_mb = stats.memory_available / 1024 / 1024;
  132. let cached_mb = stats.memory_cached / 1024 / 1024;
  133. let free_mb = stats.memory_free / 1024 / 1024;
  134. let cpu_percent = (stats.cpu_usage * 100.0) as u32;
  135. // 格式化时间戳为可读格式
  136. let timestamp = format!("{:?}", stats.timestamp);
  137. // 使用内置模板(编译进二进制文件)
  138. let template = include_str!("../templates/index.html");
  139. // 使用 String::with_capacity 预分配容量,减少重新分配
  140. let mut result = String::with_capacity(template.len() + 256);
  141. // 手动替换变量,避免多次字符串分配
  142. result.push_str(template);
  143. result = result.replace("{hostname}", &stats.hostname);
  144. result = result.replace("{cpu_percent}", &cpu_percent.to_string());
  145. result = result.replace("{memory_total_mb}", &total_mb.to_string());
  146. result = result.replace("{memory_used_mb}", &used_mb.to_string());
  147. result = result.replace("{memory_available_mb}", &available_mb.to_string());
  148. result = result.replace("{memory_cached_mb}", &cached_mb.to_string());
  149. result = result.replace("{memory_free_mb}", &free_mb.to_string());
  150. result = result.replace("{timestamp}", &timestamp);
  151. result
  152. }
  153. }
  154. #[cfg(test)]
  155. mod tests {
  156. use super::*;
  157. use crate::cache::create_cache;
  158. use crate::stats::SystemStats;
  159. use hyper::{Body, Request, StatusCode};
  160. use std::time::Instant;
  161. fn create_test_stats(hostname: &str, cpu_usage: f32) -> SystemStats {
  162. SystemStats {
  163. hostname: hostname.to_string(),
  164. cpu_usage,
  165. memory_total: 1024 * 1024 * 1024, // 1GB
  166. memory_used: 512 * 1024 * 1024, // 512MB
  167. memory_available: 256 * 1024 * 1024, // 256MB
  168. memory_cached: 128 * 1024 * 1024, // 128MB
  169. memory_free: 128 * 1024 * 1024, // 128MB
  170. timestamp: Instant::now(),
  171. }
  172. }
  173. #[tokio::test]
  174. async fn test_config_default() {
  175. let config = Config::default();
  176. assert_eq!(config.bind_address, "0.0.0.0");
  177. assert_eq!(config.port, 8080);
  178. assert_eq!(config.cache_ttl_seconds, 10);
  179. }
  180. #[tokio::test]
  181. async fn test_config_address() {
  182. let config = Config::default();
  183. let addr = config.address();
  184. assert_eq!(addr.to_string(), "0.0.0.0:8080");
  185. }
  186. #[tokio::test]
  187. async fn test_status_server_creation() {
  188. let cache = create_cache(10);
  189. let _server = StatusServer::new(cache);
  190. // 服务器创建成功,没有 panic
  191. }
  192. #[tokio::test]
  193. async fn test_serve_health() {
  194. let response = StatusServer::serve_health();
  195. assert_eq!(response.status(), StatusCode::OK);
  196. let headers = response.headers();
  197. assert_eq!(headers.get("content-type").unwrap(), "text/plain");
  198. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  199. assert_eq!(std::str::from_utf8(&body).unwrap(), "OK");
  200. }
  201. #[tokio::test]
  202. async fn test_serve_404() {
  203. let response = StatusServer::serve_404();
  204. assert_eq!(response.status(), StatusCode::NOT_FOUND);
  205. let headers = response.headers();
  206. assert_eq!(headers.get("content-type").unwrap(), "text/plain; charset=utf-8");
  207. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  208. assert_eq!(std::str::from_utf8(&body).unwrap(), "页面未找到");
  209. }
  210. #[tokio::test]
  211. async fn test_serve_error() {
  212. let message = "测试错误".to_string();
  213. let response =
  214. StatusServer::serve_error(message.clone(), StatusCode::INTERNAL_SERVER_ERROR);
  215. assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
  216. let headers = response.headers();
  217. assert_eq!(
  218. headers.get("content-type").unwrap(),
  219. "text/plain; charset=utf-8"
  220. );
  221. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  222. assert_eq!(std::str::from_utf8(&body).unwrap(), message);
  223. }
  224. #[tokio::test]
  225. async fn test_render_html_template() {
  226. let stats = create_test_stats("测试主机", 0.75);
  227. let html = StatusServer::render_html_template(&stats);
  228. // 检查 HTML 是否包含预期的内容
  229. assert!(html.contains("测试主机"));
  230. assert!(html.contains("75"));
  231. assert!(html.contains("1024")); // 内存总量 MB
  232. assert!(html.contains("512")); // 已用内存 MB
  233. assert!(html.contains("256")); // 可用内存 MB
  234. assert!(html.contains("128")); // 缓存内存 MB
  235. }
  236. #[tokio::test]
  237. async fn test_render_html_template_special_chars() {
  238. let stats = create_test_stats("主机<>&\"'", 0.5);
  239. let html = StatusServer::render_html_template(&stats);
  240. // 检查特殊字符是否被正确处理
  241. assert!(html.contains("主机<>&\"'"));
  242. assert!(html.contains("50"));
  243. }
  244. #[tokio::test]
  245. async fn test_render_html_template_memory_values() {
  246. let stats = SystemStats {
  247. hostname: "test".to_string(),
  248. cpu_usage: 0.5,
  249. memory_total: 2048 * 1024 * 1024, // 2GB
  250. memory_used: 1024 * 1024 * 1024, // 1GB
  251. memory_available: 512 * 1024 * 1024, // 512MB
  252. memory_cached: 256 * 1024 * 1024, // 256MB
  253. memory_free: 256 * 1024 * 1024, // 256MB
  254. timestamp: Instant::now(),
  255. };
  256. let html = StatusServer::render_html_template(&stats);
  257. // 检查内存值是否正确转换为 MB
  258. assert!(html.contains("2048")); // 总内存 2GB = 2048MB
  259. assert!(html.contains("1024")); // 已用内存 1GB = 1024MB
  260. assert!(html.contains("512")); // 可用内存 512MB
  261. assert!(html.contains("256")); // 缓存内存 256MB
  262. assert!(html.contains("256")); // 空闲内存 256MB
  263. }
  264. #[tokio::test]
  265. async fn test_handle_request_root() {
  266. let cache = create_cache(10);
  267. let request = Request::builder()
  268. .method("GET")
  269. .uri("/")
  270. .body(Body::empty())
  271. .unwrap();
  272. let response = StatusServer::handle_request(request, cache).await.unwrap();
  273. assert_eq!(response.status(), StatusCode::OK);
  274. }
  275. #[tokio::test]
  276. async fn test_handle_request_health() {
  277. let cache = create_cache(10);
  278. let request = Request::builder()
  279. .method("GET")
  280. .uri("/health")
  281. .body(Body::empty())
  282. .unwrap();
  283. let response = StatusServer::handle_request(request, cache).await.unwrap();
  284. assert_eq!(response.status(), StatusCode::OK);
  285. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  286. assert_eq!(std::str::from_utf8(&body).unwrap(), "OK");
  287. }
  288. #[tokio::test]
  289. async fn test_handle_request_404() {
  290. let cache = create_cache(10);
  291. let request = Request::builder()
  292. .method("GET")
  293. .uri("/notfound")
  294. .body(Body::empty())
  295. .unwrap();
  296. let response = StatusServer::handle_request(request, cache).await.unwrap();
  297. assert_eq!(response.status(), StatusCode::NOT_FOUND);
  298. }
  299. #[tokio::test]
  300. async fn test_handle_request_post_method() {
  301. let cache = create_cache(10);
  302. let request = Request::builder()
  303. .method("POST")
  304. .uri("/")
  305. .body(Body::empty())
  306. .unwrap();
  307. let response = StatusServer::handle_request(request, cache).await.unwrap();
  308. assert_eq!(response.status(), StatusCode::NOT_FOUND);
  309. }
  310. #[tokio::test]
  311. async fn test_serve_html_with_cache() {
  312. let cache = create_cache(10);
  313. // 更新缓存数据
  314. let stats = create_test_stats("缓存测试", 0.8);
  315. cache.update(stats);
  316. // 模拟请求处理
  317. let request = Request::builder()
  318. .method("GET")
  319. .uri("/")
  320. .body(Body::empty())
  321. .unwrap();
  322. let response = StatusServer::handle_request(request, cache.clone())
  323. .await
  324. .unwrap();
  325. assert_eq!(response.status(), StatusCode::OK);
  326. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  327. let html = std::str::from_utf8(&body).unwrap();
  328. // 检查响应是否包含缓存的数据
  329. assert!(html.contains("缓存测试"));
  330. assert!(html.contains("80"));
  331. }
  332. }
  333. /// 配置结构
  334. #[derive(Debug, Clone)]
  335. pub struct Config {
  336. /// 服务端绑定地址
  337. pub bind_address: String,
  338. /// 服务端端口
  339. pub port: u16,
  340. /// 缓存 TTL(秒)
  341. pub cache_ttl_seconds: u64,
  342. }
  343. impl Default for Config {
  344. #[inline]
  345. fn default() -> Self {
  346. Self {
  347. bind_address: "0.0.0.0".to_string(),
  348. port: 8080,
  349. cache_ttl_seconds: 10, // 严格 10 秒过期
  350. }
  351. }
  352. }
  353. impl Config {
  354. /// 构建服务器地址
  355. #[inline]
  356. pub fn address(&self) -> SocketAddr {
  357. format!("{}:{}", self.bind_address, self.port)
  358. .parse()
  359. .expect("无效的地址格式")
  360. }
  361. }