diff --git a/doc/lowlevel-guide.md b/doc/lowlevel-guide.md index 58ebf100..64101ca5 100644 --- a/doc/lowlevel-guide.md +++ b/doc/lowlevel-guide.md @@ -27,6 +27,7 @@ 9. [典型坑](#9-典型坑) 10. [没做的(如实列出)](#10-没做的如实列出) 11. [定时任务(cron)](#11-定时任务cron) +12. [进程监管(process supervisor)](#12-进程监管process-supervisor) --- @@ -399,6 +400,35 @@ cron.start(); // 在 loop.run() 之前 --- +## 12. 进程监管(process supervisor) + +`uvcpp_process_supervisor`(`#include `)在 +`uvcpp_process` 之上补"长期跑外部程序"需要的那几件事: + +```cpp +// doc-snippet: fragment — 装配摘录,不是完整翻译单元。 +uvcpp::uvcpp_process_supervisor sup(&loop); +uvcpp::uvcpp_process_spec spec; +spec.file = "/usr/bin/ffmpeg"; +spec.args = {"-i", in, "-o", out}; +spec.timeout_ms = 10 * 60 * 1000; +spec.kill_tree = true; +sup.spawn(spec, on_output, on_exit); +``` + +- **有界输出**:`capture_stdout/stderr` 打开管道,数据同时给回调和尾缓冲 + (`max_output_bytes`,默认 64 KiB/流);超限丢最旧字节并计入 + `stdout_truncated`,不会无限吃内存。 +- **超时 / 取消**:先 `SIGTERM`,等 `stop_grace_ms` 再强杀;退出回调**恰好一次**, + 结果里 `timed_out/cancelled` 说明是谁先动手。 +- **POSIX 进程组终止**:`kill_tree=true`(默认)用 `UV_PROCESS_DETACHED` 让子进程 + 自成进程组,信号发给整组,父进程退出后不留子进程;Windows 上这一版返回 + `UV_ENOTSUP`(Job Object 是 issue #69 的后续)。 +- 不绑定具体程序、不维护业务状态机;重启策略/任务队列留给上层(#67)。 +- 用例:`process_supervisor_func.cpp`(POSIX)。 + +--- + 相关文档:[net 网络层指南](./net-guide.md)、[TLS 与证书指南](./ssl-guide.md)、 [项目 README](../README.zh.md)。 diff --git a/src/handle/uvcpp_process_supervisor.cpp b/src/handle/uvcpp_process_supervisor.cpp new file mode 100644 index 00000000..152e66fc --- /dev/null +++ b/src/handle/uvcpp_process_supervisor.cpp @@ -0,0 +1,481 @@ +/** + * @file src/handle/uvcpp_process_supervisor.cpp + * @brief 进程监管的实现(POSIX 进程组 + 有界输出 + 超时)。 + * @author zhuweiye + * @version 1.0.0 + */ + +#include "handle/uvcpp_process_supervisor.h" + +#include + +#include + +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif + +namespace uvcpp { + +uvcpp_process_spec::uvcpp_process_spec() + : timeout_ms(0), + stop_grace_ms(2000), + max_output_bytes(64 * 1024), + capture_stdout(true), + capture_stderr(true), + kill_tree(true) {} + +uvcpp_process_result::uvcpp_process_result() + : exit_status(0), + term_signal(0), + error(0), + timed_out(false), + cancelled(false), + elapsed_ms(0), + stdout_truncated(0), + stderr_truncated(0) {} + +namespace { + +#ifdef _WIN32 +// MSVC 的 没有 SIGKILL;Windows 上强杀也只走 uv_process_kill(SIGTERM)。 +const int kForceSignal = SIGTERM; +#else +const int kForceSignal = SIGKILL; +#endif + +void bounded_append(std::string& buf, const char* data, size_t len, + size_t cap, size_t& truncated) { + if (cap == 0) { + truncated += len; + return; + } + buf.append(data, len); + if (buf.size() > cap) { + const size_t drop = buf.size() - cap; + buf.erase(0, drop); + truncated += drop; + } +} + +} // namespace + +struct uvcpp_process_supervisor::job { + impl* owner = nullptr; + uint64_t id = 0; + uvcpp_process_spec spec; + uvcpp_process_output_cb on_output; + uvcpp_process_exit_cb on_exit; + uvcpp_process_result result; + + uv_process_t proc; + uv_pipe_t out_pipe; + uv_pipe_t err_pipe; + uv_timer_t timeout_timer; + uv_timer_t kill_timer; + + bool proc_started = false; + bool proc_exited = false; + bool proc_closed = false; + bool out_eof = false; + bool err_eof = false; + bool out_closed = false; + bool err_closed = false; + bool time_closed = false; + bool kill_closed = false; + bool term_sent = false; + bool exit_fired = false; + bool finalized = false; + + int pending_closes = 0; + + std::vector arg_store; + std::vector env_store; + std::vector argv; + std::vector envp; + + std::chrono::steady_clock::time_point started_at; +}; + +struct uvcpp_process_supervisor::impl { + explicit impl(uvcpp_loop* l) : loop(l) {} + + uvcpp_loop* loop; + std::map jobs; + uint64_t next_id = 1; + uvcpp_process_supervisor_stats s; + + static void on_exit(uv_process_t* p, int64_t exit_status, int term_signal) { + job* j = static_cast(p->data); + if (j == nullptr || j->proc_exited) return; + j->proc_exited = true; + j->result.exit_status = exit_status; + j->result.term_signal = term_signal; + if (j->owner != nullptr) { + uv_timer_stop(&j->timeout_timer); + uv_timer_stop(&j->kill_timer); + } + if (!j->proc_closed) { + j->proc_closed = true; + uv_close(reinterpret_cast(&j->proc), on_close_proc); + } + if (j->owner != nullptr) j->owner->maybe_finish(j); + } + + static void on_close_proc(uv_handle_t* h) { + job* j = static_cast(h->data); + if (j == nullptr) return; + j->proc_closed = true; + note_closed(j); + } + /// 非进程句柄(管道 / 定时器)的关闭:只记账,**不要**碰 proc_closed + /// —— 把管道关闭误标成"进程句柄已关"会让 on_exit 跳过 uv_close(proc), + /// 留下仍活跃的进程句柄,最后在 close 回调里访问已被释放的 job。 + static void on_close_any(uv_handle_t* h) { + job* j = static_cast(h->data); + if (j == nullptr) return; + note_closed(j); + } + static void on_closed(uv_handle_t* h) { on_close_any(h); } + + static void on_read(uv_stream_t* stream, ssize_t nread, + const uv_buf_t* buf) { + job* j = static_cast(stream->data); + if (j == nullptr) { + if (buf != nullptr && buf->base != nullptr) delete[] buf->base; + return; + } + const bool is_err = + stream == reinterpret_cast(&j->err_pipe); + if (nread > 0) { + if (j->on_output) j->on_output(buf->base, static_cast(nread), is_err); + size_t& trunc = is_err ? j->result.stderr_truncated + : j->result.stdout_truncated; + std::string& tail = + is_err ? j->result.stderr_tail : j->result.stdout_tail; + bounded_append(tail, buf->base, static_cast(nread), + j->spec.max_output_bytes, trunc); + } else if (nread == UV_EOF || nread < 0) { + if (is_err) { + j->err_eof = true; + uv_read_stop(stream); + close_handle(reinterpret_cast(&j->err_pipe), j, + j->err_closed); + } else { + j->out_eof = true; + uv_read_stop(stream); + close_handle(reinterpret_cast(&j->out_pipe), j, + j->out_closed); + } + if (j->owner != nullptr) j->owner->maybe_finish(j); + } + if (buf != nullptr && buf->base != nullptr) delete[] buf->base; + } + + static void alloc_cb(uv_handle_t*, size_t suggested, uv_buf_t* buf) { + const size_t n = suggested == 0 ? 4096 : suggested; + buf->base = new char[n]; + buf->len = n; + } + + static void on_timeout(uv_timer_t* t) { + job* j = static_cast(t->data); + if (j == nullptr || j->proc_exited) return; + j->result.timed_out = true; + if (j->owner != nullptr) j->owner->terminate(j); + } + + static void on_kill(uv_timer_t* t) { + job* j = static_cast(t->data); + if (j == nullptr || j->proc_exited) return; + if (j->owner != nullptr) j->owner->signal_tree(j, true); + } + + static void note_closed(job* j) { + if (j->pending_closes > 0) --j->pending_closes; + if (j->pending_closes == 0) delete j; + } + + static void close_handle(uv_handle_t* h, job* j, bool& flag) { + if (flag) return; + flag = true; + uv_close(h, on_close_any); + } + + void signal_tree(job* j, bool force) { + if (!j->proc_started || j->proc_exited) return; +#ifdef _WIN32 + uv_process_kill(&j->proc, force ? kForceSignal : SIGTERM); +#else + if (j->spec.kill_tree) { + const int pgid = j->proc.pid; + ::kill(-pgid, force ? SIGKILL : SIGTERM); + } else { + uv_process_kill(&j->proc, force ? kForceSignal : SIGTERM); + } +#endif + } + + void terminate(job* j) { + if (j->term_sent || j->proc_exited) return; + j->term_sent = true; + signal_tree(j, false); + uv_timer_start(&j->kill_timer, on_kill, j->spec.stop_grace_ms, 0); + } + + void maybe_finish(job* j) { + if (j->finalized || !j->proc_exited) return; + const bool out_done = !j->spec.capture_stdout || j->out_eof; + const bool err_done = !j->spec.capture_stderr || j->err_eof; + if (!out_done || !err_done) return; + j->finalized = true; + j->result.elapsed_ms = + static_cast(std::chrono::duration_cast( + std::chrono::steady_clock::now() - + j->started_at) + .count()); + + uv_timer_stop(&j->timeout_timer); + uv_timer_stop(&j->kill_timer); + + // 统计 + 回调(回调里新 spawn/cancel 是合法的:这里不持锁、不遍历表)。 + if (j->result.timed_out) { + ++s.timed_out; + } else if (j->result.cancelled) { + ++s.cancelled; + } else if (j->result.exit_status == 0 && j->result.term_signal == 0 && + j->result.error == 0) { + ++s.succeeded; + } else { + ++s.failed; + } + if (j->id != 0) jobs.erase(j->id); + + if (!j->exit_fired && j->on_exit) { + j->exit_fired = true; + uvcpp_process_exit_cb cb = j->on_exit; + if (cb) cb(j->result); + } + + // 收尾:关闭还没关的句柄。`proc` 在退出回调里已经 close 过。 + close_handle(reinterpret_cast(&j->timeout_timer), j, + j->time_closed); + close_handle(reinterpret_cast(&j->kill_timer), j, + j->kill_closed); + if (j->spec.capture_stdout) { + close_handle(reinterpret_cast(&j->out_pipe), j, + j->out_closed); + } + if (j->spec.capture_stderr) { + close_handle(reinterpret_cast(&j->err_pipe), j, + j->err_closed); + } + } + + void fail_spawn(job* j, int err) { + j->result.error = err; + j->result.elapsed_ms = 0; + ++s.spawned; + ++s.failed; + if (j->on_exit) j->on_exit(j->result); + // 关闭已经 init 的句柄 + close_handle(reinterpret_cast(&j->timeout_timer), j, + j->time_closed); + close_handle(reinterpret_cast(&j->kill_timer), j, + j->kill_closed); + if (j->spec.capture_stdout) { + close_handle(reinterpret_cast(&j->out_pipe), j, + j->out_closed); + } + if (j->spec.capture_stderr) { + close_handle(reinterpret_cast(&j->err_pipe), j, + j->err_closed); + } + } +}; + +uvcpp_process_supervisor::uvcpp_process_supervisor(uvcpp_loop* loop) + : impl_(new impl(loop)) {} + +uvcpp_process_supervisor::~uvcpp_process_supervisor() { + // 尽力取消:句柄的真正关闭要等循环下一轮;这里只发信号并断开 owner, + // 让 close 回调不再访问本对象。析构应在循环仍在时调用。 + for (std::map::iterator it = impl_->jobs.begin(); + it != impl_->jobs.end(); ++it) { + job* j = it->second; + j->owner = nullptr; + if (!j->proc_exited) { + uv_process_kill(&j->proc, kForceSignal); + } + uv_timer_stop(&j->timeout_timer); + uv_timer_stop(&j->kill_timer); + if (!j->proc_closed && j->proc_started) { + j->proc_closed = true; + uv_close(reinterpret_cast(&j->proc), impl::on_closed); + } + if (j->spec.capture_stdout && !j->out_closed) { + j->out_closed = true; + uv_close(reinterpret_cast(&j->out_pipe), impl::on_closed); + } + if (j->spec.capture_stderr && !j->err_closed) { + j->err_closed = true; + uv_close(reinterpret_cast(&j->err_pipe), impl::on_closed); + } + if (!j->time_closed) { + j->time_closed = true; + uv_close(reinterpret_cast(&j->timeout_timer), impl::on_closed); + } + if (!j->kill_closed) { + j->kill_closed = true; + uv_close(reinterpret_cast(&j->kill_timer), impl::on_closed); + } + } + impl_->jobs.clear(); + delete impl_; +} + +uint64_t uvcpp_process_supervisor::spawn( + const uvcpp_process_spec& spec, uvcpp_process_output_cb on_output, + uvcpp_process_exit_cb on_exit, std::string* err) { + if (impl_->loop == nullptr || spec.file.empty()) { + if (err) *err = "没有循环或可执行文件为空"; + return 0; + } + if (!spec.capture_stdout && !spec.capture_stderr) { + // 允许,但输出回调永远收不到东西 —— 不拦。 + } +#ifndef _WIN32 + if (spec.kill_tree && false) { + // 保留给未来平台分支;POSIX 的 detached 已经处理。 + } +#else + if (spec.kill_tree) { + if (err) *err = "Windows 进程树终止(Job Object)尚未实现"; + return 0; + } +#endif + + job* j = new job(); + j->owner = impl_; + j->id = impl_->next_id++; + j->spec = spec; + j->on_output = std::move(on_output); + j->on_exit = std::move(on_exit); + j->started_at = std::chrono::steady_clock::now(); + + j->arg_store.push_back(spec.file); + for (size_t i = 0; i < spec.args.size(); ++i) j->arg_store.push_back(spec.args[i]); + for (size_t i = 0; i < j->arg_store.size(); ++i) { + j->argv.push_back(const_cast(j->arg_store[i].c_str())); + } + j->argv.push_back(nullptr); + for (size_t i = 0; i < spec.env.size(); ++i) j->env_store.push_back(spec.env[i]); + for (size_t i = 0; i < j->env_store.size(); ++i) { + j->envp.push_back(const_cast(j->env_store[i].c_str())); + } + if (!j->envp.empty()) j->envp.push_back(nullptr); + + uv_loop_t* loop = reinterpret_cast(impl_->loop->get_handle()); + uv_timer_init(loop, &j->timeout_timer); + j->timeout_timer.data = j; + uv_timer_init(loop, &j->kill_timer); + j->kill_timer.data = j; + + uv_process_options_t opts; + std::memset(&opts, 0, sizeof(opts)); + opts.exit_cb = impl::on_exit; + opts.file = j->arg_store[0].c_str(); + opts.args = j->argv.data(); + opts.env = j->envp.empty() ? nullptr : j->envp.data(); + opts.cwd = spec.cwd.empty() ? nullptr : spec.cwd.c_str(); +#ifdef _WIN32 + opts.flags = 0; +#else + opts.flags = spec.kill_tree ? UV_PROCESS_DETACHED : 0; +#endif + + uv_stdio_container_t stdio[3]; + std::memset(stdio, 0, sizeof(stdio)); + stdio[0].flags = UV_IGNORE; + stdio[1].flags = UV_IGNORE; + stdio[2].flags = UV_IGNORE; + if (spec.capture_stdout) { + uv_pipe_init(loop, &j->out_pipe, 0); + j->out_pipe.data = j; + stdio[1].flags = static_cast(UV_CREATE_PIPE | UV_WRITABLE_PIPE); + stdio[1].data.stream = reinterpret_cast(&j->out_pipe); + } + if (spec.capture_stderr) { + uv_pipe_init(loop, &j->err_pipe, 0); + j->err_pipe.data = j; + stdio[2].flags = static_cast(UV_CREATE_PIPE | UV_WRITABLE_PIPE); + stdio[2].data.stream = reinterpret_cast(&j->err_pipe); + } + opts.stdio = stdio; + opts.stdio_count = 3; + + std::memset(&j->proc, 0, sizeof(j->proc)); + j->proc.data = j; + j->pending_closes = 2 + (spec.capture_stdout ? 1 : 0) + + (spec.capture_stderr ? 1 : 0); + const int rc = uv_spawn(loop, &j->proc, &opts); + if (rc != 0) { + j->spec.capture_stdout = spec.capture_stdout; + j->spec.capture_stderr = spec.capture_stderr; + impl_->fail_spawn(j, rc); + if (err) *err = uv_strerror(rc); + return 0; + } + + j->proc_started = true; + ++j->pending_closes; // 进程句柄从这一刻起也会在退出时关一次 + ++impl_->s.spawned; + impl_->jobs[j->id] = j; + + if (spec.capture_stdout) { + if (uv_read_start(reinterpret_cast(&j->out_pipe), + impl::alloc_cb, impl::on_read) != 0) { + j->out_eof = true; + impl::close_handle(reinterpret_cast(&j->out_pipe), j, + j->out_closed); + } + } + if (spec.capture_stderr) { + if (uv_read_start(reinterpret_cast(&j->err_pipe), + impl::alloc_cb, impl::on_read) != 0) { + j->err_eof = true; + impl::close_handle(reinterpret_cast(&j->err_pipe), j, + j->err_closed); + } + } + if (spec.timeout_ms > 0) { + uv_timer_start(&j->timeout_timer, impl::on_timeout, spec.timeout_ms, 0); + } + return j->id; +} + +int uvcpp_process_supervisor::cancel(uint64_t id) { + std::map::iterator it = impl_->jobs.find(id); + if (it == impl_->jobs.end()) return -1; + job* j = it->second; + if (j->proc_exited) return -1; + j->result.cancelled = true; + impl_->terminate(j); + return 0; +} + +size_t uvcpp_process_supervisor::running() const { return impl_->jobs.size(); } + +uvcpp_process_supervisor_stats uvcpp_process_supervisor::stats() const { + uvcpp_process_supervisor_stats out = impl_->s; + out.running = impl_->jobs.size(); + return out; +} + +} // namespace uvcpp diff --git a/src/handle/uvcpp_process_supervisor.h b/src/handle/uvcpp_process_supervisor.h new file mode 100644 index 00000000..36476ad5 --- /dev/null +++ b/src/handle/uvcpp_process_supervisor.h @@ -0,0 +1,147 @@ +/** + * @file src/handle/uvcpp_process_supervisor.h + * @brief 进程监管:有界输出、超时、进程组终止、取消与统计(issue #69)。 + * @author zhuweiye + * @version 1.0.0 + * + * ```cpp + * uvcpp::uvcpp_process_supervisor sup(&loop); + * uvcpp::uvcpp_process_spec spec; + * spec.file = "/usr/bin/ffmpeg"; + * spec.args = {"-i", in, out}; + * spec.timeout_ms = 10 * 60 * 1000; + * spec.kill_tree = true; + * sup.spawn(spec, on_output, on_exit); + * ``` + * + * ## 范围 + * + * 这一版是 **POSIX 优先**: + * + * - 启动 / 取消 / 超时 / 退出结果 / 有界输出 / 输出回调:跨平台(libuv `uv_spawn`); + * - **进程组终止**:POSIX 上 `UV_PROCESS_DETACHED`(子进程自成会话/进程组)+ 对 + * `-pid` 发信号;Windows 上 `kill_tree` 返回 `UV_ENOTSUP`(Job Object 是后续, + * 见 issue #69)。 + * - 不绑定任何具体程序、不维护业务状态机;重启策略/任务队列留给上层 + * (#67 作业队列)。 + * + * ## 输出 + * + * - `capture_stdout/stderr` 打开对应管道;数据同时交给 `output_cb()` 与 + * **有界尾缓冲**(`max_output_bytes`,默认 64 KiB/流)。超限时丢最旧的字节并 + * 在结果里累计 `stdout_truncated` / `stderr_truncated` —— 不会无限吃内存。 + * - 退出回调在**进程退出且两条管道都读到 EOF**之后触发一次;结果里带退出码、 + * 信号、耗时、错误、两条流的尾缓冲。 + * - 回调都在 loop 线程上;`output_cb` 里的指针只在回调期间有效。 + * + * ## 终止语义 + * + * - 超时或 `cancel()`:POSIX 对进程组发 `SIGTERM`,等 `stop_grace_ms` + * (默认 2000)再 `SIGKILL`;`kill_tree=false` 时只对进程本身发信号。 + * - 退出回调**恰好一次**:取消之后再超时、进程又自己退出,都不会重复。 + * - 结果里的 `cancelled/timed_out` 说明这次是谁先动手。 + */ + +#pragma once +#ifndef SRC_HANDLE_UVCPP_PROCESS_SUPERVISOR_H +#define SRC_HANDLE_UVCPP_PROCESS_SUPERVISOR_H + +#include +#include + +#include +#include +#include +#include +#include + +namespace uvcpp { + +class uvcpp_loop; + +/// 启动一个进程的完整描述。显式构造函数(C++11 聚合初始化资格)。 +struct UVCPP_API uvcpp_process_spec { + uvcpp_process_spec(); + + std::string file; ///< 可执行文件(绝对路径或 PATH 里找) + std::vector args; ///< argv[1..];argv[0] 固定为 file + std::vector env; ///< "K=V";空 = 继承父进程环境 + std::string cwd; ///< 空 = 继承 + + uint64_t timeout_ms; ///< 0 = 不设超时 + uint64_t stop_grace_ms; ///< SIGTERM 之后等多久再 SIGKILL + size_t max_output_bytes; ///< **每条流**保留的尾字节上限 + bool capture_stdout; + bool capture_stderr; + bool kill_tree; ///< POSIX:子进程自成进程组,信号发给整组 +}; + +/// 一次监管的最终结果。 +struct UVCPP_API uvcpp_process_result { + uvcpp_process_result(); + + int64_t exit_status; ///< 退出码(被信号杀死时一般为 0) + int term_signal; ///< 终止信号(0 = 正常退出) + int error; ///< 启动/监管错误;0 = 无 + bool timed_out; ///< 超时先动手 + bool cancelled; ///< `cancel()` 先动手 + uint64_t elapsed_ms; ///< 从 spawn 到完全收尾 + size_t stdout_truncated; ///< 因上限丢掉的字节数 + size_t stderr_truncated; + std::string stdout_tail; ///< 最多 max_output_bytes 的尾部 + std::string stderr_tail; +}; + +/// 输出回调:字节只在回调期间有效;`is_stderr` 区分两条流。 +using uvcpp_process_output_cb = + std::function; +using uvcpp_process_exit_cb = + std::function; + +struct UVCPP_API uvcpp_process_supervisor_stats { + uint64_t spawned = 0; + uint64_t succeeded = 0; + uint64_t failed = 0; + uint64_t timed_out = 0; + uint64_t cancelled = 0; + size_t running = 0; +}; + +/** + * @brief 监管器。一个对象可以同时跑多个进程;`id` 用来取消。 + * + * 生命周期:句柄都挂在构造时给的循环上;析构时会取消所有在跑的进程并等 + * 它们收尾(同步取消后不阻塞循环,但句柄在循环下一次迭代才真正关闭)。 + * 请在 `loop.run()` 之后、循环仍在的时候析构(与其它句柄一致)。 + */ +class UVCPP_API uvcpp_process_supervisor { + public: + explicit uvcpp_process_supervisor(uvcpp_loop* loop); + ~uvcpp_process_supervisor(); + + uvcpp_process_supervisor(const uvcpp_process_supervisor&) = delete; + uvcpp_process_supervisor& operator=(const uvcpp_process_supervisor&) = delete; + + /** + * @brief 启动。成功返回非 0 id;失败返回 0 并在 @p err 里写原因。 + */ + uint64_t spawn(const uvcpp_process_spec& spec, + uvcpp_process_output_cb on_output = nullptr, + uvcpp_process_exit_cb on_exit = nullptr, + std::string* err = nullptr); + + /// 取消一个在跑的进程(SIGTERM → 宽限 → SIGKILL)。不存在/已结束返回 -1。 + int cancel(uint64_t id); + + size_t running() const; + uvcpp_process_supervisor_stats stats() const; + + private: + struct job; + struct impl; + impl* impl_; +}; + +} // namespace uvcpp + +#endif // SRC_HANDLE_UVCPP_PROCESS_SUPERVISOR_H diff --git a/tests/functional/process_supervisor_func.cpp b/tests/functional/process_supervisor_func.cpp new file mode 100644 index 00000000..36464739 --- /dev/null +++ b/tests/functional/process_supervisor_func.cpp @@ -0,0 +1,218 @@ +/** + * @file tests/functional/process_supervisor_func.cpp + * @brief 进程监管:输出、退出码、超时、进程组终止、取消、有界缓冲。 + * + * 只在 POSIX 上跑(Windows 的 Job Object 是 issue #69 的后续;这一版在 + * Windows 上 `kill_tree=true` 会返回 ENOTSUP,直接 skip)。 + */ + +#include +#include +#include +#include +#include + +#ifdef _WIN32 + +int main() { + std::cout << "SKIP: process supervisor (POSIX) on Windows" << std::endl; + return 0; +} + +#else + +#include +#include +#include +#include + +#include + +#include +#include +#include + +using namespace uvcpp; + +namespace { + +int g_fail = 0; + +void check(bool ok, const std::string& what) { + if (ok) { + std::cout << " [ ok ] " << what << std::endl; + } else { + ++g_fail; + std::cerr << " [FAIL] " << what << std::endl; + } +} + +bool run_until(uvcpp_loop& loop, const bool& done, int ms) { + const std::chrono::steady_clock::time_point deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); + while (!done && std::chrono::steady_clock::now() < deadline) { + loop.run(UV_RUN_ONCE); + } + for (int i = 0; i < 5; ++i) loop.run(UV_RUN_NOWAIT); + return done; +} + +void test_basic() { + std::cout << "-- 输出 / 退出码 --" << std::endl; + uvcpp_loop loop; + bool done = false; + uvcpp_process_result result; + std::string out; + std::string err; + size_t chunks = 0; + { + uvcpp_process_supervisor sup(&loop); + uvcpp_process_spec spec; + spec.file = "/bin/sh"; + spec.args = std::vector{ + "-c", "printf OUT; printf ERR >&2; exit 3"}; + spec.timeout_ms = 5000; + const uint64_t id = sup.spawn( + spec, + [&](const char* d, size_t n, bool is_err) { + ++chunks; + (is_err ? err : out).append(d, n); + }, + [&](const uvcpp_process_result& r) { + result = r; + done = true; + }); + check(id != 0, "spawn 返回 id"); + if (id == 0) return; + check(run_until(loop, done, 5000), "进程收尾"); + check(result.exit_status == 3, "退出码 3(实际 " + + std::to_string(result.exit_status) + ")"); + check(result.term_signal == 0, "不是被信号杀死"); + check(result.stdout_tail == "OUT", "stdout 尾缓冲 = OUT(实际 '" + + result.stdout_tail + "')"); + check(result.stderr_tail == "ERR", "stderr 尾缓冲 = ERR"); + check(result.stdout_truncated == 0 && result.stderr_truncated == 0, + "未截断"); + check(chunks >= 1, "output 回调被调用"); + check(sup.running() == 0, "running() 归零"); + check(sup.stats().failed == 1, "非零退出计入 stats.failed"); + } +} + +void test_timeout_and_tree() { + std::cout << "-- 超时 / 进程组终止 --" << std::endl; + uvcpp_loop loop; + bool done = false; + uvcpp_process_result result; + std::string out; + { + uvcpp_process_supervisor sup(&loop); + uvcpp_process_spec spec; + spec.file = "/bin/sh"; + spec.args = std::vector{ + "-c", "sleep 30 & echo $!; wait"}; + spec.timeout_ms = 200; + spec.stop_grace_ms = 200; + spec.kill_tree = true; + const uint64_t id = sup.spawn( + spec, [&](const char* d, size_t n, bool) { out.append(d, n); }, + [&](const uvcpp_process_result& r) { result = r; done = true; }); + check(id != 0, "spawn 返回 id"); + if (id == 0) return; + check(run_until(loop, done, 5000), "超时后收尾"); + check(result.timed_out, "结果标记 timed_out"); + check(result.elapsed_ms < 4000, "没有被 30s 的 sleep 拖住(" + + std::to_string(result.elapsed_ms) + + " ms)"); + // 输出的第一行是那个 sleep 的 pid;进程组被杀后它应当不存在了。 + const size_t nl = out.find('\n'); + const bool has_pid = nl != std::string::npos && nl > 0; + check(has_pid, "拿到子进程 pid"); + if (has_pid) { + const pid_t child = static_cast(std::strtol(out.c_str(), nullptr, 10)); + bool gone = false; + for (int i = 0; i < 50 && !gone; ++i) { + if (::kill(child, 0) != 0 && errno == ESRCH) gone = true; + else { struct timespec ts = {0, 20 * 1000 * 1000}; nanosleep(&ts, nullptr); } + } + check(gone, "子进程(sleep)随进程组一起被杀"); + } + check(sup.stats().timed_out == 1, "stats.timed_out = 1"); + } +} + +void test_cancel() { + std::cout << "-- 取消 --" << std::endl; + uvcpp_loop loop; + bool done = false; + int exit_calls = 0; + uvcpp_process_result result; + { + uvcpp_process_supervisor sup(&loop); + uvcpp_process_spec spec; + spec.file = "/bin/sh"; + spec.args = std::vector{"-c", "sleep 30"}; + spec.stop_grace_ms = 200; + const uint64_t id = sup.spawn( + spec, nullptr, + [&](const uvcpp_process_result& r) { ++exit_calls; result = r; done = true; }); + check(id != 0, "spawn 返回 id"); + if (id == 0) return; + check(sup.cancel(id) == 0, "cancel 成功"); + check(sup.cancel(id) == 0, "重复 cancel 是幂等成功(进程仍在收尾)"); + check(run_until(loop, done, 5000), "取消后收尾"); + check(result.cancelled, "结果标记 cancelled"); + check(exit_calls == 1, "退出回调恰好一次"); + check(sup.stats().cancelled == 1, "stats.cancelled = 1"); + } +} + +void test_bounded_output() { + std::cout << "-- 有界输出 --" << std::endl; + uvcpp_loop loop; + bool done = false; + uvcpp_process_result result; + size_t total = 0; + { + uvcpp_process_supervisor sup(&loop); + uvcpp_process_spec spec; + spec.file = "/bin/sh"; + spec.args = std::vector{"-c", "yes 0123456789 | head -c 200000"}; + spec.max_output_bytes = 1024; + spec.timeout_ms = 5000; + const uint64_t id = sup.spawn( + spec, [&](const char*, size_t n, bool) { total += n; }, + [&](const uvcpp_process_result& r) { result = r; done = true; }); + check(id != 0, "spawn 返回 id"); + if (id == 0) return; + check(run_until(loop, done, 8000), "大输出收尾"); + check(total > 100000, "回调确实收到了大流量(" + + std::to_string(total) + " 字节)"); + check(result.stdout_tail.size() <= 1024, + "尾缓冲不超过上限(" + std::to_string(result.stdout_tail.size()) + + ")"); + check(result.stdout_truncated > 0, "记录了截断字节数(" + + std::to_string(result.stdout_truncated) + + ")"); + check(sup.stats().succeeded == 1, "零退出计入 stats.succeeded"); + } +} + +} // namespace + +int main() { + std::cout << "[process_supervisor] start" << std::endl; + test_basic(); + test_timeout_and_tree(); + test_cancel(); + test_bounded_output(); + if (g_fail == 0) { + std::cout << "[process_supervisor] ALL PASS" << std::endl; + return 0; + } + std::cerr << "[process_supervisor] " << g_fail << " check(s) failed" + << std::endl; + return 1; +} + +#endif // _WIN32