From b2d2c372f2efe1561b487054fc648febcf13f687 Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Tue, 27 Oct 2026 21:13:51 +0800 Subject: [PATCH 1/6] feat: add a scheduled service demo; count only handled requests - demo/scheduled_service_demo.cpp: a map component serves segment costs from a service trigger, and a planner sums a route with CallAsync on a single scheduler worker, triggered again by each reply. A second part makes the same call with a blocking Call, which times out because the map cannot get the worker the planner holds. Runs as a ctest. - Server::ServePending returned requests taken, counting ones dropped unhandled because their client deadline had passed. It now returns requests handled; the budget still counts every request taken, so a backlog of expired requests cannot stretch a pass. Co-Authored-By: Claude Opus 5.5 --- demo/CMakeLists.txt | 9 + demo/scheduled_service_demo.cpp | 291 ++++++++++++++++++++++++ docs/services.md | 6 + include/puppet_master/service/service.h | 12 +- src/service/service.cpp | 21 +- test/CMakeLists.txt | 12 + test/scheduled_service_test.cpp | 10 + 7 files changed, 350 insertions(+), 11 deletions(-) create mode 100644 demo/scheduled_service_demo.cpp diff --git a/demo/CMakeLists.txt b/demo/CMakeLists.txt index a1153e4..6558297 100644 --- a/demo/CMakeLists.txt +++ b/demo/CMakeLists.txt @@ -111,3 +111,12 @@ target_link_libraries(puppet_master_service_demo PRIVATE PuppetMaster::PuppetMaster ) + +add_executable(puppet_master_scheduled_service_demo + scheduled_service_demo.cpp +) + +target_link_libraries(puppet_master_scheduled_service_demo + PRIVATE + PuppetMaster::PuppetMaster +) diff --git a/demo/scheduled_service_demo.cpp b/demo/scheduled_service_demo.cpp new file mode 100644 index 0000000..7b57d98 --- /dev/null +++ b/demo/scheduled_service_demo.cpp @@ -0,0 +1,291 @@ +// Services through the scheduler: a route planner asks a map component for +// the cost of each road segment, all on one scheduler worker. +// +// puppet_master_scheduled_service_demo +// +// The map serves requests in its Execute(), run by a service trigger, so its +// handler follows the scheduler's priorities instead of a thread of its own. +// The planner calls it with CallAsync from its own Execute(): a blocking Call +// there would hold the only worker, and the map could never answer. Part 2 +// shows exactly that. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace core = puppet_master::core; +namespace runtime = puppet_master::runtime; +namespace scheduler = puppet_master::scheduler; +namespace service = puppet_master::service; +namespace transport = puppet_master::transport; + +using namespace std::chrono_literals; + +struct SegmentQuery { + std::uint32_t segment; +}; + +struct SegmentCost { + std::uint32_t segment; + double cost; +}; + +template <> +struct puppet_master::transport::MessageTypeName { + static constexpr const char* value = "demo.SegmentQuery"; + static constexpr std::uint32_t version = 1; +}; + +template <> +struct puppet_master::transport::MessageTypeName { + static constexpr const char* value = "demo.SegmentCost"; + static constexpr std::uint32_t version = 1; +}; + +namespace { + +service::ServiceSpec CostService() +{ + auto spec = service::TypedServiceSpec( + core::TopicName::Unsafe("/demo/segment_cost"), core::TransportKind::kInMemory); + spec.heartbeat_interval = 50ms; + return spec; +} + +core::TriggerSpec Trigger(core::TriggerKind kind, std::int32_t priority = 0) +{ + core::TriggerSpec trigger; + trigger.kind = kind; + trigger.priority = priority; + if (kind == core::TriggerKind::kService) { + trigger.service_dependencies = {CostService().name}; + } + return trigger; +} + +// Answers segment costs. A service trigger runs Execute() when queries +// arrive; ServePending() handles them on the scheduler's worker. +class MapComponent final : public runtime::Component { +public: + runtime::ComponentSpec Describe() const override + { + runtime::ComponentSpec spec {core::ComponentName::Unsafe("map"), "answers segment costs", {}, {}, + {Trigger(core::TriggerKind::kService, 10)}}; + spec.servers = {CostService()}; + return spec; + } + + core::Status Initialize(runtime::ComponentContext& context) override + { + service::ServerOptions options; + options.mode = service::ServeMode::kCaller; // no handler thread of its own + auto server = service::MakeTypedServer( + context.runtime(), CostService(), + [](const SegmentQuery& query) { + if (query.segment == 0) { + return core::Result::FromStatus(core::Status::NotFound("no segment 0")); + } + return core::Result(SegmentCost {query.segment, 1.5 * query.segment}); + }, + options); + if (!server.ok()) { + return server.status(); + } + server_ = std::move(server).value(); + return core::Status::Ok(); + } + + core::Status Execute(runtime::ComponentContext&) override + { + auto served = server_->ServePending(); + if (!served.ok()) { + return served.status(); + } + std::cout << " map: served " << served.value() << " quer" << (served.value() == 1 ? "y" : "ies") + << " on worker " << std::this_thread::get_id() << '\n'; + return core::Status::Ok(); + } + + core::Status Shutdown(runtime::ComponentContext&) override + { + server_.reset(); + return core::Status::Ok(); + } + +private: + std::unique_ptr server_; +}; + +// Sums the cost of a route, one segment per call. Each Execute() either +// sends the next query or consumes the reply that triggered it. +class PlannerComponent final : public runtime::Component { +public: + PlannerComponent(std::vector route, bool blocking) + : route_(std::move(route)), blocking_(blocking) + { + } + + runtime::ComponentSpec Describe() const override + { + runtime::ComponentSpec spec {core::ComponentName::Unsafe("planner"), "plans a route", {}, {}, + {Trigger(core::TriggerKind::kManual)}}; + spec.clients = {CostService()}; + return spec; + } + + core::Status Initialize(runtime::ComponentContext& context) override + { + auto client = service::MakeTypedClient(context.runtime(), CostService()); + if (!client.ok()) { + return client.status(); + } + client_.emplace(std::move(client).value()); + return core::Status::Ok(); + } + + core::Status Execute(runtime::ComponentContext&) override + { + if (blocking_) { + // Holds the only worker while waiting: the map cannot run. + const auto started = std::chrono::steady_clock::now(); + auto reply = client_->Call(SegmentQuery {route_.front()}, 300ms); + const auto waited = std::chrono::duration_cast( + std::chrono::steady_clock::now() - started); + std::cout << " planner: blocking Call -> " << reply.status().ToString() << " after " << waited.count() + << " ms\n"; + blocking_result_ = reply.status().code(); + finished_ = true; + return core::Status::Ok(); + } + + std::optional> reply; + { + std::lock_guard lock(mutex_); + reply.swap(reply_); + } + if (reply) { + if (!reply->ok()) { + std::cout << " planner: query failed: " << reply->status().ToString() << '\n'; + finished_ = true; + return reply->status(); + } + total_ += reply->value().cost; + std::cout << " planner: segment " << reply->value().segment << " costs " << reply->value().cost + << " (route so far " << total_ << ")\n"; + ++next_; + } + if (next_ == route_.size()) { + finished_ = true; + return core::Status::Ok(); + } + // Returns at once; the reply arrives on the client's dispatcher, + // which only stores it and asks the scheduler to run us again. + return client_->CallAsync(SegmentQuery {route_[next_]}, 1s, [this](core::Result result) { + { + std::lock_guard lock(mutex_); + reply_ = std::move(result); + } + scheduler_->Trigger(core::ComponentName::Unsafe("planner")); + }); + } + + core::Status Shutdown(runtime::ComponentContext&) override + { + client_.reset(); + return core::Status::Ok(); + } + + void set_scheduler(scheduler::Scheduler& scheduler) { scheduler_ = &scheduler; } + bool finished() const { return finished_.load(); } + double total() const { return total_; } + core::StatusCode blocking_result() const { return blocking_result_; } + +private: + std::vector route_; + bool blocking_; + std::optional> client_; + scheduler::Scheduler* scheduler_ {nullptr}; + std::mutex mutex_; + std::optional> reply_; + std::size_t next_ {0}; + double total_ {0}; // only touched in Execute(), which runs serially + std::atomic finished_ {false}; + core::StatusCode blocking_result_ {core::StatusCode::kOk}; +}; + +// Runs one planner against the map on a one-worker scheduler, until the +// planner finishes or `timeout` passes. +bool RunPlanner(PlannerComponent& planner_ref, const std::shared_ptr& planner, + std::chrono::milliseconds timeout) +{ + auto created = runtime::RuntimeContext::Create(); + if (!created.ok()) { + std::cerr << created.status().ToString() << '\n'; + return false; + } + auto& context = *created.value(); + auto map = std::make_shared(); + const auto names = {core::ComponentName::Unsafe("map"), core::ComponentName::Unsafe("planner")}; + if (!context.RegisterComponent(map).ok() || !context.RegisterComponent(planner).ok()) { + return false; + } + for (const auto& name : names) { + for (auto status : {context.ConfigureComponent(name), context.InitializeComponent(name), + context.StartComponent(name)}) { + if (!status.ok()) { + std::cerr << name.str() << ": " << status.ToString() << '\n'; + return false; + } + } + } + + scheduler::Scheduler sched(context); // one worker + planner_ref.set_scheduler(sched); + if (!sched.RegisterAllComponents().ok() || !sched.Start().ok()) { + return false; + } + sched.Trigger(core::ComponentName::Unsafe("planner")); + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (!planner_ref.finished() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(5ms); + } + sched.WaitIdle(1s); + sched.Stop(); + for (const auto& name : {core::ComponentName::Unsafe("planner"), core::ComponentName::Unsafe("map")}) { + context.StopComponent(name); + context.ShutdownComponent(name); + } + return planner_ref.finished(); +} + +} // namespace + +int main() +{ + std::cout << "1. CallAsync from Execute(), one worker\n"; + auto planner = std::make_shared(std::vector {3, 1, 4, 2}, false); + const bool async_ok = RunPlanner(*planner, planner, 3s) && planner->total() == 15.0; + std::cout << " route cost: " << planner->total() << '\n'; + + std::cout << "2. blocking Call from Execute(), one worker\n"; + auto blocking = std::make_shared(std::vector {3}, true); + const bool blocking_ok = RunPlanner(*blocking, blocking, 3s) + && blocking->blocking_result() == core::StatusCode::kDeadlineExceeded; + std::cout << " the map only got the worker after the planner had given up: use CallAsync\n"; + + const bool ok = async_ok && blocking_ok; + std::cout << (ok ? "scheduled service demo finished\n" : "scheduled service demo FAILED\n"); + return ok ? 0 : 1; +} diff --git a/docs/services.md b/docs/services.md index d2887fe..3c11e86 100644 --- a/docs/services.md +++ b/docs/services.md @@ -331,6 +331,12 @@ typed get/set calls, handler errors, a slow handler that times out (`DeadlineExceeded`), an orderly server stop that fails calls at once (`Unavailable`), and a restart picked up through a new instance id. +`demo/scheduled_service_demo.cpp` runs both sides on one scheduler worker: a +map component serves segment costs from a service trigger, and a planner +fetches them one by one with `CallAsync`, triggered again by each reply. Its +second part shows the same call made with a blocking `Call`, which times out +because the map cannot get the worker the planner holds. + ## Limits - Requests and replies are bounded by the transport's message size; on diff --git a/include/puppet_master/service/service.h b/include/puppet_master/service/service.h index 56361f9..f66d74b 100644 --- a/include/puppet_master/service/service.h +++ b/include/puppet_master/service/service.h @@ -86,11 +86,13 @@ class PUPPET_MASTER_API Server final { static core::Result> Create( runtime::RuntimeContext& runtime, ServiceSpec spec, Handler handler, ServerOptions options = {}); - // kCaller only: handles queued requests in arrival order on the calling - // thread and returns how many, at most `limit` (0 means all queued). - // Requests that arrive meanwhile are left for the next call, so a burst - // cannot keep one call running forever. FailedPrecondition in kOwnThread - // mode or after Close(). + // kCaller only: takes queued requests in arrival order on the calling + // thread, at most `limit` (0 means all queued), and returns how many it + // handled. Requests whose client deadline already passed are taken but + // dropped unhandled (see expired_count()), so they do not count. Requests + // that arrive meanwhile are left for the next call, so a burst cannot + // keep one call running forever. FailedPrecondition in kOwnThread mode + // or after Close(). core::Result ServePending(std::size_t limit = 0); // Requests waiting to be handled, where the transport can tell. diff --git a/src/service/service.cpp b/src/service/service.cpp index fbea9f0..b269ab9 100644 --- a/src/service/service.cpp +++ b/src/service/service.cpp @@ -276,12 +276,14 @@ struct Server::Impl { replies->Write(ByteView(message)); } - void Serve(const transport::Message& message) + // True if the handler ran; false for a request that was dropped + // unhandled (malformed, or past its deadline). + bool Serve(const transport::Message& message) { Header header; ByteView payload; if (!Decode(message.payload, kRequestMagic, header, payload)) { - return; + return false; } // The deadline is measured on this host's clock from when the request // arrived. Transit time is not counted, so the server errs toward @@ -293,7 +295,7 @@ struct Server::Impl { Request request {payload, header.client_id, header.request_id, deadline}; if (header.budget_ns != 0 && Now() > deadline) { ++expired; // the client has stopped waiting - return; + return false; } core::Result result = core::Result::FromStatus(core::Status::Internal("")); try { @@ -312,6 +314,7 @@ struct Server::Impl { Reply(header, result.status().code(), ByteView(reinterpret_cast(text.data()), text.size())); } + return true; } // Serves requests in arrival order. Polls as well as waiting for the data @@ -437,8 +440,12 @@ core::Result Server::ServePending(std::size_t limit) auto queued = impl.requests->PendingMessageCount(); budget = queued.ok() ? queued.value() : impl.spec.queue_depth; } + // The budget counts requests taken, expired ones included, so a backlog + // of expired requests cannot stretch the pass; only handled ones count + // toward the result. + std::size_t taken = 0; std::size_t served = 0; - while (served < budget) { + while (taken < budget) { if (is_closed()) { break; // Close() from a handler, or from another thread } @@ -446,8 +453,10 @@ core::Result Server::ServePending(std::size_t limit) if (!message.ok()) { break; // drained } - impl.Serve(message.value()); - ++served; + ++taken; + if (impl.Serve(message.value())) { + ++served; + } } return ResultType(served); } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 7bd37ac..6de37a8 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -207,6 +207,18 @@ if(TARGET puppet_master_service_demo) ) endif() +if(TARGET puppet_master_scheduled_service_demo) + add_test( + NAME puppet_master.scheduled_service_demo + COMMAND puppet_master_scheduled_service_demo + ) + set_tests_properties(puppet_master.scheduled_service_demo + PROPERTIES + PASS_REGULAR_EXPRESSION "scheduled service demo finished" + TIMEOUT 30 + ) +endif() + if(TARGET puppet_master_launcher_demo) set(PUPPETMASTER_DEMO_CONFIG "${PROJECT_SOURCE_DIR}/demo/config/speed_pipeline.json") diff --git a/test/scheduled_service_test.cpp b/test/scheduled_service_test.cpp index 3a39918..647fcc3 100644 --- a/test/scheduled_service_test.cpp +++ b/test/scheduled_service_test.cpp @@ -541,6 +541,16 @@ void ServePendingContract() assert(nested.code() == core::StatusCode::kFailedPrecondition); assert(nested.message().find("its own handler") != std::string::npos); + // A request whose client gave up is taken but not handled: it counts + // toward expired_count(), not toward what ServePending returns. + const auto handled_before = server.value()->handled_count(); + assert(client.value()->Call(Bytes("late"), 30ms).status().code() == core::StatusCode::kDeadlineExceeded); + assert(server.value()->PendingCount().value() == 1); + assert(server.value()->ServePending().value() == 0); + assert(server.value()->expired_count() == 1); + assert(server.value()->handled_count() == handled_before); + assert(server.value()->PendingCount().value() == 0); + server.value()->Close(); assert(server.value()->ServePending().status().code() == core::StatusCode::kFailedPrecondition); } From fe39b44dde9870d2ccd43b1b4f52728c90df5ada Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Tue, 27 Oct 2026 21:24:50 +0800 Subject: [PATCH 2/6] feat: add supervision fields to system manifests Nodes in a system manifest can now say how a supervisor should treat them: - restart: "never" (default), "on_failure", or "always" - max_restarts: restarts allowed before giving up (default 5; 0 = no limit) - restart_delay_ms: wait before a restart (default 500) - required: whether a node that exits for good stops the whole system (default true) - stop_timeout_ms: grace period between asking a node to stop and killing it (default 5000) Values are validated with errors naming the field. `puppet_master_config system describe` prints them. They are read by the launcher in the next commit. Co-Authored-By: Claude Opus 5.5 --- docs/configuration.md | 9 +++ .../configuration/system_manifest.h | 21 ++++++ src/configuration/system_manifest.cpp | 66 +++++++++++++++++-- test/system_manifest_test.cpp | 42 ++++++++++++ tools/puppet_master_config.cpp | 6 ++ 5 files changed, 138 insertions(+), 6 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index a7962e2..a36fd0f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -359,6 +359,15 @@ system manifest is the one list of a system's processes: - `nodes` are in start order. Names must be unique and are used as labels in system reports. +- Supervision fields, read by `puppet_master_launch`: + + | Field | Default | Meaning | + |---|---|---| + | `restart` | `"never"` | `"never"`, `"on_failure"` (non-zero exit or signal), or `"always"` | + | `max_restarts` | 5 | restarts allowed before giving up; 0 means no limit | + | `restart_delay_ms` | 500 | wait before a restart; doubles for quick repeated failures, up to 30 s | + | `required` | `true` | a required node that exits for good stops the whole system | + | `stop_timeout_ms` | 5000 | after asking a node to stop, how long before it is killed | - `${NAME}` in any string is replaced with the environment variable `NAME`, so one manifest serves any install prefix. An unset variable is an error, not an empty string. diff --git a/include/puppet_master/configuration/system_manifest.h b/include/puppet_master/configuration/system_manifest.h index 464dfe6..a8cb9cf 100644 --- a/include/puppet_master/configuration/system_manifest.h +++ b/include/puppet_master/configuration/system_manifest.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -28,8 +29,28 @@ struct NodeManifest { std::vector arguments; // passed after the launcher options // How long to wait after starting this node before starting the next. std::chrono::milliseconds start_delay {0}; + + // Supervision, for puppet_master_launch. + enum class Restart : std::uint8_t { + kNever = 0, // an exit is final + kOnFailure, // restart after a non-zero exit or a signal + kAlways, // restart after any exit + }; + Restart restart {Restart::kNever}; + // Restarts allowed before giving up on the node; 0 means no limit. + std::uint32_t max_restarts {5}; + // Wait before a restart, doubling after each one that follows within + // a minute of the previous, up to 30 s. + std::chrono::milliseconds restart_delay {std::chrono::milliseconds(500)}; + // A required node that exits for good (no restart left) stops the whole + // system; an optional one is left stopped. + bool required {true}; + // After asking the node to stop, how long to wait before killing it. + std::chrono::milliseconds stop_timeout {std::chrono::milliseconds(5000)}; }; +PUPPET_MASTER_API const char* ToString(NodeManifest::Restart restart) noexcept; + struct SystemManifest { std::string name; std::string path; // the manifest file diff --git a/src/configuration/system_manifest.cpp b/src/configuration/system_manifest.cpp index a4c1ed1..3111cc5 100644 --- a/src/configuration/system_manifest.cpp +++ b/src/configuration/system_manifest.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -37,6 +38,22 @@ void CheckFields(const Json& value, const std::string& path, std::initializer_li } } +// A non-negative millisecond count, at most a day; leaves `output` alone if +// the field is absent. +void ReadMilliseconds(const Json& object, const char* key, const std::string& path, + std::chrono::milliseconds& output) +{ + if (!object.contains(key)) { + return; + } + const auto& value = object.at(key); + constexpr std::int64_t kDay = 24LL * 60 * 60 * 1000; + if (!value.is_number_integer() || value.get() < 0 || value.get() > kDay) { + Fail(path + "." + key + " must be a non-negative integer of milliseconds, at most a day"); + } + output = std::chrono::milliseconds(value.get()); +} + std::string GetEnvironment(const std::string& name, bool& found) { #ifdef _WIN32 @@ -212,7 +229,8 @@ SystemManifest Decode(const Json& root, const fs::path& file) std::size_t index = 0; for (const auto& value : *nodes) { const auto path = "$.nodes[" + std::to_string(index++) + "]"; - CheckFields(value, path, {"name", "executable", "config", "arguments", "start_delay_ms"}); + CheckFields(value, path, {"name", "executable", "config", "arguments", "start_delay_ms", "restart", + "max_restarts", "restart_delay_ms", "required", "stop_timeout_ms"}); NodeManifest node; node.name = String(value, "name", path, true); auto status = core::ValidateName("node name", node.name); @@ -231,12 +249,35 @@ SystemManifest Decode(const Json& root, const fs::path& file) Fail(path + ".arguments: arguments must not contain tabs or line breaks"); } } - if (value.contains("start_delay_ms")) { - const auto& delay = value.at("start_delay_ms"); - if (!delay.is_number_integer() || delay.get() < 0) { - Fail(path + ".start_delay_ms must be a non-negative integer"); + ReadMilliseconds(value, "start_delay_ms", path, node.start_delay); + ReadMilliseconds(value, "restart_delay_ms", path, node.restart_delay); + ReadMilliseconds(value, "stop_timeout_ms", path, node.stop_timeout); + if (value.contains("restart")) { + const auto& restart = value.at("restart"); + const std::string text = restart.is_string() ? restart.get() : std::string(); + if (text == "never") { + node.restart = NodeManifest::Restart::kNever; + } else if (text == "on_failure") { + node.restart = NodeManifest::Restart::kOnFailure; + } else if (text == "always") { + node.restart = NodeManifest::Restart::kAlways; + } else { + Fail(path + ".restart must be \"never\", \"on_failure\", or \"always\""); + } + } + if (value.contains("max_restarts")) { + const auto& count = value.at("max_restarts"); + if (!count.is_number_integer() || count.get() < 0 + || count.get() > 1000000) { + Fail(path + ".max_restarts must be a non-negative integer"); } - node.start_delay = std::chrono::milliseconds(delay.get()); + node.max_restarts = static_cast(count.get()); + } + if (value.contains("required")) { + if (!value.at("required").is_boolean()) { + Fail(path + ".required must be true or false"); + } + node.required = value.at("required").get(); } node.executable = ResolveExecutable(manifest, base, node.executable); node.config = ResolveConfig(manifest, base, node, path); @@ -273,6 +314,19 @@ std::vector SystemManifest::CommandFor(const NodeManifest& node) co return command; } +const char* ToString(NodeManifest::Restart restart) noexcept +{ + switch (restart) { + case NodeManifest::Restart::kNever: + return "never"; + case NodeManifest::Restart::kOnFailure: + return "on_failure"; + case NodeManifest::Restart::kAlways: + return "always"; + } + return "unknown"; +} + core::Result LoadSystemManifest(const std::string& path) { using ResultType = core::Result; diff --git a/test/system_manifest_test.cpp b/test/system_manifest_test.cpp index 295a513..0c5e975 100644 --- a/test/system_manifest_test.cpp +++ b/test/system_manifest_test.cpp @@ -120,6 +120,12 @@ void LoadsAndResolves() const auto& producer = system.nodes[1]; assert(producer.executable == tree.Path("bin/producer_node")); + // Supervision defaults: no restart, required, 5 s to stop. + assert(consumer.restart == config::NodeManifest::Restart::kNever); + assert(consumer.max_restarts == 5 && consumer.restart_delay == std::chrono::milliseconds(500)); + assert(consumer.required && consumer.stop_timeout == std::chrono::milliseconds(5000)); + assert(std::string(config::ToString(consumer.restart)) == "never"); + const auto command = system.CommandFor(producer); const std::vector expected {tree.Path("bin/producer_node"), "--config-path", tree.Path("share"), "--deployment", tree.Path("etc/deploy.json"), "--describe", @@ -197,11 +203,46 @@ void RejectsInvalidManifests() check(R"json({"nodes": [{"name": "a", "executable": "a", "config": "share/producer/producer.json", "arguments": ["a\tb"]}]})json", "must not contain tabs"); + const std::string base = R"json({"name": "a", "executable": "a", "config": "share/producer/producer.json", )json"; + check(R"json({"nodes": [)json" + base + R"json("restart": "sometimes"}]})json", + "restart must be \"never\", \"on_failure\", or \"always\""); + check(R"json({"nodes": [)json" + base + R"json("restart": 1}]})json", "restart must be"); + check(R"json({"nodes": [)json" + base + R"json("max_restarts": -1}]})json", + "max_restarts must be a non-negative integer"); + check(R"json({"nodes": [)json" + base + R"json("required": "yes"}]})json", "required must be true or false"); + check(R"json({"nodes": [)json" + base + R"json("stop_timeout_ms": 1.5}]})json", + "stop_timeout_ms must be a non-negative integer"); + check(R"json({"nodes": [)json" + base + R"json("restart_delay_ms": 100000000}]})json", "at most a day"); check("{not json", "parse"); assert(config::LoadSystemManifest(tree.Path("absent.json")).status().code() == core::StatusCode::kUnavailable); } +void ReadsSupervision() +{ + TempTree tree; + WriteSystem(tree); + const auto path = tree.Write("system.json", R"json({ + "config_paths": ["share"], + "nodes": [ + {"name": "producer", "executable": "p", "config": "producer/producer.json", + "restart": "on_failure", "max_restarts": 0, "restart_delay_ms": 250, "stop_timeout_ms": 1000}, + {"name": "consumer", "executable": "c", "config": "consumer/consumer.json", + "restart": "always", "required": false} + ]})json"); + auto manifest = config::LoadSystemManifest(path); + assert(manifest.ok()); + const auto& producer = manifest.value().nodes[0]; + assert(producer.restart == config::NodeManifest::Restart::kOnFailure); + assert(producer.max_restarts == 0); // no limit + assert(producer.restart_delay == std::chrono::milliseconds(250)); + assert(producer.stop_timeout == std::chrono::milliseconds(1000) && producer.required); + const auto& consumer = manifest.value().nodes[1]; + assert(consumer.restart == config::NodeManifest::Restart::kAlways && !consumer.required); + assert(std::string(config::ToString(consumer.restart)) == "always"); + assert(std::string(config::ToString(producer.restart)) == "on_failure"); +} + } // namespace int main() @@ -209,5 +250,6 @@ int main() LoadsAndResolves(); SystemProblemsNameNodes(); RejectsInvalidManifests(); + ReadsSupervision(); return 0; } diff --git a/tools/puppet_master_config.cpp b/tools/puppet_master_config.cpp index c872525..a7650bf 100644 --- a/tools/puppet_master_config.cpp +++ b/tools/puppet_master_config.cpp @@ -99,6 +99,12 @@ int RunSystem(const std::string& action, const std::string& path) for (std::size_t index = 0; index < system.nodes.size(); ++index) { const auto& node = system.nodes[index]; std::cout << "\nnode " << node.name << " (" << node.executable << ", " << node.config << ")\n"; + std::cout << " restart " << config::ToString(node.restart); + if (node.restart != config::NodeManifest::Restart::kNever) { + std::cout << " (max " << node.max_restarts << ", delay " << node.restart_delay.count() << " ms)"; + } + std::cout << ", " << (node.required ? "required" : "optional") << ", stop timeout " + << node.stop_timeout.count() << " ms\n"; std::cout << config::DescribeProject(nodes.value()[index].project); } return 0; From e71253f9fad76384eed073b8884d47a1e1c99d9d Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 28 Oct 2026 15:09:06 +0800 Subject: [PATCH 3/6] feat: add puppet_master_launch to supervise system manifests Supervisor starts a manifest's nodes in order, restarts them by their restart policy with a doubling delay (reset, along with the restart count, by a stable run), ends the system when a required node ends for good, and stops the rest in reverse order: a stop request, then a kill after stop_timeout. Each node runs in a process group of its own and can log to /.log. Process handling sits behind ProcessLauncher (posix_spawnp on POSIX, CreateProcess with CTRL_BREAK on Windows), so the policy tests use fake processes. Applications now also stop on SIGBREAK, which is how the launcher stops a node on Windows. The vehicle pipeline integration run now starts the system with puppet_master_launch. Co-Authored-By: Claude Opus 5.5 --- docs/configuration.md | 10 +- docs/launcher.md | 56 +- examples/vehicle_pipeline/README.md | 9 +- .../integration/run_pipeline.sh | 60 +- .../puppet_master/configuration/supervisor.h | 127 ++++ .../configuration/system_manifest.h | 8 +- src/CMakeLists.txt | 3 + src/configuration/application.cpp | 25 +- src/configuration/supervisor.cpp | 614 +++++++++++++++++ test/CMakeLists.txt | 13 + test/supervisor_test.cpp | 651 ++++++++++++++++++ tools/CMakeLists.txt | 17 +- tools/puppet_master_launch.cpp | 130 ++++ 13 files changed, 1671 insertions(+), 52 deletions(-) create mode 100644 include/puppet_master/configuration/supervisor.h create mode 100644 src/configuration/supervisor.cpp create mode 100644 test/supervisor_test.cpp create mode 100644 tools/puppet_master_launch.cpp diff --git a/docs/configuration.md b/docs/configuration.md index a36fd0f..13c59f1 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -389,9 +389,13 @@ system manifest is the one list of a system's processes: | `system describe system.json` | Print every node's configuration | | `system commands system.json` | Print each node's start command, one per line | -`system commands` prints `name`, then the command's words, then -`#delay_ms=N`, separated by tabs. The command is the executable, the -launcher's `--config-path` and `--deployment` options, the node's +`puppet_master_launch system.json` starts and supervises the whole system +with the manifest's restart and stop settings; see +[System Launcher](launcher.md#system-launcher). + +For your own scripts, `system commands` prints `name`, then the command's +words, then `#delay_ms=N`, separated by tabs. The command is the executable, +the launcher's `--config-path` and `--deployment` options, the node's `arguments`, and its config, so a launch script needs no paths of its own: ```bash diff --git a/docs/launcher.md b/docs/launcher.md index 263d16e..df03b6b 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -27,7 +27,7 @@ resulting binary accepts: | Command | Effect | Exit code | |---|---|---| -| `app config.json` | Run until SIGINT or SIGTERM, then shut down cleanly | 0, or 1 on error | +| `app config.json` | Run until SIGINT or SIGTERM (or Ctrl+Break on Windows), then shut down cleanly | 0, or 1 on error | | `app --validate config.json` | Check the configuration and that every component type has a factory | 0 or 1 | | `app --describe config.json` | Print topics, components, and triggers | 0 or 1 | | `app --help` | Usage | 0 | @@ -64,8 +64,9 @@ auto status = app.value()->Run(); // Start(), wait, Stop() destructor calls it. - `Run` is `Start`, then a wait for `RequestStop()`, then `Stop`. `RequestStop()` is safe from any thread, including component callbacks. -- `InstallSignalHandlers` makes SIGINT and SIGTERM call `RequestStop()`. Only - one application per process can own the handlers. +- `InstallSignalHandlers` makes SIGINT and SIGTERM call `RequestStop()`, and + SIGBREAK on Windows, which is how `puppet_master_launch` stops a node there. + Only one application per process can own the handlers. An application runs once; create a new one to run again. @@ -132,6 +133,55 @@ launch scripts. See [System Manifests](configuration.md#system-manifests). (when the shared-memory adapter is built). See [Listing And Cleaning Up](shm-transport.md#listing-and-cleaning-up). +## System Launcher + +`puppet_master_launch` runs every node of a +[system manifest](configuration.md#system-manifests) and supervises them. It +is built and installed with the JSON adapter, next to `puppet_master_config`. + +```bash +puppet_master_launch system.json +puppet_master_launch --log-dir logs system.json +``` + +| Option | Effect | +|---|---| +| `--log-dir DIR` | write each node's output to `DIR/.log`, appended across restarts | +| `--no-validate` | skip the check of the nodes together before starting | + +It runs as follows: + +1. Check the manifest like `puppet_master_config system validate`, and exit + with 1 on any error. +2. Start the nodes in manifest order, waiting each node's `start_delay_ms` + before the next. Each node runs in a process group of its own. +3. Supervise them. A node that exits is restarted by its `restart` policy + after `restart_delay_ms`. The delay doubles for each restart that follows + a run shorter than 10 s, up to 30 s. A longer run resets the delay and the + `max_restarts` count. +4. On SIGINT or SIGTERM (Ctrl+C or Ctrl+Break on Windows), stop the running + nodes in reverse start order. Each node gets SIGTERM (Ctrl+Break on + Windows), then is killed if it is still running after `stop_timeout_ms`. + +The system also stops when a `required` node ends for good: it exited and +its policy allows no restart, or it failed to start. A node with +`"required": false` is left stopped and the others keep running. When every +node has ended, the launcher exits too. + +The launcher prints one line per event to stderr: `started`, `start-failed`, +`exited`, `restarting`, `gave-up`, `stopping`, `killed`, and `stopped`. It +exits with 0 after a stop request or when every node ended successfully. It +exits with 1 when a required node failed or any node ended with a failure. + +Component types are not checked here, because only each node's binary knows +its factories. Run `node --validate` in CI for that, as +`examples/vehicle_pipeline/integration/run_pipeline.sh` does before it +starts the system. + +In C++, `configuration::Supervisor` in +`puppet_master/configuration/supervisor.h` does the same. Its +`ProcessLauncher` interface lets tests replace real processes. + ## Library Helpers These are in the core library and need no JSON: diff --git a/examples/vehicle_pipeline/README.md b/examples/vehicle_pipeline/README.md index 9bc1a1d..a204c6a 100644 --- a/examples/vehicle_pipeline/README.md +++ b/examples/vehicle_pipeline/README.md @@ -60,19 +60,20 @@ cmake --install pm-build --prefix "$HOME/pm-install" # Each package in its own build tree, installed into one prefix. integration/build_all.sh "$HOME/pm-install" "$HOME/vehicle" -# System check, then three processes over shared memory for 3 seconds. +# Node checks, then puppet_master_launch runs the three processes over +# shared memory for 3 seconds and stops them in reverse order. integration/run_pipeline.sh "$HOME/vehicle" "$HOME/pm-install/bin/puppet_master_config" 3 ``` `integration/system.json` is the system manifest: it lists the three nodes in start order with their binaries and config files, the import search path, -and the deployment. `run_pipeline.sh` reads everything from it, so the -system check, CI, and the launch use the same node list: +and the deployment. `run_pipeline.sh` and the launcher read everything from +it, so the system check, CI, and the launch use the same node list: ```bash export VEHICLE_PREFIX="$HOME/vehicle" # the manifest's ${VEHICLE_PREFIX} puppet_master_config system validate integration/system.json -puppet_master_config system commands integration/system.json # start commands +puppet_master_launch --log-dir logs integration/system.json # Ctrl+C stops it ``` To run a node by hand, point the import search path at the shared `share` diff --git a/examples/vehicle_pipeline/integration/run_pipeline.sh b/examples/vehicle_pipeline/integration/run_pipeline.sh index 23b7ed7..713f58b 100755 --- a/examples/vehicle_pipeline/integration/run_pipeline.sh +++ b/examples/vehicle_pipeline/integration/run_pipeline.sh @@ -1,65 +1,61 @@ #!/usr/bin/env bash -# System integration: checks every node of system.json together, then starts -# them in manifest order over shared memory, stops them after a few seconds, -# and checks that the monitor received states without loss. +# System integration: checks every node of system.json together, starts the +# system over shared memory with puppet_master_launch, stops it after a few +# seconds, and checks that the monitor received states without loss. # # ./run_pipeline.sh [seconds] # -# holds every package, as installed by build_all.sh. The -# node list, search paths, and deployment all come from system.json; nothing -# here names a node's files. +# holds every package, as installed by build_all.sh. +# puppet_master_launch is taken from next to . The node +# list, search paths, and deployment all come from system.json; nothing here +# names a node's files. set -euo pipefail PREFIX=$(cd "${1:?usage: run_pipeline.sh [seconds]}" && pwd) CONFIG_TOOL=${2:?usage: run_pipeline.sh [seconds]} SECONDS_TO_RUN=${3:-3} +LAUNCH=$(dirname "$CONFIG_TOOL")/puppet_master_launch MANIFEST=$(cd "$(dirname "$0")" && pwd)/system.json export VEHICLE_PREFIX=$PREFIX LOGS=$(mktemp -d) trap 'kill $(jobs -p) 2>/dev/null || true; rm -rf "$LOGS"' EXIT -# One check for the whole system: no node can see the others' files. -"$CONFIG_TOOL" system validate "$MANIFEST" - -# Each node: its own --validate checks component types, then it starts. -# Lines are namecommand...#delay_ms=N, in start order. -NAMES=() -PIDS=() +# Each node's own --validate checks its component types, which only the +# node binary knows. Lines are namecommand...#delay_ms=N. while IFS=$'\t' read -r -a fields; do - name=${fields[0]} - delay=${fields[${#fields[@]}-1]#\#delay_ms=} command=("${fields[@]:1:${#fields[@]}-2}") node_config=${command[${#command[@]}-1]} "${command[@]:0:${#command[@]}-1}" --validate "$node_config" > /dev/null - "${command[@]}" > "$LOGS/$name.log" 2>&1 & - NAMES+=("$name") - PIDS+=($!) - sleep "$(awk "BEGIN {print $delay / 1000}")" done < <("$CONFIG_TOOL" system commands "$MANIFEST") +# The launcher checks the nodes together, starts them in manifest order, +# and on SIGINT stops them in reverse order, so producers stop first and +# downstream nodes drain what is in flight. +"$LAUNCH" --log-dir "$LOGS" "$MANIFEST" 2> "$LOGS/launch.txt" & +launcher=$! sleep "$SECONDS_TO_RUN" - -# Reverse start order, so producers stop first and downstream nodes drain -# what is in flight. +kill -INT "$launcher" status=0 -for ((index = ${#PIDS[@]} - 1; index >= 0; --index)); do - kill -INT "${PIDS[$index]}" 2>/dev/null || true - wait "${PIDS[$index]}" || status=1 - sleep 0.2 -done +wait "$launcher" || status=$? -for name in "${NAMES[@]}"; do - echo "--- $name" - grep -v "" "$LOGS/$name.log" || true +cat "$LOGS/launch.txt" +for log in "$LOGS"/*.log; do + echo "--- $(basename "$log" .log)" + grep -v "" "$log" || true done +nodes=$("$CONFIG_TOOL" system commands "$MANIFEST" | wc -l) +clean_stops=$(grep -c ": stopped (exit code 0)" "$LOGS/launch.txt" || true) + summary=$(grep "monitor summary" "$LOGS/monitor.log" || true) received=$(echo "$summary" | sed -n 's/.*received \([0-9]*\).*/\1/p') lost=$(echo "$summary" | sed -n 's/.*lost \([0-9]*\).*/\1/p') out_of_range=$(echo "$summary" | sed -n 's/.*out of range \([0-9]*\).*/\1/p') -if [ "$status" -ne 0 ] || [ -z "$received" ] || [ "$received" -lt 50 ] || [ "$lost" -ne 0 ] || [ "$out_of_range" -ne 0 ]; then - echo "FAILED: exit status $status, received ${received:-none}, lost ${lost:-?}, out of range ${out_of_range:-?}" +if [ "$status" -ne 0 ] || [ "$clean_stops" -ne "$nodes" ] || [ -z "$received" ] || [ "$received" -lt 50 ] || + [ "$lost" -ne 0 ] || [ "$out_of_range" -ne 0 ]; then + echo "FAILED: launcher exit $status, $clean_stops of $nodes nodes stopped cleanly," \ + "received ${received:-none}, lost ${lost:-?}, out of range ${out_of_range:-?}" exit 1 fi echo "OK: received $received states across processes, none lost" diff --git a/include/puppet_master/configuration/supervisor.h b/include/puppet_master/configuration/supervisor.h new file mode 100644 index 0000000..3266793 --- /dev/null +++ b/include/puppet_master/configuration/supervisor.h @@ -0,0 +1,127 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +// Supervises the nodes of a system manifest: starts them in order, restarts +// them by policy, and stops them in reverse order. Process handling is behind +// ProcessLauncher, so the policy can be tested without real processes. +namespace puppet_master::configuration { + +// How a process ended. +struct ProcessExit { + // Exit code, or the signal number when `signaled`. + int code {0}; + bool signaled {false}; + + bool success() const noexcept { return !signaled && code == 0; } +}; + +PUPPET_MASTER_API std::string ToString(const ProcessExit& exit); + +class PUPPET_MASTER_API ChildProcess { +public: + virtual ~ChildProcess() = default; + + virtual std::int64_t id() const noexcept = 0; + // The exit, once the process has ended; does not block. + virtual std::optional Poll() = 0; + // Asks the process to stop: SIGTERM on POSIX, CTRL_BREAK to its process + // group on Windows. + virtual void RequestStop() = 0; + // Ends it at once: SIGKILL, TerminateProcess. + virtual void Kill() = 0; +}; + +class PUPPET_MASTER_API ProcessLauncher { +public: + virtual ~ProcessLauncher() = default; + + // Starts `command` (program, then arguments; the program is looked up on + // PATH unless it has a directory part) in a process group of its own, so + // stop requests reach only it. With `log_path`, its stdout and stderr are + // appended to that file; otherwise it shares the caller's. + virtual core::Result> Start( + const std::vector& command, const std::string& log_path) = 0; +}; + +// Real processes on this platform. +PUPPET_MASTER_API std::unique_ptr MakeSystemProcessLauncher(); + +// What happened to a node, for logs and tests. +struct SupervisorEvent { + enum class Kind : std::uint8_t { + kStarted, + kStartFailed, + kExited, + kRestarting, + kGaveUp, // its restart policy wants a restart, but none is left + kStopping, + kKilled, // did not stop within stop_timeout + kStopped, + }; + Kind kind; + std::string node; + std::string detail; +}; + +PUPPET_MASTER_API const char* ToString(SupervisorEvent::Kind kind) noexcept; + +struct SupervisorOptions { + std::unique_ptr launcher; // MakeSystemProcessLauncher() if empty + // Called on the thread running Run(), which it blocks while it runs. + std::function on_event; + // With a directory, each node's output goes to /.log, + // appended across restarts; the directory is created if needed. + std::string log_directory; + // How often child processes are checked. + std::chrono::milliseconds poll_interval {std::chrono::milliseconds(50)}; + // Restart delays double for each restart that follows a run shorter than + // this, up to max_restart_delay; a longer run resets the delay and the + // restart count. + std::chrono::milliseconds stable_run {std::chrono::milliseconds(10000)}; + std::chrono::milliseconds max_restart_delay {std::chrono::milliseconds(30000)}; +}; + +// The outcome of a run. +struct SupervisorResult { + // Why the system stopped: a stop request, a required node that ended + // for good (an exit or a failed start), or every node done. + std::string reason; + // 1 when a required node ended with a failure, every node ended and one + // failed, or the log directory could not be created; 0 otherwise. + int exit_code {0}; +}; + +class PUPPET_MASTER_API Supervisor final { +public: + Supervisor(SystemManifest manifest, SupervisorOptions options = {}); + ~Supervisor(); + Supervisor(const Supervisor&) = delete; + Supervisor& operator=(const Supervisor&) = delete; + + // Starts the nodes and supervises them until RequestStop(), a required + // node ends for good, or every node has ended; then stops the ones still + // running in reverse start order. Call once. + SupervisorResult Run(); + + // Thread-safe and async-signal-unsafe: call it from a signal watcher + // thread, not a signal handler. + void RequestStop() noexcept; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace puppet_master::configuration diff --git a/include/puppet_master/configuration/system_manifest.h b/include/puppet_master/configuration/system_manifest.h index a8cb9cf..c4a0b1d 100644 --- a/include/puppet_master/configuration/system_manifest.h +++ b/include/puppet_master/configuration/system_manifest.h @@ -37,10 +37,12 @@ struct NodeManifest { kAlways, // restart after any exit }; Restart restart {Restart::kNever}; - // Restarts allowed before giving up on the node; 0 means no limit. + // Restarts allowed before giving up on the node; 0 means no limit. A run + // longer than SupervisorOptions::stable_run resets the count. std::uint32_t max_restarts {5}; - // Wait before a restart, doubling after each one that follows within - // a minute of the previous, up to 30 s. + // Wait before a restart. It doubles for each restart after a short run + // (SupervisorOptions::stable_run, 10 s by default), up to 30 s, and is + // reset by a long one. std::chrono::milliseconds restart_delay {std::chrono::milliseconds(500)}; // A required node that exits for good (no restart left) stops the whole // system; an optional one is left stopped. diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index fd5a211..d158406 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -18,6 +18,7 @@ set(PUPPETMASTER_PUBLIC_HEADERS "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/configuration.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/json_launcher.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/json_loader.h" + "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/supervisor.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/system_manifest.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/core/message_policy.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/core/result.h" @@ -275,9 +276,11 @@ if(PUPPETMASTER_ENABLE_JSON_CONFIG) add_library(puppet_master_json_config_adapter configuration/json_launcher.cpp configuration/json_loader.cpp + configuration/supervisor.cpp configuration/system_manifest.cpp "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/json_launcher.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/json_loader.h" + "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/supervisor.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/configuration/system_manifest.h" ) diff --git a/src/configuration/application.cpp b/src/configuration/application.cpp index b3b0781..b2e1a29 100644 --- a/src/configuration/application.cpp +++ b/src/configuration/application.cpp @@ -52,6 +52,15 @@ void HandleStopSignal(int) g_signal_received.store(true); } +void ResetStopSignals() noexcept +{ + std::signal(SIGINT, SIG_DFL); + std::signal(SIGTERM, SIG_DFL); +#if defined(SIGBREAK) + std::signal(SIGBREAK, SIG_DFL); +#endif +} + } // namespace ValidationReport ValidateProject(const ProjectConfig& project, const ComponentFactoryRegistry* factories) @@ -392,8 +401,7 @@ struct Application::Impl { } watcher_stop.store(true); signal_watcher.join(); - std::signal(SIGINT, SIG_DFL); - std::signal(SIGTERM, SIG_DFL); + ResetStopSignals(); g_signal_owner.store(nullptr); } }; @@ -568,11 +576,16 @@ core::Status Application::InstallSignalHandlers() } g_signal_received.store(false); impl_->watcher_stop.store(false); - if (std::signal(SIGINT, HandleStopSignal) == SIG_ERR || std::signal(SIGTERM, HandleStopSignal) == SIG_ERR) { - std::signal(SIGINT, SIG_DFL); - std::signal(SIGTERM, SIG_DFL); + bool installed = std::signal(SIGINT, HandleStopSignal) != SIG_ERR && + std::signal(SIGTERM, HandleStopSignal) != SIG_ERR; +#if defined(SIGBREAK) + // Ctrl+Break, which puppet_master_launch sends to stop a node on Windows. + installed = installed && std::signal(SIGBREAK, HandleStopSignal) != SIG_ERR; +#endif + if (!installed) { + ResetStopSignals(); g_signal_owner.store(nullptr); - return core::Status::Internal("installing SIGINT/SIGTERM handlers failed"); + return core::Status::Internal("installing stop signal handlers failed"); } // A handler may only set a lock-free flag; this thread turns it into a // RequestStop() within one polling interval. diff --git a/src/configuration/supervisor.cpp b/src/configuration/supervisor.cpp new file mode 100644 index 0000000..b6d86cc --- /dev/null +++ b/src/configuration/supervisor.cpp @@ -0,0 +1,614 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef NOMINMAX +#define NOMINMAX +#endif +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#else +#include +#include +#include +#include +#include +#include +#include + +extern char** environ; +#endif + +namespace puppet_master::configuration { + +std::string ToString(const ProcessExit& exit) +{ + return (exit.signaled ? "signal " : "exit code ") + std::to_string(exit.code); +} + +const char* ToString(SupervisorEvent::Kind kind) noexcept +{ + switch (kind) { + case SupervisorEvent::Kind::kStarted: + return "started"; + case SupervisorEvent::Kind::kStartFailed: + return "start-failed"; + case SupervisorEvent::Kind::kExited: + return "exited"; + case SupervisorEvent::Kind::kRestarting: + return "restarting"; + case SupervisorEvent::Kind::kGaveUp: + return "gave-up"; + case SupervisorEvent::Kind::kStopping: + return "stopping"; + case SupervisorEvent::Kind::kKilled: + return "killed"; + case SupervisorEvent::Kind::kStopped: + return "stopped"; + } + return "unknown"; +} + +namespace { + +std::unique_ptr AsChild(ChildProcess* child) +{ + return std::unique_ptr(child); +} + +#if !defined(_WIN32) + +class PosixChild final : public ChildProcess { +public: + explicit PosixChild(pid_t pid) : pid_(pid) {} + + ~PosixChild() override + { + // Never leave a zombie or an orphan behind. + if (!exit_) { + Kill(); + int status = 0; + while (::waitpid(pid_, &status, 0) < 0 && errno == EINTR) { + } + } + } + + std::int64_t id() const noexcept override { return pid_; } + + std::optional Poll() override + { + if (exit_) { + return exit_; + } + int status = 0; + pid_t result = 0; + do { + result = ::waitpid(pid_, &status, WNOHANG); + } while (result < 0 && errno == EINTR); + if (result == pid_) { + ProcessExit exit; + if (WIFSIGNALED(status)) { + exit.signaled = true; + exit.code = WTERMSIG(status); + } else { + exit.code = WEXITSTATUS(status); + } + exit_ = exit; + } else if (result < 0) { + // Reaped by someone else; the exit status is lost. + exit_ = ProcessExit {-1, false}; + } + return exit_; + } + + void RequestStop() override { Signal(SIGTERM); } + void Kill() override { Signal(SIGKILL); } + +private: + // The child leads its own process group; signalling the group reaches + // what it started too. + void Signal(int signal_number) + { + if (exit_) { + return; + } + if (::kill(-pid_, signal_number) != 0) { + ::kill(pid_, signal_number); + } + } + + pid_t pid_; + std::optional exit_; +}; + +class PosixLauncher final : public ProcessLauncher { +public: + core::Result> Start( + const std::vector& command, const std::string& log_path) override + { + if (command.empty()) { + return core::Result>(core::Status::InvalidArgument("empty command")); + } + std::vector argv; + argv.reserve(command.size() + 1); + for (const auto& word : command) { + argv.push_back(const_cast(word.c_str())); + } + argv.push_back(nullptr); + + posix_spawn_file_actions_t actions; + posix_spawnattr_t attributes; + posix_spawn_file_actions_init(&actions); + posix_spawnattr_init(&attributes); + + int error = 0; + if (!log_path.empty()) { + error = posix_spawn_file_actions_addopen( + &actions, STDOUT_FILENO, log_path.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0644); + if (error == 0) { + error = posix_spawn_file_actions_adddup2(&actions, STDOUT_FILENO, STDERR_FILENO); + } + } + // Our own stop handlers must not leak into the child as blocked or + // ignored signals. + sigset_t defaults; + sigemptyset(&defaults); + sigaddset(&defaults, SIGINT); + sigaddset(&defaults, SIGTERM); + sigaddset(&defaults, SIGPIPE); + sigset_t mask; + sigemptyset(&mask); + if (error == 0) { + error = posix_spawnattr_setflags( + &attributes, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK); + } + if (error == 0) { + error = posix_spawnattr_setpgroup(&attributes, 0); + } + if (error == 0) { + error = posix_spawnattr_setsigdefault(&attributes, &defaults); + } + if (error == 0) { + error = posix_spawnattr_setsigmask(&attributes, &mask); + } + pid_t pid = 0; + if (error == 0) { + error = ::posix_spawnp(&pid, argv[0], &actions, &attributes, argv.data(), environ); + } + posix_spawnattr_destroy(&attributes); + posix_spawn_file_actions_destroy(&actions); + + if (error != 0) { + return core::Result>(core::Status::Unavailable( + "starting " + command.front() + ": " + std::generic_category().message(error))); + } + return AsChild(new PosixChild(pid)); + } +}; + +std::unique_ptr MakePlatformLauncher() +{ + return std::make_unique(); +} + +#else + +// Quotes one argument the way the C runtime's command-line parser splits +// it back: backslashes are literal unless they precede a quote. +void AppendQuoted(std::string& line, const std::string& word) +{ + if (!word.empty() && word.find_first_of(" \t\n\v\"") == std::string::npos) { + line += word; + return; + } + line += '"'; + std::size_t backslashes = 0; + for (const char c : word) { + if (c == '\\') { + ++backslashes; + continue; + } + if (c == '"') { + line.append(backslashes * 2 + 1, '\\'); + } else { + line.append(backslashes, '\\'); + } + backslashes = 0; + line += c; + } + line.append(backslashes * 2, '\\'); + line += '"'; +} + +std::string LastError(const std::string& what) +{ + return what + ": " + std::system_category().message(static_cast(::GetLastError())); +} + +class WindowsChild final : public ChildProcess { +public: + WindowsChild(HANDLE process, DWORD id) : process_(process), id_(id) {} + + ~WindowsChild() override + { + if (!exit_) { + Kill(); + ::WaitForSingleObject(process_, INFINITE); + } + ::CloseHandle(process_); + } + + std::int64_t id() const noexcept override { return id_; } + + std::optional Poll() override + { + if (exit_) { + return exit_; + } + if (::WaitForSingleObject(process_, 0) != WAIT_OBJECT_0) { + return std::nullopt; + } + DWORD code = 0; + ::GetExitCodeProcess(process_, &code); + exit_ = ProcessExit {static_cast(code), false}; + return exit_; + } + + // The child leads a process group of its own, so the break reaches only + // it (and what it started on the same console). + void RequestStop() override + { + if (!exit_) { + ::GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, id_); + } + } + + void Kill() override + { + if (!exit_) { + ::TerminateProcess(process_, 1); + } + } + +private: + HANDLE process_; + DWORD id_; + std::optional exit_; +}; + +class WindowsLauncher final : public ProcessLauncher { +public: + core::Result> Start( + const std::vector& command, const std::string& log_path) override + { + if (command.empty()) { + return core::Result>(core::Status::InvalidArgument("empty command")); + } + std::string line; + for (const auto& word : command) { + if (!line.empty()) { + line += ' '; + } + AppendQuoted(line, word); + } + + STARTUPINFOA startup {}; + startup.cb = sizeof(startup); + HANDLE log = INVALID_HANDLE_VALUE; + if (!log_path.empty()) { + SECURITY_ATTRIBUTES inherit {}; + inherit.nLength = sizeof(inherit); + inherit.bInheritHandle = TRUE; + log = ::CreateFileA(log_path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, &inherit, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (log == INVALID_HANDLE_VALUE) { + return core::Result>( + core::Status::Unavailable(LastError("opening " + log_path))); + } + startup.dwFlags = STARTF_USESTDHANDLES; + startup.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); + startup.hStdOutput = log; + startup.hStdError = log; + } + + PROCESS_INFORMATION info {}; + // A null application name makes CreateProcess search PATH for the + // first word, adding .exe. + const BOOL created = ::CreateProcessA(nullptr, line.data(), nullptr, nullptr, TRUE, + CREATE_NEW_PROCESS_GROUP, nullptr, nullptr, &startup, &info); + const std::string error = created ? std::string() : LastError("starting " + command.front()); + if (log != INVALID_HANDLE_VALUE) { + ::CloseHandle(log); + } + if (!created) { + return core::Result>(core::Status::Unavailable(error)); + } + ::CloseHandle(info.hThread); + return AsChild(new WindowsChild(info.hProcess, info.dwProcessId)); + } +}; + +std::unique_ptr MakePlatformLauncher() +{ + return std::make_unique(); +} + +#endif + +using Clock = std::chrono::steady_clock; +using Kind = SupervisorEvent::Kind; + +std::string Milliseconds(std::chrono::milliseconds value) +{ + return std::to_string(value.count()) + " ms"; +} + +} // namespace + +std::unique_ptr MakeSystemProcessLauncher() +{ + return MakePlatformLauncher(); +} + +struct Supervisor::Impl { + struct Node { + enum class Phase : std::uint8_t { kPending, kRunning, kBackoff, kDone }; + + const NodeManifest* manifest {nullptr}; + Phase phase {Phase::kPending}; + std::unique_ptr child; + Clock::time_point started_at {}; + Clock::time_point restart_at {}; + std::chrono::milliseconds delay {0}; // before the next restart + std::uint32_t restarts {0}; // since the last stable run + bool failed {false}; // the final exit was a failure + }; + + SystemManifest manifest; + SupervisorOptions options; + std::vector nodes; + + std::mutex mutex; + std::condition_variable wake; + bool stop_requested {false}; + bool ran {false}; + + // Set once the system has to stop for a reason other than a request. + std::optional ending; + + Impl(SystemManifest system, SupervisorOptions supervisor_options) + : manifest(std::move(system)), options(std::move(supervisor_options)) + { + if (!options.launcher) { + options.launcher = MakeSystemProcessLauncher(); + } + nodes.resize(manifest.nodes.size()); + for (std::size_t index = 0; index < nodes.size(); ++index) { + nodes[index].manifest = &manifest.nodes[index]; + nodes[index].delay = manifest.nodes[index].restart_delay; + } + } + + void Emit(Kind kind, const Node& node, std::string detail) + { + if (options.on_event) { + options.on_event(SupervisorEvent {kind, node.manifest->name, std::move(detail)}); + } + } + + bool StopRequested() + { + std::lock_guard lock(mutex); + return stop_requested; + } + + // Sleeps until `deadline` or a stop request. + void SleepUntil(Clock::time_point deadline) + { + std::unique_lock lock(mutex); + wake.wait_until(lock, deadline, [this] { return stop_requested; }); + } + + std::string LogPath(const Node& node) const + { + if (options.log_directory.empty()) { + return {}; + } + return (std::filesystem::path(options.log_directory) / (node.manifest->name + ".log")).string(); + } + + void Start(Node& node, Clock::time_point now) + { + auto child = options.launcher->Start(manifest.CommandFor(*node.manifest), LogPath(node)); + if (!child.ok()) { + Emit(Kind::kStartFailed, node, child.status().message()); + Ended(node, false, now, now); + return; + } + node.child = std::move(child).value(); + node.phase = Node::Phase::kRunning; + node.started_at = now; + Emit(Kind::kStarted, node, "pid " + std::to_string(node.child->id())); + } + + // Applies the restart policy to a node whose process ended (or did not + // start) after running since `started_at`. + void Ended(Node& node, bool success, Clock::time_point started_at, Clock::time_point now) + { + const NodeManifest& spec = *node.manifest; + node.child.reset(); + if (now - started_at >= options.stable_run) { + node.restarts = 0; + node.delay = spec.restart_delay; + } + + const bool wanted = spec.restart == NodeManifest::Restart::kAlways || + (spec.restart == NodeManifest::Restart::kOnFailure && !success); + const bool allowed = spec.max_restarts == 0 || node.restarts < spec.max_restarts; + if (wanted && allowed) { + ++node.restarts; + node.phase = Node::Phase::kBackoff; + node.restart_at = now + node.delay; + std::string detail = "in " + Milliseconds(node.delay) + ", restart " + std::to_string(node.restarts); + if (spec.max_restarts != 0) { + detail += " of " + std::to_string(spec.max_restarts); + } + Emit(Kind::kRestarting, node, std::move(detail)); + const auto cap = std::max(options.max_restart_delay, spec.restart_delay); + node.delay = std::min(node.delay * 2, cap); + return; + } + + node.phase = Node::Phase::kDone; + node.failed = !success; + if (wanted) { + Emit(Kind::kGaveUp, node, "after " + std::to_string(node.restarts) + " restarts"); + } + if (spec.required && !ending) { + ending = SupervisorResult { + "required node " + spec.name + (success ? " ended" : " failed"), success ? 0 : 1}; + } + } + + // One round of supervision over the nodes started so far. + void Supervise() + { + for (auto& node : nodes) { + const auto now = Clock::now(); + if (node.phase == Node::Phase::kRunning) { + const auto exit = node.child->Poll(); + if (exit) { + Emit(Kind::kExited, node, ToString(*exit)); + Ended(node, exit->success(), node.started_at, now); + } + } else if (node.phase == Node::Phase::kBackoff && now >= node.restart_at) { + Start(node, now); + } + } + if (ending) { + return; + } + const bool all_done = std::all_of( + nodes.begin(), nodes.end(), [](const Node& node) { return node.phase == Node::Phase::kDone; }); + if (all_done) { + const bool any_failed = + std::any_of(nodes.begin(), nodes.end(), [](const Node& node) { return node.failed; }); + ending = SupervisorResult {"every node ended", any_failed ? 1 : 0}; + } + } + + // Supervises until `deadline`, a stop request, or a reason to end. + void SuperviseUntil(Clock::time_point deadline) + { + while (!ending && !StopRequested()) { + Supervise(); + const auto now = Clock::now(); + if (ending || now >= deadline) { + return; + } + SleepUntil(std::min(deadline, now + options.poll_interval)); + } + } + + // Stops the running nodes, last started first. + void StopAll() + { + for (auto it = nodes.rbegin(); it != nodes.rend(); ++it) { + Node& node = *it; + if (node.phase != Node::Phase::kRunning) { + node.phase = Node::Phase::kDone; + continue; + } + Emit(Kind::kStopping, node, "pid " + std::to_string(node.child->id())); + node.child->RequestStop(); + auto exit = WaitForExit(node, node.manifest->stop_timeout); + if (!exit) { + node.child->Kill(); + Emit(Kind::kKilled, node, "still running after " + Milliseconds(node.manifest->stop_timeout)); + exit = WaitForExit(node, std::chrono::milliseconds(5000)); + } + Emit(Kind::kStopped, node, exit ? ToString(*exit) : "did not end after a kill"); + node.child.reset(); // reaps it, waiting if it has to + node.phase = Node::Phase::kDone; + } + } + + std::optional WaitForExit(Node& node, std::chrono::milliseconds timeout) + { + const auto deadline = Clock::now() + timeout; + while (true) { + auto exit = node.child->Poll(); + const auto now = Clock::now(); + if (exit || now >= deadline) { + return exit; + } + // Stop requests are already being served; sleep without them. + std::this_thread::sleep_for(std::min(deadline - now, options.poll_interval)); + } + } + + SupervisorResult Run() + { + if (!options.log_directory.empty()) { + std::error_code error; + std::filesystem::create_directories(options.log_directory, error); + if (error) { + return SupervisorResult {"creating " + options.log_directory + ": " + error.message(), 1}; + } + } + + for (auto& node : nodes) { + if (ending || StopRequested()) { + break; + } + const auto now = Clock::now(); + Start(node, now); + SuperviseUntil(now + node.manifest->start_delay); + } + SuperviseUntil(Clock::time_point::max()); + + SupervisorResult result = ending ? *ending : SupervisorResult {"stop requested", 0}; + StopAll(); + return result; + } +}; + +Supervisor::Supervisor(SystemManifest manifest, SupervisorOptions options) + : impl_(std::make_unique(std::move(manifest), std::move(options))) +{ +} + +Supervisor::~Supervisor() = default; + +SupervisorResult Supervisor::Run() +{ + { + std::lock_guard lock(impl_->mutex); + if (impl_->ran) { + return SupervisorResult {"Run() was already called", 1}; + } + impl_->ran = true; + } + return impl_->Run(); +} + +void Supervisor::RequestStop() noexcept +{ + { + std::lock_guard lock(impl_->mutex); + impl_->stop_requested = true; + } + impl_->wake.notify_all(); +} + +} // namespace puppet_master::configuration diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 6de37a8..71e94de 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -273,6 +273,19 @@ if(PUPPETMASTER_ENABLE_JSON_CONFIG) NAME puppet_master.system_manifest COMMAND puppet_master_system_manifest_test ) + + add_executable(puppet_master_supervisor_test + supervisor_test.cpp + ) + + target_link_libraries(puppet_master_supervisor_test + PRIVATE PuppetMaster::JsonConfigAdapter + ) + + add_test( + NAME puppet_master.supervisor + COMMAND puppet_master_supervisor_test + ) endif() if(PUPPETMASTER_ENABLE_JSON_CONFIG AND TARGET PuppetMaster::ShmAdapter) diff --git a/test/supervisor_test.cpp b/test/supervisor_test.cpp new file mode 100644 index 0000000..766032d --- /dev/null +++ b/test/supervisor_test.cpp @@ -0,0 +1,651 @@ +// Supervisor: start order, restart policy, and stopping, first with scripted +// fake processes, then with real ones (this binary started in child modes). + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace config = puppet_master::configuration; +namespace core = puppet_master::core; +namespace fs = std::filesystem; + +using Kind = config::SupervisorEvent::Kind; +using Restart = config::NodeManifest::Restart; +using namespace std::chrono_literals; + +namespace { + +// One scripted run of a fake process. +struct Run { + int exit_after_polls {-1}; // -1: runs until stopped + config::ProcessExit exit {}; + bool ignores_stop {false}; +}; + +// What the fake processes did, in order: "start a", "stop a", "kill a". +struct World { + std::map> scripts; // by executable + std::set fail_start; + std::vector log; + std::int64_t next_id {100}; + + std::size_t Count(const std::string& entry) const + { + std::size_t count = 0; + for (const auto& line : log) { + count += line == entry ? 1 : 0; + } + return count; + } +}; + +class FakeChild final : public config::ChildProcess { +public: + FakeChild(World& world, std::string name, Run run, std::int64_t id) + : world_(world), name_(std::move(name)), run_(run), id_(id) + { + } + + std::int64_t id() const noexcept override { return id_; } + + std::optional Poll() override + { + if (!exit_ && run_.exit_after_polls >= 0 && polls_++ >= run_.exit_after_polls) { + exit_ = run_.exit; + } + return exit_; + } + + void RequestStop() override + { + world_.log.push_back("stop " + name_); + if (!exit_ && !run_.ignores_stop) { + exit_ = config::ProcessExit {0, false}; + } + } + + void Kill() override + { + world_.log.push_back("kill " + name_); + if (!exit_) { + exit_ = config::ProcessExit {9, true}; + } + } + +private: + World& world_; + std::string name_; + Run run_; + std::int64_t id_; + int polls_ {0}; + std::optional exit_; +}; + +class FakeLauncher final : public config::ProcessLauncher { +public: + explicit FakeLauncher(World& world) : world_(world) {} + + core::Result> Start( + const std::vector& command, const std::string&) override + { + const std::string& name = command.front(); + if (world_.fail_start.count(name) != 0) { + return core::Result>(core::Status::Unavailable("no " + name)); + } + world_.log.push_back("start " + name); + Run run; + auto& script = world_.scripts[name]; + if (!script.empty()) { + run = script.front(); + script.pop_front(); + } + return std::unique_ptr(new FakeChild(world_, name, run, world_.next_id++)); + } + +private: + World& world_; +}; + +config::NodeManifest Node(const std::string& name) +{ + config::NodeManifest node; + node.name = name; + node.executable = name; + node.config = name + ".json"; + node.restart_delay = 1ms; + node.stop_timeout = 50ms; + return node; +} + +config::SystemManifest System(std::vector nodes) +{ + config::SystemManifest system; + system.name = "test"; + system.nodes = std::move(nodes); + return system; +} + +Run ExitsWith(int code, int after_polls = 0) +{ + Run run; + run.exit_after_polls = after_polls; + run.exit = config::ProcessExit {code, false}; + return run; +} + +// A supervisor over fake processes that records its events and can stop +// itself from them: `stop_on(event)` returns true to request a stop. +struct Harness { + World world; + std::vector events; + std::function stop_on; + + config::SupervisorResult Run(config::SystemManifest system, std::chrono::milliseconds stable_run = 10s, + std::chrono::milliseconds max_restart_delay = 30s) + { + config::Supervisor* self = nullptr; + config::SupervisorOptions options; + options.launcher = std::make_unique(world); + options.poll_interval = 1ms; + options.stable_run = stable_run; + options.max_restart_delay = max_restart_delay; + options.on_event = [this, &self](const config::SupervisorEvent& event) { + events.push_back(event); + if (stop_on && stop_on(event)) { + self->RequestStop(); + } + }; + config::Supervisor supervisor(std::move(system), std::move(options)); + self = &supervisor; + return supervisor.Run(); + } + + std::vector Details(Kind kind, const std::string& node) const + { + std::vector details; + for (const auto& event : events) { + if (event.kind == kind && event.node == node) { + details.push_back(event.detail); + } + } + return details; + } +}; + +bool Contains(const std::string& text, const std::string& part) +{ + return text.find(part) != std::string::npos; +} + +// --- fake processes --------------------------------------------------------- + +void TestStartsInOrderAndStopsInReverse() +{ + Harness harness; + harness.stop_on = [](const config::SupervisorEvent& event) { + return event.kind == Kind::kStarted && event.node == "c"; + }; + const auto result = harness.Run(System({Node("a"), Node("b"), Node("c")})); + assert(result.exit_code == 0); + assert(result.reason == "stop requested"); + const std::vector expected { + "start a", "start b", "start c", "stop c", "stop b", "stop a"}; + assert(harness.world.log == expected); + assert(harness.Details(Kind::kStopped, "a") == std::vector {"exit code 0"}); +} + +void TestRestartsOnFailureWithGrowingDelay() +{ + Harness harness; + harness.world.scripts["a"] = {ExitsWith(1), ExitsWith(1, 2)}; + auto a = Node("a"); + a.restart = Restart::kOnFailure; + int starts = 0; + harness.stop_on = [&starts](const config::SupervisorEvent& event) { + return event.kind == Kind::kStarted && ++starts == 3; + }; + const auto result = harness.Run(System({a})); + assert(result.exit_code == 0); + assert(harness.world.Count("start a") == 3); + const std::vector expected {"in 1 ms, restart 1 of 5", "in 2 ms, restart 2 of 5"}; + assert(harness.Details(Kind::kRestarting, "a") == expected); + assert(harness.Details(Kind::kExited, "a") == std::vector(2, "exit code 1")); +} + +void TestOnFailureDoesNotRestartASuccess() +{ + Harness harness; + harness.world.scripts["a"] = {ExitsWith(0)}; + auto a = Node("a"); + a.restart = Restart::kOnFailure; + a.required = false; + const auto result = harness.Run(System({a})); + assert(result.reason == "every node ended"); + assert(result.exit_code == 0); + assert(harness.world.Count("start a") == 1); + assert(harness.Details(Kind::kGaveUp, "a").empty()); +} + +void TestRequiredNodeThatGivesUpStopsTheSystem() +{ + Harness harness; + harness.world.scripts["a"] = {ExitsWith(1, 3), ExitsWith(1, 3), ExitsWith(1, 3)}; + auto a = Node("a"); + a.restart = Restart::kAlways; + a.max_restarts = 2; + const auto result = harness.Run(System({Node("b"), a})); + assert(result.exit_code == 1); + assert(result.reason == "required node a failed"); + assert(harness.world.Count("start a") == 3); + assert(harness.Details(Kind::kGaveUp, "a") == std::vector {"after 2 restarts"}); + // b keeps running until the system stops it. + assert(harness.world.log.back() == "stop b"); +} + +void TestRequiredNodeThatEndsWellStopsTheSystemCleanly() +{ + Harness harness; + harness.world.scripts["batch"] = {ExitsWith(0, 2)}; + const auto result = harness.Run(System({Node("server"), Node("batch")})); + assert(result.exit_code == 0); + assert(result.reason == "required node batch ended"); + assert(harness.world.log.back() == "stop server"); +} + +void TestOptionalNodeIsLeftStopped() +{ + Harness harness; + harness.world.scripts["tool"] = {ExitsWith(4)}; + auto tool = Node("tool"); + tool.required = false; + // Stop from another thread once the optional node has ended. + config::SupervisorOptions options; + options.launcher = std::make_unique(harness.world); + options.poll_interval = 1ms; + std::atomic tool_ended {false}; + options.on_event = [&](const config::SupervisorEvent& event) { + harness.events.push_back(event); + if (event.node == "tool" && event.kind == Kind::kExited) { + tool_ended.store(true); + } + }; + config::Supervisor supervisor(System({tool, Node("server")}), std::move(options)); + std::thread stopper([&] { + while (!tool_ended.load()) { + std::this_thread::sleep_for(1ms); + } + std::this_thread::sleep_for(20ms); // the system keeps running + supervisor.RequestStop(); + }); + const auto result = supervisor.Run(); + stopper.join(); + assert(result.reason == "stop requested"); + assert(result.exit_code == 0); + assert(harness.world.Count("start tool") == 1); + assert(harness.world.Count("stop tool") == 0); + assert(harness.world.log.back() == "stop server"); +} + +void TestEveryNodeEnded() +{ + Harness harness; + harness.world.scripts["a"] = {ExitsWith(0)}; + harness.world.scripts["b"] = {ExitsWith(2, 1)}; + auto a = Node("a"); + auto b = Node("b"); + a.required = false; + b.required = false; + const auto result = harness.Run(System({a, b})); + assert(result.reason == "every node ended"); + assert(result.exit_code == 1); // b failed +} + +void TestDelayIsCappedAndResetByAStableRun() +{ + { + Harness harness; + harness.world.scripts["a"] = {ExitsWith(1), ExitsWith(1), ExitsWith(1), ExitsWith(1), ExitsWith(1)}; + auto a = Node("a"); + a.restart = Restart::kAlways; + a.max_restarts = 4; + harness.Run(System({a}), 10s, 3ms); + const std::vector expected { + "in 1 ms, restart 1 of 4", "in 2 ms, restart 2 of 4", "in 3 ms, restart 3 of 4", "in 3 ms, restart 4 of 4"}; + assert(harness.Details(Kind::kRestarting, "a") == expected); + } + { + // Every run counts as stable: the delay and the count start over. + Harness harness; + harness.world.scripts["a"] = {ExitsWith(1), ExitsWith(1), ExitsWith(1)}; + auto a = Node("a"); + a.restart = Restart::kOnFailure; + a.max_restarts = 1; + int starts = 0; + harness.stop_on = [&starts](const config::SupervisorEvent& event) { + return event.kind == Kind::kStarted && ++starts == 4; + }; + harness.Run(System({a}), 0ms); + assert(harness.Details(Kind::kRestarting, "a") == std::vector(3, "in 1 ms, restart 1 of 1")); + assert(harness.Details(Kind::kGaveUp, "a").empty()); + } +} + +void TestFailedStart() +{ + { + Harness harness; + harness.world.fail_start = {"b"}; + const auto result = harness.Run(System({Node("a"), Node("b"), Node("c")})); + assert(result.exit_code == 1); + assert(result.reason == "required node b failed"); + assert(harness.Details(Kind::kStartFailed, "b") == std::vector {"no b"}); + // c is never started; a is stopped. + const std::vector expected {"start a", "stop a"}; + assert(harness.world.log == expected); + } + { + // A restart policy covers failed starts too. + Harness harness; + harness.world.fail_start = {"b"}; + auto b = Node("b"); + b.restart = Restart::kOnFailure; + b.max_restarts = 2; + b.required = false; + int failures = 0; + harness.stop_on = [&failures](const config::SupervisorEvent& event) { + failures += event.kind == Kind::kStartFailed ? 1 : 0; + return false; + }; + harness.world.scripts["a"] = {ExitsWith(0, 50)}; + auto a = Node("a"); + a.required = false; + harness.Run(System({b, a})); + assert(failures == 3); + assert(harness.Details(Kind::kGaveUp, "b") == std::vector {"after 2 restarts"}); + } +} + +void TestKillsANodeThatDoesNotStop() +{ + Harness harness; + Run stubborn; + stubborn.ignores_stop = true; + harness.world.scripts["a"] = {stubborn}; + harness.stop_on = [](const config::SupervisorEvent& event) { return event.kind == Kind::kStarted; }; + const auto started = std::chrono::steady_clock::now(); + const auto result = harness.Run(System({Node("a")})); + const auto elapsed = std::chrono::steady_clock::now() - started; + assert(result.exit_code == 0); + const std::vector expected {"start a", "stop a", "kill a"}; + assert(harness.world.log == expected); + assert(harness.Details(Kind::kKilled, "a") == std::vector {"still running after 50 ms"}); + assert(harness.Details(Kind::kStopped, "a") == std::vector {"signal 9"}); + assert(elapsed >= 50ms); +} + +void TestStopDuringStartDelay() +{ + Harness harness; + auto a = Node("a"); + a.start_delay = 10s; + harness.stop_on = [](const config::SupervisorEvent& event) { return event.kind == Kind::kStarted; }; + const auto started = std::chrono::steady_clock::now(); + harness.Run(System({a, Node("b")})); + assert(std::chrono::steady_clock::now() - started < 5s); + assert(harness.world.Count("start b") == 0); +} + +void TestRunOnce() +{ + World world; + config::SupervisorOptions options; + options.launcher = std::make_unique(world); + world.scripts["a"] = {ExitsWith(0)}; + config::Supervisor supervisor(System({Node("a")}), std::move(options)); + assert(supervisor.Run().exit_code == 0); + const auto again = supervisor.Run(); + assert(again.exit_code == 1); + assert(Contains(again.reason, "already")); +} + +// --- real processes --------------------------------------------------------- + +std::atomic g_child_stop {false}; + +void HandleChildStop(int) +{ + g_child_stop.store(true); +} + +// This binary as a node: `--child exit N`, `--child serve`, `--child stubborn`, +// followed by the config argument the supervisor adds. +int RunChild(const std::string& mode, const std::string& argument) +{ + if (mode == "exit") { + std::cout << "child " << mode << " started" << std::endl; + return std::stoi(argument); + } + // Handlers first: "started" tells the test a stop request is handled. + if (mode == "serve") { + std::signal(SIGINT, HandleChildStop); + std::signal(SIGTERM, HandleChildStop); +#if defined(SIGBREAK) + std::signal(SIGBREAK, HandleChildStop); +#endif + } else { + std::signal(SIGTERM, SIG_IGN); +#if defined(SIGBREAK) + std::signal(SIGBREAK, SIG_IGN); +#endif + } + std::cout << "child " << mode << " started" << std::endl; + // Bounded, so a broken test never leaves a process behind for long. + const auto deadline = std::chrono::steady_clock::now() + 30s; + while (!g_child_stop.load() && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(5ms); + } + std::cout << "child " << mode << " stopping" << std::endl; + return 0; +} + +config::NodeManifest ChildNode(const std::string& self, const std::string& name, std::vector arguments) +{ + config::NodeManifest node; + node.name = name; + node.executable = self; + node.arguments = {"--child"}; + node.arguments.insert(node.arguments.end(), arguments.begin(), arguments.end()); + node.config = "unused.json"; + node.restart_delay = 10ms; + node.stop_timeout = 3s; + return node; +} + +std::string ReadFile(const fs::path& path) +{ + std::ifstream in(path, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); +} + +std::size_t Occurrences(const std::string& text, const std::string& part) +{ + std::size_t count = 0; + for (auto at = text.find(part); at != std::string::npos; at = text.find(part, at + 1)) { + ++count; + } + return count; +} + +// Waits until a node's log has `text`; used before stopping a node, so the +// stop finds its signal handlers installed. +void WaitForLog(const fs::path& path, const std::string& text) +{ + const auto deadline = std::chrono::steady_clock::now() + 20s; + while (!Contains(ReadFile(path), text)) { + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(5ms); + } +} + +struct RealRun { + config::SupervisorResult result; + std::vector events; + + std::vector Details(Kind kind, const std::string& node) const + { + std::vector details; + for (const auto& event : events) { + if (event.kind == kind && event.node == node) { + details.push_back(event.detail); + } + } + return details; + } +}; + +// Runs real processes; `stop_on` is checked for every event. +RealRun RunReal(config::SystemManifest system, const std::string& log_directory, + std::function stop_on) +{ + RealRun run; + config::Supervisor* self = nullptr; + config::SupervisorOptions options; + options.log_directory = log_directory; + options.poll_interval = 5ms; + options.on_event = [&](const config::SupervisorEvent& event) { + std::cout << " " << event.node << ": " << config::ToString(event.kind) << " (" << event.detail << ")\n"; + run.events.push_back(event); + if (stop_on && stop_on(event)) { + self->RequestStop(); + } + }; + config::Supervisor supervisor(std::move(system), std::move(options)); + self = &supervisor; + run.result = supervisor.Run(); + return run; +} + +fs::path TempDirectory(const std::string& name) +{ + const auto path = fs::temp_directory_path() / + (name + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())); + fs::remove_all(path); + return path; +} + +void TestRealProcessesRestartLogAndStop(const std::string& self) +{ + const auto logs = TempDirectory("pm_supervisor_logs_"); + auto worker = ChildNode(self, "worker", {"exit", "3"}); + worker.restart = Restart::kOnFailure; + worker.max_restarts = 2; + worker.required = false; + auto server = ChildNode(self, "server", {"serve"}); + + const auto run = RunReal(System({server, worker}), logs.string(), [&](const config::SupervisorEvent& event) { + if (event.kind != Kind::kGaveUp || event.node != "worker") { + return false; + } + WaitForLog(logs / "server.log", "child serve started"); + return true; + }); + assert(run.result.reason == "stop requested"); + assert(run.result.exit_code == 0); + assert(run.Details(Kind::kExited, "worker") == std::vector(3, "exit code 3")); + assert(run.Details(Kind::kStopped, "server").size() == 1); + assert(run.Details(Kind::kStopped, "worker").empty()); + + // Output is appended across restarts, one file per node. + const auto worker_log = ReadFile(logs / "worker.log"); + assert(Occurrences(worker_log, "child exit started") == 3); + const auto server_log = ReadFile(logs / "server.log"); + assert(Contains(server_log, "child serve started")); +#if !defined(_WIN32) + // The stop request reached the node's handler, which ended it cleanly. + // (Windows CI runners may have no console to deliver Ctrl+Break.) + assert(run.Details(Kind::kStopped, "server") == std::vector {"exit code 0"}); + assert(Contains(server_log, "child serve stopping")); +#endif + fs::remove_all(logs); +} + +void TestRealProcessThatIgnoresStopIsKilled(const std::string& self) +{ + auto stubborn = ChildNode(self, "stubborn", {"stubborn"}); + stubborn.stop_timeout = 200ms; + const auto logs = TempDirectory("pm_supervisor_kill_"); + // Stop once it ignores the stop request. + const auto run = RunReal(System({stubborn}), logs.string(), [&](const config::SupervisorEvent& event) { + if (event.kind != Kind::kStarted) { + return false; + } + WaitForLog(logs / "stubborn.log", "child stubborn started"); + return true; + }); + assert(run.result.exit_code == 0); + assert(run.Details(Kind::kKilled, "stubborn") == std::vector {"still running after 200 ms"}); +#if !defined(_WIN32) + assert(run.Details(Kind::kStopped, "stubborn") == std::vector {"signal 9"}); +#endif + fs::remove_all(logs); +} + +void TestRealStartFailure() +{ + config::NodeManifest missing; + missing.name = "missing"; + missing.executable = "puppet_master_no_such_program_for_supervisor_test"; + missing.config = "unused.json"; + const auto run = RunReal(System({missing}), "", nullptr); + assert(run.result.exit_code == 1); + assert(run.result.reason == "required node missing failed"); + const auto failures = run.Details(Kind::kStartFailed, "missing"); + assert(failures.size() == 1); + assert(Contains(failures.front(), "starting puppet_master_no_such_program_for_supervisor_test")); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc >= 3 && std::string(argv[1]) == "--child") { + return RunChild(argv[2], argc >= 4 ? argv[3] : ""); + } + + TestStartsInOrderAndStopsInReverse(); + TestRestartsOnFailureWithGrowingDelay(); + TestOnFailureDoesNotRestartASuccess(); + TestRequiredNodeThatGivesUpStopsTheSystem(); + TestRequiredNodeThatEndsWellStopsTheSystemCleanly(); + TestOptionalNodeIsLeftStopped(); + TestEveryNodeEnded(); + TestDelayIsCappedAndResetByAStableRun(); + TestFailedStart(); + TestKillsANodeThatDoesNotStop(); + TestStopDuringStartDelay(); + TestRunOnce(); + + const std::string self = fs::absolute(argv[0]).string(); + TestRealProcessesRestartLogAndStop(self); + TestRealProcessThatIgnoresStopIsKilled(self); + TestRealStartFailure(); + + std::cout << "supervisor tests passed\n"; + return 0; +} diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index d088024..71eda8b 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -21,7 +21,22 @@ else() target_compile_options(puppet_master_config PRIVATE -Wall -Wextra -Wpedantic) endif() +add_executable(puppet_master_launch + puppet_master_launch.cpp +) + +target_link_libraries(puppet_master_launch + PRIVATE + PuppetMaster::JsonConfigAdapter +) + +if(MSVC) + target_compile_options(puppet_master_launch PRIVATE /W4 /permissive-) +else() + target_compile_options(puppet_master_launch PRIVATE -Wall -Wextra -Wpedantic) +endif() + install( - TARGETS puppet_master_config + TARGETS puppet_master_config puppet_master_launch RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) diff --git a/tools/puppet_master_launch.cpp b/tools/puppet_master_launch.cpp new file mode 100644 index 0000000..de7ec7c --- /dev/null +++ b/tools/puppet_master_launch.cpp @@ -0,0 +1,130 @@ +// puppet_master_launch: starts the nodes of a system manifest, restarts them +// by their policy, and stops them in reverse order on SIGINT/SIGTERM (Ctrl+C +// or Ctrl+Break on Windows). +// +// puppet_master_launch system.json +// puppet_master_launch --log-dir logs system.json +// +// The manifest is checked as one system first, as by +// `puppet_master_config system validate`; --no-validate skips that. + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace config = puppet_master::configuration; + +namespace { + +std::atomic g_stop_signal {false}; + +void HandleStopSignal(int) +{ + g_stop_signal.store(true); +} + +int Usage(std::ostream& out) +{ + out << "usage: puppet_master_launch [--log-dir DIR] [--no-validate] \n" + << " --log-dir DIR write each node's output to DIR/.log\n" + << " --no-validate start without checking the nodes' configurations together\n"; + return 2; +} + +bool Validate(const config::SystemManifest& system) +{ + auto report = config::ValidateSystemManifest(system); + if (!report.ok()) { + std::cerr << "launch: " << report.status().ToString() << '\n'; + return false; + } + for (const auto& warning : report.value().warnings) { + std::cerr << "launch: warning: " << warning << '\n'; + } + for (const auto& error : report.value().errors) { + std::cerr << "launch: " << error << '\n'; + } + return report.value().ok(); +} + +} // namespace + +int main(int argc, char** argv) +{ + std::string log_directory; + std::string path; + bool validate = true; + for (int index = 1; index < argc; ++index) { + const std::string argument = argv[index]; + if (argument == "--help" || argument == "-h") { + Usage(std::cout); + return 0; + } + if (argument == "--log-dir" && index + 1 < argc) { + log_directory = argv[++index]; + } else if (argument == "--no-validate") { + validate = false; + } else if (!argument.empty() && argument[0] != '-' && path.empty()) { + path = argument; + } else { + return Usage(std::cerr); + } + } + if (path.empty()) { + return Usage(std::cerr); + } + + auto manifest = config::LoadSystemManifest(path); + if (!manifest.ok()) { + std::cerr << "launch: " << manifest.status().ToString() << '\n'; + return 1; + } + if (validate && !Validate(manifest.value())) { + return 1; + } + const std::string name = manifest.value().name.empty() ? path : manifest.value().name; + + config::SupervisorOptions options; + options.log_directory = log_directory; + options.on_event = [](const config::SupervisorEvent& event) { + std::cerr << "launch: " << event.node << ": " << config::ToString(event.kind); + if (!event.detail.empty()) { + std::cerr << " (" << event.detail << ')'; + } + std::cerr << std::endl; + }; + config::Supervisor supervisor(std::move(manifest).value(), std::move(options)); + + // The nodes run in process groups of their own, so a Ctrl+C reaches only + // this process, which stops them in order. + std::signal(SIGINT, HandleStopSignal); + std::signal(SIGTERM, HandleStopSignal); +#if defined(SIGBREAK) + std::signal(SIGBREAK, HandleStopSignal); +#endif + std::atomic done {false}; + std::thread watcher([&] { + while (!done.load()) { + if (g_stop_signal.exchange(false)) { + std::cerr << "launch: stopping " << name << std::endl; + supervisor.RequestStop(); + } + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + }); + + std::cerr << "launch: starting " << name << std::endl; + const auto result = supervisor.Run(); + done.store(true); + watcher.join(); + + std::cerr << "launch: " << name << " stopped: " << result.reason << std::endl; + return result.exit_code; +} From 50cb9d8bc5af18d39ea2571e8c8320ee9be8116d Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 28 Oct 2026 17:56:35 +0800 Subject: [PATCH 4/6] feat: add puppet_master_topic list/echo/hz for shm topics list shows the shm topics on this host from their segment headers (Linux), or with --system the topics a manifest's nodes declare and which components write and read them. echo prints each message's sequence, size, latency, and bytes; hz reports the rate, intervals by publish time, and losses per window. echo and hz subscribe as an ordinary reader queued to the ring size, so they never slow a writer; what they fall behind on is reported as lost. With --system the type and ring size come from the manifest, which also works on Windows and before the writer starts. Co-Authored-By: Claude Opus 5.5 --- docs/launcher.md | 35 ++ docs/shm-transport.md | 2 + test/CMakeLists.txt | 15 + test/topic_tool_test.cpp | 264 +++++++++++++++ tools/CMakeLists.txt | 24 ++ tools/puppet_master_topic.cpp | 609 ++++++++++++++++++++++++++++++++++ 6 files changed, 949 insertions(+) create mode 100644 test/topic_tool_test.cpp create mode 100644 tools/puppet_master_topic.cpp diff --git a/docs/launcher.md b/docs/launcher.md index df03b6b..bd3a524 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -182,6 +182,41 @@ In C++, `configuration::Supervisor` in `puppet_master/configuration/supervisor.h` does the same. Its `ProcessLauncher` interface lets tests replace real processes. +## Topic Tool + +`puppet_master_topic` looks at the shared-memory topics of a running system. +It is built and installed with the JSON and shared-memory adapters. + +```bash +puppet_master_topic list +puppet_master_topic list --system system.json +puppet_master_topic echo /vehicle/state --count 5 +puppet_master_topic hz /vehicle/state --window-ms 500 +``` + +| Command | Effect | +|---|---| +| `list` | the topics with a segment on this host: type, ring size, state, messages written, attached pids (Linux) | +| `list --system FILE` | the topics the manifest's nodes declare, with their ring size and which components write and read them | +| `echo TOPIC` | each message's sequence, size, and latency, and its first `--bytes N` bytes in hex (32 by default), or `--text` | +| `hz TOPIC` | every `--window-ms` (1000 by default): the rate, bytes per second, shortest and longest interval, and losses | + +`echo` and `hz` subscribe like any other reader and change nothing for the +writer. They start after the newest message and queue up to one ring. A +message they fall behind on is overwritten in the ring and shown as lost. +Intervals are measured between publish times, so the tool's own delays do +not show up as jitter. + +The topic's type and ring size come from its segment header, which needs +Linux and a writer that has started. With `--system FILE` they come from +the manifest's nodes and deployment instead, which also works on Windows +and before the writer starts. `--domain N` picks a domain when a topic +exists in several. + +`echo --count N` stops after N messages. With `--timeout-ms`, it exits with +1 if fewer arrived, so scripts can wait for traffic. `hz --duration-ms N` +stops after N ms. Ctrl+C stops either one. + ## Library Helpers These are in the core library and need no JSON: diff --git a/docs/shm-transport.md b/docs/shm-transport.md index 06a90a1..f0ddea1 100644 --- a/docs/shm-transport.md +++ b/docs/shm-transport.md @@ -161,6 +161,8 @@ puppet_master_config shm clean [--domain N] [--dry-run] `list` prints each segment's object name, state, topic, message descriptor, geometry, messages written, and the pids of running processes attached to it. +To see the messages themselves, use `puppet_master_topic echo` and `hz`; see +[Topic Tool](launcher.md#topic-tool). The states are: | State | Meaning | Removed by `clean` | diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 71e94de..e742512 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -289,6 +289,21 @@ if(PUPPETMASTER_ENABLE_JSON_CONFIG) endif() if(PUPPETMASTER_ENABLE_JSON_CONFIG AND TARGET PuppetMaster::ShmAdapter) + add_executable(puppet_master_topic_tool_test + topic_tool_test.cpp + ) + + target_link_libraries(puppet_master_topic_tool_test + PRIVATE + PuppetMaster::JsonConfigAdapter + PuppetMaster::ShmAdapter + ) + + add_test( + NAME puppet_master.topic_tool + COMMAND puppet_master_topic_tool_test $ + ) + add_executable(puppet_master_json_imports_test json_imports_test.cpp ) diff --git a/test/topic_tool_test.cpp b/test/topic_tool_test.cpp new file mode 100644 index 0000000..740feb4 --- /dev/null +++ b/test/topic_tool_test.cpp @@ -0,0 +1,264 @@ +// puppet_master_topic against a live shared-memory topic: this process +// writes, the tool runs as a child process and its output is checked. +// +// puppet_master_topic_tool_test + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace config = puppet_master::configuration; +namespace core = puppet_master::core; +namespace fs = std::filesystem; +namespace shm = puppet_master::transport::shm; +namespace transport = puppet_master::transport; + +using namespace std::chrono_literals; + +namespace { + +constexpr core::DomainId kDomain = 77; + +bool Contains(const std::string& text, const std::string& part) +{ + return text.find(part) != std::string::npos; +} + +std::string ReadFile(const fs::path& path) +{ + std::ifstream in(path, std::ios::binary); + return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); +} + +void WriteFile(const fs::path& path, const std::string& text) +{ + fs::create_directories(path.parent_path()); + std::ofstream(path, std::ios::binary) << text; +} + +// A one-node system whose producer writes `topic` over shm, plus a writer on +// the same topic in this process. +class Fixture { +public: + Fixture() + : stamp_(std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())), + root_(fs::temp_directory_path() / ("pm_topic_tool_" + stamp_)), + topic_("/pm_topic_test/text_" + stamp_) + { + WriteFile(root_ / "share/test_interfaces/topics.json", + R"({"topics": [{"id": "text", "name": ")" + topic_ + R"(", "message_type": "test.Text"}]})"); + WriteFile(root_ / "share/producer/producer.json", R"({ + "imports": ["test_interfaces/topics.json"], + "components": [{"name": "producer", "writers": ["text"], "triggers": [{"kind": "manual"}]}]})"); + WriteFile(root_ / "share/consumer/consumer.json", R"({ + "imports": ["test_interfaces/topics.json"], + "components": [{"name": "consumer", "readers": ["text"], + "triggers": [{"kind": "data", "data_topics": ["text"]}]}]})"); + WriteFile(root_ / "deploy.json", + R"({"defaults": {"transport": "shm", "transport_parameters": {"domain_id": 77}}, + "topics": [{"name": ")" + topic_ + + R"(", "transport_parameters": {"slot_payload_size": 256, "slot_count": 8}}]})"); + WriteFile(root_ / "system.json", R"({ + "name": "topic_test", "config_paths": ["share"], "deployment": "deploy.json", + "nodes": [ + {"name": "producer", "executable": "producer_node", "config": "producer/producer.json"}, + {"name": "consumer", "executable": "consumer_node", "config": "consumer/consumer.json"}]})"); + + shm::Options options; + options.domain_id = kDomain; + options.topics[topic_] = shm::TopicOptions {256, 8}; + transport_ = std::make_unique(core::TransportName::Create("test").value(), options); + assert(transport_->Open().ok()); + const transport::EndpointConfig endpoint { + core::TopicSpec {core::TopicName::Create(topic_).value(), core::TransportKind::kIpc, {}}, + transport::MessageDescriptor {"test.Text", "application/octet-stream", 0}}; + auto writer = transport_->CreateWriter(endpoint); + assert(writer.ok()); + writer_ = writer.value(); + } + + ~Fixture() + { + writer_.reset(); + transport_.reset(); + shm::RemoveSegment(kDomain, topic_); + std::error_code ignored; + fs::remove_all(root_, ignored); + } + + const std::string& topic() const noexcept { return topic_; } + std::string system() const { return (root_ / "system.json").string(); } + + void Publish(const std::string& text) + { + const auto status = writer_->Write(transport::ByteView::From(text.data(), text.size())); + assert(status.ok()); + } + + struct Outcome { + config::ProcessExit exit; + std::string output; + }; + + // Runs the tool, publishing "hello N" every `period` (if not zero) until + // it exits. + Outcome Run(const std::vector& command, std::chrono::milliseconds period) + { + const auto log = root_ / ("run_" + std::to_string(runs_++) + ".log"); + auto launcher = config::MakeSystemProcessLauncher(); + auto child = launcher->Start(command, log.string()); + assert(child.ok()); + const auto deadline = std::chrono::steady_clock::now() + 30s; + std::optional exit; + int sent = 0; + while (!(exit = child.value()->Poll())) { + if (std::chrono::steady_clock::now() > deadline) { + child.value()->Kill(); + std::cerr << "tool did not exit; output:\n" << ReadFile(log) << '\n'; + assert(false); + } + if (period.count() != 0) { + Publish("hello " + std::to_string(sent++)); + std::this_thread::sleep_for(period); + } else { + std::this_thread::sleep_for(5ms); + } + } + Outcome outcome {*exit, ReadFile(log)}; + std::cout << "$"; + for (const auto& word : command) { + std::cout << ' ' << word; + } + std::cout << " -> " << config::ToString(*exit) << '\n' << outcome.output; + return outcome; + } + +private: + std::string stamp_; + fs::path root_; + std::string topic_; + std::unique_ptr transport_; + transport::WriterPtr writer_; + int runs_ {0}; +}; + +void TestListFromSystem(Fixture& fixture, const std::string& tool) +{ + const auto run = fixture.Run({tool, "list", "--system", fixture.system()}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, fixture.topic() + " test.Text (application/octet-stream) domain 77, 256 B x 8 slots")); + assert(Contains(run.output, "writers: producer/producer")); + assert(Contains(run.output, "readers: consumer/consumer")); +} + +void TestEcho(Fixture& fixture, const std::string& tool, bool with_system) +{ + std::vector command {tool, "echo", fixture.topic(), "--count", "3", "--timeout-ms", "20000", "--text"}; + if (with_system) { + command.insert(command.end(), {"--system", fixture.system()}); + } + const auto run = fixture.Run(command, 10ms); + assert(run.exit.success()); + assert(Contains(run.output, "echo " + fixture.topic() + ": test.Text (application/octet-stream)")); + assert(Contains(run.output, " hello ")); + assert(Contains(run.output, "echo: 3 received")); +} + +void TestEchoHex(Fixture& fixture, const std::string& tool) +{ + const auto run = fixture.Run( + {tool, "echo", fixture.topic(), "--system", fixture.system(), "--count", "1", "--bytes", "4"}, 10ms); + assert(run.exit.success()); + // "hell" in hex, then a mark for the bytes not shown. + assert(Contains(run.output, " 68 65 6c 6c ...")); +} + +void TestEchoTimesOut(Fixture& fixture, const std::string& tool) +{ + const auto run = fixture.Run( + {tool, "echo", fixture.topic(), "--system", fixture.system(), "--count", "1", "--timeout-ms", "300"}, 0ms); + assert(run.exit.code == 1 && !run.exit.signaled); + assert(Contains(run.output, "echo: 0 received")); +} + +void TestHz(Fixture& fixture, const std::string& tool) +{ + const auto run = fixture.Run( + {tool, "hz", fixture.topic(), "--system", fixture.system(), "--window-ms", "300", "--duration-ms", "1000"}, + 10ms); + assert(run.exit.success()); + assert(Contains(run.output, "rate ")); + assert(Contains(run.output, " Hz ")); + assert(Contains(run.output, "interval min ")); + assert(Contains(run.output, "lost 0")); +} + +void TestErrors(Fixture& fixture, const std::string& tool) +{ + auto run = fixture.Run({tool, "echo", "/pm_topic_test/nobody", "--system", fixture.system()}, 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "declares topic /pm_topic_test/nobody")); + + run = fixture.Run({tool, "hz"}, 0ms); + assert(run.exit.code == 2); + assert(Contains(run.output, "usage: puppet_master_topic")); + + run = fixture.Run({tool, "echo", fixture.topic(), "--count", "x"}, 0ms); + assert(run.exit.code == 2); +} + +#if !defined(_WIN32) +void TestListFromSegments(Fixture& fixture, const std::string& tool) +{ + fixture.Publish("first"); + const auto run = fixture.Run({tool, "list", "--domain", "77"}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, fixture.topic() + " test.Text (application/octet-stream) domain 77, 256 B x 8 slots")); + assert(Contains(run.output, "in_use")); +} + +void TestMissingSegment(Fixture& fixture, const std::string& tool) +{ + const auto run = fixture.Run({tool, "echo", "/pm_topic_test/nobody", "--domain", "77"}, 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "no shm segment for topic /pm_topic_test/nobody")); +} +#endif + +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 2) { + std::cerr << "usage: puppet_master_topic_tool_test \n"; + return 2; + } + const std::string tool = fs::absolute(argv[1]).string(); + Fixture fixture; + + TestListFromSystem(fixture, tool); + TestEcho(fixture, tool, true); + TestEchoHex(fixture, tool); + TestEchoTimesOut(fixture, tool); + TestHz(fixture, tool); + TestErrors(fixture, tool); +#if !defined(_WIN32) + // Segment headers can only be read on Linux. + TestListFromSegments(fixture, tool); + TestEcho(fixture, tool, false); + TestMissingSegment(fixture, tool); +#endif + + std::cout << "topic tool tests passed\n"; + return 0; +} diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 71eda8b..b4f0816 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -40,3 +40,27 @@ install( TARGETS puppet_master_config puppet_master_launch RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) + +# Topic inspection reads shared-memory topics. +if(TARGET PuppetMaster::ShmAdapter) + add_executable(puppet_master_topic + puppet_master_topic.cpp + ) + + target_link_libraries(puppet_master_topic + PRIVATE + PuppetMaster::JsonConfigAdapter + PuppetMaster::ShmAdapter + ) + + if(MSVC) + target_compile_options(puppet_master_topic PRIVATE /W4 /permissive-) + else() + target_compile_options(puppet_master_topic PRIVATE -Wall -Wextra -Wpedantic) + endif() + + install( + TARGETS puppet_master_topic + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" + ) +endif() diff --git a/tools/puppet_master_topic.cpp b/tools/puppet_master_topic.cpp new file mode 100644 index 0000000..11da385 --- /dev/null +++ b/tools/puppet_master_topic.cpp @@ -0,0 +1,609 @@ +// puppet_master_topic: looks at the shared-memory topics of a running system +// without changing it. +// +// puppet_master_topic list +// puppet_master_topic echo /vehicle/state --count 5 +// puppet_master_topic hz /vehicle/state +// puppet_master_topic echo --system system.json /vehicle/state +// +// echo and hz subscribe like any other reader: they never slow a writer +// down, and what they miss when they fall behind is overwritten in the ring +// and reported as lost. A topic's type and ring size come from its segment +// (Linux only), or with --system from the manifest's nodes and deployment, +// which also works on Windows and before the writer starts. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace config = puppet_master::configuration; +namespace core = puppet_master::core; +namespace shm = puppet_master::transport::shm; +namespace transport = puppet_master::transport; + +namespace { + +using Clock = std::chrono::steady_clock; +using std::chrono::milliseconds; + +// Reads wait this long at most, so a stop or a deadline is noticed. +constexpr milliseconds kReadSlice {100}; + +std::atomic g_stop {false}; + +void HandleStop(int) +{ + g_stop.store(true); +} + +int Usage(std::ostream& out) +{ + out << "usage: puppet_master_topic list [--system FILE] [--domain N]\n" + << " puppet_master_topic echo [--system FILE] [--domain N] [--count N]\n" + << " [--timeout-ms N] [--bytes N] [--text]\n" + << " puppet_master_topic hz [--system FILE] [--domain N] [--window-ms N]\n" + << " [--duration-ms N]\n" + << " list the topics with a shared-memory segment on this host (Linux);\n" + << " with --system, the system's topics and who writes and reads them\n" + << " echo print each message: sequence, size, latency, and its bytes\n" + << " hz print the message rate, intervals, and losses every window\n" + << " --system FILE take topics from a system manifest instead of segment headers\n" + << " --domain N the shared-memory domain (default: any, or the deployment's)\n" + << " --count N echo: stop after N messages\n" + << " --timeout-ms N echo: stop after N ms; fails if --count was not reached\n" + << " --bytes N echo: show at most N bytes of each message in hex (default 32)\n" + << " --text echo: print the payload as text instead\n" + << " --window-ms N hz: report every N ms (default 1000)\n" + << " --duration-ms N hz: stop after N ms\n" + << "Ctrl+C stops echo and hz.\n"; + return 2; +} + +struct Arguments { + std::string command; + std::string topic; + std::string system; + std::optional domain; + std::uint64_t count {0}; + milliseconds timeout {0}; + milliseconds window {1000}; + milliseconds duration {0}; + std::uint64_t bytes {32}; + bool text {false}; +}; + +bool ParseNumber(const std::string& text, std::uint64_t& value) +{ + if (text.empty() || text.size() > 12 || text.find_first_not_of("0123456789") != std::string::npos) { + return false; + } + value = std::stoull(text); + return true; +} + +// Returns 0 when the arguments are good, else the exit code. +int Parse(int argc, char** argv, Arguments& args) +{ + if (argc < 2) { + return Usage(std::cerr); + } + args.command = argv[1]; + if (args.command == "--help" || args.command == "-h") { + Usage(std::cout); + return -1; + } + if (args.command != "list" && args.command != "echo" && args.command != "hz") { + return Usage(std::cerr); + } + for (int index = 2; index < argc; ++index) { + const std::string argument = argv[index]; + const bool has_value = index + 1 < argc; + std::uint64_t number = 0; + const auto numeric = [&](const char* name) { + if (!has_value || !ParseNumber(argv[index + 1], number)) { + std::cerr << name << " needs a number\n"; + return false; + } + ++index; + return true; + }; + if (argument == "--system" && has_value) { + args.system = argv[++index]; + } else if (argument == "--domain") { + if (!numeric("--domain") || number > 0xffffffffULL) { + return 2; + } + args.domain = static_cast(number); + } else if (argument == "--count" && args.command == "echo") { + if (!numeric("--count")) { + return 2; + } + args.count = number; + } else if (argument == "--timeout-ms" && args.command == "echo") { + if (!numeric("--timeout-ms")) { + return 2; + } + args.timeout = milliseconds(number); + } else if (argument == "--bytes" && args.command == "echo") { + if (!numeric("--bytes")) { + return 2; + } + args.bytes = number; + } else if (argument == "--text" && args.command == "echo") { + args.text = true; + } else if (argument == "--window-ms" && args.command == "hz") { + if (!numeric("--window-ms") || number == 0) { + return 2; + } + args.window = milliseconds(number); + } else if (argument == "--duration-ms" && args.command == "hz") { + if (!numeric("--duration-ms")) { + return 2; + } + args.duration = milliseconds(number); + } else if (!argument.empty() && argument[0] != '-' && args.topic.empty() && args.command != "list") { + args.topic = argument; + } else { + return Usage(std::cerr); + } + } + if (args.command != "list" && args.topic.empty()) { + return Usage(std::cerr); + } + return 0; +} + +// --- finding topics ----------------------------------------------------- + +struct TopicInfo { + std::string name; + core::TransportKind transport {core::TransportKind::kIpc}; + transport::MessageDescriptor descriptor; + shm::TopicOptions geometry; + core::DomainId domain {0}; + // From a segment header. + bool from_segment {false}; + std::string state; + std::uint64_t written {0}; + std::vector pids; + // From a manifest: "node/component". + std::set writers; + std::set readers; +}; + +using Topics = core::Result>; + +Topics TopicsFromSegments(std::optional domain) +{ + auto segments = shm::ListSegments(domain); + if (!segments.ok()) { + std::string message = segments.status().message(); + if (segments.status().code() == core::StatusCode::kUnsupported) { + message += "; pass --system FILE to take topics from a system manifest"; + } + return Topics::FromStatus(core::Status::Error(segments.status().code(), message)); + } + std::vector topics; + for (const auto& segment : segments.value()) { + if (segment.topic.empty()) { + continue; // never initialized or another layout: nothing to read + } + TopicInfo info; + info.name = segment.topic; + info.descriptor = segment.descriptor; + info.geometry = segment.geometry; + info.domain = segment.domain_id; + info.from_segment = true; + info.state = shm::ToString(segment.state); + info.written = segment.messages_written; + info.pids = segment.live_pids; + topics.push_back(std::move(info)); + } + std::sort(topics.begin(), topics.end(), [](const TopicInfo& lhs, const TopicInfo& rhs) { + return lhs.name != rhs.name ? lhs.name < rhs.name : lhs.domain < rhs.domain; + }); + return Topics(std::move(topics)); +} + +core::Status Differs(const std::string& topic, const std::string& node) +{ + return core::Status::InvalidArgument("topic " + topic + " is declared differently in node " + node + + "; run puppet_master_config system validate"); +} + +// Every topic the manifest's nodes declare, with the deployment's transport +// settings, and which components write and read it. +Topics TopicsFromSystem(const std::string& path, std::optional domain) +{ + auto manifest = config::LoadSystemManifest(path); + if (!manifest.ok()) { + return Topics::FromStatus(manifest.status()); + } + auto nodes = config::LoadSystemNodes(manifest.value()); + if (!nodes.ok()) { + return Topics::FromStatus(nodes.status()); + } + std::map by_name; + for (const auto& node : nodes.value()) { + auto options = shm::OptionsFromProject(node.project); + if (!options.ok()) { + return Topics::FromStatus(core::Status::Error( + options.status().code(), "node " + node.name + ": " + options.status().message())); + } + std::map names; // topic id -> wire name + for (const auto& topic : node.project.topics) { + names[topic.id] = topic.name; + TopicInfo info; + info.name = topic.name; + info.transport = topic.transport; + info.descriptor = transport::MessageDescriptor {topic.message_type, topic.encoding, topic.message_version}; + info.geometry = options.value().ForTopic(topic.name); + info.domain = domain ? *domain : options.value().domain_id; + const auto found = by_name.find(topic.name); + if (found == by_name.end()) { + by_name.emplace(topic.name, std::move(info)); + continue; + } + const auto& known = found->second; + const bool same_geometry = known.geometry.slot_payload_size == info.geometry.slot_payload_size && + known.geometry.slot_count == info.geometry.slot_count; + if (known.descriptor != info.descriptor || known.transport != info.transport || + known.domain != info.domain || + (info.transport == core::TransportKind::kIpc && !same_geometry)) { + return Topics::FromStatus(Differs(topic.name, node.name)); + } + } + const auto add = [&](const std::vector& ids, const std::string& component, bool writes) { + for (const auto& id : ids) { + const auto name = names.find(id); + if (name != names.end()) { + auto& info = by_name[name->second]; + (writes ? info.writers : info.readers).insert(node.name + "/" + component); + } + } + }; + for (const auto& component : node.project.components) { + add(component.writers, component.name, true); + add(component.readers, component.name, false); + } + } + std::vector topics; + for (auto& entry : by_name) { + topics.push_back(std::move(entry.second)); + } + return Topics(std::move(topics)); +} + +core::Result FindTopic(const Arguments& args) +{ + using ResultType = core::Result; + auto topics = args.system.empty() ? TopicsFromSegments(args.domain) : TopicsFromSystem(args.system, args.domain); + if (!topics.ok()) { + return ResultType::FromStatus(topics.status()); + } + std::vector matches; + for (auto& topic : topics.value()) { + if (topic.name == args.topic) { + matches.push_back(std::move(topic)); + } + } + if (matches.empty()) { + return ResultType::FromStatus(core::Status::NotFound( + args.system.empty() ? "no shm segment for topic " + args.topic + + " on this host; is its writer running? (--system FILE finds it from the " + "manifest instead)" + : "no node of " + args.system + " declares topic " + args.topic)); + } + if (matches.size() > 1) { + std::string domains; + for (const auto& match : matches) { + domains += (domains.empty() ? "" : ", ") + std::to_string(match.domain); + } + return ResultType::FromStatus(core::Status::InvalidArgument( + "topic " + args.topic + " exists in domains " + domains + "; pick one with --domain")); + } + if (matches.front().transport != core::TransportKind::kIpc) { + return ResultType::FromStatus(core::Status::Unsupported( + "topic " + args.topic + " uses the " + core::ToString(matches.front().transport) + + " transport; puppet_master_topic reads shared-memory topics only")); + } + return ResultType(std::move(matches.front())); +} + +// --- reading ------------------------------------------------------------ + +// A plain reader on the topic. It starts after the newest message and keeps +// up to a ring's worth queued; the ring overwrites what it falls behind on. +struct Subscription { + std::unique_ptr shm_transport; + transport::ReaderPtr reader; // declared last: released first +}; + +core::Result Subscribe(const TopicInfo& topic) +{ + using ResultType = core::Result; + const auto failed = [&topic](const core::Status& status) { + return ResultType::FromStatus( + core::Status::Error(status.code(), "subscribing to " + topic.name + ": " + status.message())); + }; + shm::Options options; + options.domain_id = topic.domain; + options.topics[topic.name] = topic.geometry; + auto transport_name = core::TransportName::Create("puppet_master_topic"); + auto topic_name = core::TopicName::Create(topic.name); + if (!topic_name.ok()) { + return failed(topic_name.status()); + } + + Subscription subscription; + subscription.shm_transport = std::make_unique(transport_name.value(), options); + auto status = subscription.shm_transport->Open(); + if (!status.ok()) { + return failed(status); + } + core::MessagePolicy policy; + policy.freshness = core::FreshnessPolicy::kQueued; + policy.retention = core::RetentionPolicy::kKeepLast; + policy.queue_depth = topic.geometry.slot_count; + const transport::EndpointConfig endpoint { + core::TopicSpec {topic_name.value(), core::TransportKind::kIpc, policy}, topic.descriptor}; + auto reader = subscription.shm_transport->CreateReader(endpoint); + if (!reader.ok()) { + return failed(reader.status()); + } + subscription.reader = reader.value(); + return ResultType(std::move(subscription)); +} + +// The next message, or none after a short wait. +core::Result> Next(Subscription& subscription) +{ + using ResultType = core::Result>; + auto message = subscription.reader->Read(transport::ReadOptions {true, kReadSlice}); + if (message.ok()) { + return ResultType(std::optional(std::move(message).value())); + } + if (message.status().code() == core::StatusCode::kDeadlineExceeded) { + return ResultType(std::optional()); + } + return ResultType::FromStatus(message.status()); +} + +// Messages skipped before `sequence`, given the previous one seen. +std::uint64_t Gap(const std::optional& last, core::SequenceNumber sequence) +{ + return last && sequence > *last + 1 ? sequence - *last - 1 : 0; +} + +double Microseconds(core::Nanoseconds value) +{ + return static_cast(value.count()) / 1000.0; +} + +// --- commands ----------------------------------------------------------- + +std::string Join(const std::set& names) +{ + std::string text; + for (const auto& name : names) { + text += (text.empty() ? "" : ", ") + name; + } + return text.empty() ? "-" : text; +} + +int List(const Arguments& args) +{ + auto topics = args.system.empty() ? TopicsFromSegments(args.domain) : TopicsFromSystem(args.system, args.domain); + if (!topics.ok()) { + std::cerr << topics.status().ToString() << '\n'; + return 1; + } + if (topics.value().empty()) { + std::cout << (args.system.empty() ? "no shm topics\n" : "no topics\n"); + return 0; + } + for (const auto& topic : topics.value()) { + std::cout << topic.name << " " << topic.descriptor.ToString(); + if (topic.transport != core::TransportKind::kIpc) { + std::cout << " " << core::ToString(topic.transport); + } else { + std::cout << " domain " << topic.domain << ", " << topic.geometry.slot_payload_size << " B x " + << topic.geometry.slot_count << " slots"; + } + if (topic.from_segment) { + std::cout << " " << topic.state << ", " << topic.written << " written"; + if (!topic.pids.empty()) { + std::cout << ", pids"; + for (const auto pid : topic.pids) { + std::cout << ' ' << pid; + } + } + } else { + std::cout << "\n writers: " << Join(topic.writers) << "\n readers: " << Join(topic.readers); + } + std::cout << '\n'; + } + return 0; +} + +void PrintPayload(const transport::ByteBuffer& payload, const Arguments& args) +{ + if (args.text) { + std::string text; + for (const auto byte : payload) { + const auto c = static_cast(byte); + text += (byte >= 0x20 && byte < 0x7f) || c == '\t' ? c : '.'; + } + std::cout << " " << text; + return; + } + const auto shown = static_cast(std::min(payload.size(), args.bytes)); + if (shown == 0) { + return; + } + std::ostringstream hex; + hex << std::hex << std::setfill('0'); + for (std::size_t index = 0; index < shown; ++index) { + hex << (index == 0 ? "" : " ") << std::setw(2) << static_cast(payload[index]); + } + std::cout << " " << hex.str() << (shown < payload.size() ? " ..." : ""); +} + +int Echo(const Arguments& args) +{ + auto topic = FindTopic(args); + if (!topic.ok()) { + std::cerr << topic.status().ToString() << '\n'; + return 1; + } + auto subscription = Subscribe(topic.value()); + if (!subscription.ok()) { + std::cerr << subscription.status().ToString() << '\n'; + return 1; + } + std::cerr << "echo " << topic.value().name << ": " << topic.value().descriptor.ToString() << std::endl; + + const auto deadline = args.timeout.count() == 0 ? Clock::time_point::max() : Clock::now() + args.timeout; + std::uint64_t received = 0; + std::uint64_t lost = 0; + std::optional last; + while (!g_stop.load() && Clock::now() < deadline && (args.count == 0 || received < args.count)) { + auto next = Next(subscription.value()); + if (!next.ok()) { + std::cerr << next.status().ToString() << '\n'; + return 1; + } + if (!next.value()) { + continue; + } + const auto& message = *next.value(); + const auto gap = Gap(last, message.metadata.sequence); + if (gap != 0) { + std::cout << "(" << gap << " lost)\n"; + lost += gap; + } + last = message.metadata.sequence; + ++received; + std::cout << "#" << message.metadata.sequence << " " << message.payload.size() << " B latency " + << std::fixed << std::setprecision(1) + << Microseconds(message.metadata.reception_timestamp - message.metadata.source_timestamp) << " us"; + std::cout.unsetf(std::ios::floatfield); + PrintPayload(message.payload, args); + std::cout << std::endl; + } + std::cerr << "echo: " << received << " received, " << lost << " lost" << std::endl; + // With --count, ending early (timeout) is a failure, so scripts can wait + // for traffic; Ctrl+C is not. + return args.count != 0 && received < args.count && !g_stop.load() ? 1 : 0; +} + +struct Window { + std::uint64_t received {0}; + std::uint64_t lost {0}; + std::uint64_t bytes {0}; + core::Nanoseconds min_interval {core::Nanoseconds::max()}; + core::Nanoseconds max_interval {0}; +}; + +void Report(const Window& window, Clock::duration elapsed) +{ + const double seconds = std::chrono::duration(elapsed).count(); + std::cout << std::fixed << std::setprecision(2) << "rate " << (seconds > 0 ? window.received / seconds : 0.0) + << " Hz " << window.received << " msgs " << (seconds > 0 ? window.bytes / seconds : 0.0) << " B/s"; + if (window.received >= 2) { + std::cout << std::setprecision(3) << " interval min " << Microseconds(window.min_interval) / 1000.0 + << " ms, max " << Microseconds(window.max_interval) / 1000.0 << " ms"; + } + std::cout << " lost " << window.lost << std::endl; + std::cout.unsetf(std::ios::floatfield); +} + +int Hz(const Arguments& args) +{ + auto topic = FindTopic(args); + if (!topic.ok()) { + std::cerr << topic.status().ToString() << '\n'; + return 1; + } + auto subscription = Subscribe(topic.value()); + if (!subscription.ok()) { + std::cerr << subscription.status().ToString() << '\n'; + return 1; + } + std::cerr << "hz " << topic.value().name << ": " << topic.value().descriptor.ToString() << std::endl; + + const auto started = Clock::now(); + const auto deadline = args.duration.count() == 0 ? Clock::time_point::max() : started + args.duration; + auto window_start = started; + Window window; + std::optional last; + std::optional last_time; + while (!g_stop.load()) { + auto next = Next(subscription.value()); + if (!next.ok()) { + std::cerr << next.status().ToString() << '\n'; + return 1; + } + if (next.value()) { + const auto& message = *next.value(); + window.lost += Gap(last, message.metadata.sequence); + last = message.metadata.sequence; + ++window.received; + window.bytes += message.payload.size(); + // Intervals by publish time, so the reader's own delays do not + // show up as jitter. + const auto stamp = message.metadata.source_timestamp; + if (last_time) { + const auto interval = stamp - *last_time; + window.min_interval = std::min(window.min_interval, interval); + window.max_interval = std::max(window.max_interval, interval); + } + last_time = stamp; + } + const auto now = Clock::now(); + if (now - window_start >= args.window || now >= deadline) { + Report(window, now - window_start); + window = Window {}; + window_start = now; + } + if (now >= deadline) { + break; + } + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + Arguments args; + const int parsed = Parse(argc, argv, args); + if (parsed != 0) { + return parsed < 0 ? 0 : parsed; + } + std::signal(SIGINT, HandleStop); + std::signal(SIGTERM, HandleStop); +#if defined(SIGBREAK) + std::signal(SIGBREAK, HandleStop); +#endif + if (args.command == "list") { + return List(args); + } + return args.command == "echo" ? Echo(args) : Hz(args); +} From f50603221a5d9c5ec6e416f2d617971b74e9efa8 Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 28 Oct 2026 18:17:36 +0800 Subject: [PATCH 5/6] feat: record and replay shm topics RecordingWriter and RecordingReader (transport/recording.h, core library) store messages of several topics in one file: topic records with the name, descriptor, and free-form parameters, then message records with the topic id, time since the start, sequence, and payload. Readers stop cleanly at a record cut off by a crash, skip unknown record kinds, and refuse other format versions. puppet_master_topic gains record (every shm topic found, or those named; --count, --duration-ms), replay (all or named topics, at the recorded pace times --rate, with the recorded domain and ring size or --domain), and info. The recorder stores publish times so a replay keeps the writers' pace, and reports what it lost per topic. Co-Authored-By: Claude Opus 5.5 --- docs/launcher.md | 10 + docs/recording.md | 93 ++++ include/puppet_master/transport/recording.h | 93 ++++ src/CMakeLists.txt | 2 + src/transport/recording.cpp | 412 ++++++++++++++++ test/CMakeLists.txt | 14 + test/recording_test.cpp | 230 +++++++++ test/topic_tool_test.cpp | 97 +++- tools/puppet_master_topic.cpp | 521 ++++++++++++++++++-- 9 files changed, 1439 insertions(+), 33 deletions(-) create mode 100644 docs/recording.md create mode 100644 include/puppet_master/transport/recording.h create mode 100644 src/transport/recording.cpp create mode 100644 test/recording_test.cpp diff --git a/docs/launcher.md b/docs/launcher.md index bd3a524..1cc0b54 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -217,6 +217,16 @@ exists in several. 1 if fewer arrived, so scripts can wait for traffic. `hz --duration-ms N` stops after N ms. Ctrl+C stops either one. +The tool also records and replays topics: + +| Command | Effect | +|---|---| +| `record [TOPIC...] -o FILE` | write the topics' messages to FILE; with no topic named, every shm topic found (or the system's, with `--system`); stops after `--count N` messages, `--duration-ms N`, or Ctrl+C | +| `replay FILE [TOPIC...]` | publish the recording's messages again, all or the topics named, at the recorded pace times `--rate X` (`0`: at once) | +| `info FILE` | the recording's topics, message counts, sizes, rates, and length | + +See [Recordings](recording.md). + ## Library Helpers These are in the core library and need no JSON: diff --git a/docs/recording.md b/docs/recording.md new file mode 100644 index 0000000..2b90c3e --- /dev/null +++ b/docs/recording.md @@ -0,0 +1,93 @@ +# Recordings + +A recording holds the messages of several topics in one file, in the order +they arrived, so they can be replayed later or read by a program. +`puppet_master_topic record` writes them, `replay` publishes them again, and +`info` summarizes them; see [Topic Tool](launcher.md#topic-tool). + +```bash +puppet_master_topic record -o drive.pmrec --system system.json --duration-ms 60000 +puppet_master_topic info drive.pmrec +puppet_master_topic replay drive.pmrec /vehicle/imu /vehicle/wheel_speed --rate 2 +``` + +## Recording + +`record` subscribes to the topics named, or with none named, to every +shared-memory topic found: those with a segment on this host, or with +`--system FILE`, those the manifest's nodes declare. It stops after +`--count N` messages in total, after `--duration-ms N`, or on Ctrl+C, and +prints how many messages of each topic it recorded and lost. + +The recorder is an ordinary reader that queues up to one ring per topic. It +never slows a writer down. When it falls behind by more than a ring, the +oldest messages are overwritten and counted as lost. A larger `slot_count` +in the deployment gives it more room. + +Each message is stored with its payload, the writer's sequence number, and +its publish time relative to the start of the recording. Each topic is +stored with its name, its message descriptor (type, encoding, and version), +and the shared-memory domain and ring size it was recorded from. + +The recorder flushes the file every 200 ms. If it is killed, the file ends +inside a record at worst; readers stop there and report the recording as cut +off, and everything before is kept. + +## Replaying + +`replay` publishes the messages of every topic, or of the topics named, with +the descriptor, domain, and ring size each was recorded with. `--domain N` +publishes to another domain instead, for example to replay next to a live +system without disturbing it. + +Messages keep their recorded spacing, measured from the first message +replayed. `--rate 2` replays twice as fast, `--rate 0.5` at half speed, and +`--rate 0` publishes everything at once. Readers see new sequence numbers and +publish times, as from any other writer. + +Stop the system's own writers of a topic before replaying it, or readers +receive both. + +## Reading In C++ + +`RecordingReader` and `RecordingWriter` in +`puppet_master/transport/recording.h` are in the core library and need no +transport: + +```cpp +auto recording = transport::RecordingReader::Open("drive.pmrec"); +if (!recording.ok()) { /* missing, not a recording, or a newer format */ } +while (true) { + auto next = recording.value()->Next(); + if (!next.ok()) { /* corrupt */ } + if (!next.value()) { + break; // the end; truncated() tells whether it was cut off + } + const auto& message = *next.value(); + const auto* topic = recording.value()->FindTopic(message.topic); + // topic->name, topic->descriptor, message.time, message.payload +} +``` + +Topics are declared before their first message, so `FindTopic` always finds +the topic of a message just read. `topics()` grows as the file is read. + +## File Format + +All integers are little-endian. A string is a `u32` byte count followed by +the bytes. + +| Part | Contents | +|---|---| +| file header | `"PMREC001"`, `u32` format version (1), `u32` reserved (0) | +| record | `u32` kind, `u32` body size, body | +| topic body (kind 1) | `u32` id, string name, string type, string encoding, `u32` message version, `u32` parameter count, then each parameter as two strings, key and value | +| message body (kind 2) | `u32` topic id, `i64` time in ns since the start, `u64` sequence, payload (the rest of the body) | + +Topic ids start at 1, in the order topics are declared. Readers skip records +of unknown kinds, so later versions can add kinds without breaking them. A +change to an existing record raises the format version, which older readers +refuse. + +The recorder stores these topic parameters: `transport` (`shm`), +`domain_id`, `slot_payload_size`, and `slot_count`. diff --git a/include/puppet_master/transport/recording.h b/include/puppet_master/transport/recording.h new file mode 100644 index 0000000..c30e66c --- /dev/null +++ b/include/puppet_master/transport/recording.h @@ -0,0 +1,93 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +// Recordings: messages of several topics in one file, in arrival order, for +// replaying them later or reading them from a program. Written by +// `puppet_master_topic record`. The format is documented in +// docs/recording.md; it does not depend on a transport. +namespace puppet_master::transport { + +// One topic of a recording. +struct RecordedTopic { + std::uint32_t id {0}; // assigned by RecordingWriter::AddTopic + std::string name; + MessageDescriptor descriptor; + // Free-form settings, such as the transport the topic was recorded from + // and its shared-memory ring size, so a replay can recreate it. + std::map parameters; +}; + +struct RecordedMessage { + std::uint32_t topic {0}; // RecordedTopic::id + core::Nanoseconds time {0}; // since the recording started + core::SequenceNumber sequence {0}; // as the writer numbered it + ByteBuffer payload; +}; + +// Writes a recording. Not thread-safe. +class PUPPET_MASTER_API RecordingWriter final { +public: + // Creates `path`, replacing an existing file. + static core::Result> Create(const std::string& path); + + ~RecordingWriter(); // closes + RecordingWriter(const RecordingWriter&) = delete; + RecordingWriter& operator=(const RecordingWriter&) = delete; + + // Declares a topic and returns its id; the id in `topic` is ignored. + core::Result AddTopic(const RecordedTopic& topic); + + core::Status Write(std::uint32_t topic, core::Nanoseconds time, core::SequenceNumber sequence, ByteView payload); + + // Pushes buffered records to the file, so a reader (or a crash) sees + // everything written so far. + core::Status Flush(); + core::Status Close(); + + std::uint64_t message_count() const noexcept; + +private: + struct Impl; + explicit RecordingWriter(std::unique_ptr impl); + std::unique_ptr impl_; +}; + +// Reads a recording front to back. Not thread-safe. +class PUPPET_MASTER_API RecordingReader final { +public: + static core::Result> Open(const std::string& path); + + ~RecordingReader(); + RecordingReader(const RecordingReader&) = delete; + RecordingReader& operator=(const RecordingReader&) = delete; + + // The next message, or none at the end. Topics are declared before their + // first message, and topics() grows as they are read. A recording that + // ends inside a record, as one cut off by a crash does, ends there: + // truncated() tells. Records of unknown kinds are skipped. + core::Result> Next(); + + const std::vector& topics() const noexcept; + // The topic with this id, or nullptr. + const RecordedTopic* FindTopic(std::uint32_t id) const noexcept; + bool truncated() const noexcept; + +private: + struct Impl; + explicit RecordingReader(std::unique_ptr impl); + std::unique_ptr impl_; +}; + +} // namespace puppet_master::transport diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index d158406..6df3bb9 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -39,6 +39,7 @@ set(PUPPETMASTER_PUBLIC_HEADERS "${PROJECT_SOURCE_DIR}/include/puppet_master/service/service.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/service/typed_service.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/transport/message.h" + "${PROJECT_SOURCE_DIR}/include/puppet_master/transport/recording.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/transport/registry.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/transport/transport.h" "${PROJECT_SOURCE_DIR}/include/puppet_master/transport/portable_codec.h" @@ -63,6 +64,7 @@ add_library(puppet_master scheduler/scheduler.cpp service/service.cpp transport/inmemory/inmemory_transport.cpp + transport/recording.cpp ${PUPPETMASTER_PUBLIC_HEADERS} ) diff --git a/src/transport/recording.cpp b/src/transport/recording.cpp new file mode 100644 index 0000000..c8a61e8 --- /dev/null +++ b/src/transport/recording.cpp @@ -0,0 +1,412 @@ +#include + +#include +#include +#include +#include +#include + +// Layout (docs/recording.md), little-endian throughout: +// file header "PMREC001", u32 format version, u32 reserved +// record u32 kind, u32 body size, body +// topic body u32 id, str name, str type, str encoding, u32 version, +// u32 parameter count, (str key, str value)... +// message body u32 topic, i64 time ns, u64 sequence, payload (the rest) +// str u32 size, bytes +namespace puppet_master::transport { + +namespace { + +constexpr char kMagic[8] = {'P', 'M', 'R', 'E', 'C', '0', '0', '1'}; +constexpr std::uint32_t kFormatVersion = 1; +constexpr std::size_t kFileHeaderSize = 16; +constexpr std::size_t kRecordHeaderSize = 8; +constexpr std::uint32_t kTopicRecord = 1; +constexpr std::uint32_t kMessageRecord = 2; +constexpr std::size_t kMessageFixedSize = 4 + 8 + 8; +constexpr std::size_t kMaxRecordSize = std::numeric_limits::max(); + +void PutU32(ByteBuffer& out, std::uint32_t value) +{ + for (int shift = 0; shift < 32; shift += 8) { + out.push_back(static_cast(value >> shift)); + } +} + +void PutU64(ByteBuffer& out, std::uint64_t value) +{ + for (int shift = 0; shift < 64; shift += 8) { + out.push_back(static_cast(value >> shift)); + } +} + +void PutString(ByteBuffer& out, const std::string& text) +{ + PutU32(out, static_cast(text.size())); + out.insert(out.end(), text.begin(), text.end()); +} + +std::uint32_t GetU32(const core::Byte* data) +{ + std::uint32_t value = 0; + for (int index = 3; index >= 0; --index) { + value = (value << 8) | data[index]; + } + return value; +} + +std::uint64_t GetU64(const core::Byte* data) +{ + std::uint64_t value = 0; + for (int index = 7; index >= 0; --index) { + value = (value << 8) | data[index]; + } + return value; +} + +// Bounds-checked reads from one record body. +class BodyReader { +public: + explicit BodyReader(const ByteBuffer& body) : body_(body) {} + + bool U32(std::uint32_t& value) + { + if (left() < 4) { + return false; + } + value = GetU32(body_.data() + offset_); + offset_ += 4; + return true; + } + + bool String(std::string& text) + { + std::uint32_t size = 0; + if (!U32(size) || left() < size) { + return false; + } + text.assign(reinterpret_cast(body_.data() + offset_), size); + offset_ += size; + return true; + } + +private: + std::size_t left() const noexcept { return body_.size() - offset_; } + + const ByteBuffer& body_; + std::size_t offset_ {0}; +}; + +bool TooLong(const std::string& text) +{ + return text.size() > std::numeric_limits::max(); +} + +} // namespace + +// --- writer ------------------------------------------------------------- + +struct RecordingWriter::Impl { + std::string path; + std::ofstream out; + std::vector topics; // declared ids, in order + std::uint64_t messages {0}; + ByteBuffer scratch; + bool closed {false}; + + core::Status Failed(const std::string& what) const + { + return core::Status::Unavailable(what + " " + path + " failed"); + } + + core::Status Emit(std::uint32_t kind, const ByteBuffer& body, ByteView tail = {}) + { + if (closed) { + return core::Status::FailedPrecondition("recording " + path + " is closed"); + } + const std::size_t size = body.size() + tail.size(); + if (size > kMaxRecordSize) { + return core::Status::InvalidArgument("record of " + std::to_string(size) + " bytes is too large"); + } + ByteBuffer header; + PutU32(header, kind); + PutU32(header, static_cast(size)); + out.write(reinterpret_cast(header.data()), static_cast(header.size())); + out.write(reinterpret_cast(body.data()), static_cast(body.size())); + if (tail.size() != 0) { + out.write(reinterpret_cast(tail.data()), static_cast(tail.size())); + } + return out ? core::Status::Ok() : Failed("writing"); + } +}; + +RecordingWriter::RecordingWriter(std::unique_ptr impl) : impl_(std::move(impl)) {} + +RecordingWriter::~RecordingWriter() +{ + Close(); +} + +core::Result> RecordingWriter::Create(const std::string& path) +{ + using ResultType = core::Result>; + auto impl = std::make_unique(); + impl->path = path; + impl->out.open(path, std::ios::binary | std::ios::trunc); + if (!impl->out) { + return ResultType::FromStatus(core::Status::Unavailable("cannot create recording " + path)); + } + ByteBuffer header(kMagic, kMagic + sizeof(kMagic)); + PutU32(header, kFormatVersion); + PutU32(header, 0); + impl->out.write(reinterpret_cast(header.data()), static_cast(header.size())); + if (!impl->out) { + return ResultType::FromStatus(impl->Failed("writing")); + } + return ResultType(std::unique_ptr(new RecordingWriter(std::move(impl)))); +} + +core::Result RecordingWriter::AddTopic(const RecordedTopic& topic) +{ + using ResultType = core::Result; + auto status = core::ValidateName("topic name", topic.name); + if (status.ok()) { + status = topic.descriptor.Validate(); + } + if (!status.ok()) { + return ResultType::FromStatus(std::move(status)); + } + const auto id = static_cast(impl_->topics.size() + 1); + ByteBuffer body; + PutU32(body, id); + PutString(body, topic.name); + PutString(body, topic.descriptor.type_name); + PutString(body, topic.descriptor.encoding); + PutU32(body, topic.descriptor.version); + PutU32(body, static_cast(topic.parameters.size())); + for (const auto& entry : topic.parameters) { + if (TooLong(entry.first) || TooLong(entry.second)) { + return ResultType::FromStatus(core::Status::InvalidArgument("topic parameter is too long")); + } + PutString(body, entry.first); + PutString(body, entry.second); + } + status = impl_->Emit(kTopicRecord, body); + if (!status.ok()) { + return ResultType::FromStatus(std::move(status)); + } + impl_->topics.push_back(id); + return ResultType(id); +} + +core::Status RecordingWriter::Write( + std::uint32_t topic, core::Nanoseconds time, core::SequenceNumber sequence, ByteView payload) +{ + if (topic == 0 || topic > impl_->topics.size()) { + return core::Status::InvalidArgument("topic id " + std::to_string(topic) + " was not added"); + } + if (time.count() < 0) { + return core::Status::InvalidArgument("message time must not be negative"); + } + auto& body = impl_->scratch; + body.clear(); + PutU32(body, topic); + PutU64(body, static_cast(time.count())); + PutU64(body, sequence); + auto status = impl_->Emit(kMessageRecord, body, payload); + if (status.ok()) { + ++impl_->messages; + } + return status; +} + +core::Status RecordingWriter::Flush() +{ + if (impl_->closed) { + return core::Status::FailedPrecondition("recording " + impl_->path + " is closed"); + } + impl_->out.flush(); + return impl_->out ? core::Status::Ok() : impl_->Failed("flushing"); +} + +core::Status RecordingWriter::Close() +{ + if (impl_->closed) { + return core::Status::Ok(); + } + impl_->closed = true; + impl_->out.close(); + return impl_->out ? core::Status::Ok() : impl_->Failed("closing"); +} + +std::uint64_t RecordingWriter::message_count() const noexcept +{ + return impl_->messages; +} + +// --- reader ------------------------------------------------------------- + +struct RecordingReader::Impl { + std::string path; + std::ifstream in; + std::vector topics; + ByteBuffer body; + std::uint64_t file_size {0}; + std::uint64_t position {kFileHeaderSize}; // of the next record + bool truncated {false}; + bool ended {false}; + + core::Status Corrupt(const std::string& what) const + { + return core::Status::DataLoss("recording " + path + ": " + what); + } + + // Reads exactly `size` bytes; false at the end of the file. + bool ReadExactly(core::Byte* data, std::size_t size) + { + in.read(reinterpret_cast(data), static_cast(size)); + return static_cast(in.gcount()) == size; + } + + core::Status DecodeTopic() + { + BodyReader reader(body); + RecordedTopic topic; + std::uint32_t count = 0; + if (!reader.U32(topic.id) || !reader.String(topic.name) || !reader.String(topic.descriptor.type_name) || + !reader.String(topic.descriptor.encoding) || !reader.U32(topic.descriptor.version) || + !reader.U32(count)) { + return Corrupt("malformed topic record"); + } + for (std::uint32_t index = 0; index < count; ++index) { + std::string key; + std::string value; + if (!reader.String(key) || !reader.String(value)) { + return Corrupt("malformed topic record"); + } + topic.parameters[std::move(key)] = std::move(value); + } + if (topic.id == 0 || FindTopic(topic.id) != nullptr) { + return Corrupt("topic id " + std::to_string(topic.id) + " is invalid or declared twice"); + } + topics.push_back(std::move(topic)); + return core::Status::Ok(); + } + + const RecordedTopic* FindTopic(std::uint32_t id) const noexcept + { + for (const auto& topic : topics) { + if (topic.id == id) { + return &topic; + } + } + return nullptr; + } +}; + +RecordingReader::RecordingReader(std::unique_ptr impl) : impl_(std::move(impl)) {} + +RecordingReader::~RecordingReader() = default; + +core::Result> RecordingReader::Open(const std::string& path) +{ + using ResultType = core::Result>; + auto impl = std::make_unique(); + impl->path = path; + impl->in.open(path, std::ios::binary | std::ios::ate); + if (!impl->in) { + return ResultType::FromStatus(core::Status::NotFound("cannot open recording " + path)); + } + impl->file_size = static_cast(impl->in.tellg()); + impl->in.seekg(0); + core::Byte header[kFileHeaderSize] {}; + if (!impl->ReadExactly(header, sizeof(header)) || std::memcmp(header, kMagic, sizeof(kMagic)) != 0) { + return ResultType::FromStatus(core::Status::InvalidArgument(path + " is not a PuppetMaster recording")); + } + const auto version = GetU32(header + 8); + if (version != kFormatVersion) { + return ResultType::FromStatus(core::Status::Unsupported( + "recording " + path + " has format version " + std::to_string(version) + ", expected " + + std::to_string(kFormatVersion))); + } + return ResultType(std::unique_ptr(new RecordingReader(std::move(impl)))); +} + +core::Result> RecordingReader::Next() +{ + using ResultType = core::Result>; + auto& impl = *impl_; + while (!impl.ended) { + core::Byte header[kRecordHeaderSize] {}; + impl.in.read(reinterpret_cast(header), sizeof(header)); + const auto got = static_cast(impl.in.gcount()); + if (got != sizeof(header)) { + // A clean end falls between records; anything else was cut off. + impl.truncated = got != 0; + impl.ended = true; + break; + } + const auto kind = GetU32(header); + const auto size = GetU32(header + 4); + impl.position += sizeof(header); + // A size past the end of the file is a cut-off record; checking it + // first keeps a garbage size from allocating gigabytes. + if (size > impl.file_size - std::min(impl.file_size, impl.position)) { + impl.truncated = true; + impl.ended = true; + break; + } + impl.body.resize(size); + if (!impl.ReadExactly(impl.body.data(), size)) { + impl.truncated = true; + impl.ended = true; + break; + } + impl.position += size; + if (kind == kTopicRecord) { + auto status = impl.DecodeTopic(); + if (!status.ok()) { + return ResultType::FromStatus(std::move(status)); + } + continue; + } + if (kind != kMessageRecord) { + continue; // a newer record kind: skip it + } + if (size < kMessageFixedSize) { + return ResultType::FromStatus(impl.Corrupt("malformed message record")); + } + RecordedMessage message; + message.topic = GetU32(impl.body.data()); + const auto time = GetU64(impl.body.data() + 4); + if (time > static_cast(std::numeric_limits::max())) { + return ResultType::FromStatus(impl.Corrupt("message time out of range")); + } + message.time = core::Nanoseconds(static_cast(time)); + message.sequence = GetU64(impl.body.data() + 12); + if (impl.FindTopic(message.topic) == nullptr) { + return ResultType::FromStatus( + impl.Corrupt("message of undeclared topic id " + std::to_string(message.topic))); + } + message.payload.assign(impl.body.begin() + kMessageFixedSize, impl.body.end()); + return ResultType(std::optional(std::move(message))); + } + return ResultType(std::optional()); +} + +const std::vector& RecordingReader::topics() const noexcept +{ + return impl_->topics; +} + +const RecordedTopic* RecordingReader::FindTopic(std::uint32_t id) const noexcept +{ + return impl_->FindTopic(id); +} + +bool RecordingReader::truncated() const noexcept +{ + return impl_->truncated; +} + +} // namespace puppet_master::transport diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index e742512..ad46436 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -74,6 +74,20 @@ add_test( COMMAND puppet_master_portable_codec_test ) +add_executable(puppet_master_recording_test + recording_test.cpp +) + +target_link_libraries(puppet_master_recording_test + PRIVATE + PuppetMaster::PuppetMaster +) + +add_test( + NAME puppet_master.recording + COMMAND puppet_master_recording_test +) + add_executable(puppet_master_component_parameters_test component_parameters_test.cpp ) diff --git a/test/recording_test.cpp b/test/recording_test.cpp new file mode 100644 index 0000000..ce22139 --- /dev/null +++ b/test/recording_test.cpp @@ -0,0 +1,230 @@ +// Recordings: round trip, cut-off files, and malformed input. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace core = puppet_master::core; +namespace fs = std::filesystem; +namespace transport = puppet_master::transport; + +using namespace std::chrono_literals; + +namespace { + +class TempFile { +public: + explicit TempFile(const std::string& name) + : path_(fs::temp_directory_path() + / ("pm_recording_" + name + "_" + + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".pmrec")) + { + } + ~TempFile() + { + std::error_code ignored; + fs::remove(path_, ignored); + } + + std::string str() const { return path_.string(); } + + std::vector Bytes() const + { + std::ifstream in(path_, std::ios::binary); + return std::vector(std::istreambuf_iterator(in), std::istreambuf_iterator()); + } + + void Replace(const std::vector& bytes) const + { + std::ofstream(path_, std::ios::binary | std::ios::trunc).write(bytes.data(), bytes.size()); + } + +private: + fs::path path_; +}; + +transport::ByteView View(const std::string& text) +{ + return transport::ByteView::From(text.data(), text.size()); +} + +std::string Text(const transport::ByteBuffer& bytes) +{ + return std::string(bytes.begin(), bytes.end()); +} + +transport::RecordedTopic Topic(const std::string& name, const std::string& type) +{ + transport::RecordedTopic topic; + topic.name = name; + topic.descriptor = transport::MessageDescriptor {type, "application/x-test", 3}; + return topic; +} + +// Writes two topics and three messages, the last one empty. +void WriteSample(const TempFile& file) +{ + auto writer = transport::RecordingWriter::Create(file.str()); + assert(writer.ok()); + auto speed = Topic("/demo/speed", "demo.Speed"); + speed.parameters = {{"transport", "shm"}, {"slot_count", "8"}}; + const auto speed_id = writer.value()->AddTopic(speed); + assert(speed_id.ok() && speed_id.value() == 1); + assert(writer.value()->Write(1, 0ns, 10, View("first")).ok()); + const auto text_id = writer.value()->AddTopic(Topic("/demo/text", "demo.Text")); + assert(text_id.ok() && text_id.value() == 2); + assert(writer.value()->Write(2, 1500us, 4, View("second")).ok()); + assert(writer.value()->Write(1, 3ms, 11, View("")).ok()); + assert(writer.value()->message_count() == 3); + assert(writer.value()->Close().ok()); + assert(writer.value()->Close().ok()); // twice is fine + assert(writer.value()->Write(1, 4ms, 12, View("late")).code() == core::StatusCode::kFailedPrecondition); +} + +void TestRoundTrip() +{ + TempFile file("round_trip"); + WriteSample(file); + + auto reader = transport::RecordingReader::Open(file.str()); + assert(reader.ok()); + auto& recording = *reader.value(); + + auto first = recording.Next(); + assert(first.ok() && first.value()); + assert(first.value()->topic == 1 && first.value()->time == 0ns && first.value()->sequence == 10); + assert(Text(first.value()->payload) == "first"); + assert(recording.topics().size() == 1); // the second is not read yet + + auto second = recording.Next(); + assert(second.ok() && second.value()); + assert(second.value()->topic == 2 && second.value()->time == 1500us && second.value()->sequence == 4); + assert(Text(second.value()->payload) == "second"); + + auto third = recording.Next(); + assert(third.ok() && third.value() && third.value()->payload.empty() && third.value()->time == 3ms); + + auto end = recording.Next(); + assert(end.ok() && !end.value()); + assert(!recording.truncated()); + assert(recording.Next().ok()); // stays at the end + + assert(recording.topics().size() == 2); + const auto* speed = recording.FindTopic(1); + assert(speed != nullptr && speed->name == "/demo/speed"); + assert(speed->descriptor == (transport::MessageDescriptor {"demo.Speed", "application/x-test", 3})); + assert(speed->parameters.at("transport") == "shm" && speed->parameters.at("slot_count") == "8"); + assert(recording.FindTopic(3) == nullptr); +} + +void TestCutOffRecording() +{ + TempFile file("cut"); + WriteSample(file); + auto bytes = file.Bytes(); + // The last record is an 8-byte header and a 20-byte body (empty payload): + // cut inside its body, then inside its header. + for (const std::size_t cut : {std::size_t {10}, std::size_t {25}}) { + file.Replace(std::vector(bytes.begin(), bytes.end() - static_cast(cut))); + auto reader = transport::RecordingReader::Open(file.str()); + assert(reader.ok()); + int messages = 0; + while (true) { + auto next = reader.value()->Next(); + assert(next.ok()); + if (!next.value()) { + break; + } + ++messages; + } + assert(messages == 2); + assert(reader.value()->truncated()); + } +} + +void TestMalformed() +{ + TempFile file("bad"); + file.Replace({'n', 'o', 't', ' ', 'a', ' ', 'r', 'e', 'c', 'o', 'r', 'd', 'i', 'n', 'g', '!'}); + assert(transport::RecordingReader::Open(file.str()).status().code() == core::StatusCode::kInvalidArgument); + + WriteSample(file); + auto bytes = file.Bytes(); + bytes[8] = 9; // format version + file.Replace(bytes); + assert(transport::RecordingReader::Open(file.str()).status().code() == core::StatusCode::kUnsupported); + + // A garbage record size larger than the file ends the read as cut off, + // without trying to allocate it. + WriteSample(file); + bytes = file.Bytes(); + bytes[16 + 4] = '\xff'; + bytes[16 + 5] = '\xff'; + bytes[16 + 6] = '\xff'; + bytes[16 + 7] = '\x7f'; + file.Replace(bytes); + auto reader = transport::RecordingReader::Open(file.str()); + assert(reader.ok()); + auto next = reader.value()->Next(); + assert(next.ok() && !next.value() && reader.value()->truncated()); + + // A message whose topic was never declared. + { + auto writer = transport::RecordingWriter::Create(file.str()); + assert(writer.ok()); + assert(writer.value()->AddTopic(Topic("/demo/a", "demo.A")).ok()); + assert(writer.value()->Write(1, 0ns, 1, View("x")).ok()); + assert(writer.value()->Close().ok()); + } + bytes = file.Bytes(); + // First record is the topic; find the message record's topic id: the + // last 1 + 20 bytes are its body. + bytes[bytes.size() - 21] = 5; + file.Replace(bytes); + reader = transport::RecordingReader::Open(file.str()); + assert(reader.ok()); + next = reader.value()->Next(); + assert(next.status().code() == core::StatusCode::kDataLoss); + + assert(transport::RecordingReader::Open(file.str() + ".missing").status().code() == core::StatusCode::kNotFound); +} + +void TestWriterChecks() +{ + TempFile file("checks"); + auto writer = transport::RecordingWriter::Create(file.str()); + assert(writer.ok()); + assert(writer.value()->Write(1, 0ns, 1, View("x")).code() == core::StatusCode::kInvalidArgument); + assert(!writer.value()->AddTopic(Topic("", "demo.A")).ok()); + assert(!writer.value()->AddTopic(Topic("/demo/a", "")).ok()); + assert(writer.value()->AddTopic(Topic("/demo/a", "demo.A")).ok()); + assert(writer.value()->Write(1, -1ns, 1, View("x")).code() == core::StatusCode::kInvalidArgument); + assert(writer.value()->Flush().ok()); + + // Flushed records are readable while the writer is still open. + auto reader = transport::RecordingReader::Open(file.str()); + assert(reader.ok()); + assert(reader.value()->Next().ok()); + assert(reader.value()->topics().size() == 1); + + assert(transport::RecordingWriter::Create((fs::path(file.str()) / "no" / "dir.pmrec").string()).status().code() + == core::StatusCode::kUnavailable); +} + +} // namespace + +int main() +{ + TestRoundTrip(); + TestCutOffRecording(); + TestMalformed(); + TestWriterChecks(); + return 0; +} diff --git a/test/topic_tool_test.cpp b/test/topic_tool_test.cpp index 740feb4..8e958b3 100644 --- a/test/topic_tool_test.cpp +++ b/test/topic_tool_test.cpp @@ -79,14 +79,31 @@ class Fixture { options.topics[topic_] = shm::TopicOptions {256, 8}; transport_ = std::make_unique(core::TransportName::Create("test").value(), options); assert(transport_->Open().ok()); - const transport::EndpointConfig endpoint { - core::TopicSpec {core::TopicName::Create(topic_).value(), core::TransportKind::kIpc, {}}, - transport::MessageDescriptor {"test.Text", "application/octet-stream", 0}}; - auto writer = transport_->CreateWriter(endpoint); + auto writer = transport_->CreateWriter(Endpoint({})); assert(writer.ok()); writer_ = writer.value(); } + transport::EndpointConfig Endpoint(core::MessagePolicy policy) const + { + return transport::EndpointConfig { + core::TopicSpec {core::TopicName::Create(topic_).value(), core::TransportKind::kIpc, policy}, + transport::MessageDescriptor {"test.Text", "application/octet-stream", 0}}; + } + + // A reader in this process that queues a whole ring. + transport::ReaderPtr Subscribe() + { + core::MessagePolicy policy; + policy.freshness = core::FreshnessPolicy::kQueued; + policy.queue_depth = 8; + auto reader = transport_->CreateReader(Endpoint(policy)); + assert(reader.ok()); + return reader.value(); + } + + std::string File(const std::string& name) const { return (root_ / name).string(); } + ~Fixture() { writer_.reset(); @@ -217,6 +234,77 @@ void TestErrors(Fixture& fixture, const std::string& tool) assert(run.exit.code == 2); } +std::vector Drain(const transport::ReaderPtr& reader) +{ + std::vector payloads; + while (true) { + auto message = reader->Read(); + if (!message.ok()) { + return payloads; + } + payloads.emplace_back(message.value().payload.begin(), message.value().payload.end()); + } +} + +void TestRecordInfoReplay(Fixture& fixture, const std::string& tool) +{ + const auto file = fixture.File("capture.pmrec"); + + // With no topic named, every topic of the system is recorded. + auto run = fixture.Run( + {tool, "record", "-o", file, "--system", fixture.system(), "--count", "5", "--duration-ms", "20000"}, 10ms); + assert(run.exit.success()); + assert(Contains(run.output, "record " + fixture.topic() + ": 5 messages, 0 lost")); + assert(Contains(run.output, "record: 5 messages to ")); + + run = fixture.Run({tool, "info", file}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, ": 1 topics, 5 messages, ")); + assert(Contains(run.output, fixture.topic() + " test.Text (application/octet-stream) 5 messages, ")); + assert(Contains(run.output, "shm domain 77, 256 B x 8 slots")); + + // As fast as possible: the payloads come back in order. + { + auto reader = fixture.Subscribe(); + run = fixture.Run({tool, "replay", file, "--rate", "0"}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, "replay: 5 messages")); + const auto payloads = Drain(reader); + assert(payloads.size() == 5); + const int first = std::stoi(payloads.front().substr(6)); + for (int index = 0; index < 5; ++index) { + assert(payloads[static_cast(index)] == "hello " + std::to_string(first + index)); + } + } + + // At the recorded pace: about 10 ms between messages, so 40 ms or more. + { + auto reader = fixture.Subscribe(); + const auto started = std::chrono::steady_clock::now(); + run = fixture.Run({tool, "replay", file, fixture.topic()}, 0ms); + assert(run.exit.success()); + assert(std::chrono::steady_clock::now() - started >= 35ms); + assert(Drain(reader).size() == 5); + } + + // Topics left out are not replayed; one not in the recording is an error. + { + auto reader = fixture.Subscribe(); + run = fixture.Run({tool, "replay", file, "/pm_topic_test/nobody", "--rate", "0"}, 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "topic /pm_topic_test/nobody is not in")); + assert(Contains(run.output, "replay: 0 messages")); + assert(Drain(reader).empty()); + } + + run = fixture.Run({tool, "info", fixture.File("missing.pmrec")}, 0ms); + assert(run.exit.code == 1); + run = fixture.Run({tool, "record", fixture.topic()}, 0ms); // no -o + assert(run.exit.code == 2); + run = fixture.Run({tool, "replay", file, "--rate", "fast"}, 0ms); + assert(run.exit.code == 2); +} + #if !defined(_WIN32) void TestListFromSegments(Fixture& fixture, const std::string& tool) { @@ -252,6 +340,7 @@ int main(int argc, char** argv) TestEchoTimesOut(fixture, tool); TestHz(fixture, tool); TestErrors(fixture, tool); + TestRecordInfoReplay(fixture, tool); #if !defined(_WIN32) // Segment headers can only be read on Linux. TestListFromSegments(fixture, tool); diff --git a/tools/puppet_master_topic.cpp b/tools/puppet_master_topic.cpp index 11da385..6250781 100644 --- a/tools/puppet_master_topic.cpp +++ b/tools/puppet_master_topic.cpp @@ -15,20 +15,24 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include #include #include +#include #include #include #include +#include #include namespace config = puppet_master::configuration; @@ -69,14 +73,27 @@ int Usage(std::ostream& out) << " --bytes N echo: show at most N bytes of each message in hex (default 32)\n" << " --text echo: print the payload as text instead\n" << " --window-ms N hz: report every N ms (default 1000)\n" - << " --duration-ms N hz: stop after N ms\n" - << "Ctrl+C stops echo and hz.\n"; + << " --duration-ms N hz, record: stop after N ms\n" + << " puppet_master_topic record [...] -o FILE [--system FILE] [--domain N]\n" + << " [--count N] [--duration-ms N]\n" + << " puppet_master_topic replay FILE [...] [--domain N] [--rate X]\n" + << " puppet_master_topic info FILE\n" + << " record write the topics' messages to FILE; with no topic, every\n" + << " shm topic found (or the system's, with --system)\n" + << " -o FILE record: the recording to write, replacing it\n" + << " --count N record: stop after N messages in total\n" + << " replay publish a recording's messages again (all, or the topics\n" + << " named) at their recorded pace\n" + << " --rate X replay: X times the recorded pace; 0 publishes at once\n" + << " info the topics, message counts, and length of a recording\n" + << "Ctrl+C stops echo, hz, record, and replay.\n"; return 2; } struct Arguments { std::string command; - std::string topic; + std::vector topics; + std::string file; // record: -o; replay, info: the first operand std::string system; std::optional domain; std::uint64_t count {0}; @@ -85,8 +102,19 @@ struct Arguments { milliseconds duration {0}; std::uint64_t bytes {32}; bool text {false}; + double rate {1.0}; }; +bool ParseRate(const std::string& text, double& value) +{ + if (text.empty() || text.size() > 12 || text.find_first_not_of("0123456789.") != std::string::npos || + text.find('.') != text.rfind('.') || text == ".") { + return false; + } + value = std::stod(text); + return value <= 1000.0; +} + bool ParseNumber(const std::string& text, std::uint64_t& value) { if (text.empty() || text.size() > 12 || text.find_first_not_of("0123456789") != std::string::npos) { @@ -107,9 +135,12 @@ int Parse(int argc, char** argv, Arguments& args) Usage(std::cout); return -1; } - if (args.command != "list" && args.command != "echo" && args.command != "hz") { + const std::set commands {"list", "echo", "hz", "record", "replay", "info"}; + if (commands.count(args.command) == 0) { return Usage(std::cerr); } + const bool echo = args.command == "echo"; + const bool record = args.command == "record"; for (int index = 2; index < argc; ++index) { const std::string argument = argv[index]; const bool has_value = index + 1 < argc; @@ -129,7 +160,7 @@ int Parse(int argc, char** argv, Arguments& args) return 2; } args.domain = static_cast(number); - } else if (argument == "--count" && args.command == "echo") { + } else if (argument == "--count" && (echo || record)) { if (!numeric("--count")) { return 2; } @@ -151,18 +182,35 @@ int Parse(int argc, char** argv, Arguments& args) return 2; } args.window = milliseconds(number); - } else if (argument == "--duration-ms" && args.command == "hz") { + } else if (argument == "--duration-ms" && (args.command == "hz" || record)) { if (!numeric("--duration-ms")) { return 2; } args.duration = milliseconds(number); - } else if (!argument.empty() && argument[0] != '-' && args.topic.empty() && args.command != "list") { - args.topic = argument; + } else if ((argument == "-o" || argument == "--output") && record && has_value) { + args.file = argv[++index]; + } else if (argument == "--rate" && args.command == "replay") { + if (!has_value || !ParseRate(argv[index + 1], args.rate)) { + std::cerr << "--rate needs a number from 0 to 1000\n"; + return 2; + } + ++index; + } else if (!argument.empty() && argument[0] != '-' && args.command != "list") { + const bool takes_file = args.command == "replay" || args.command == "info"; + if (takes_file && args.file.empty()) { + args.file = argument; + } else if (args.command == "info") { + return Usage(std::cerr); + } else { + args.topics.push_back(argument); + } } else { return Usage(std::cerr); } } - if (args.command != "list" && args.topic.empty()) { + const bool one_topic = echo || args.command == "hz"; + if ((one_topic && args.topics.size() != 1) || + ((record || args.command == "replay" || args.command == "info") && args.file.empty())) { return Usage(std::cerr); } return 0; @@ -289,40 +337,51 @@ Topics TopicsFromSystem(const std::string& path, std::optional d return Topics(std::move(topics)); } -core::Result FindTopic(const Arguments& args) +Topics LoadTopics(const Arguments& args) +{ + return args.system.empty() ? TopicsFromSegments(args.domain) : TopicsFromSystem(args.system, args.domain); +} + +// The one shared-memory topic called `name` among `topics`. +core::Result FindTopic(const Arguments& args, const std::vector& topics, const std::string& name) { using ResultType = core::Result; - auto topics = args.system.empty() ? TopicsFromSegments(args.domain) : TopicsFromSystem(args.system, args.domain); - if (!topics.ok()) { - return ResultType::FromStatus(topics.status()); - } - std::vector matches; - for (auto& topic : topics.value()) { - if (topic.name == args.topic) { - matches.push_back(std::move(topic)); + std::vector matches; + for (const auto& topic : topics) { + if (topic.name == name) { + matches.push_back(&topic); } } if (matches.empty()) { return ResultType::FromStatus(core::Status::NotFound( - args.system.empty() ? "no shm segment for topic " + args.topic + + args.system.empty() ? "no shm segment for topic " + name + " on this host; is its writer running? (--system FILE finds it from the " "manifest instead)" - : "no node of " + args.system + " declares topic " + args.topic)); + : "no node of " + args.system + " declares topic " + name)); } if (matches.size() > 1) { std::string domains; - for (const auto& match : matches) { - domains += (domains.empty() ? "" : ", ") + std::to_string(match.domain); + for (const auto* match : matches) { + domains += (domains.empty() ? "" : ", ") + std::to_string(match->domain); } return ResultType::FromStatus(core::Status::InvalidArgument( - "topic " + args.topic + " exists in domains " + domains + "; pick one with --domain")); + "topic " + name + " exists in domains " + domains + "; pick one with --domain")); } - if (matches.front().transport != core::TransportKind::kIpc) { + if (matches.front()->transport != core::TransportKind::kIpc) { return ResultType::FromStatus(core::Status::Unsupported( - "topic " + args.topic + " uses the " + core::ToString(matches.front().transport) + + "topic " + name + " uses the " + core::ToString(matches.front()->transport) + " transport; puppet_master_topic reads shared-memory topics only")); } - return ResultType(std::move(matches.front())); + return ResultType(*matches.front()); +} + +core::Result FindTopic(const Arguments& args, const std::string& name) +{ + auto topics = LoadTopics(args); + if (!topics.ok()) { + return core::Result::FromStatus(topics.status()); + } + return FindTopic(args, topics.value(), name); } // --- reading ------------------------------------------------------------ @@ -466,7 +525,7 @@ void PrintPayload(const transport::ByteBuffer& payload, const Arguments& args) int Echo(const Arguments& args) { - auto topic = FindTopic(args); + auto topic = FindTopic(args, args.topics.front()); if (!topic.ok()) { std::cerr << topic.status().ToString() << '\n'; return 1; @@ -535,7 +594,7 @@ void Report(const Window& window, Clock::duration elapsed) int Hz(const Arguments& args) { - auto topic = FindTopic(args); + auto topic = FindTopic(args, args.topics.front()); if (!topic.ok()) { std::cerr << topic.status().ToString() << '\n'; return 1; @@ -588,6 +647,401 @@ int Hz(const Arguments& args) return 0; } +// --- record ------------------------------------------------------------- + +// Wakes the recording loop when any of its readers has data. +struct Wakeup { + std::mutex mutex; + std::condition_variable cv; + bool pending {false}; + + void Notify() + { + { + std::lock_guard lock(mutex); + pending = true; + } + cv.notify_one(); + } + + void Wait(milliseconds timeout) + { + std::unique_lock lock(mutex); + cv.wait_for(lock, timeout, [this] { return pending; }); + pending = false; + } +}; + +struct RecordedChannel { + TopicInfo topic; + std::uint32_t id {0}; + std::optional last; + std::uint64_t received {0}; + std::uint64_t lost {0}; + Subscription subscription; // last: its reader's callback uses the wakeup +}; + +std::map RecordedParameters(const TopicInfo& topic) +{ + return { + {"transport", "shm"}, + {"domain_id", std::to_string(topic.domain)}, + {"slot_payload_size", std::to_string(topic.geometry.slot_payload_size)}, + {"slot_count", std::to_string(topic.geometry.slot_count)}, + }; +} + +core::Result> TopicsToRecord(const Arguments& args) +{ + using ResultType = core::Result>; + auto topics = LoadTopics(args); + if (!topics.ok()) { + return ResultType::FromStatus(topics.status()); + } + std::vector chosen; + if (args.topics.empty()) { + for (const auto& topic : topics.value()) { + if (topic.transport == core::TransportKind::kIpc) { + chosen.push_back(topic); + } + } + if (chosen.empty()) { + return ResultType::FromStatus(core::Status::NotFound("no shm topics to record")); + } + return ResultType(std::move(chosen)); + } + for (const auto& name : args.topics) { + auto topic = FindTopic(args, topics.value(), name); + if (!topic.ok()) { + return ResultType::FromStatus(topic.status()); + } + chosen.push_back(std::move(topic).value()); + } + return ResultType(std::move(chosen)); +} + +int Record(const Arguments& args) +{ + auto topics = TopicsToRecord(args); + if (!topics.ok()) { + std::cerr << topics.status().ToString() << '\n'; + return 1; + } + auto recording = transport::RecordingWriter::Create(args.file); + if (!recording.ok()) { + std::cerr << recording.status().ToString() << '\n'; + return 1; + } + auto& writer = *recording.value(); + + Wakeup wakeup; + std::vector> channels; + for (auto& topic : topics.value()) { + auto channel = std::make_unique(); + transport::RecordedTopic recorded; + recorded.name = topic.name; + recorded.descriptor = topic.descriptor; + recorded.parameters = RecordedParameters(topic); + auto id = writer.AddTopic(recorded); + if (!id.ok()) { + std::cerr << id.status().ToString() << '\n'; + return 1; + } + channel->id = id.value(); + auto subscription = Subscribe(topic); + if (!subscription.ok()) { + std::cerr << subscription.status().ToString() << '\n'; + return 1; + } + channel->subscription = std::move(subscription).value(); + auto status = channel->subscription.reader->SetDataAvailableCallback([&wakeup] { wakeup.Notify(); }); + if (!status.ok()) { + std::cerr << status.ToString() << '\n'; + return 1; + } + channel->topic = std::move(topic); + std::cerr << "record " << channel->topic.name << ": " << channel->topic.descriptor.ToString() << std::endl; + channels.push_back(std::move(channel)); + } + + // Times are publish times relative to the start, so the replay keeps the + // writers' pace rather than this reader's. + const auto started = core::TimePoint(std::chrono::duration_cast( + core::SteadyClock::now().time_since_epoch())); + const auto deadline = args.duration.count() == 0 ? Clock::time_point::max() : Clock::now() + args.duration; + auto next_flush = Clock::now() + milliseconds(200); + std::uint64_t total = 0; + const auto done = [&] { return g_stop.load() || (args.count != 0 && total >= args.count); }; + while (!done() && Clock::now() < deadline) { + bool any = false; + for (auto& channel : channels) { + while (!done()) { + auto pending = channel->subscription.reader->PendingMessageCount(); + if (!pending.ok()) { + std::cerr << channel->topic.name << ": " << pending.status().ToString() << '\n'; + return 1; + } + if (pending.value() == 0) { + break; + } + auto message = channel->subscription.reader->Read(); + if (!message.ok()) { + break; // raced with the ring: try again next round + } + any = true; + const auto& metadata = message.value().metadata; + channel->lost += Gap(channel->last, metadata.sequence); + channel->last = metadata.sequence; + ++channel->received; + ++total; + const auto time = std::max(core::Nanoseconds(0), metadata.source_timestamp - started); + auto status = writer.Write(channel->id, time, metadata.sequence, transport::ByteView(message.value().payload)); + if (!status.ok()) { + std::cerr << status.ToString() << '\n'; + return 1; + } + } + } + if (Clock::now() >= next_flush) { + auto status = writer.Flush(); + if (!status.ok()) { + std::cerr << status.ToString() << '\n'; + return 1; + } + next_flush = Clock::now() + milliseconds(200); + } + if (!any) { + const auto left = std::max(deadline - Clock::now(), Clock::duration::zero()); + wakeup.Wait(left < kReadSlice ? std::chrono::duration_cast(left) : kReadSlice); + } + } + for (const auto& channel : channels) { + std::cerr << "record " << channel->topic.name << ": " << channel->received << " messages, " + << channel->lost << " lost" << std::endl; + } + channels.clear(); // stop the callbacks before the wakeup goes away + auto status = writer.Close(); + if (!status.ok()) { + std::cerr << status.ToString() << '\n'; + return 1; + } + std::cerr << "record: " << total << " messages to " << args.file << std::endl; + return 0; +} + +// --- replay and info ---------------------------------------------------- + +std::uint64_t ParameterOr(const transport::RecordedTopic& topic, const std::string& key, std::uint64_t fallback) +{ + const auto found = topic.parameters.find(key); + std::uint64_t value = 0; + return found != topic.parameters.end() && ParseNumber(found->second, value) ? value : fallback; +} + +struct ReplayChannel { + std::unique_ptr shm_transport; + transport::WriterPtr writer; // declared last: released first + std::uint64_t sent {0}; +}; + +// A writer for a recorded topic, with the ring size and domain it was +// recorded with (or --domain). +core::Result> OpenReplayChannel( + const transport::RecordedTopic& topic, const Arguments& args) +{ + using ResultType = core::Result>; + const auto failed = [&topic](const core::Status& status) { + return ResultType::FromStatus( + core::Status::Error(status.code(), "replaying to " + topic.name + ": " + status.message())); + }; + const shm::TopicOptions defaults; + const auto domain = ParameterOr(topic, "domain_id", 0); + if (domain > 0xffffffffULL) { + return failed(core::Status::InvalidArgument("recorded domain_id is out of range")); + } + shm::Options options; + options.domain_id = args.domain ? *args.domain : static_cast(domain); + options.topics[topic.name] = shm::TopicOptions { + static_cast(ParameterOr(topic, "slot_payload_size", defaults.slot_payload_size)), + static_cast(ParameterOr(topic, "slot_count", defaults.slot_count))}; + auto status = options.Validate(); + if (!status.ok()) { + return failed(status); + } + auto topic_name = core::TopicName::Create(topic.name); + if (!topic_name.ok()) { + return failed(topic_name.status()); + } + + auto channel = std::make_unique(); + channel->shm_transport = std::make_unique( + core::TransportName::Create("puppet_master_topic").value(), options); + status = channel->shm_transport->Open(); + if (!status.ok()) { + return failed(status); + } + const transport::EndpointConfig endpoint { + core::TopicSpec {topic_name.value(), core::TransportKind::kIpc, core::MessagePolicy {}}, topic.descriptor}; + auto writer = channel->shm_transport->CreateWriter(endpoint); + if (!writer.ok()) { + return failed(writer.status()); + } + channel->writer = writer.value(); + return ResultType(std::move(channel)); +} + +int Replay(const Arguments& args) +{ + auto opened = transport::RecordingReader::Open(args.file); + if (!opened.ok()) { + std::cerr << opened.status().ToString() << '\n'; + return 1; + } + auto& recording = *opened.value(); + const std::set wanted(args.topics.begin(), args.topics.end()); + + // By recorded topic id; null for a topic left out. + std::map> channels; + // Paced from the first replayed message, so a quiet start is skipped. + std::optional first_time; + auto started = Clock::now(); + std::uint64_t total = 0; + while (!g_stop.load()) { + auto next = recording.Next(); + if (!next.ok()) { + std::cerr << next.status().ToString() << '\n'; + return 1; + } + if (!next.value()) { + break; + } + const auto& message = *next.value(); + auto found = channels.find(message.topic); + if (found == channels.end()) { + const auto* topic = recording.FindTopic(message.topic); + std::unique_ptr channel; + if (wanted.empty() || wanted.count(topic->name) != 0) { + auto created = OpenReplayChannel(*topic, args); + if (!created.ok()) { + std::cerr << created.status().ToString() << '\n'; + return 1; + } + channel = std::move(created).value(); + std::cerr << "replay " << topic->name << ": " << topic->descriptor.ToString() << std::endl; + } + found = channels.emplace(message.topic, std::move(channel)).first; + } + if (!found->second) { + continue; + } + if (!first_time) { + first_time = message.time; + started = Clock::now(); + } + if (args.rate > 0) { + const auto offset = std::chrono::duration_cast(std::chrono::duration( + static_cast((message.time - *first_time).count()) / args.rate)); + const auto target = started + offset; + // In slices, so Ctrl+C is noticed during a long gap. + for (auto now = Clock::now(); now < target && !g_stop.load(); now = Clock::now()) { + std::this_thread::sleep_for(std::min(target - now, kReadSlice)); + } + if (g_stop.load()) { + break; + } + } + auto status = found->second->writer->Write(transport::ByteView(message.payload)); + if (!status.ok()) { + std::cerr << "replaying to " << recording.FindTopic(message.topic)->name << ": " << status.ToString() + << '\n'; + return 1; + } + ++found->second->sent; + ++total; + } + + int exit_code = 0; + for (const auto& name : wanted) { + const auto& topics = recording.topics(); + const bool known = std::any_of( + topics.begin(), topics.end(), [&name](const transport::RecordedTopic& topic) { return topic.name == name; }); + if (!known && !g_stop.load()) { + std::cerr << "replay: topic " << name << " is not in " << args.file << '\n'; + exit_code = 1; + } + } + std::cerr << "replay: " << total << " messages" << (recording.truncated() ? " (the recording was cut off)" : "") + << std::endl; + return exit_code; +} + +int Info(const Arguments& args) +{ + auto opened = transport::RecordingReader::Open(args.file); + if (!opened.ok()) { + std::cerr << opened.status().ToString() << '\n'; + return 1; + } + auto& recording = *opened.value(); + struct Stats { + std::uint64_t messages {0}; + std::uint64_t bytes {0}; + core::Nanoseconds first {0}; + core::Nanoseconds last {0}; + }; + std::map stats; + std::uint64_t total = 0; + std::optional first; + core::Nanoseconds last {0}; + while (true) { + auto next = recording.Next(); + if (!next.ok()) { + std::cerr << next.status().ToString() << '\n'; + return 1; + } + if (!next.value()) { + break; + } + const auto& message = *next.value(); + auto& topic = stats[message.topic]; + if (topic.messages == 0) { + topic.first = message.time; + } + ++topic.messages; + topic.bytes += message.payload.size(); + topic.last = message.time; + if (!first) { + first = message.time; + } + last = std::max(last, message.time); + ++total; + } + + const auto seconds = [](core::Nanoseconds value) { return std::chrono::duration(value).count(); }; + std::cout << std::fixed << std::setprecision(3) << args.file << ": " << recording.topics().size() << " topics, " + << total << " messages, " << (first ? seconds(last - *first) : 0.0) << " s" + << (recording.truncated() ? ", cut off at the end" : "") << '\n'; + for (const auto& topic : recording.topics()) { + const auto& topic_stats = stats[topic.id]; + std::cout << " " << topic.name << " " << topic.descriptor.ToString() << " " << topic_stats.messages + << " messages, " << topic_stats.bytes << " B"; + const auto span = seconds(topic_stats.last - topic_stats.first); + if (topic_stats.messages >= 2 && span > 0) { + std::cout << std::setprecision(2) << ", " << static_cast(topic_stats.messages - 1) / span + << " Hz" << std::setprecision(3); + } + const auto transport_name = topic.parameters.find("transport"); + if (transport_name != topic.parameters.end() && transport_name->second == "shm") { + std::cout << " shm domain " << ParameterOr(topic, "domain_id", 0) << ", " + << ParameterOr(topic, "slot_payload_size", 0) << " B x " << ParameterOr(topic, "slot_count", 0) + << " slots"; + } + std::cout << '\n'; + } + std::cout.unsetf(std::ios::floatfield); + return 0; +} + } // namespace int main(int argc, char** argv) @@ -605,5 +1059,14 @@ int main(int argc, char** argv) if (args.command == "list") { return List(args); } - return args.command == "echo" ? Echo(args) : Hz(args); + if (args.command == "echo") { + return Echo(args); + } + if (args.command == "hz") { + return Hz(args); + } + if (args.command == "record") { + return Record(args); + } + return args.command == "replay" ? Replay(args) : Info(args); } From 5f2cfb53d23f63343b7a38c2770c9d18f7f0964f Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 28 Oct 2026 18:19:31 +0800 Subject: [PATCH 6/6] docs: changelog and README for the operations tools Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 26 ++++++++++++++++++++++++++ README.md | 16 +++++++++++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b7a12b7..9dba454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,24 @@ the minor version in their soname (`libpuppet_master.so.0.2`), and send without blocking and report the result to a callback, so a component can call a service from `Execute()` without holding a scheduler worker. See [Asynchronous Calls](docs/services.md#asynchronous-calls). + `demo/scheduled_service_demo.cpp` shows both together. +- **System launcher.** `puppet_master_launch system.json` checks a system + manifest, starts its nodes in order, restarts them by their new + `restart`, `max_restarts`, and `restart_delay_ms` settings, ends the + system when a `required` node ends for good, and stops the rest in + reverse order on Ctrl+C, killing a node after its `stop_timeout_ms`. + `--log-dir` writes one log per node. `configuration::Supervisor` does the + same in C++. See [System Launcher](docs/launcher.md#system-launcher). +- **Topic tool.** `puppet_master_topic list|echo|hz` shows the shared-memory + topics of a running system, prints their messages, and measures their + rate and losses without slowing writers down. `--system FILE` takes the + topics from a manifest, which also works on Windows. See + [Topic Tool](docs/launcher.md#topic-tool). +- **Recordings.** `puppet_master_topic record|replay|info` records + shared-memory topics to a file and publishes them again at the recorded + pace (`--rate`). `RecordingWriter` and `RecordingReader` in + `puppet_master/transport/recording.h` read and write the format from C++. + See [Recordings](docs/recording.md). ### Changed @@ -27,6 +45,14 @@ the minor version in their soname (`libpuppet_master.so.0.2`), and `service_dependencies`, and `TriggerKind` a new value, `kService`; code that switches over `TriggerKind` needs a case for it. - `Server::Create` and `MakeTypedServer` take an optional `ServerOptions`. +- `Server::ServePending()` counts only the requests it handled, not expired + or malformed ones it dropped. +- `Application::InstallSignalHandlers()` also handles SIGBREAK on Windows, + which `puppet_master_launch` sends to stop a node. +- Breaking ABI: `configuration::NodeManifest` has new fields for + supervision. +- The vehicle pipeline example starts its system with + `puppet_master_launch`. ## 0.2.0 diff --git a/README.md b/README.md index d11febf..a75ed36 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ include/puppet_master/ Public headers for downstream projects. src/ Library and optional adapter implementations. demo/ Small runnable examples and an example configuration. examples/ Standalone downstream projects built against an install. -tools/ Command-line tools such as puppet_master_config. +tools/ Command-line tools: puppet_master_config, _launch, _topic. test/ Unit, integration, and smoke tests. bench/ Transport benchmarks (PUPPETMASTER_BUILD_BENCHMARKS). cmake/ Package configuration templates. @@ -109,7 +109,11 @@ cmake --install build --prefix /opt/puppetmaster ``` This installs headers under `include/`, the libraries, the CMake package under -`lib/cmake/PuppetMaster`, and, with the JSON adapter, `bin/puppet_master_config`. +`lib/cmake/PuppetMaster`, and, with the JSON adapter, the tools in `bin/`: +`puppet_master_config` checks configurations, `puppet_master_launch` runs and +supervises a system, and `puppet_master_topic` inspects, records, and replays +shared-memory topics (with the shm adapter too). See +[Launcher And Configuration Tools](docs/launcher.md). Add `-DBUILD_SHARED_LIBS=ON` for shared libraries. Before 1.0 each minor release may break the API and the ABI, so the shared @@ -172,6 +176,10 @@ Follow-up phases, all complete: 7. Services and release 0.2. Done: request/reply services on every transport, system manifests, a portable codec, shared-memory segment tools, benchmarks, and Windows JSON CI. See [CHANGELOG](CHANGELOG.md). +8. Scheduled services. Done: service triggers, asynchronous calls, and a + demo. +9. Operations tools. Done: a system launcher with restart policies, topic + list/echo/hz, and record/replay. See [Recordings](docs/recording.md). See [Architecture](docs/architecture.md) for the intended module boundaries. See [Core API](docs/core.md) for the current public core model. @@ -191,7 +199,9 @@ server liveness. See [Configuration System](docs/configuration.md) for code-first project assembly. See [Launcher And Configuration Tools](docs/launcher.md) for running -JSON-configured applications and checking configurations in CI. +JSON-configured applications, checking configurations in CI, launching a +system, and inspecting its topics. +See [Recordings](docs/recording.md) for recording and replaying topics. See [itage_engine Compatibility Facade](docs/compatibility-facade.md) for the transitional node/reader/writer API. See [Observability](docs/observability.md) for runtime metrics, trace hooks,