From 15d7eae1e041127c633e4048354cf7e99ec1d57f Mon Sep 17 00:00:00 2001 From: Odboy Date: Sun, 15 Nov 2026 12:10:59 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=20rust=20=E7=A4=BA?= =?UTF-8?q?=E4=BE=8B=EF=BC=88=E6=A0=87=E5=87=86=E5=BA=93=20TcpListener=20W?= =?UTF-8?q?eb=20=E6=9C=8D=E5=8A=A1=EF=BC=8Ccompile-rust=20/=20runtime-rust?= =?UTF-8?q?=20=E4=B8=A4=E9=98=B6=E6=AE=B5=E6=9E=84=E5=BB=BA=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/main.rs:零第三方依赖的 HTTP/1.1 服务,提供 /、/api/info、/health、 /api/hello、/page;App 用 Arc 共享后 clone 进 thread::spawn,保证 'static - Dockerfile:依赖预热层的桩产物放到 /tmp/deps-target,避免与正式编译 共用 /src/target 时被判定 up-to-date、把桩二进制拷进运行镜像;运行阶段 增加 grep 启动日志的构建期自检 - docker-compose.yml:固定 IP 172.31.2.20,端口 8088,netstat 健康检查 --- demo/app/rust/.dockerignore | 3 + demo/app/rust/.gitignore | 1 + demo/app/rust/Cargo.toml | 15 +++ demo/app/rust/Dockerfile | 30 ++++++ demo/app/rust/README.md | 64 +++++++++++ demo/app/rust/build.sh | 11 ++ demo/app/rust/docker-compose.yml | 27 +++++ demo/app/rust/shutdown.sh | 4 + demo/app/rust/src/main.rs | 180 +++++++++++++++++++++++++++++++ demo/app/rust/startup.sh | 4 + 10 files changed, 339 insertions(+) create mode 100644 demo/app/rust/.dockerignore create mode 100644 demo/app/rust/.gitignore create mode 100644 demo/app/rust/Cargo.toml create mode 100644 demo/app/rust/Dockerfile create mode 100644 demo/app/rust/README.md create mode 100755 demo/app/rust/build.sh create mode 100644 demo/app/rust/docker-compose.yml create mode 100755 demo/app/rust/shutdown.sh create mode 100644 demo/app/rust/src/main.rs create mode 100755 demo/app/rust/startup.sh diff --git a/demo/app/rust/.dockerignore b/demo/app/rust/.dockerignore new file mode 100644 index 0000000..5c3ba1e --- /dev/null +++ b/demo/app/rust/.dockerignore @@ -0,0 +1,3 @@ +target/ +.git/ +.DS_Store diff --git a/demo/app/rust/.gitignore b/demo/app/rust/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/demo/app/rust/.gitignore @@ -0,0 +1 @@ +/target diff --git a/demo/app/rust/Cargo.toml b/demo/app/rust/Cargo.toml new file mode 100644 index 0000000..caf453d --- /dev/null +++ b/demo/app/rust/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "rust-demo" +version = "1.0.0" +edition = "2021" +description = "Rust 简单 Web 示例,只用标准库 TcpListener,无第三方依赖" + +[dependencies] + +[profile.release] +# 产物更小、启动更快;运行镜像里只需这一个静态二进制 +opt-level = "z" +lto = true +codegen-units = 1 +strip = true +panic = "abort" diff --git a/demo/app/rust/Dockerfile b/demo/app/rust/Dockerfile new file mode 100644 index 0000000..7842710 --- /dev/null +++ b/demo/app/rust/Dockerfile @@ -0,0 +1,30 @@ +# 编译阶段:compile-rust(Rust 1.100 + gcc/make,crates 源走 USTC 镜像) +FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-rust AS build +WORKDIR /src + +# 先只拷贝清单文件,预热依赖层;本示例无第三方依赖,有依赖时会走 CARGO_HOME 里的镜像源 +COPY Cargo.toml Cargo.lock* ./ +# 用单独的 target-dir 放桩产物,不要落在 /src/target: +# 否则后面的正式编译会看到“产物比源码新”而跳过重编,把桩二进制拷进运行镜像。 +RUN mkdir -p src && echo 'fn main() {}' > src/main.rs \ + && cargo build --release --target-dir /tmp/deps-target \ + && rm -rf src + +COPY src ./src +# 先只读离线编译,失败再回退联网(无第三方依赖时 --offline 一定成功) +RUN cargo build --release --target-dir /src/target --offline \ + || cargo build --release --target-dir /src/target + +# 运行阶段:runtime-rust(rustc/cargo 运行时基础,自带 glibc) +FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-rust AS runtime +LABEL MAINTAINER="tianjun@odboy.cn" +ENV TimeZone=Asia/Shanghai +ENV APP_PORT=8088 +WORKDIR /home/admin +COPY --from=build /src/target/release/rust-demo ./rust-demo +# 构建期自检:二进制里必须有启动日志,否则说明拷进来的是桩程序,让构建直接失败 +RUN grep -q "rust demo listening on" /home/admin/rust-demo || \ + (echo "stale/stub binary copied into runtime image" >&2 && exit 1) +EXPOSE 8088 +# exec 形式,示例只用标准库,不依赖 tokio;SIGTERM 由内核默认终止,无额外清理逻辑 +ENTRYPOINT ["/home/admin/rust-demo"] diff --git a/demo/app/rust/README.md b/demo/app/rust/README.md new file mode 100644 index 0000000..968957d --- /dev/null +++ b/demo/app/rust/README.md @@ -0,0 +1,64 @@ +# rust 示例 + +演示如何用 `compile-rust` + `runtime-rust` 两阶段构建一个 Rust 1.100 Web 服务。只用标准库 `TcpListener` 手写 HTTP/1.1, +无第三方 crate,因此示例构建不依赖 crates.io,离线也能编译。 + +| 阶段 | 镜像 | 说明 | +| --- | --- | --- | +| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-rust` | rustc/cargo + gcc/make,crates 源走阿里云镜像 | +| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:runtime-rust` | rustc/cargo 运行时;示例只跑二进制,不需要工具链 | + +### 示例内容 + +``` +rust/ +├── Cargo.toml # edition 2021,无依赖;release 开 LTO / strip / panic=abort 减小体积 +├── src/main.rs # 标准库 TcpListener:/、/api/info、/health、/api/hello、/page +├── Dockerfile # 两阶段:compile-rust -> runtime-rust +├── build.sh # 构建镜像(PUSH=1 时同时推送) +├── docker-compose.yml # 部署编排(端口 8088,固定 IP 172.31.2.20) +├── startup.sh # docker-compose up -d +└── shutdown.sh # docker-compose down +``` + +### 构建与部署 + +```shell +sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-rust . +PUSH=1 sh build.sh # 构建并推送 +sh startup.sh # docker-compose -f docker-compose.yml -p rust-demo up -d +``` + +访问: + +```shell +curl http://127.0.0.1:8088/ # {"message":"rust demo is running",...} +curl http://127.0.0.1:8088/health # ok +curl http://127.0.0.1:8088/api/hello?name=demo +``` + +浏览器打开 http://127.0.0.1:8088/page 可看到 HTML 页面。 + +### 关键点 + +**无第三方依赖**:示例只用了 `std`,构建时不需要访问 crates.io。要用 axum / actix-web 时, +在 `Cargo.toml` 加依赖即可,`compile-rust` 里已经把 crates 源换成阿里云稀疏索引,Dockerfile 不用改。 + +**依赖层缓存**:先 `COPY Cargo.toml` 并用一个空 `main.rs` 跑一次 `cargo build --release`, +再 `COPY src` 正式编译;只有 `Cargo.toml` 变化时才会重新编译依赖。 + +桩产物放在 `--target-dir /tmp/deps-target`,不落到 `/src/target`,避免正式编译看到“产物比源码新” +而跳过重编、把桩程序拷进运行镜像;运行阶段还会 `grep` 二进制里的启动日志做构建期自检。 + +**时间换算不引 chrono**:标准库里没有日期格式化,示例用 Howard Hinnant 的 `civil_from_days` 算法把 UTC 秒数 +换成 `YYYY-MM-DD HH:MM:SS +08:00`,保持零依赖。 + +**线程模型**:`App` 用 `Arc` 共享,每个连接 `Arc::clone` 后 `thread::spawn`,只适合示例;生产用 tokio/axum 异步处理。 + +**停止**:`ENTRYPOINT ["/home/admin/rust-demo"]` 为 exec 形式,SIGTERM 可直接终止进程,无额外清理逻辑。 + +### 停止 + +```shell +sh shutdown.sh +``` diff --git a/demo/app/rust/build.sh b/demo/app/rust/build.sh new file mode 100755 index 0000000..3452a4c --- /dev/null +++ b/demo/app/rust/build.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成) +set -euo pipefail +cd "$(dirname "$0")" + +IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-rust} +docker build -t "${IMAGE}" . + +if [ "${PUSH:-0}" = "1" ]; then + docker push "${IMAGE}" +fi diff --git a/demo/app/rust/docker-compose.yml b/demo/app/rust/docker-compose.yml new file mode 100644 index 0000000..a9a6b8b --- /dev/null +++ b/demo/app/rust/docker-compose.yml @@ -0,0 +1,27 @@ +networks: + rust-demo: + ipam: + driver: default + config: + - subnet: "172.31.2.0/24" + +services: + demo: + image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-rust # 镜像由 build.sh 构建 + container_name: rust-demo + restart: unless-stopped + ports: # 映射端口 + - "8088:8088" + environment: # 设置环境变量,相当于docker run命令中的-e + TZ: Asia/Shanghai + APP_PORT: "8088" + healthcheck: + # 运行镜像自带 net-tools,直接用端口探测,不额外安装 curl + test: ["CMD-SHELL", "netstat -tln | grep -q ':8088 '"] + interval: 30s + timeout: 5s + retries: 3 + start_period: 5s + networks: + rust-demo: + ipv4_address: 172.31.2.20 diff --git a/demo/app/rust/shutdown.sh b/demo/app/rust/shutdown.sh new file mode 100755 index 0000000..85742b5 --- /dev/null +++ b/demo/app/rust/shutdown.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +docker-compose -f docker-compose.yml -p rust-demo down diff --git a/demo/app/rust/src/main.rs b/demo/app/rust/src/main.rs new file mode 100644 index 0000000..a897723 --- /dev/null +++ b/demo/app/rust/src/main.rs @@ -0,0 +1,180 @@ +//! Rust 简单 Web 示例:只用标准库 `TcpListener` 手写 HTTP/1.1,无第三方依赖。 +//! +//! 这样示例的构建不依赖 crates.io,离线也能编译;换成 axum/actix-web 只需替换 +//! `handle` 与 `Cargo.toml` 的依赖,Dockerfile 与部署方式不用改。 + +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::Arc; +use std::thread; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; + +/// 国内时区 UTC+8,容器内 TZ 即使没生效也能输出正确时间 +const TZ_OFFSET_SECS: u64 = 8 * 3600; + +struct App { + started: Instant, +} + +impl App { + fn info(&self) -> String { + format!( + "{{\"message\":\"rust demo is running\",\"rust\":\"{}\",\"os\":\"{}\",\"hostname\":\"{}\",\"zoneId\":\"+08:00\",\"time\":\"{}\",\"uptime\":\"{}s\"}}", + env!("CARGO_PKG_VERSION"), + std::env::consts::OS, + hostname(), + now_tz8(), + self.started.elapsed().as_secs(), + ) + } +} + +fn main() { + let port = std::env::var("APP_PORT").unwrap_or_else(|_| "8088".to_string()); + let addr = format!("0.0.0.0:{port}"); + let listener = TcpListener::bind(&addr).unwrap_or_else(|e| { + eprintln!("rust demo: bind {addr} failed: {e}"); + std::process::exit(1); + }); + println!("rust demo listening on http://{addr}"); + + let app = Arc::new(App { + started: Instant::now(), + }); + for stream in listener.incoming() { + let stream = match stream { + Ok(s) => s, + Err(e) => { + eprintln!("rust demo: accept failed: {e}"); + continue; + } + }; + // 每个连接一个线程:示例规模够用;生产建议用 tokio/axum。 + // App 用 Arc 共享,clone 出的 Arc 是 'static 的,可以直接 move 进线程。 + let app = Arc::clone(&app); + thread::spawn(move || handle(stream, &app)); + } +} + +fn handle(mut stream: TcpStream, app: &App) { + let mut buf = [0u8; 2048]; + let n = match stream.read(&mut buf) { + Ok(n) if n > 0 => n, + _ => return, + }; + let req = String::from_utf8_lossy(&buf[..n]); + let mut parts = req.lines().next().unwrap_or("").split_whitespace(); + let method = parts.next().unwrap_or(""); + let target = parts.next().unwrap_or("/"); + let path = target.split('?').next().unwrap_or("/"); + let query = target.split_once('?').map(|(_, q)| q).unwrap_or(""); + + let (code, ctype, body) = match (method, path) { + ("GET" | "HEAD", "/" | "/api/info") => (200, "application/json; charset=utf-8", app.info()), + ("GET" | "HEAD", "/health") => (200, "text/plain; charset=utf-8", "ok\n".to_string()), + ("GET" | "HEAD", "/api/hello") => { + let name = query_value(query, "name").unwrap_or_else(|| "demo".to_string()); + ( + 200, + "application/json; charset=utf-8", + format!( + "{{\"message\":\"Hello, {}!\",\"time\":\"{}\"}}", + json_escape(&name), + now_tz8() + ), + ) + } + ("GET" | "HEAD", "/page") => (200, "text/html; charset=utf-8", page(app)), + ("GET" | "HEAD", _) => ( + 404, + "application/json; charset=utf-8", + "{\"error\":\"not found\"}".to_string(), + ), + _ => (405, "text/plain; charset=utf-8", "method not allowed".to_string()), + }; + + let head_only = method == "HEAD"; + let body = if head_only { String::new() } else { body }; + let resp = format!( + "HTTP/1.1 {code} {reason}\r\nContent-Type: {ctype}\r\nContent-Length: {len}\r\nConnection: close\r\n\r\n{body}", + reason = status_reason(code), + len = body.len(), + ); + let _ = stream.write_all(resp.as_bytes()); + let _ = stream.flush(); +} + +fn status_reason(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 405 => "Method Not Allowed", + _ => "Unknown", + } +} + +fn page(app: &App) -> String { + let info = app.info(); + format!( + "\n\nrust demo\n\ +\n\n\n

rust demo 运行信息

\n\ +
{info}
\n

其他接口:/health、/api/hello?name=x

\n\n\n" + ) +} + +fn query_value(query: &str, key: &str) -> Option { + query.split('&').find_map(|kv| { + let (k, v) = kv.split_once('=')?; + if k == key { + Some( + v.replace('+', " ") + .replace("%20", " "), + ) + } else { + None + } + }) +} + +fn json_escape(s: &str) -> String { + s.replace('\\', "\\\\").replace('"', "\\\"") +} + +fn hostname() -> String { + std::fs::read_to_string("/etc/hostname") + .map(|s| s.trim().to_string()) + .unwrap_or_else(|_| "unknown".to_string()) +} + +/// 输出 `YYYY-MM-DD HH:MM:SS +08:00`,只用标准库推算,不引 chrono +fn now_tz8() -> String { + let secs = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) + + TZ_OFFSET_SECS; + let (y, m, d) = civil_from_days((secs / 86400) as i64); + let rem = secs % 86400; + format!( + "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02} +08:00", + rem / 3600, + (rem % 3600) / 60, + rem % 60 + ) +} + +/// 天数(自 1970-01-01)转公历年月日,Howard Hinnant 的 civil_from_days 算法 +fn civil_from_days(z: i64) -> (i64, u32, u32) { + let z = z + 719468; + let era = if z >= 0 { z } else { z - 146096 } / 146097; + let doe = (z - era * 146097) as u64; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + let y = yoe as i64 + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} diff --git a/demo/app/rust/startup.sh b/demo/app/rust/startup.sh new file mode 100755 index 0000000..b1c8e22 --- /dev/null +++ b/demo/app/rust/startup.sh @@ -0,0 +1,4 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")" +docker-compose -f docker-compose.yml -p rust-demo up -d