diff --git a/.cocoon-plan.md b/.cocoon-plan.md index b6b6131..f501849 100644 --- a/.cocoon-plan.md +++ b/.cocoon-plan.md @@ -1,447 +1,13 @@ -# Cocoon 发展规划(自主维护) -> 此文件由 cron 任务每3小时更新,记录项目状态与下一步计划。 - -## 路线图 - -### Phase 1 — 核心稳定(当前) -- [x] HTTP/1.1 请求解析 -- [x] 响应头格式化 -- [x] 静态文件服务(sendfile) -- [x] 目录浏览 -- [x] Range 请求 -- [x] MIME 类型识别 -- [x] 多线程 M:N 调度 -- [x] 命令行参数 -- [x] 优雅关闭 - -### Phase 2 — 健壮性 -- [x] HTTP 缓存(ETag / Last-Modified / If-None-Match)✅ 2026-06-03 -- [x] 连接超时管理(空闲连接自动清理)✅ 2026-06-03 -- [x] 最大并发连接数限制 ✅ 2026-06-03 -- [x] 分级日志系统(error / warn / info / debug)✅ 2026-06-03 -- [x] 访问日志(Nginx combined 格式,含 User-Agent / Referer)✅ 2026-06-05 -- [x] Gzip 压缩 ✅ 2026-06-03(已接入响应流程) -- [x] Brotli 压缩 ✅ 2026-06-04(优先于 Gzip) -- [x] 集成测试 suite(68 项 curl/bash 测试全部通过)✅ 2026-06-06 -- [x] 性能基准(wrk: ~16.2K RPS / ~60μs 延迟)✅ 2026-06-03 -- [x] 请求体解析(POST 支持)✅ 2026-06-03 - - Content-Length 读取 - - JSON / form-urlencoded 回显 - - **multipart/form-data 文件上传**(保存到 root_dir/uploads/)✅ 2026-06-04 -- [x] C 语言单元测试框架 ✅ 2026-06-03(Unity 框架,142 个测试全部通过) -- [x] **WebSocket 单元测试** ✅ 2026-06-06(12 项,覆盖帧解析/编码/握手/粘包/大负载) -- [x] **健康检查端点** /_health ✅ 2026-06-06(JSON 状态:连接数、插件、中间件、运行时间) - -### Phase 3 — 扩展(已完成) -- [x] **配置文件支持** — JSON 配置替代纯命令行 ✅ 2026-06-04 -- [x] **Brotli 压缩** — 比 gzip 更高压缩率,现代浏览器均支持 ✅ 2026-06-04 -- [x] **HTTPS / TLS** — OpenSSL Memory BIO 集成 ✅ 2026-06-04 -- [x] **HTTP/2** — nghttp2 完整实现(TLS ALPN + h2c + 静态文件 + 缓存)✅ 2026-06-04 -- [x] **HTTP/2 目录浏览** — 无 index.html 时返回目录列表 ✅ 2026-06-04 -- [x] **WebSocket 支持** — RFC 6455 握手 + 帧解析/编码 + echo + 广播/频道 ✅ 2026-06-05 -- [x] **Windows 兼容性** — 跨平台抽象层 ✅ 2026-06-04 -- [x] **反向代理** — 路径前缀匹配 → HTTP/1.1 后端,JSON 配置支持 ✅ 2026-06-07 - - `proxy.h` / `proxy.c`:路径前缀匹配、HTTP/1.1 后端转发、X-Forwarded-* 头透传 - - `cocoon.json`:支持 `proxies` 数组配置 - - 80 项集成测试全部通过(含 3 项代理测试) - -### Phase 4 — 生态 -- [x] **WebSocket 广播/频道路由** — 全局连接注册表 + 广播/定向发送 API ✅ 2026-06-05 -- [x] **中间件机制** — 注册表 + 链式执行,内置 CORS / Basic Auth / Rate Limit ✅ 2026-06-06 -- [x] **插件系统** — 动态加载 .so/.dll 扩展 ✅ 2026-06-06(MVP:dlopen + 中间件注册 + 示例插件) -- [x] **反向代理 HTTPS 后端** — 轻量级 OpenSSL 客户端封装,支持 TLS 1.2+ 握手 + SNI ✅ 2026-06-08 -- [x] **反向代理负载均衡** — 轮询调度 + 故障自动转移,多后端支持(最多8个)✅ 2026-06-08 -- [x] **Prometheus 指标端点** — `/_metrics` 导出 10 项指标,响应码分类计数器 ✅ 2026-06-08 - -## 当前状态:恢复开发 - -> **注意**:用户已指示恢复 cocoon 开发,继续推进新功能。不暂停。 - -- 所有 Phase 1-4 核心功能已完成 -- 编译通过,零警告 -- **190 个单元测试全部通过** + **106 项集成测试全部通过** -- 待办池已清空,所有计划项已完成 -## 待办池(活跃) -1. ~~HTTP/2 代理支持~~ ✅ 2026-06-09 -2. ~~连接池 HTTP/1.0 兼容~~ ✅ 2026-06-09 - - 后端发送 Connection: close 时正确关闭连接而非归还 -3. ~~HTTP/2 代理流式转发~~ ✅ 2026-06-10 — 响应头立即发送,body 通过 DATA 帧实时流式转发,避免完整缓冲大响应体 -4. ~~虚拟主机 / 多站点~~ ✅ 2026-06-09 — 基于 Host 头匹配,HTTP/1.1 + HTTP/2 均支持 -5. ~~主动健康检查~~ ✅ 2026-06-09 — 后台线程定期探测后端,4 项集成测试 + 17 项单元测试覆盖 - -## 最近行动记录 - -- 2026-06-10 00:00: **HTTP/2 代理流式转发** - - `http2.h`: `http2_stream_data_t` 新增流式代理字段(`proxy_backend_fd`, `proxy_tls_conn`, `proxy_use_https`, `proxy_eof`, `proxy_close_backend`, `proxy_backend`) - - `http2.c`: 新增 `proxy_data_source_read_callback` 回调函数 - - 优先返回已缓存的 body(recv_headers 可能已经读取部分 body) - - 然后从后端 socket/TLS 实时读取数据流式转发 - - 数据读取完毕后自动关闭后端连接或归还连接池 - - `http2.c`: `http2_serve_proxy` 重构为流式转发模式 - - 解析响应头后立即发送 HTTP/2 响应头(使用 `proxy_data_source_read_callback`) - - 删除完整缓冲 body 的旧逻辑(64KB response_buf 限制解除) - - 支持任意大小的响应体流式转发 - - `http2.c`: 流创建/销毁处正确初始化/清理代理字段 - - 编译零警告,190 个单元测试 + 106 项集成测试全部通过 - - 提交已推送到 `main` - -- 2026-06-09 21:00: **proxy 模块单元测试(31项)** - - 新增 `tests/unit/test_proxy.c`:31 项单元测试,白盒包含 `proxy.c` 访问 static 函数 - - `proxy_init`:配置初始化清零 - - `proxy_add_rule`:添加规则、追加后端、参数校验(空值/空字符串) - - `proxy_match`:精确匹配、前缀匹配、多规则、NULL参数 - - `select_backend_sww`:平滑加权轮询(单后端、等权重分布、不等权重 3:1 严格验证、跳过不健康、全部不健康返回 NULL) - - `select_backend_sww_all`:fallback 包含不健康后端 - - `parse_backend_url`:http/https/无 scheme/无端口/带路径解析 - - `proxy_build_forwarded_path`:无目标路径、有目标路径拼接、空剩余路径 - - `proxy_update_health`:成功阈值恢复(2次)、失败阈值标记(3次)、计数器重置 - - `proxy_pool_init`:默认大小、超过上限裁剪(16)、零值回退默认(4) - - `Makefile`:新增 `test_proxy` 编译规则 - - `.gitignore`:补全 `test_healthcheck` / `test_proxy` 二进制忽略 - - 编译零警告,190 个单元测试 + 106 项集成测试全部通过 - - 提交已推送到 `main` (`5d4c78c`) - -- 2026-06-09 18:00: **主动健康检查单元测试** - - 新增 `tests/unit/test_healthcheck.c`:17 项单元测试 - - `healthcheck_parse_status`:覆盖 200/404/500/100/302/503 正常解析、长度不足、非 HTTP 协议、非法状态码 - - `healthcheck_build_request`:覆盖默认路径 `/health`、自定义路径 `/ready`、空路径回退 - - `healthcheck_update_state`:覆盖健康阈值恢复(连续 2 次成功)、不健康阈值标记(连续 3 次失败)、计数器重置、单次失败/成功不触发状态变更、`last_check` 时间戳更新 - - `healthcheck_probe_once`:NULL 后端返回 false - - 使用 `#include "healthcheck.c"` 白盒测试技巧访问静态函数 - - `Makefile`:新增 `test_healthcheck` 编译规则(链接 proxy.c、http.c、platform.c 等依赖) - - 编译零警告,159 个单元测试 + 106 项集成测试全部通过 - - `.cocoon-plan.md`:标记主动健康检查完成 - - 提交已推送到 `main` - -- 2026-06-09 15:00: **虚拟主机 / 多站点支持** - - `cocoon.h`: 新增 `cocoon_vhost_t` 结构体(`server_name[256]` + `root_dir[512]`),`cocoon_config_t` 新增 `vhosts[COCOON_MAX_VHOSTS]` 和 `num_vhosts` - - `config.c`: JSON 解析器新增 `vhosts` 数组解析,每个对象支持 `server_name` 和 `root_dir` 字段 - - `server.c`: 新增 `vhost_match_root_dir()` + `conn_get_host()` 辅助函数 - - `handle_request()` 中解析请求后根据 Host 头匹配虚拟主机,使用对应的 `root_dir` 提供静态文件服务 - - `http2.h`: `http2_session_t` 新增 `server_config` 指针(用于虚拟主机匹配) - - `http2.c`: 新增 `http2_session_set_server_config()` API,`vhost_match_root_dir()` 辅助函数 - - `on_header_callback()`: `:authority` 伪头不再忽略,存储为 `Host` 普通头供匹配使用 - - `http2_serve_static()` / `http2_serve_post()`: 根据 stream 的 Host 头匹配虚拟主机根目录 - - `server.c`: 所有 HTTP/2 会话创建点(h2c 直接连接、Upgrade 升级、TLS ALPN)均调用 `http2_session_set_server_config()` - - `cocoon.json`: 示例配置添加 `vhosts` 数组示例 - - `tests/integration_test.sh`: 新增 3 项虚拟主机集成测试 - - `site-a.local` → 返回 Site A 内容 - - `site-b.local` → 返回 Site B 内容 - - `unknown.local` → 回退到全局默认内容 - - 编译零警告,142 个单元测试 + 106 项集成测试全部通过 - - 提交已推送到 `main` - -- 2026-06-09 12:00: **连接池 HTTP/1.0 兼容 + 配置合并 bug 修复** - - `proxy.c`: `proxy_relay_backend()` 中新增 `connection_closed` 标志 - - 当 `recv() == 0`(后端关闭连接)时标记 `connection_closed = true` - - 归还条件改为 `success && total > 0 && !connection_closed`,避免归还已关闭连接 - - `http2.c`: `http2_serve_proxy()` 中检测 HTTP/1.0 响应 - - `is_http10 = strncmp(response_buf, "HTTP/1.0", 8) == 0` - - HTTP/1.0 默认关闭连接,除非显式 `Connection: keep-alive` - - 修复 HTTP/2 代理复用 HTTP/1.0 后端已关闭连接导致响应失败的问题 - - `main.c`: 重写 `parse_args()` 参数解析逻辑 - - 问题:`config_merge(config, config, ...)` 中 `base == cmdline`,`free(base->tls_cert)` 后 `strdup(cmdline->tls_cert)` 导致 use-after-free - - 修复:先加载配置文件,再解析命令行参数(覆盖配置文件),避免 `config_merge` 自引用 - - `tests/http10_backend.py`: 新增 HTTP/1.0 后端模拟器 - - 模拟发送 `Connection: close` 后主动关闭连接的后端 - - 用于验证连接池正确处理已关闭连接 - - `tests/integration_test.sh`: 新增 HTTP/1.0 后端兼容测试(3 项) - - 第一次请求 200、第二次请求 200(必须新建连接)、连接管理日志检测 - - 编译零警告,142 个单元测试 + 99 项集成测试全部通过 - - 提交 `90601e0` 已推送到 `main` - - `http2.h`: `http2_session_t` 新增 `proxy_config` 和 `client_addr` 字段 - - `http2.c`: 新增 `http2_session_set_proxy_config()` 注入代理配置 - - `http2.c`: 新增 `http2_serve_proxy()` 函数,实现 HTTP/2 流 → HTTP/1.1 后端转发 - - 请求重组:将 HTTP/2 伪头(:method, :path, :authority)重组为 HTTP/1.1 请求 - - 后端响应解析:解析 HTTP/1.1 响应头,通过 nghttp2 提交 HTTP/2 响应帧 - - 过滤 hop-by-hop 头(Connection, Transfer-Encoding 等) - - 添加 X-Forwarded-For 头 - - 支持 TLS 和非 TLS 后端连接(通过 `proxy_tls.c`) - - `server.c`: `handle_http2()` 中调用 `http2_session_set_proxy_config()` 注入配置 - - `http2.c`: 修复 `parse_http1_response()` 中 `body_len` 下溢问题(当 `len < blank + 4 - data` 时) - - `tests/integration_test.sh`: 新增 HTTP/2 代理集成测试(GET 请求验证) - - 编译零警告,142 单元测试全部通过 - - 集成测试:HTTP/2 GET 代理测试通过,POST 待完善(连接池 HTTP/1.0 兼容问题) - - 提交已推送 `main` (7fe52a3) - -- 2026-06-09 06:00: **平滑加权轮询负载均衡** - - `proxy.h`: 后端结构添加 `weight`(配置权重)和 `current_weight`(动态权重)字段 - - `proxy.c`: 实现平滑加权轮询算法(Nginx SWW),`select_backend_sww()` + `select_backend_sww_all()` - - 算法:健康后端 current_weight += weight,选最大,选中后 -= total_weight - - 保证权重比例严格满足,分布均匀,不会连续打到同一后端 - - `proxy.c`: `proxy_add_rule` 新增 `weight` 参数,`backend_init` 初始化权重(默认1) - - `config.c`: JSON 解析器新增 `weight` 数字字段解析 - - `cocoon.h`: 代理配置结构新增 `uint32_t weight` 字段 - - `server.c`: 加载代理规则时传入配置的 `weight` - - `cocoon.json`: 示例配置展示多后端权重用法(`/api` → 3000:3 + 3001:1) - - `tests/integration_test.sh`: 新增加权轮询测试(3项:HTTP 200、权重日志验证、多后端分布验证) - - 编译零警告,142 单元测试 + 93 集成测试全部通过 - - 提交已推送 `main` (dc76585) - -- 2026-06-09 03:00: **连接池大小可配置** - - `proxy.h`: `COCOON_MAX_POOL_SIZE` → `COCOON_POOL_MAX_CAPACITY`(上限16)+ `COCOON_POOL_DEFAULT_SIZE`(默认4),`cocoon_conn_pool_t` 新增 `max_size` 字段 - - `proxy.c`: `proxy_pool_init` 接收 `max_pool_size` 参数,自动裁剪到上限;所有循环改用 `backend->pool.max_size` - - `proxy.c`: `proxy_add_rule` 新增 `pool_size` 参数,传递给 `parse_backend_url` → `proxy_pool_init` - - `cocoon.h`: `proxies` 配置结构新增 `uint32_t pool_size` 字段 - - `config.c`: JSON 解析器新增 `pool_size` 数字字段解析,默认值为 4 - - `server.c`: 调用 `proxy_add_rule` 时传入配置的 `pool_size` - - `cocoon.json`: 示例配置添加 `pool_size` 展示(`/api` → 8,`/backend` → 4) - - 编译零警告,142 单元测试 + 90 集成测试全部通过 - - 提交已推送 `main` - -- 2026-06-09 00:15: **后端连接池/keep-alive** - - `proxy.h`: 新增 `cocoon_pooled_conn_t` / `cocoon_conn_pool_t`(pthread_mutex 保护),后端嵌入连接池 - - `proxy.c`: 实现 `proxy_pool_init`/`destroy`/`acquire`/`release` + `proxy_config_destroy` - - `proxy.c`: `proxy_relay_backend` 使用连接池获取/归还,向后端发送 `Connection: keep-alive` - - `server.c`: `server_destroy` 调用 `proxy_config_destroy` 关闭所有连接池 - - `proxy.c`: 修复后端关闭连接后复用导致客户端超时的问题(recv 返回 0 时不再归还,直接重建) - - 编译零警告,142 单元测试 + 90 集成测试全部通过 - - 提交 `e13ff54` 已推送到 `main` - -- 2026-06-08 21:00: **后端被动健康检查 + SIGPIPE 崩溃修复** - - `proxy.h`: 为 `cocoon_proxy_backend_t` 增加健康状态字段(`healthy`/`fail_count`/`success_count`/`last_check`) - - `proxy.c`: 新增 `proxy_relay_backend()` 辅助函数,提取流式转发逻辑,避免两轮循环代码重复 - - `proxy.c`: `proxy_forward()` 优先尝试 healthy 后端,全部失败后再 fallback 到所有后端(含 unhealthy) - - `proxy.c`: 健康阈值:连续 2 次成功恢复,连续 3 次失败标记不健康(被动式检测) - - `main.c`: 新增 `signal(SIGPIPE, SIG_IGN)`,修复客户端提前关闭连接时 `SIGPIPE` 导致进程崩溃的问题 - - 编译零警告,142 单元测试 + 90 集成测试全部通过 - - 提交 `77979b4` 已推送到 `main` - -- 2026-06-08 18:00: **Prometheus 指标端点 /_metrics** - - `server.c`: 新增 7 个原子计数器(`g_total_requests`, `g_response_2xx/3xx/4xx/5xx/200/404`) - - `server.c`: 新增 `update_metrics()` 辅助函数,在 `handle_request` 所有响应路径统一调用 - - `server.c`: 新增 `/_metrics` 端点,返回 Prometheus 文本格式(10 项指标:7 个计数器 + 3 个仪表盘) - - `tests/integration_test.sh`: 新增 8 项 Prometheus 指标测试(状态码、字段检查、HEAD 支持、计数器递增验证) - - 编译零警告,142 单元测试 + 90 集成测试全部通过 - - 提交 `8ad8eca` 已推送到 `main` - -- 2026-06-08 16:10: **负载均衡(轮询 + 故障转移)** - - `proxy.h`: 重构数据结构,支持多后端(`cocoon_proxy_backend_t`,最多8个) - - `proxy.c`: 实现轮询调度 + 自动故障转移(后端连接失败时自动尝试下一个) - - `proxy.c`: `proxy_add_rule` 支持同 prefix 追加后端,自动合并为多后端规则 - - `server.c`: 匹配新签名 - - `cocoon.json`: 示例配置展示多后端用法(两个 backend 3000/3001) - - 编译零警告,142 单元测试 + 82 集成测试全部通过 - - 提交 `acda3b9` 已推送到 `main` - -- 2026-06-08 15:00: **维护检查** — 项目处于暂停状态(用户指示 "🤚cocoon") - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 82 项集成测试全部通过 ✓ - - 代码无改动,更新 `.cocoon-plan.md` 标注暂停状态 - - 不推进新功能,仅做状态验证 - - 特性列表新增 `🔄 反向代理` 条目 - - 路线图标记反向代理为 ✅ 完成 - - 模块职责表新增 `proxy.c` / `proxy_tls.c` - - 新增配置文件示例(含反向代理配置) - - 编译零警告,142 单元测试 + 82 集成测试全部通过 - - 提交并推送 `main` - -- 2026-06-08 11:35: **恢复开发 + HTTPS 反向代理** - - 恢复项目开发状态,暂停 ephemeral 方向 - - 新增 `proxy_tls.c` / `proxy_tls.h`:轻量级 OpenSSL 客户端封装 - - `proxy.c`:支持 HTTPS 后端连接(TLS 握手 + SNI + 透传 X-Forwarded-Proto: https) - - 集成测试:新增 `tests/https_backend.py` + 2 项 HTTPS 反向代理测试 - - 编译零警告,142 单元测试 + 82 集成测试全部通过 - - 提交 `a86b8a4` 已推送到 `main` -- 2026-06-08 09:00: **维护检查** — 项目处于暂停状态 - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓ - - 代码无改动,.cocoon-plan.md 记录更新 -- 2026-06-08 06:00: **维护检查** — 项目处于暂停状态 - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓ - - 代码无改动,.cocoon-plan.md 记录更新 -- 2026-06-08 03:00: **维护检查** — 项目处于暂停状态 - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓ - - 代码无改动,.cocoon-plan.md 记录更新 -- 2026-06-08 00:00: **维护检查 + 编译修复** — 项目处于暂停状态 - - 修复链接错误:移除 `server.c` 中 3 行重复的 `coco_version()` 日志调用(coco v2.2.0 子模块中 version.c 未编译进 libcoco.a,导致符号未定义) - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓(新增中间件相关测试项) - - 提交并推送 `90b0388` -- 2026-06-07 21:00: **维护检查** — 项目处于暂停状态,执行编译与测试验证 - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓ - - 代码无改动,.cocoon-plan.md 记录更新 -- 2026-06-07 18:00: **维护检查** — 项目处于暂停状态,执行编译与测试验证 - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓ - - 代码无改动,.cocoon-plan.md 记录更新 -- 2026-06-07 15:00: **维护检查** — 项目处于暂停状态,执行编译与测试验证 - - 编译通过:零警告(仅 coco 子模块 `.S` 文件 linker 提示,不影响功能) - - 142 个单元测试全部通过 ✓ - - 80 项集成测试全部通过 ✓ - - 代码无改动,无需提交 -- 2026-06-07 12:00: **项目暂停** — 用户指示停止 cocoon 新功能开发,核心任务转向 ephemeral 软件引擎。本轮 cron 执行仅更新计划文件,未新增代码。项目所有功能保持可用,编译和测试全部通过。 -- 2026-06-07: **本轮行动 — 为 config.c、log.c、tls.c 添加函数级 Doxygen 注释** - - `config.c`: 为 JSON 解析器内部函数(parser_init、parser_skip_ws、parser_next_token、token_expect、token_str_dup、token_to_long、str_to_log_level)和公共 API(config_load_from_file、config_merge)添加完整 Doxygen 注释 - - `log.c`: 为日志级别转换和输出函数(level_str、log_set_level、log_set_prefix、log_get_level、log_output、log_error、log_warn、log_info、log_debug)添加注释 - - `tls.c`: 为 TLS 连接管理(tls_lookup、tls_map_set、tls_map_clear)、Memory BIO 操作(socket_read、socket_write_all、flush_wbio)、ALPN 回调(tls_alpn_select_cb)和公共 API(tls_create_context、tls_destroy_context、tls_has_context、tls_accept、tls_read、tls_write、tls_close、tls_has_connection、tls_negotiated_http2)添加注释 - - `http2.c`: 移除过时的 TODO 占位注释(请求体收集已实现) - - 编译零警告,142 个单元测试 + 80 项集成测试全部通过 - - 推送到 main(9da9bd9) -- 2026-06-07: **本轮行动 — 修复编译警告与测试清理** - - `config.c`: 将 `strncpy` 替换为 `memcpy` + 显式 null 结尾,消除 `-Wstringop-truncation` 警告 - - `proxy.c`: 同上,修复 `proxy_add_rule` 中的 `strncpy` 警告 - - `tests/integration_test.sh`: 修复 `kill_server` 函数,补充 `pgrep -f "cocoon.*-c "` 以清理通过 `-c` 配置文件启动的测试服务器进程,解决端口占用导致测试失败的问题 - - 编译零警告,142 个单元测试 + 80 项集成测试全部通过 - - 推送到 main(1b930aa) -- 2026-06-07: **本轮行动 — 反向代理支持(MVP)** - - `proxy.h` / `proxy.c`:新增反向代理模块 - - `cocoon_proxy_rule_t` / `cocoon_proxy_config_t`:路径前缀匹配规则(最多 8 条) - - `proxy_init()` / `proxy_add_rule()`:解析 URL(`http://host:port/path`),提取 host / port / path / https 标志 - - `proxy_match()`:根据路径前缀查找匹配规则 - - `proxy_forward()`:连接后端(`gethostbyname` + `socket` + `connect`),流式转发 HTTP/1.1 请求 + 响应 - - 透传头:Host、X-Forwarded-For、X-Forwarded-Proto、Content-Type、Content-Length - - 目前不支持 HTTPS 后端(运行时拒绝并警告) - - `cocoon.h`:新增 `COCOON_MAX_PROXY_RULES = 8`,`cocoon_config_t` 添加 `proxies[8]` 和 `num_proxies` - - `config.c`:JSON 解析器新增 `proxies` 数组解析(对象项含 `prefix` 和 `target` 字符串) - - `server.c`: - - `connection_t` 新增 `server_context_t *ctx` 指针,用于 `handle_request()` 访问代理配置 - - `accept_loop()` 中设置 `conn->ctx = ctx` - - `server_create()` 中初始化代理规则(从配置加载) - - `handle_request()` 中在静态文件服务之前检查代理规则,匹配时调用 `proxy_forward()` - - `Makefile`:`proxy.c` 加入 `SRCS` 和 `test_server` 编译规则 - - `cocoon.json`:示例配置添加 `"proxies": [{"prefix": "/api", "target": "http://localhost:3000"}]` - - `tests/integration_test.sh`:新增 3 项反向代理集成测试(代理 GET 200、响应体包含后端内容、非代理路径静态文件正常) - - 编译通过(零警告),142 个单元测试 + 80 项集成测试全部通过 +- 2026-06-10 03:00: **SIGHUP 配置热重载** + - `server.h` / `server.c`: 新增 `server_request_reload()` 和 `server_reload_config()` 热重载 API + - `server_create()` 新增 `config_file_path` 参数,存储配置文件路径用于重载 + - `server_context_t` 新增 `config_file_path` 和 `volatile int reload_requested` 字段 + - 热重载范围:root_dir、log_level、access_log、gzip/brotli、timeout、max_connections、vhosts、proxies、healthcheck + - 保守策略:不释放旧字符串指针(避免活跃连接竞态),接受小内存泄漏 + - 不可热重载项:port、threaded、num_workers、tls_cert/key(日志警告) + - `accept_loop()`: 在 `accept()` 之后也检查 `reload_requested`,确保新连接使用最新配置 + - `main.c`: 新增 `sighup_handler()` 注册 `SIGHUP` 信号,`--help` 更新 Signals 说明 + - `tests/integration_test.sh`: 新增 SIGHUP 热重载集成测试(3项:初始配置、热重载后 root_dir 更新、热重载日志验证) + - 编译零警告,190 个单元测试 + 109 项集成测试全部通过 - 推送到 main -- 2026-06-07: **本轮行动 — HTTP/2 POST 请求体支持** - - `on_data_chunk_recv_callback`: 实现请求体收集,将 DATA 帧数据追加到 `stream->request.body` - - `on_frame_recv_callback`: 根据请求方法选择处理方式(GET/HEAD → `http2_serve_static`,POST → `http2_serve_post`) - - `http2_serve_post`: 新增函数,处理 HTTP/2 POST 请求 - - 支持 multipart/form-data 文件上传(保存到 root_dir/uploads/) - - 支持 application/json 和 x-www-form-urlencoded 回显 - - 构建 JSON 响应并通过 nghttp2 发送 - - 包含 `multipart.h` 和 `platform.h` 到 `http2.c` - - 全部 142 个单元测试 + 77 项集成测试通过,编译零警告 - - 推送到 main -- 2026-06-06: **本轮行动 — WebSocket 空闲超时 + 跨平台 poll/select 抽象** - - `platform.h` / `platform.c`: 新增 `cocoon_socket_poll_readable()` 跨平台 socket 可读等待 - - POSIX: `poll()` + `POLLIN` - - Windows: `select()` + `fd_set`(readfds) - - `websocket.c`: `ws_handle_connection()` 实现 `timeout_ms` 空闲超时处理 - - 每次循环前调用 `cocoon_socket_poll_readable()` 等待数据或超时 - - 超时时发送 `1001 Idle timeout` 关闭帧,清理连接资源 - - 解决 TODO: `/* TODO: 超时处理 */` - - `tests/websocket_test.py`: 新增 `test_timeout()` 测试(Python 标准库,零依赖) - - 连接后不发帧,验证服务端 2 秒后发送 1001 关闭帧 - - `tests/integration_test.sh`: 新增 WebSocket 空闲超时集成测试(启动 `-o 2000` 短超时服务器) - - `Makefile`: 补全 `test_websocket` 单元测试编译规则,加入 `platform.c`(修复 undefined reference) - - 全部 142 个单元测试 + 77 项集成测试通过,编译零警告 - - 推送到 main(待提交) -- 2026-06-06: **本轮行动 — 基础设施完善(Makefile + CI + README)** - - `Makefile`: 添加 `integration-test` 别名和 `test-all` 目标(一键运行全部测试) - - `.github/workflows/ci.yml`: GitHub Actions 工作流,push/PR 时自动编译 + 单元测试 + 集成测试 - - `README.md`: 同步项目现状,添加 CI badge、补充全部新特性与模块说明 - - 编译零警告,142 个单元测试 + 77 项集成测试全部通过 - - 推送到 main(87f89f5 → b0ae0f7 → 068ab7d) -- 2026-06-06: **本轮行动 — 插件热重载支持(SIGUSR1)** - - `plugin.c` / `plugin.h`: 新增 `cocoon_plugin_reload()` API,自动存储已加载插件路径 - - 热重载流程:卸载所有插件 → 按存储路径重新加载 → 日志输出成功/失败数量 - - `main.c`: 注册 SIGUSR1 信号处理器,收到信号后触发 `cocoon_plugin_reload()` - - `--help` 新增 Signals 说明文档 - - 集成测试:新增 2 项热重载测试(SIGUSR1 后 HTTP 200 验证 + 热重载日志验证) - - 全部 142 个单元测试 + 77 项集成测试通过,编译零警告 - - 推送到 main(80385d9) -- 2026-06-06: **本轮行动 — 健康检查端点 /_health** - - `server.c`:新增 `/_health` 路由,返回 JSON 服务器状态 - - 包含:uptime_seconds、connections.active/max、plugins.count/list、middleware.count/names - - `middleware.c` / `middleware.h`:新增 `cocoon_middleware_list()` 查询 API - - 集成测试:新增 7 项测试(状态码 200、JSON 字段验证、HEAD 支持、路径遍历防护) - - 全部 142 个单元测试 + 75 项集成测试通过,编译零警告 - - 推送到 main(09e592d) -- 2026-06-06: **本轮行动 — 插件配置数组支持 + 杂项修复** - - `config.c`:极简 JSON 解析器新增 `[`/`]` token 类型,支持字符串数组解析 - - `plugins` 字段向后兼容单字符串 `"plugins.so"`,向前支持数组 `["a.so", "b.so"]` - - `.gitignore`:补全遗漏的 `tests/unit/test_websocket` 二进制 - - `Makefile`:补全 `test_log` 单元测试编译规则(缺失导致 `make unit-test` 失败) - - `cocoon.json`:示例配置改为数组格式 `"plugins": ["plugins/hello.so"]` - - `test_config.c`:新增 3 项测试(`test_load_plugins_string`、`test_load_plugins_array`、`test_load_plugins_array_multiple`) - - 全部 142 个单元测试 + 68 项集成测试通过,编译零警告 - - 推送到 main(2dc29d0) -- 2026-06-06: **本轮行动 — 添加 WebSocket 单元测试** - - 新增 `tests/unit/test_websocket.c`:12 项 WebSocket 协议单元测试 - - 覆盖:帧解析(文本/二进制/关闭/空负载、掩码解掩码、16位/64位长度)、帧编码(文本/关闭/ping/pong)、握手验证(Sec-WebSocket-Accept)、粘包多帧解析、64KB 大负载、空负载边界 - - 使用 socketpair 创建内部通信管道,无需真实网络依赖 - - 全部 12 项测试通过,139 个单元测试 + 68 项集成测试全部通过 - - 推送到 main(faedbd5) -- 2026-06-06: **本轮行动 — 实现动态插件系统(Phase 4 MVP)** - - 新增 `tests/unit/test_websocket.c`:12 项 WebSocket 协议单元测试 - - 覆盖:帧解析(文本/二进制/关闭/空负载、掩码解掩码、16位/64位长度)、帧编码(文本/关闭/ping/pong)、握手验证(Sec-WebSocket-Accept)、粘包多帧解析、64KB 大负载、空负载边界 - - 使用 socketpair 创建内部通信管道,无需真实网络依赖 - - 全部 12 项测试通过,139 个单元测试 + 68 项集成测试全部通过 - - 推送到 main(faedbd5) -- 2026-06-06: **本轮行动 — 实现动态插件系统(Phase 4 MVP)** - - `plugin.h` / `plugin.c`:基于 dlopen/dlsym 的插件加载器,最多8个插件,逆序卸载 - - 插件接口:`cocoon_plugin_init()`(初始化)、`cocoon_plugin_shutdown()`(清理)、`cocoon_plugin_version()`(版本) - - 插件通过 `cocoon_middleware_register()` 注册中间件参与请求处理 - - 命令行:`--plugin ` 可多次指定 - - 配置文件:`plugins` 字段支持字符串路径(单插件,数组支持待扩展) - - `server.c`:在 `server_create()` 中加载插件,`server_destroy()` 中逆序卸载 - - `plugins/hello.c`:示例插件,演示中间件注册/注销/版本返回 - - `Makefile`:添加 `plugin.c` 和 `-ldl` 链接选项 - - `cocoon.json`:示例配置添加 `"plugins": "plugins/hello.so"` - - `.gitignore`:排除 `plugins/*.so` 和 `www/uploads/` - - 集成测试:68项全部通过(新增插件加载+日志验证2项) - - 单元测试:139个全部通过 - - 编译零警告,推送到 main(952cc66) -- 2026-06-06: **本轮行动 — 中间件框架(CORS / Basic Auth / Rate Limit)** - - `middleware.c` / `middleware.h`:注册表(最多 16 个)+ 链式执行 + 短路机制 - - CORS 中间件:OPTIONS 预检 204 + 跨域响应头(Access-Control-Allow-Origin/Methods/Headers) - - Basic Auth 中间件:HTTP 基础认证,Base64 解码,401 Unauthorized + WWW-Authenticate 头 - - Rate Limit 中间件:基于 IP 秒级限流,哈希表(256 桶),429 Too Many Requests - - `config.c` / `config.h`:新增 `cors_enabled` / `auth_user` / `auth_pass` / `rate_limit` 字段 - - `main.c`:新增 `--cors` / `--auth-user` / `--auth-pass` / `--rate-limit` CLI 选项;修复 `access_log_path` 未初始化段错误 - - `server.c`:集成 `cocoon_middleware_init_builtin()` 在 `server_create()` 中初始化;修复 `server_destroy` 与 `main()` 双重释放字符串指针;新增 `mw_config` 字段避免栈变量悬空 - - 修复 `rate_limit_hash`:仅使用 IP 地址计算哈希,排除端口,避免同一 IP 不同 bucket - - 修复 401/429 响应 Content-Length:与 body 长度严格匹配,避免 curl 挂起等待 - - 集成测试:66 项全部通过(新增 CORS/Basic Auth/Rate Limit 5 项测试) - - 单元测试:127 个全部通过(修复 `test_config.c` 中 `config_merge` 参数不匹配) - - 编译零警告,推送到 main(dd41464) -- 2026-06-05: **本轮行动 — WebSocket 广播/频道路由系统** - - `websocket.c`:新增全局连接注册表(链表 + pthread_mutex + 原子计数) - - `ws_registry_add/remove`: 连接自动注册/注销 - - `ws_broadcast()`: 向所有活跃连接广播文本消息 - - `ws_broadcast_to_path()`: 按握手路径(如 `/ws/chat`)定向广播 - - `ws_connection_count()`: 获取当前连接数 - - `ws_handle_connection()` 新增 `path` 参数,用于频道标识 - - `server.c`:修改调用处,传入 `req.path` 作为频道 - - `websocket.h`:新增广播 API 声明 - - 编译零警告,61 项集成测试 + 127 个单元测试全部通过 - - 提交:`fix(coco)` 修正子模块 + `feat(websocket)` 广播系统 -- 2026-06-05: **本轮行动 — 实现 WebSocket 支持(RFC 6455)** - - 新增 `websocket.h` / `websocket.c`:WebSocket 协议完整实现 - - 帧解析:支持 FIN、opcode、payload length(7/16/64 位)、mask 解掩码 - - 帧编码:服务器端发送(无掩码),支持文本/二进制/close/ping/pong - - 握手:Sec-WebSocket-Key + SHA1 + Base64 计算 Accept - - `server.c`:添加 `is_websocket_upgrade_request()` 检测,握手后进入 `ws_handle_connection()` - - 连接处理:文本/二进制 echo、ping/pong 自动响应、close 帧处理 - - 集成测试:`tests/websocket_test.py`(Python 标准库,零依赖) - - 编译通过,零警告 - - **61 项集成测试全部通过,127 个单元测试全部通过** - - 推送到 main(2775033) -- 2026-06-05: **本轮行动 — 访问日志(Nginx combined 格式)** - - 新增 `access_log.c` / `access_log.h`:Nginx combined 格式访问日志,线程安全(pthread_mutex) - - `cocoon.h`:新增 `access_log_path` 配置字段 - - `config.c` / `config.h`:JSON 配置和命令行参数支持 `access_log` - - `main.c`:新增 `--access-log ` CLI 选项,`-` 表示输出到 stdout - - `server.c`:扩展 `connection_t` 结构体,添加 `client_addr` / `addr_len` / `response_status` - - `server.c`:`handle_request()` 中每个响应路径设置 `response_status`,请求结束时调用 `access_log_write()` - - `server.c`:`accept_loop()` 将客户端地址复制到连接上下文 - - `Makefile`:加入 `access_log.c`,更新单元测试编译规则 - - `cocoon.json`:示例配置添加 `"access_log": "-"` - - `tests/integration_test.sh`:新增 5 项访问日志测试 - - 编译通过,零警告 - - **59 项集成测试全部通过,127 个单元测试全部通过** - - 推送到 main -- 2026-06-04: 其他历史记录...(省略) diff --git a/main.c b/main.c index f6a577a..b6405a8 100644 --- a/main.c +++ b/main.c @@ -56,6 +56,12 @@ static void reload_handler(int sig) { cocoon_plugin_reload(); } +static void sighup_handler(int sig) { + (void)sig; + printf("\n[Cocoon] 收到 SIGHUP,准备热重载配置...\n"); + server_request_reload(g_ctx); +} + /** * print_usage - 打印使用说明 * @@ -84,8 +90,9 @@ static void print_usage(const char *prog) { printf(" --rate-limit 每秒最大请求数(限流)\n"); printf(" --plugin 加载插件(可多次指定)\n"); printf("\nSignals:\n"); - printf(" SIGUSR1 热重载所有插件(无需重启服务器)\n"); - printf("\nExample:\n"); + printf(" SIGHUP 热重载配置文件(无需重启服务器)\n"); + printf(" SIGUSR1 热重载所有插件(无需重启服务器)\n"); + printf("\nExample:\n"); printf(" %s -c cocoon.json\n", prog); printf(" %s -r ./www -p 8080\n", prog); printf(" %s -c cocoon.json -p 9090 # 命令行覆盖配置文件的端口\n", prog); @@ -228,12 +235,21 @@ static bool parse_args(int argc, char *argv[], cocoon_config_t *config) { */ int main(int argc, char *argv[]) { cocoon_config_t config = {0}; + const char *config_file_path = NULL; if (!parse_args(argc, argv, &config)) { print_usage(argv[0]); return 1; } + /* 从参数中查找配置文件路径 */ + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-c") == 0 && i + 1 < argc) { + config_file_path = argv[i + 1]; + break; + } + } + /* 初始化 socket 子系统(Windows 下 WSAStartup) */ if (cocoon_socket_init() != 0) { fprintf(stderr, "[Cocoon] socket 子系统初始化失败\n"); @@ -243,6 +259,7 @@ int main(int argc, char *argv[]) { /* 注册信号处理 */ cocoon_signal_setup(signal_handler); signal(SIGUSR1, reload_handler); + signal(SIGHUP, sighup_handler); signal(SIGPIPE, SIG_IGN); /* 忽略 SIGPIPE,防止写入已关闭的连接时进程终止 */ /* 设置日志级别 */ @@ -254,7 +271,7 @@ int main(int argc, char *argv[]) { } /* 创建服务器 */ - g_ctx = server_create(&config); + g_ctx = server_create(&config, config_file_path); if (!g_ctx) { fprintf(stderr, "[Cocoon] 创建服务器失败\n"); return 1; diff --git a/server.c b/server.c index dadc0c0..cdbbd83 100644 --- a/server.c +++ b/server.c @@ -30,6 +30,7 @@ #include "middleware.h" #include "proxy.h" #include "healthcheck.h" +#include "config.h" #include #include #include @@ -74,6 +75,8 @@ struct server_context { cocoon_healthcheck_manager_t hc_manager; /**< 主动健康检查管理器 */ volatile int running; /**< 运行标志 */ coco_sched_t *sched; /**< 协程调度器 */ + const char *config_file_path; /**< 配置文件路径(用于热重载) */ + volatile int reload_requested; /**< 配置热重载请求标志 */ }; /* 全局活跃连接计数器(线程安全) */ @@ -1115,6 +1118,12 @@ static void accept_loop(void *arg) { while (ctx->running) { if (ctx->listen_fd < 0) break; + + if (ctx->reload_requested) { + ctx->reload_requested = 0; + server_reload_config(ctx); + } + struct sockaddr_storage client_addr; socklen_t addr_len = sizeof(client_addr); cocoon_socket_t client_fd = accept(ctx->listen_fd, @@ -1128,6 +1137,12 @@ static void accept_loop(void *arg) { break; } + /* accept 返回后再次检查热重载请求,确保新连接使用最新配置 */ + if (ctx->reload_requested) { + ctx->reload_requested = 0; + server_reload_config(ctx); + } + /* 检查最大连接数限制 */ if (ctx->config.max_connections > 0) { int current = atomic_load(&g_active_connections); @@ -1249,7 +1264,7 @@ static void accept_loop(void *arg) { * @param config 配置指针 * @return 服务器上下文,失败返回 NULL */ -server_context_t *server_create(const cocoon_config_t *config) { +server_context_t *server_create(const cocoon_config_t *config, const char *config_file_path) { if (!config || !config->root_dir) return NULL; server_context_t *ctx = (server_context_t *)calloc(1, sizeof(server_context_t)); @@ -1260,6 +1275,10 @@ server_context_t *server_create(const cocoon_config_t *config) { ctx->config.root_dir = strdup(config->root_dir); ctx->running = 1; + if (config_file_path) { + ctx->config_file_path = strdup(config_file_path); + } + g_max_connections = config->max_connections; /* 创建监听 socket */ @@ -1399,6 +1418,137 @@ void server_stop(server_context_t *ctx) { * * @param ctx 服务器上下文 */ +void server_request_reload(server_context_t *ctx) { + if (ctx) { + ctx->reload_requested = 1; + } +} + +void server_reload_config(server_context_t *ctx) { + if (!ctx || !ctx->config_file_path) { + log_warn("配置热重载:未指定配置文件路径"); + return; + } + + log_info("配置热重载开始:%s", ctx->config_file_path); + + cocoon_config_t new_config = {0}; + new_config.port = 8080; + new_config.log_level = LOG_LEVEL_INFO; + new_config.gzip_enabled = true; + new_config.brotli_enabled = true; + + if (!config_load_from_file(ctx->config_file_path, &new_config)) { + log_error("配置热重载失败:无法加载配置文件"); + return; + } + + /* 检查不可热重载项 */ + if (new_config.port != ctx->config.port) { + log_warn("端口变化(%d -> %d)需要重启才能生效", ctx->config.port, new_config.port); + } + if (new_config.threaded != ctx->config.threaded) { + log_warn("线程模式变化需要重启才能生效"); + } + if (new_config.num_workers != ctx->config.num_workers) { + log_warn("工作线程数变化(%u -> %u)需要重启才能生效", ctx->config.num_workers, new_config.num_workers); + } + if ((new_config.tls_cert && !ctx->config.tls_cert) || + (!new_config.tls_cert && ctx->config.tls_cert) || + (new_config.tls_cert && ctx->config.tls_cert && strcmp(new_config.tls_cert, ctx->config.tls_cert) != 0)) { + log_warn("TLS 证书变化需要重启才能生效"); + } + + /* 热重载:root_dir(不释放旧指针,避免竞态) */ + if (new_config.root_dir && (!ctx->config.root_dir || strcmp(new_config.root_dir, ctx->config.root_dir) != 0)) { + ctx->config.root_dir = strdup(new_config.root_dir); + log_info("根目录已更新:%s", ctx->config.root_dir); + } + + /* 热重载:log_level */ + if (new_config.log_level != ctx->config.log_level) { + ctx->config.log_level = new_config.log_level; + log_set_level(new_config.log_level); + log_info("日志级别已更新:%d", new_config.log_level); + } + + /* 热重载:access_log */ + if (new_config.access_log_path) { + if (!ctx->config.access_log_path || strcmp(new_config.access_log_path, ctx->config.access_log_path) != 0) { + access_log_close(); + access_log_init(new_config.access_log_path); + ctx->config.access_log_path = strdup(new_config.access_log_path); + log_info("访问日志路径已更新:%s", ctx->config.access_log_path); + } + } else if (ctx->config.access_log_path) { + access_log_close(); + ctx->config.access_log_path = NULL; + log_info("访问日志已关闭"); + } + + /* 热重载:压缩 */ + if (new_config.gzip_enabled != ctx->config.gzip_enabled) { + ctx->config.gzip_enabled = new_config.gzip_enabled; + log_info("gzip 压缩已%s", ctx->config.gzip_enabled ? "启用" : "禁用"); + } + if (new_config.brotli_enabled != ctx->config.brotli_enabled) { + ctx->config.brotli_enabled = new_config.brotli_enabled; + log_info("brotli 压缩已%s", ctx->config.brotli_enabled ? "启用" : "禁用"); + } + + /* 热重载:超时和连接限制 */ + if (new_config.timeout_ms != ctx->config.timeout_ms) { + ctx->config.timeout_ms = new_config.timeout_ms; + log_info("连接超时已更新:%u ms", ctx->config.timeout_ms); + } + if (new_config.max_connections != ctx->config.max_connections) { + ctx->config.max_connections = new_config.max_connections; + g_max_connections = new_config.max_connections; + log_info("最大连接数已更新:%u", ctx->config.max_connections); + } + + /* 热重载:vhosts */ + if (new_config.num_vhosts > 0 || ctx->config.num_vhosts > 0) { + if (new_config.num_vhosts != ctx->config.num_vhosts || + memcmp(new_config.vhosts, ctx->config.vhosts, sizeof(new_config.vhosts)) != 0) { + memcpy(ctx->config.vhosts, new_config.vhosts, sizeof(new_config.vhosts)); + ctx->config.num_vhosts = new_config.num_vhosts; + log_info("虚拟主机已更新:%zu 个", ctx->config.num_vhosts); + } + } + + /* 热重载:proxies */ + if (new_config.num_proxies > 0 || ctx->config.num_proxies > 0) { + proxy_config_destroy(&ctx->proxy_config); + proxy_init(&ctx->proxy_config); + for (size_t i = 0; i < new_config.num_proxies; i++) { + proxy_add_rule(&ctx->proxy_config, new_config.proxies[i].prefix, new_config.proxies[i].target, new_config.proxies[i].pool_size, new_config.proxies[i].weight, &new_config.proxies[i].healthcheck); + } + ctx->config.num_proxies = new_config.num_proxies; + memcpy(ctx->config.proxies, new_config.proxies, sizeof(new_config.proxies)); + log_info("代理规则已更新:%zu 条", ctx->config.num_proxies); + } + + /* 热重载:healthcheck */ + healthcheck_stop(&ctx->hc_manager); + healthcheck_manager_init(&ctx->hc_manager); + healthcheck_start(&ctx->hc_manager, &ctx->proxy_config, ctx->config.timeout_ms); + log_info("健康检查已重新配置"); + + log_info("配置热重载完成"); + + /* 清理 new_config 分配的内存 */ + if (new_config.root_dir) free((void*)new_config.root_dir); + if (new_config.tls_cert) free((void*)new_config.tls_cert); + if (new_config.tls_key) free((void*)new_config.tls_key); + if (new_config.access_log_path) free((void*)new_config.access_log_path); + if (new_config.auth_user) free((void*)new_config.auth_user); + if (new_config.auth_pass) free((void*)new_config.auth_pass); + for (size_t i = 0; i < new_config.num_plugins; i++) { + free((void*)new_config.plugins[i]); + } +} + void server_destroy(server_context_t *ctx) { if (!ctx) return; @@ -1420,6 +1570,11 @@ void server_destroy(server_context_t *ctx) { ctx->listen_fd = COCOON_INVALID_SOCKET; } + if (ctx->config_file_path) { + free((void*)ctx->config_file_path); + ctx->config_file_path = NULL; + } + if (ctx->config.root_dir) { free((void *)ctx->config.root_dir); ctx->config.root_dir = NULL; diff --git a/server.h b/server.h index 19483c4..f46698b 100644 --- a/server.h +++ b/server.h @@ -17,6 +17,26 @@ */ typedef struct server_context server_context_t; +/** + * server_request_reload - 请求配置热重载 + * + * 设置热重载标志,由 accept_loop 在下次迭代时执行。 + * 安全地从信号处理器中调用。 + * + * @param ctx 服务器上下文 + */ +void server_request_reload(server_context_t *ctx); + +/** + * server_reload_config - 热重载配置 + * + * 重新加载配置文件,应用可热重载的配置项。 + * 不可热重载的项(端口、线程数等)如有变化会日志提示。 + * + * @param ctx 服务器上下文 + */ +void server_reload_config(server_context_t *ctx); + /** * server_start - 启动服务器(阻塞直到 stop 被调用) * @@ -38,9 +58,10 @@ void server_stop(server_context_t *ctx); * server_create - 创建服务器上下文 * * @param config 配置指针 + * @param config_file_path 配置文件路径(用于热重载),可为 NULL * @return 服务器上下文,失败返回 NULL */ -server_context_t *server_create(const cocoon_config_t *config); +server_context_t *server_create(const cocoon_config_t *config, const char *config_file_path); /** * server_destroy - 销毁服务器上下文 diff --git a/tests/fixtures/reload_test.json b/tests/fixtures/reload_test.json new file mode 100644 index 0000000..128450e --- /dev/null +++ b/tests/fixtures/reload_test.json @@ -0,0 +1,7 @@ +{ + "port": 9999, + "root_dir": "./tests/fixtures", + "log_level": "debug", + "gzip_enabled": true, + "brotli_enabled": true +} diff --git a/tests/integration_test.sh b/tests/integration_test.sh index cab70ad..3f6652f 100755 --- a/tests/integration_test.sh +++ b/tests/integration_test.sh @@ -1524,6 +1524,94 @@ done # 恢复默认服务器 start_server +# === SIGHUP 配置热重载测试 === +echo "" +echo "=== SIGHUP 配置热重载测试 ===" + +# 关闭默认服务器 +fuser -k 9999/tcp 2>/dev/null || true +sleep 0.5 +for i in {1..20}; do + if ! ss -tlnp 2>/dev/null | grep -q ':9999'; then + break + fi + sleep 0.1 +done + +RELOAD_CONFIG="$TMPDIR/reload_test.json" +cat > "$RELOAD_CONFIG" <<'EOF' +{ + "port": 9999, + "root_dir": "./tests/fixtures", + "log_level": "debug", + "gzip_enabled": true, + "brotli_enabled": true +} +EOF + +$SERVER -c "$RELOAD_CONFIG" > "$TMPDIR/server_reload.log" 2>&1 & +reload_pid=$! +sleep 1 +for i in {1..20}; do + if ss -tlnp 2>/dev/null | grep -q ':9999'; then + break + fi + sleep 0.1 +done + +# 1. 确认初始配置生效 +reload_before=$(curl -s "http://$HOST/") +if echo "$reload_before" | grep -q "Cocoon"; then + echo " ✓ 初始配置 — 返回 fixtures 目录内容" + pass +else + echo " ✗ 初始配置 — 期望 Cocoon 内容, 实际: $reload_before" + fail +fi + +# 2. 修改配置文件(更换 root_dir) +cat > "$RELOAD_CONFIG" <<'EOF' +{ + "port": 9999, + "root_dir": "./tests/fixtures/vhost_a", + "log_level": "debug", + "gzip_enabled": false, + "brotli_enabled": false +} +EOF + +# 3. 发送 SIGHUP 信号 +kill -HUP $reload_pid 2>/dev/null +sleep 1 + +# 4. 确认新配置生效 +reload_after=$(curl -s "http://$HOST/") +if echo "$reload_after" | grep -q "Site A"; then + echo " ✓ 热重载后 — root_dir 已更新为 vhost_a" + pass +else + echo " ✗ 热重载后 — 期望 Site A, 实际: $reload_after" + fail +fi + +# 5. 检查日志中是否出现热重载完成信息 +if grep -q "配置热重载完成" "$TMPDIR/server_reload.log"; then + echo " ✓ 热重载日志 — 检测到完成日志" + pass +else + echo " ✗ 热重载日志 — 未检测到完成日志" + fail +fi + +kill -9 $reload_pid 2>/dev/null || true +sleep 0.5 +for i in {1..20}; do + if ! ss -tlnp 2>/dev/null | grep -q ':9999'; then + break + fi + sleep 0.1 +done + echo "" echo "=== 结果汇总 ===" echo "通过: $PASS" diff --git a/tests/unit/test_server.c b/tests/unit/test_server.c index e58053a..19c4b7c 100644 --- a/tests/unit/test_server.c +++ b/tests/unit/test_server.c @@ -7,19 +7,19 @@ /* ===== server_create 参数校验 ===== */ void test_create_null_config(void) { - TEST_ASSERT_NULL(server_create(NULL)); + TEST_ASSERT_NULL(server_create(NULL, NULL)); } void test_create_null_root_dir(void) { cocoon_config_t cfg = {.port = 8080}; /* root_dir 为 NULL,应提前返回 NULL */ - TEST_ASSERT_NULL(server_create(&cfg)); + TEST_ASSERT_NULL(server_create(&cfg, NULL)); } void test_create_empty_root_dir(void) { cocoon_config_t cfg = {.root_dir = "", .port = 30001}; /* 空字符串 root_dir 应该也失败(或成功取决于实现) */ - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); } @@ -36,7 +36,7 @@ void test_create_port_zero(void) { .port = 0, .threaded = false }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -51,7 +51,7 @@ void test_create_high_port(void) { .port = 65535, .threaded = false }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -67,7 +67,7 @@ void test_create_multithread_config(void) { .threaded = true, .num_workers = 2 }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -84,7 +84,7 @@ void test_create_zero_workers(void) { .threaded = true, .num_workers = 0 }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -100,7 +100,7 @@ void test_create_with_timeout(void) { .threaded = false, .timeout_ms = 5000 }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -116,7 +116,7 @@ void test_create_with_max_connections(void) { .threaded = false, .max_connections = 100 }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -133,7 +133,7 @@ void test_create_with_compression_flags(void) { .gzip_enabled = false, .brotli_enabled = false }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (ctx) { server_destroy(ctx); TEST_ASSERT_TRUE(1); @@ -162,7 +162,7 @@ void test_stop_then_destroy(void) { .port = 30007, .threaded = false }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); if (!ctx) { TEST_IGNORE_MESSAGE("server_create failed, possibly port in use"); return; @@ -187,7 +187,7 @@ void test_create_and_destroy(void) { .port = 29999, /* 使用高位端口减少冲突 */ .threaded = false }; - server_context_t *ctx = server_create(&cfg); + server_context_t *ctx = server_create(&cfg, NULL); /* 高位端口通常可用,但测试环境可能被占用,保守处理 */ if (ctx) { server_stop(ctx); @@ -211,8 +211,8 @@ void test_create_multiple_instances(void) { .port = 30009, .threaded = false }; - server_context_t *ctx1 = server_create(&cfg1); - server_context_t *ctx2 = server_create(&cfg2); + server_context_t *ctx1 = server_create(&cfg1, NULL); + server_context_t *ctx2 = server_create(&cfg2, NULL); if (ctx1 && ctx2) { server_destroy(ctx2);