Files

439 lines
17 KiB
C++

// VDE 进程外服务协议(P2 草案)最小 runner。
//
// 职责:
// - 发现服务清单(vde-service.json,递归 2 层);
// - 按清单启动外部服务可执行文件(--request/--response 文件交换);
// - 超时强制终止、退出码/响应状态校验、结果回显。
//
// 退出码(与 docs/design/vde-service-protocol.md 一致):
// 0 = 成功;2 = 用法错误;3 = 清单/协议错误;4 = 超时;5 = 服务失败。
//
// 说明:本 runner 是最小验证实现,不依赖任何 VDE 库;真实宿主应复用同一协议
// 但换成正式进程管理/沙箱实现。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <chrono>
#include "vde/fs_compat.h"
#include <string>
#include <thread>
#include <vector>
#include "../common/service_common.h"
#ifdef _WIN32
#include <windows.h>
#else
#include <cerrno>
#include <csignal>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
namespace {
namespace fs = vde::fs;
using namespace vde_service;
constexpr int kExitOk = 0;
constexpr int kExitUsage = 2;
constexpr int kExitProtocol = 3;
constexpr int kExitTimeout = 4;
constexpr int kExitServiceFailed = 5;
std::string platform_entry_key() {
#if defined(_WIN32)
return "windows";
#elif defined(__APPLE__)
return "macos";
#else
return "linux";
#endif
}
std::string quote_arg(const std::string& value) {
std::string out = "\"";
for (char c : value) {
if (c != '"') out.push_back(c);
}
out.push_back('"');
return out;
}
struct Manifest {
std::string id;
std::string name;
std::string version;
std::string protocol;
std::string executable;
std::string manifest_path;
int default_timeout_ms = 30000;
bool valid = false;
std::string error;
};
Manifest load_manifest(const std::string& path) {
Manifest manifest;
manifest.manifest_path = path;
std::string text;
if (!read_file(path, &text)) {
manifest.error = "cannot read service manifest '" + path + "'";
return manifest;
}
manifest.id = find_string(text, "id");
manifest.name = find_string(text, "name");
manifest.version = find_string(text, "version");
manifest.protocol = find_string(text, "version"); // 兼容:protocol.version 由外层解析
// protocol: { "name": "vde-service", "version": "0.1" }:直接取首个 protocol 块后的字段
const std::size_t protocol_pos = text.find("\"protocol\"");
if (protocol_pos != std::string::npos) {
const std::string tail = text.substr(protocol_pos);
const std::string name = find_string(tail, "name");
const std::string version = find_string(tail, "version");
const std::string timeout = std::to_string(static_cast<int>(find_number(tail, "request_ms", 0.0)));
(void)timeout;
if (!name.empty()) manifest.protocol = name + "/" + version;
const double request_ms = find_number(tail, "request_ms", 0.0);
if (request_ms > 0.0) manifest.default_timeout_ms = static_cast<int>(request_ms);
}
const std::size_t entry_pos = text.find("\"executable\"");
if (entry_pos != std::string::npos) {
const std::string tail = text.substr(entry_pos);
manifest.executable = find_string(tail, platform_entry_key());
if (manifest.executable.empty()) manifest.executable = find_string(tail, "windows");
if (manifest.executable.empty()) manifest.executable = find_string(tail, "linux");
}
if (manifest.id.empty()) {
manifest.error = "service manifest missing 'id'";
return manifest;
}
if (manifest.executable.empty()) {
manifest.error = "service manifest missing platform executable entry";
return manifest;
}
manifest.valid = true;
return manifest;
}
struct ProcessResult {
bool started = false;
bool timed_out = false;
int exit_code = -1;
std::string error;
};
ProcessResult run_process(const std::string& command, int timeout_ms) {
ProcessResult result;
#ifdef _WIN32
STARTUPINFOA startup{};
startup.cb = sizeof(startup);
PROCESS_INFORMATION process{};
std::vector<char> command_line(command.begin(), command.end());
command_line.push_back('\0');
if (!CreateProcessA(nullptr, command_line.data(), nullptr, nullptr, FALSE,
CREATE_NO_WINDOW, nullptr, nullptr, &startup, &process)) {
result.error = "CreateProcess failed (error=" + std::to_string(GetLastError()) + ")";
return result;
}
result.started = true;
const DWORD wait = WaitForSingleObject(process.hProcess,
static_cast<DWORD>(timeout_ms < 0 ? 0 : timeout_ms));
if (wait == WAIT_TIMEOUT) {
TerminateProcess(process.hProcess, 4);
WaitForSingleObject(process.hProcess, 5000);
result.timed_out = true;
}
DWORD code = 0;
GetExitCodeProcess(process.hProcess, &code);
result.exit_code = static_cast<int>(code);
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
return result;
#else
const pid_t pid = fork();
if (pid < 0) {
result.error = "fork failed";
return result;
}
if (pid == 0) {
execl("/bin/sh", "sh", "-c", command.c_str(), static_cast<char*>(nullptr));
_exit(127);
}
result.started = true;
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
int status = 0;
for (;;) {
const pid_t waited = waitpid(pid, &status, WNOHANG);
if (waited == pid) break;
if (waited < 0) {
result.error = "waitpid failed";
return result;
}
if (std::chrono::steady_clock::now() > deadline) {
kill(pid, SIGKILL);
waitpid(pid, &status, 0);
result.timed_out = true;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(20));
}
if (WIFEXITED(status)) result.exit_code = WEXITSTATUS(status);
else result.exit_code = kExitServiceFailed;
return result;
#endif
}
void print_usage() {
std::printf(
"vde_service_runner (VDE external service protocol draft, P2)\n"
"\n"
"Usage:\n"
" vde_service_runner --list <dir>\n"
" scan <dir> (2 levels) for vde-service.json and print discovered services\n"
" vde_service_runner --run --manifest <vde-service.json> (--request <req.json> | --request-json <json>)\n"
" [--workdir <dir>] [--timeout-ms <n>]\n"
" start the service executable with request/response file exchange\n"
" vde_service_runner --abi\n"
" print protocol version\n"
"\n"
"Exit codes: 0 ok, 2 usage error, 3 manifest/protocol error, 4 timeout, 5 service failed.\n");
}
int command_list(const std::string& dir) {
std::error_code ec;
if (!fs::is_directory(dir, ec) || ec) {
std::fprintf(stderr, "[vde-service-runner] error: not a directory: '%s'\n", dir.c_str());
return kExitProtocol;
}
std::vector<fs::path> candidates;
candidates.push_back(dir);
std::vector<fs::path> level1;
for (const auto& entry : fs::directory_iterator(dir, ec)) {
if (ec) break;
if (entry.is_directory()) {
level1.push_back(entry.path());
candidates.push_back(entry.path());
}
}
for (const auto& first : level1) {
for (const auto& entry : fs::directory_iterator(first, ec)) {
if (ec) break;
if (entry.is_directory()) candidates.push_back(entry.path());
}
}
int found = 0;
for (const auto& candidate : candidates) {
const fs::path manifest_path = candidate / "vde-service.json";
std::error_code file_ec;
if (!fs::is_regular_file(manifest_path, file_ec) || file_ec) continue;
const Manifest manifest = load_manifest(manifest_path.string());
if (!manifest.valid) {
std::fprintf(stderr, "[vde-service-runner] skip '%s': %s\n",
manifest_path.string().c_str(), manifest.error.c_str());
continue;
}
++found;
std::string text;
read_file(manifest_path.string(), &text);
std::printf("- id : %s\n", manifest.id.c_str());
std::printf(" name : %s\n", manifest.name.c_str());
std::printf(" version : %s\n", manifest.version.c_str());
std::printf(" protocol : %s\n", manifest.protocol.c_str());
std::printf(" executable : %s\n", manifest.executable.c_str());
std::printf(" timeout_ms : %d\n", manifest.default_timeout_ms);
std::string capabilities;
for (const auto& capability : find_string_array(text, "capabilities")) {
if (!capabilities.empty()) capabilities += "; ";
capabilities += capability;
}
std::printf(" capabilities : %s\n", capabilities.c_str());
std::printf(" manifest : %s\n", manifest_path.string().c_str());
}
std::printf("discovered %d external service manifest(s)\n", found);
return kExitOk;
}
int command_run(const std::string& manifest_path, const std::string& request_file,
const std::string& request_json, const std::string& workdir_override,
int timeout_override_ms) {
if (manifest_path.empty()) {
std::fprintf(stderr, "[vde-service-runner] error: missing --manifest\n");
return kExitUsage;
}
if (request_file.empty() && request_json.empty()) {
std::fprintf(stderr,
"[vde-service-runner] error: need --request <file> or --request-json <json>\n");
return kExitUsage;
}
const Manifest manifest = load_manifest(manifest_path);
if (!manifest.valid) {
std::fprintf(stderr, "[vde-service-runner] error: %s\n", manifest.error.c_str());
return kExitProtocol;
}
const fs::path manifest_dir = fs::path(manifest_path).parent_path();
fs::path executable = fs::path(manifest.executable);
if (executable.is_relative()) executable = manifest_dir / executable;
std::error_code ec;
if (!fs::is_regular_file(executable, ec) || ec) {
std::fprintf(stderr, "[vde-service-runner] error: executable not found: '%s'\n",
executable.string().c_str());
return kExitProtocol;
}
fs::path workdir;
if (!workdir_override.empty()) {
workdir = fs::path(workdir_override);
} else {
workdir = fs::temp_directory_path(ec);
if (ec) workdir = manifest_dir;
}
workdir /= "vde_service_" + std::to_string(
#ifdef _WIN32
static_cast<long long>(GetCurrentProcessId())
#else
static_cast<long long>(getpid())
#endif
) +
"_" + std::to_string(
static_cast<long long>(
std::chrono::steady_clock::now().time_since_epoch().count())
);
fs::create_directories(workdir, ec);
if (ec) {
std::fprintf(stderr, "[vde-service-runner] error: cannot create workdir '%s': %s\n",
workdir.string().c_str(), ec.message().c_str());
return kExitProtocol;
}
const fs::path request_path = workdir / "request.json";
const fs::path response_path = workdir / "response.json";
std::string request_text = request_json;
if (!request_file.empty()) {
if (!read_file(request_file, &request_text)) {
std::fprintf(stderr, "[vde-service-runner] error: cannot read request file '%s'\n",
request_file.c_str());
return kExitProtocol;
}
}
if (!write_file(request_path.string(), request_text)) {
std::fprintf(stderr, "[vde-service-runner] error: cannot write request '%s'\n",
request_path.string().c_str());
return kExitProtocol;
}
std::error_code remove_ec;
fs::remove(response_path, remove_ec);
const int timeout_ms = timeout_override_ms > 0 ? timeout_override_ms : manifest.default_timeout_ms;
const std::string command = quote_arg(executable.string()) + " --request " +
quote_arg(request_path.string()) + " --response " +
quote_arg(response_path.string());
const auto begin = std::chrono::steady_clock::now();
const ProcessResult process = run_process(command, timeout_ms);
const double elapsed_ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - begin).count();
if (!process.started) {
std::fprintf(stderr, "[vde-service-runner] error: cannot start service: %s\n",
process.error.c_str());
return kExitServiceFailed;
}
if (process.timed_out) {
std::fprintf(stderr,
"[vde-service-runner] error: timeout after %.0f ms (limit %d ms), service '%s' killed\n",
elapsed_ms, timeout_ms, manifest.id.c_str());
return kExitTimeout;
}
// 响应优先:即使服务以非 0 退出,只要写了可解析的 response.json,就以响应
// 的 status/code 为准判定(区分「协议/业务错误」与「进程崩溃」)。
std::string response;
const bool has_response = read_file(response_path.string(), &response);
const std::string status = has_response ? find_string(response, "status") : std::string();
const int child_exit = process.exit_code;
if (!has_response || status.empty()) {
if (child_exit != 0) {
std::fprintf(stderr,
"[vde-service-runner] error: service '%s' failed (exit=%d, no response, %.0f ms)\n",
manifest.id.c_str(), child_exit, elapsed_ms);
return kExitServiceFailed;
}
std::fprintf(stderr, "[vde-service-runner] error: service '%s' produced no response file\n",
manifest.id.c_str());
return kExitProtocol;
}
if (status != "ok") {
const std::string code = find_string(response, "code");
const std::string message = find_string(response, "message");
std::fprintf(stderr,
"[vde-service-runner] error: service '%s' status='%s' code='%s' message='%s' exit=%d (%.0f ms)\n",
manifest.id.c_str(), status.c_str(), code.c_str(), message.c_str(),
child_exit, elapsed_ms);
// 服务显式报告协议/业务错误:退出码 3;进程异常退出(非声明错误)归 5。
return (child_exit == 0 || child_exit == kExitProtocol) ? kExitProtocol
: kExitServiceFailed;
}
if (child_exit != 0) {
std::fprintf(stderr,
"[vde-service-runner] error: service '%s' reported ok but exited with code %d (%.0f ms)\n",
manifest.id.c_str(), child_exit, elapsed_ms);
return kExitServiceFailed;
}
std::printf("service=%s protocol=%s status=ok elapsed_ms=%.0f\n", manifest.id.c_str(),
manifest.protocol.c_str(), elapsed_ms);
std::printf("%s\n", response.c_str());
return kExitOk;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
print_usage();
return kExitUsage;
}
const std::string mode = argv[1];
if (mode == "--help" || mode == "-h") {
print_usage();
return kExitOk;
}
if (mode == "--abi") {
std::printf("vde-service protocol %s/%s\n", protocol_name(), protocol_version());
return kExitOk;
}
if (mode == "--list") {
if (argc < 3) {
print_usage();
return kExitUsage;
}
return command_list(argv[2]);
}
if (mode == "--run") {
std::string manifest_path;
std::string request_file;
std::string request_json;
std::string workdir;
int timeout_ms = 0;
for (int i = 2; i < argc; ++i) {
const std::string arg = argv[i];
const auto next = [&](const char* name) -> std::string {
if (i + 1 >= argc) {
std::fprintf(stderr, "[vde-service-runner] error: %s needs a value\n", name);
std::exit(kExitUsage);
}
return argv[++i];
};
if (arg == "--manifest") manifest_path = next("--manifest");
else if (arg == "--request") request_file = next("--request");
else if (arg == "--request-json") request_json = next("--request-json");
else if (arg == "--workdir") workdir = next("--workdir");
else if (arg == "--timeout-ms") timeout_ms = std::atoi(next("--timeout-ms").c_str());
else {
std::fprintf(stderr, "[vde-service-runner] error: unknown option '%s'\n", arg.c_str());
return kExitUsage;
}
}
return command_run(manifest_path, request_file, request_json, workdir, timeout_ms);
}
std::fprintf(stderr, "[vde-service-runner] error: unknown mode '%s'\n", mode.c_str());
print_usage();
return kExitUsage;
}