server.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. cache_ttl_seconds: u64,
  13. }
  14. impl StatusServer {
  15. /// 创建新的状态服务器实例,带 TTL 配置
  16. #[inline]
  17. pub fn new_with_ttl(cache: CacheRef, cache_ttl_seconds: u64) -> Self {
  18. Self {
  19. cache,
  20. cache_ttl_seconds,
  21. }
  22. }
  23. /// 运行服务器
  24. pub async fn run(self, addr: SocketAddr) -> Result<()> {
  25. let cache = self.cache.clone();
  26. let cache_ttl_seconds = self.cache_ttl_seconds;
  27. let make_svc = make_service_fn(move |_conn| {
  28. let cache = cache.clone();
  29. let cache_ttl_seconds = cache_ttl_seconds;
  30. async move {
  31. Ok::<_, Infallible>(service_fn(move |req| {
  32. let cache = cache.clone();
  33. let cache_ttl_seconds = cache_ttl_seconds;
  34. Self::handle_request(req, cache, cache_ttl_seconds)
  35. }))
  36. }
  37. });
  38. // 创建服务器并配置高并发参数
  39. let server = Server::bind(&addr)
  40. .http1_keepalive(true)
  41. .http1_half_close(false)
  42. .tcp_keepalive(Some(std::time::Duration::from_secs(10)))
  43. .tcp_nodelay(true)
  44. .serve(make_svc);
  45. info!("服务器运行在: http://{addr}");
  46. info!("已启用高并发模式,支持 HTTP/1.1 keep-alive");
  47. server.await.map_err(|e| {
  48. error!("服务器错误: {e}");
  49. anyhow::anyhow!("服务器运行错误: {e}")
  50. })?;
  51. info!("服务器正常关闭");
  52. Ok(())
  53. }
  54. /// 处理 HTTP 请求
  55. async fn handle_request(
  56. req: Request<Body>,
  57. cache: CacheRef,
  58. cache_ttl_seconds: u64,
  59. ) -> std::result::Result<Response<Body>, Infallible> {
  60. // 添加连接信息头部,便于调试
  61. match (req.method(), req.uri().path()) {
  62. (&Method::GET, "/") => {
  63. match Self::serve_html(cache, cache_ttl_seconds).await {
  64. Ok(mut response) => {
  65. // 添加缓存控制头,允许客户端在 TTL 秒内使用缓存
  66. // 与 HTML meta refresh 和服务器缓存 TTL 保持一致,减少服务器负载
  67. response.headers_mut().insert(
  68. "Cache-Control",
  69. hyper::header::HeaderValue::from_str(&format!(
  70. "public, max-age={cache_ttl_seconds}"
  71. ))
  72. .unwrap_or_else(|_| {
  73. hyper::header::HeaderValue::from_static("public, max-age=10")
  74. }),
  75. );
  76. Ok(response)
  77. }
  78. Err(_) => Ok(Self::serve_error(
  79. "数据获取失败".to_string(),
  80. StatusCode::INTERNAL_SERVER_ERROR,
  81. )),
  82. }
  83. }
  84. (&Method::GET, "/health") => Ok(Self::serve_health()),
  85. _ => Ok(Self::serve_404()),
  86. }
  87. }
  88. /// 提供健康检查端点
  89. #[inline]
  90. fn serve_health() -> Response<Body> {
  91. Response::builder()
  92. .status(StatusCode::OK)
  93. .header("content-type", "text/plain")
  94. .header("Cache-Control", "no-cache")
  95. .body(Body::from("OK"))
  96. .unwrap()
  97. }
  98. /// 提供 404 页面
  99. #[inline]
  100. fn serve_404() -> Response<Body> {
  101. warn!("请求了不存在的页面");
  102. Response::builder()
  103. .status(StatusCode::NOT_FOUND)
  104. .header("content-type", "text/plain; charset=utf-8")
  105. .body(Body::from("页面未找到"))
  106. .unwrap()
  107. }
  108. /// 提供错误页面
  109. #[inline]
  110. fn serve_error(message: String, status: StatusCode) -> Response<Body> {
  111. Response::builder()
  112. .status(status)
  113. .header("content-type", "text/plain; charset=utf-8")
  114. .body(Body::from(message))
  115. .unwrap()
  116. }
  117. /// 提供主页面
  118. async fn serve_html(cache: CacheRef, cache_ttl_seconds: u64) -> Result<Response<Body>> {
  119. // 获取系统数据
  120. let stats = cache.get_or_update().await.map_err(|e| {
  121. error!("获取系统数据失败: {e}");
  122. e
  123. })?;
  124. // 渲染 HTML 模板
  125. let html = Self::render_html_template(&stats, cache_ttl_seconds);
  126. Ok(Response::builder()
  127. .status(StatusCode::OK)
  128. .header("content-type", "text/html; charset=utf-8")
  129. .body(Body::from(html))
  130. .unwrap())
  131. }
  132. /// 渲染 HTML 模板
  133. pub fn render_html_template(
  134. stats: &crate::stats::SystemStats,
  135. cache_ttl_seconds: u64,
  136. ) -> String {
  137. let total_mb = stats.memory_total / 1024 / 1024;
  138. let used_mb = stats.memory_used / 1024 / 1024;
  139. let available_mb = stats.memory_available / 1024 / 1024;
  140. let cached_mb = stats.memory_cached / 1024 / 1024;
  141. let free_mb = stats.memory_free / 1024 / 1024;
  142. let cpu_percent = (stats.cpu_usage * 100.0) as u32;
  143. let cpu_user_percent = stats.cpu_stats.overall.user_percent as u32;
  144. let cpu_system_percent = stats.cpu_stats.overall.system_percent as u32;
  145. let cpu_nice_percent = stats.cpu_stats.overall.nice_percent as u32;
  146. // 生成多核 CPU 部分
  147. let cpu_cores_section = if stats.cpu_stats.core_count > 0 {
  148. let mut cores_html = String::from("<fieldset><legend>处理器 - 各核心使用率</legend>");
  149. for (i, core_stats) in stats.cpu_stats.per_core.iter().enumerate() {
  150. cores_html.push_str(&format!(
  151. "<p>核心 {}:<progress title=\"{}%\" value=\"{}\" max=\"100\">{}%</progress></p>",
  152. i, core_stats.total_percent as u32, core_stats.total_percent as u32, core_stats.total_percent as u32
  153. ));
  154. }
  155. cores_html.push_str("</fieldset>");
  156. cores_html
  157. } else {
  158. String::new()
  159. };
  160. // 格式化时间戳为可读格式
  161. let timestamp = format!("{:?}", stats.timestamp);
  162. // 使用内置模板(编译进二进制文件)
  163. let template = include_str!("../templates/index.html");
  164. // 使用 String::with_capacity 预分配容量,减少重新分配
  165. let mut result = String::with_capacity(template.len() + 512);
  166. // 手动替换变量,避免多次字符串分配
  167. result.push_str(template);
  168. result = result.replace("{hostname}", &stats.hostname);
  169. result = result.replace("{cpu_percent}", &cpu_percent.to_string());
  170. result = result.replace("{cpu_user_percent}", &cpu_user_percent.to_string());
  171. result = result.replace("{cpu_system_percent}", &cpu_system_percent.to_string());
  172. result = result.replace("{cpu_nice_percent}", &cpu_nice_percent.to_string());
  173. result = result.replace("{cpu_cores_section}", &cpu_cores_section);
  174. result = result.replace("{memory_total_mb}", &total_mb.to_string());
  175. result = result.replace("{memory_used_mb}", &used_mb.to_string());
  176. result = result.replace("{memory_available_mb}", &available_mb.to_string());
  177. result = result.replace("{memory_cached_mb}", &cached_mb.to_string());
  178. result = result.replace("{memory_free_mb}", &free_mb.to_string());
  179. result = result.replace("{timestamp}", &timestamp);
  180. result = result.replace("{ttl}", &cache_ttl_seconds.to_string());
  181. result
  182. }
  183. }
  184. #[cfg(test)]
  185. mod tests {
  186. use super::*;
  187. use crate::cache::create_cache;
  188. use crate::stats::SystemStats;
  189. use hyper::{Body, Request, StatusCode};
  190. use std::time::Instant;
  191. fn create_test_stats(hostname: &str, cpu_usage: f32) -> SystemStats {
  192. SystemStats {
  193. hostname: hostname.to_string(),
  194. cpu_usage,
  195. cpu_stats: crate::stats::CpuStats {
  196. overall: crate::stats::CpuUsageBreakdown {
  197. user_percent: cpu_usage * 50.0,
  198. nice_percent: cpu_usage * 10.0,
  199. system_percent: cpu_usage * 40.0,
  200. total_percent: cpu_usage * 100.0,
  201. },
  202. per_core: Vec::new(),
  203. core_count: 0,
  204. },
  205. memory_total: 1024 * 1024 * 1024, // 1GB
  206. memory_used: 512 * 1024 * 1024, // 512MB
  207. memory_available: 256 * 1024 * 1024, // 256MB
  208. memory_cached: 128 * 1024 * 1024, // 128MB
  209. memory_free: 128 * 1024 * 1024, // 128MB
  210. timestamp: Instant::now(),
  211. }
  212. }
  213. #[tokio::test]
  214. async fn test_config_default() {
  215. let config = Config::default();
  216. assert_eq!(config.bind_address, "::");
  217. assert_eq!(config.port, 8080);
  218. assert_eq!(config.cache_ttl_seconds, 10);
  219. }
  220. #[tokio::test]
  221. async fn test_config_address_ipv4() {
  222. let config = Config {
  223. bind_address: "0.0.0.0".to_string(),
  224. port: 8080,
  225. cache_ttl_seconds: 10,
  226. };
  227. let addr = config.address();
  228. assert_eq!(addr.to_string(), "0.0.0.0:8080");
  229. }
  230. #[tokio::test]
  231. async fn test_config_address_ipv6() {
  232. let config = Config {
  233. bind_address: "::".to_string(),
  234. port: 8080,
  235. cache_ttl_seconds: 10,
  236. };
  237. let addr = config.address();
  238. assert_eq!(addr.to_string(), "[::]:8080");
  239. }
  240. #[tokio::test]
  241. async fn test_config_address_ipv6_specific() {
  242. let config = Config {
  243. bind_address: "2001:db8::1".to_string(),
  244. port: 9090,
  245. cache_ttl_seconds: 10,
  246. };
  247. let addr = config.address();
  248. assert_eq!(addr.to_string(), "[2001:db8::1]:9090");
  249. }
  250. #[tokio::test]
  251. async fn test_config_address_ipv6_with_brackets() {
  252. let config = Config {
  253. bind_address: "[::1]".to_string(),
  254. port: 8080,
  255. cache_ttl_seconds: 10,
  256. };
  257. let addr = config.address();
  258. assert_eq!(addr.to_string(), "[::1]:8080");
  259. }
  260. #[tokio::test]
  261. async fn test_status_server_creation() {
  262. let cache = create_cache(10);
  263. let _server = StatusServer::new_with_ttl(cache, 10);
  264. // 服务器创建成功,没有 panic
  265. }
  266. #[tokio::test]
  267. async fn test_serve_health() {
  268. let response = StatusServer::serve_health();
  269. assert_eq!(response.status(), StatusCode::OK);
  270. let headers = response.headers();
  271. assert_eq!(headers.get("content-type").unwrap(), "text/plain");
  272. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  273. assert_eq!(std::str::from_utf8(&body).unwrap(), "OK");
  274. }
  275. #[tokio::test]
  276. async fn test_serve_404() {
  277. let response = StatusServer::serve_404();
  278. assert_eq!(response.status(), StatusCode::NOT_FOUND);
  279. let headers = response.headers();
  280. assert_eq!(
  281. headers.get("content-type").unwrap(),
  282. "text/plain; charset=utf-8"
  283. );
  284. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  285. assert_eq!(std::str::from_utf8(&body).unwrap(), "页面未找到");
  286. }
  287. #[tokio::test]
  288. async fn test_serve_error() {
  289. let message = "测试错误".to_string();
  290. let response =
  291. StatusServer::serve_error(message.clone(), StatusCode::INTERNAL_SERVER_ERROR);
  292. assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
  293. let headers = response.headers();
  294. assert_eq!(
  295. headers.get("content-type").unwrap(),
  296. "text/plain; charset=utf-8"
  297. );
  298. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  299. assert_eq!(std::str::from_utf8(&body).unwrap(), message);
  300. }
  301. #[tokio::test]
  302. async fn test_render_html_template() {
  303. let stats = create_test_stats("测试主机", 0.75);
  304. let html = StatusServer::render_html_template(&stats, 10);
  305. // 检查 HTML 是否包含预期的内容
  306. assert!(html.contains("测试主机"));
  307. assert!(html.contains("75"));
  308. assert!(html.contains("1024")); // 内存总量 MB
  309. assert!(html.contains("512")); // 已用内存 MB
  310. assert!(html.contains("256")); // 可用内存 MB
  311. assert!(html.contains("128")); // 缓存内存 MB
  312. // 检查 CPU 详细分解
  313. assert!(html.contains("处理器"));
  314. assert!(html.contains("用户态"));
  315. assert!(html.contains("内核态"));
  316. assert!(html.contains("低优先级"));
  317. }
  318. #[tokio::test]
  319. async fn test_render_html_template_special_chars() {
  320. let stats = create_test_stats("主机<>&\"'", 0.5);
  321. let html = StatusServer::render_html_template(&stats, 10);
  322. // 检查特殊字符是否被正确处理
  323. assert!(html.contains("主机<>&\"'"));
  324. assert!(html.contains("50"));
  325. }
  326. #[tokio::test]
  327. async fn test_render_html_template_memory_values() {
  328. let stats = SystemStats {
  329. hostname: "test".to_string(),
  330. cpu_usage: 0.5,
  331. cpu_stats: crate::stats::CpuStats {
  332. overall: crate::stats::CpuUsageBreakdown {
  333. user_percent: 25.0,
  334. nice_percent: 5.0,
  335. system_percent: 20.0,
  336. total_percent: 50.0,
  337. },
  338. per_core: vec![
  339. crate::stats::CpuUsageBreakdown {
  340. user_percent: 30.0,
  341. nice_percent: 5.0,
  342. system_percent: 15.0,
  343. total_percent: 50.0,
  344. },
  345. crate::stats::CpuUsageBreakdown {
  346. user_percent: 20.0,
  347. nice_percent: 5.0,
  348. system_percent: 25.0,
  349. total_percent: 50.0,
  350. },
  351. ],
  352. core_count: 2,
  353. },
  354. memory_total: 2048 * 1024 * 1024, // 2GB
  355. memory_used: 1024 * 1024 * 1024, // 1GB
  356. memory_available: 512 * 1024 * 1024, // 512MB
  357. memory_cached: 256 * 1024 * 1024, // 256MB
  358. memory_free: 256 * 1024 * 1024, // 256MB
  359. timestamp: Instant::now(),
  360. };
  361. let html = StatusServer::render_html_template(&stats, 10);
  362. // 检查内存值是否正确转换为 MB
  363. assert!(html.contains("2048")); // 总内存 2GB = 2048MB
  364. assert!(html.contains("1024")); // 已用内存 1GB = 1024MB
  365. assert!(html.contains("512")); // 可用内存 512MB
  366. assert!(html.contains("256")); // 缓存内存 256MB
  367. assert!(html.contains("256")); // 空闲内存 256MB
  368. }
  369. #[tokio::test]
  370. async fn test_handle_request_root() {
  371. let cache = create_cache(10);
  372. let request = Request::builder()
  373. .method("GET")
  374. .uri("/")
  375. .body(Body::empty())
  376. .unwrap();
  377. let response = StatusServer::handle_request(request, cache, 10)
  378. .await
  379. .unwrap();
  380. assert_eq!(response.status(), StatusCode::OK);
  381. }
  382. #[tokio::test]
  383. async fn test_handle_request_health() {
  384. let cache = create_cache(10);
  385. let request = Request::builder()
  386. .method("GET")
  387. .uri("/health")
  388. .body(Body::empty())
  389. .unwrap();
  390. let response = StatusServer::handle_request(request, cache, 10)
  391. .await
  392. .unwrap();
  393. assert_eq!(response.status(), StatusCode::OK);
  394. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  395. assert_eq!(std::str::from_utf8(&body).unwrap(), "OK");
  396. }
  397. #[tokio::test]
  398. async fn test_handle_request_404() {
  399. let cache = create_cache(10);
  400. let request = Request::builder()
  401. .method("GET")
  402. .uri("/notfound")
  403. .body(Body::empty())
  404. .unwrap();
  405. let response = StatusServer::handle_request(request, cache, 10)
  406. .await
  407. .unwrap();
  408. assert_eq!(response.status(), StatusCode::NOT_FOUND);
  409. }
  410. #[tokio::test]
  411. async fn test_handle_request_post_method() {
  412. let cache = create_cache(10);
  413. let request = Request::builder()
  414. .method("POST")
  415. .uri("/")
  416. .body(Body::empty())
  417. .unwrap();
  418. let response = StatusServer::handle_request(request, cache, 10)
  419. .await
  420. .unwrap();
  421. assert_eq!(response.status(), StatusCode::NOT_FOUND);
  422. }
  423. #[tokio::test]
  424. async fn test_serve_html_with_cache() {
  425. let cache = create_cache(10);
  426. // 更新缓存数据
  427. let stats = create_test_stats("缓存测试", 0.8);
  428. cache.update(stats);
  429. // 模拟请求处理
  430. let request = Request::builder()
  431. .method("GET")
  432. .uri("/")
  433. .body(Body::empty())
  434. .unwrap();
  435. let response = StatusServer::handle_request(request, cache.clone(), 10)
  436. .await
  437. .unwrap();
  438. assert_eq!(response.status(), StatusCode::OK);
  439. let body = hyper::body::to_bytes(response.into_body()).await.unwrap();
  440. let html = std::str::from_utf8(&body).unwrap();
  441. // 检查响应是否包含缓存的数据
  442. assert!(html.contains("缓存测试"));
  443. assert!(html.contains("80"));
  444. }
  445. }
  446. /// 配置结构
  447. #[derive(Debug, Clone)]
  448. pub struct Config {
  449. /// 服务端绑定地址(支持 IPv4 和 IPv6)
  450. pub bind_address: String,
  451. /// 服务端端口
  452. pub port: u16,
  453. /// 缓存 TTL(秒)
  454. pub cache_ttl_seconds: u64,
  455. }
  456. impl Default for Config {
  457. #[inline]
  458. fn default() -> Self {
  459. Self {
  460. // 使用 :: 作为默认地址,支持 IPv4 和 IPv6 双栈
  461. bind_address: "::".to_string(),
  462. port: 8080,
  463. cache_ttl_seconds: 10, // 严格 10 秒过期
  464. }
  465. }
  466. }
  467. impl Config {
  468. /// 构建服务器地址
  469. #[inline]
  470. pub fn address(&self) -> SocketAddr {
  471. // 对于 IPv6 地址,需要用方括号包围
  472. let addr_str = if self.bind_address.contains(':') && !self.bind_address.starts_with('[') {
  473. format!("[{}]:{}", self.bind_address, self.port)
  474. } else {
  475. format!("{}:{}", self.bind_address, self.port)
  476. };
  477. addr_str.parse().expect("无效的地址格式")
  478. }
  479. }